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.
 
 
 
 
 
 

384 lines
9.9 KiB

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