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.
 
 
 
 
 
 

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