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 10 KiB

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