25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

309 lines
8.1 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. """build query for doclistview and return results"""
  23. import webnotes, json
  24. tables = None
  25. doctypes = {}
  26. roles = []
  27. @webnotes.whitelist()
  28. def get(arg=None):
  29. """
  30. build query
  31. gets doctype, subject, filters
  32. limit_start, limit_page_length
  33. """
  34. data = webnotes.form_dict
  35. global tables
  36. if 'query' in data:
  37. return run_custom_query(data)
  38. filters = json.loads(data['filters'])
  39. fields = json.loads(data['fields'])
  40. tables = get_tables()
  41. load_doctypes()
  42. remove_user_tags(fields)
  43. # conditions
  44. conditions = build_conditions(filters)
  45. # query dict
  46. data['tables'] = ', '.join(tables)
  47. data['conditions'] = ' and '.join(conditions)
  48. data['fields'] = ', '.join(fields)
  49. if not data.get('order_by'):
  50. data['order_by'] = tables[0] + '.modified desc'
  51. add_limit(data)
  52. query = """select %(fields)s from %(tables)s where %(conditions)s
  53. order by %(order_by)s %(limit)s""" % data
  54. return webnotes.conn.sql(query, as_dict=1)
  55. def run_custom_query(data):
  56. """run custom query"""
  57. query = data['query']
  58. if '%(key)s' in query:
  59. query = query.replace('%(key)s', 'name')
  60. return webnotes.conn.sql(query, as_dict=1, debug=1)
  61. def load_doctypes():
  62. """load all doctypes and roles"""
  63. global doctypes, roles
  64. import webnotes.model.doctype
  65. roles = webnotes.get_roles()
  66. for t in tables:
  67. if t.startswith('`'):
  68. doctype = t[4:-1]
  69. if not doctype in webnotes.user.can_get_report:
  70. webnotes.response['403'] = 1
  71. raise webnotes.PermissionError
  72. doctypes[doctype] = webnotes.model.doctype.get(doctype)
  73. def remove_user_tags(fields):
  74. """remove column _user_tags if not in table"""
  75. for fld in fields:
  76. if '_user_tags' in fld:
  77. if not '_user_tags' in get_table_columns(webnotes.form_dict['doctype']):
  78. del fields[fld]
  79. break
  80. def add_limit(data):
  81. if 'limit_page_length' in data:
  82. data['limit'] = 'limit %(limit_start)s, %(limit_page_length)s' % data
  83. else:
  84. data['limit'] = ''
  85. def build_conditions(filters):
  86. """build conditions"""
  87. data = webnotes.form_dict
  88. # docstatus condition
  89. docstatus = json.loads(data['docstatus'])
  90. if docstatus:
  91. conditions = [tables[0] + '.docstatus in (' + ','.join(docstatus) + ')']
  92. else:
  93. # default condition
  94. conditions = [tables[0] + '.docstatus < 2']
  95. # make conditions from filters
  96. build_filter_conditions(data, filters, conditions)
  97. # join parent, child tables
  98. for tname in tables[1:]:
  99. conditions.append(tname + '.parent = ' + tables[0] + '.name')
  100. # match conditions
  101. build_match_conditions(data, conditions)
  102. return conditions
  103. def build_filter_conditions(data, filters, conditions):
  104. """build conditions from user filters"""
  105. for f in filters:
  106. tname = ('`tab' + f[0] + '`')
  107. if not tname in tables:
  108. tables.append(tname)
  109. # prepare in condition
  110. if f[2]=='in':
  111. opts = ["'" + t.strip().replace("'", "\'") + "'" for t in f[3].split(',')]
  112. f[3] = "(" + ', '.join(opts) + ")"
  113. else:
  114. f[3] = "'" + f[3].replace("'", "\'") + "'"
  115. conditions.append(tname + '.' + f[1] + " " + f[2] + " " + f[3])
  116. def build_match_conditions(data, conditions):
  117. """add match conditions if applicable"""
  118. match_conditions = []
  119. match = True
  120. for d in doctypes[data['doctype']]:
  121. if d.doctype == 'DocPerm':
  122. if d.role in roles:
  123. if d.match: # role applicable
  124. for v in webnotes.user.defaults.get(d.match, ['**No Match**']):
  125. match_conditions.append('`tab%s`.%s="%s"' % (data['doctype'], d.match,v))
  126. else:
  127. match = False
  128. if match_conditions and match:
  129. conditions.append('('+ ' or '.join(match_conditions) +')')
  130. def get_tables():
  131. """extract tables from fields"""
  132. data = webnotes.form_dict
  133. tables = ['`tab' + data['doctype'] + '`']
  134. # add tables from fields
  135. for f in json.loads(data['fields']):
  136. table_name = f.split('.')[0]
  137. # check if ifnull function is used
  138. if table_name.lower().startswith('ifnull('):
  139. table_name = table_name[7:]
  140. if not table_name[0]=='`':
  141. table_name = '`' + table_name + '`'
  142. if not table_name in tables:
  143. tables.append(table_name)
  144. return tables
  145. @webnotes.whitelist()
  146. def save_report():
  147. """save report"""
  148. from webnotes.model.doc import Document
  149. data = webnotes.form_dict
  150. if webnotes.conn.exists('Report', data['name']):
  151. d = Document('Report', data['name'])
  152. else:
  153. d = Document('Report')
  154. d.name = data['name']
  155. d.ref_doctype = data['doctype']
  156. d.json = data['json']
  157. d.save()
  158. webnotes.msgprint("%s saved." % d.name)
  159. return d.name
  160. @webnotes.whitelist()
  161. def export_query():
  162. """export from report builder"""
  163. # TODO: validate use is allowed to export
  164. verify_export_allowed()
  165. ret = get()
  166. columns = [x[0] for x in webnotes.conn.get_description()]
  167. data = [['Sr'] + get_labels(columns),]
  168. # flatten dict
  169. cnt = 1
  170. for row in ret:
  171. flat = [cnt,]
  172. for c in columns:
  173. flat.append(row.get(c))
  174. data.append(flat)
  175. cnt += 1
  176. # convert to csv
  177. from cStringIO import StringIO
  178. import csv
  179. f = StringIO()
  180. writer = csv.writer(f)
  181. for r in data:
  182. for i in xrange(len(r)):
  183. if type(r[i]) is unicode:
  184. r[i] = r[i].encode('utf-8')
  185. writer.writerow(r)
  186. f.seek(0)
  187. webnotes.response['result'] = f.read()
  188. webnotes.response['type'] = 'csv'
  189. webnotes.response['doctype'] = [t[4:-1] for t in tables][0]
  190. def verify_export_allowed():
  191. """throw exception if user is not allowed to export"""
  192. global roles
  193. roles = webnotes.get_roles()
  194. if not ('Administrator' in roles or 'System Manager' in roles or 'Report Manager' in roles):
  195. raise webnotes.PermissionError
  196. def get_labels(columns):
  197. """get column labels based on column names"""
  198. label_dict = {}
  199. for doctype in doctypes:
  200. for d in doctypes[doctype]:
  201. if d.doctype=='DocField' and d.fieldname:
  202. label_dict[d.fieldname] = d.label
  203. return map(lambda x: label_dict.get(x, x.title()), columns)
  204. @webnotes.whitelist()
  205. def delete_items():
  206. """delete selected items"""
  207. import json
  208. from webnotes.model import delete_doc
  209. from webnotes.model.code import get_obj
  210. il = json.loads(webnotes.form_dict.get('items'))
  211. doctype = webnotes.form_dict.get('doctype')
  212. for d in il:
  213. dt_obj = get_obj(doctype, d)
  214. if hasattr(dt_obj, 'on_trash'):
  215. dt_obj.on_trash()
  216. delete_doc(doctype, d)
  217. @webnotes.whitelist()
  218. def get_stats():
  219. """get tag info"""
  220. import json
  221. tags = json.loads(webnotes.form_dict.get('stats'))
  222. doctype = webnotes.form_dict['doctype']
  223. stats = {}
  224. columns = get_table_columns(doctype)
  225. for tag in tags:
  226. if not tag in columns: continue
  227. tagcount = webnotes.conn.sql("""select %(tag)s, count(*)
  228. from `tab%(doctype)s`
  229. where ifnull(%(tag)s, '')!=''
  230. group by %(tag)s;""" % locals(), as_list=1)
  231. if tag=='_user_tags':
  232. stats[tag] = scrub_user_tags(tagcount)
  233. else:
  234. stats[tag] = tagcount
  235. return stats
  236. def scrub_user_tags(tagcount):
  237. """rebuild tag list for tags"""
  238. rdict = {}
  239. tagdict = dict(tagcount)
  240. for t in tagdict:
  241. alltags = t.split(',')
  242. for tag in alltags:
  243. if tag:
  244. if not tag in rdict:
  245. rdict[tag] = 0
  246. rdict[tag] += tagdict[t]
  247. rlist = []
  248. for tag in rdict:
  249. rlist.append([tag, rdict[tag]])
  250. return rlist
  251. def get_table_columns(table):
  252. res = webnotes.conn.sql("DESC `tab%s`" % table, as_dict=1)
  253. if res: return [r['Field'] for r in res]