Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

reportview.py 10 KiB

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