You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reportview.py 9.9 KiB

13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
13 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. from __future__ import unicode_literals
  23. """build query for doclistview and return results"""
  24. import webnotes, json
  25. tables = None
  26. doctypes = {}
  27. roles = []
  28. @webnotes.whitelist()
  29. def get(arg=None):
  30. query = build_query(arg)
  31. return compress(webnotes.conn.sql(query, as_dict=1))
  32. def build_query(arg=None):
  33. """
  34. build query
  35. gets doctype, subject, filters
  36. limit_start, limit_page_length
  37. """
  38. data = webnotes.form_dict
  39. global tables
  40. if 'query' in data:
  41. return run_custom_query(data)
  42. filters = json.loads(data['filters'])
  43. fields = json.loads(data['fields'])
  44. tables = get_tables()
  45. load_doctypes()
  46. remove_user_tags(fields)
  47. # conditions
  48. conditions = build_conditions(filters)
  49. # query dict
  50. data['tables'] = ', '.join(tables)
  51. data['conditions'] = ' and '.join(conditions)
  52. data['fields'] = ', '.join(fields)
  53. if not data.get('order_by'):
  54. data['order_by'] = tables[0] + '.modified desc'
  55. if data.get('group_by'):
  56. data['group_by'] = "group by " + data.get('group_by')
  57. else:
  58. data['group_by'] = ''
  59. check_sort_by_table(data.get('order_by'), tables)
  60. add_limit(data)
  61. query = """select %(fields)s from %(tables)s where %(conditions)s
  62. %(group_by)s order by %(order_by)s %(limit)s""" % data
  63. return query
  64. def compress(data):
  65. """separate keys and values"""
  66. if not data: return data
  67. values = []
  68. keys = data[0].keys()
  69. for row in data:
  70. new_row = []
  71. for key in keys:
  72. new_row.append(row[key])
  73. values.append(new_row)
  74. return {
  75. "keys": keys,
  76. "values": values
  77. }
  78. def check_sort_by_table(sort_by, tables):
  79. """check atleast 1 column selected from the sort by table """
  80. tbl = sort_by.split('.')[0]
  81. if tbl not in tables:
  82. if tbl.startswith('`'):
  83. tbl = tbl[4:-1]
  84. webnotes.msgprint("Please select atleast 1 column from '%s' to sort"\
  85. % tbl, raise_exception=1)
  86. def run_custom_query(data):
  87. """run custom query"""
  88. query = data['query']
  89. if '%(key)s' in query:
  90. query = query.replace('%(key)s', 'name')
  91. return webnotes.conn.sql(query, as_dict=1)
  92. def load_doctypes():
  93. """load all doctypes and roles"""
  94. global doctypes, roles
  95. import webnotes.model.doctype
  96. roles = webnotes.get_roles()
  97. for t in tables:
  98. if t.startswith('`'):
  99. doctype = t[4:-1]
  100. if not webnotes.has_permission(doctype):
  101. webnotes.response['403'] = 1
  102. raise webnotes.PermissionError, doctype
  103. doctypes[doctype] = webnotes.model.doctype.get(doctype)
  104. def remove_user_tags(fields):
  105. """remove column _user_tags if not in table"""
  106. for fld in fields:
  107. if '_user_tags' in fld:
  108. if not '_user_tags' in get_table_columns(webnotes.form_dict['doctype']):
  109. del fields[fields.index(fld)]
  110. break
  111. def add_limit(data):
  112. if 'limit_page_length' in data:
  113. data['limit'] = 'limit %(limit_start)s, %(limit_page_length)s' % data
  114. else:
  115. data['limit'] = ''
  116. def build_conditions(filters):
  117. """build conditions"""
  118. data = webnotes.form_dict
  119. # docstatus condition
  120. docstatus = json.loads(data['docstatus'])
  121. if docstatus:
  122. conditions = [tables[0] + '.docstatus in (' + ','.join(docstatus) + ')']
  123. else:
  124. # default condition
  125. conditions = [tables[0] + '.docstatus < 2']
  126. # make conditions from filters
  127. build_filter_conditions(data, filters, conditions)
  128. # join parent, child tables
  129. for tname in tables[1:]:
  130. conditions.append(tname + '.parent = ' + tables[0] + '.name')
  131. # match conditions
  132. build_match_conditions(data, conditions)
  133. return conditions
  134. def build_filter_conditions(data, filters, conditions):
  135. """build conditions from user filters"""
  136. from webnotes.utils import cstr
  137. for f in filters:
  138. tname = ('`tab' + f[0] + '`')
  139. if not tname in tables:
  140. tables.append(tname)
  141. # prepare in condition
  142. if f[2]=='in':
  143. opts = ["'" + t.strip().replace("'", "\'") + "'" for t in f[3].split(',')]
  144. f[3] = "(" + ', '.join(opts) + ")"
  145. conditions.append(tname + '.' + f[1] + " " + f[2] + " " + f[3])
  146. else:
  147. if isinstance(f[3], basestring):
  148. f[3] = "'" + f[3].replace("'", "\'") + "'"
  149. conditions.append(tname + '.' + f[1] + " " + f[2] + " " + f[3])
  150. else:
  151. conditions.append('ifnull(' + tname + '.' + f[1] + ",0) " + f[2] \
  152. + " " + cstr(f[3]))
  153. def build_match_conditions(data, conditions):
  154. """add match conditions if applicable"""
  155. match_conditions = []
  156. match = True
  157. for d in doctypes[data['doctype']]:
  158. if d.doctype == 'DocPerm' and d.parent == data['doctype']:
  159. if d.role in roles:
  160. if d.match: # role applicable
  161. if ':' in d.match:
  162. document_key, default_key = d.match.split(":")
  163. else:
  164. default_key = document_key = d.match
  165. for v in webnotes.user.get_defaults().get(default_key, ['**No Match**']):
  166. match_conditions.append('`tab%s`.%s="%s"' % (data['doctype'],
  167. document_key, v))
  168. elif d.read == 1 and d.permlevel == 0:
  169. # don't restrict if another read permission at level 0
  170. # exists without a match restriction
  171. match = False
  172. if match_conditions and match:
  173. conditions.append('('+ ' or '.join(match_conditions) +')')
  174. def get_tables():
  175. """extract tables from fields"""
  176. data = webnotes.form_dict
  177. tables = ['`tab' + data['doctype'] + '`']
  178. # add tables from fields
  179. for f in json.loads(data['fields']):
  180. table_name = f.split('.')[0]
  181. if table_name.lower().startswith('group_concat('):
  182. table_name = table_name[13:]
  183. # check if ifnull function is used
  184. if table_name.lower().startswith('ifnull('):
  185. table_name = table_name[7:]
  186. if not table_name[0]=='`':
  187. table_name = '`' + table_name + '`'
  188. if not table_name in tables:
  189. tables.append(table_name)
  190. return tables
  191. @webnotes.whitelist()
  192. def save_report():
  193. """save report"""
  194. from webnotes.model.doc import Document
  195. data = webnotes.form_dict
  196. if webnotes.conn.exists('Report', data['name'].title()):
  197. d = Document('Report', data['name'].title())
  198. else:
  199. d = Document('Report')
  200. d.name = data['name']
  201. d.ref_doctype = data['doctype']
  202. d.json = data['json']
  203. webnotes.model_wrapper([d]).save()
  204. webnotes.msgprint("%s saved." % d.name)
  205. return d.name
  206. @webnotes.whitelist()
  207. def export_query():
  208. """export from report builder"""
  209. # TODO: validate use is allowed to export
  210. verify_export_allowed()
  211. ret = webnotes.conn.sql(build_query(), as_dict=1)
  212. columns = [x[0] for x in webnotes.conn.get_description()]
  213. data = [['Sr'] + get_labels(columns),]
  214. # flatten dict
  215. cnt = 1
  216. for row in ret:
  217. flat = [cnt,]
  218. for c in columns:
  219. flat.append(row.get(c))
  220. data.append(flat)
  221. cnt += 1
  222. # convert to csv
  223. from cStringIO import StringIO
  224. import csv
  225. f = StringIO()
  226. writer = csv.writer(f)
  227. from webnotes.utils import cstr
  228. for r in data:
  229. # encode only unicode type strings and not int, floats etc.
  230. writer.writerow(map(lambda v: isinstance(v, unicode) and v.encode('utf-8') or v, r))
  231. f.seek(0)
  232. webnotes.response['result'] = unicode(f.read(), 'utf-8')
  233. webnotes.response['type'] = 'csv'
  234. webnotes.response['doctype'] = [t[4:-1] for t in tables][0]
  235. def verify_export_allowed():
  236. """throw exception if user is not allowed to export"""
  237. global roles
  238. roles = webnotes.get_roles()
  239. if not ('Administrator' in roles or 'System Manager' in roles or 'Report Manager' in roles):
  240. raise webnotes.PermissionError
  241. def get_labels(columns):
  242. """get column labels based on column names"""
  243. label_dict = {}
  244. for doctype in doctypes:
  245. for d in doctypes[doctype]:
  246. if d.doctype=='DocField' and d.fieldname:
  247. label_dict[d.fieldname] = d.label
  248. return map(lambda x: label_dict.get(x, x.title()), columns)
  249. @webnotes.whitelist()
  250. def delete_items():
  251. """delete selected items"""
  252. import json
  253. from webnotes.model import delete_doc
  254. from webnotes.model.code import get_obj
  255. il = json.loads(webnotes.form_dict.get('items'))
  256. doctype = webnotes.form_dict.get('doctype')
  257. for d in il:
  258. try:
  259. dt_obj = get_obj(doctype, d)
  260. if hasattr(dt_obj, 'on_trash'):
  261. dt_obj.on_trash()
  262. delete_doc(doctype, d)
  263. except Exception, e:
  264. webnotes.errprint(webnotes.getTraceback())
  265. pass
  266. @webnotes.whitelist()
  267. def get_stats():
  268. """get tag info"""
  269. import json
  270. tags = json.loads(webnotes.form_dict.get('stats'))
  271. doctype = webnotes.form_dict['doctype']
  272. stats = {}
  273. columns = get_table_columns(doctype)
  274. for tag in tags:
  275. if not tag in columns: continue
  276. tagcount = webnotes.conn.sql("""select %(tag)s, count(*)
  277. from `tab%(doctype)s`
  278. where ifnull(%(tag)s, '')!=''
  279. group by %(tag)s;""" % locals(), as_list=1)
  280. if tag=='_user_tags':
  281. stats[tag] = scrub_user_tags(tagcount)
  282. else:
  283. stats[tag] = tagcount
  284. return stats
  285. def scrub_user_tags(tagcount):
  286. """rebuild tag list for tags"""
  287. rdict = {}
  288. tagdict = dict(tagcount)
  289. for t in tagdict:
  290. alltags = t.split(',')
  291. for tag in alltags:
  292. if tag:
  293. if not tag in rdict:
  294. rdict[tag] = 0
  295. rdict[tag] += tagdict[t]
  296. rlist = []
  297. for tag in rdict:
  298. rlist.append([tag, rdict[tag]])
  299. return rlist
  300. def get_table_columns(table):
  301. res = webnotes.conn.sql("DESC `tab%s`" % table, as_dict=1)
  302. if res: return [r['Field'] for r in res]