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.
 
 
 
 
 
 

366 lines
9.7 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. 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 doctype in webnotes.user.can_get_report:
  101. webnotes.response['403'] = 1
  102. raise webnotes.PermissionError
  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. else:
  146. if isinstance(f[3], basestring):
  147. f[3] = "'" + f[3].replace("'", "\'") + "'"
  148. conditions.append(tname + '.' + f[1] + " " + f[2] + " " + f[3])
  149. else:
  150. conditions.append('ifnull(' + tname + '.' + f[1] + ",0) " + f[2] \
  151. + " " + cstr(f[3]))
  152. def build_match_conditions(data, conditions):
  153. """add match conditions if applicable"""
  154. match_conditions = []
  155. match = True
  156. for d in doctypes[data['doctype']]:
  157. if d.doctype == 'DocPerm' and d.parent == data['doctype']:
  158. if d.role in roles:
  159. if d.match: # role applicable
  160. if ':' in d.match:
  161. document_key, default_key = d.match.split(":")
  162. else:
  163. default_key = document_key = d.match
  164. for v in webnotes.user.defaults.get(default_key, ['**No Match**']):
  165. match_conditions.append('`tab%s`.%s="%s"' % (data['doctype'],
  166. document_key, v))
  167. elif d.read == 1 and d.permlevel == 0:
  168. # don't restrict if another read permission at level 0
  169. # exists without a match restriction
  170. match = False
  171. if match_conditions and match:
  172. conditions.append('('+ ' or '.join(match_conditions) +')')
  173. def get_tables():
  174. """extract tables from fields"""
  175. data = webnotes.form_dict
  176. tables = ['`tab' + data['doctype'] + '`']
  177. # add tables from fields
  178. for f in json.loads(data['fields']):
  179. table_name = f.split('.')[0]
  180. if table_name.lower().startswith('group_concat('):
  181. table_name = table_name[13:]
  182. # check if ifnull function is used
  183. if table_name.lower().startswith('ifnull('):
  184. table_name = table_name[7:]
  185. if not table_name[0]=='`':
  186. table_name = '`' + table_name + '`'
  187. if not table_name in tables:
  188. tables.append(table_name)
  189. return tables
  190. @webnotes.whitelist()
  191. def save_report():
  192. """save report"""
  193. from webnotes.model.doc import Document
  194. data = webnotes.form_dict
  195. if webnotes.conn.exists('Report', data['name'].title()):
  196. d = Document('Report', data['name'].title())
  197. else:
  198. d = Document('Report')
  199. d.name = data['name']
  200. d.ref_doctype = data['doctype']
  201. d.json = data['json']
  202. d.save()
  203. webnotes.msgprint("%s saved." % d.name)
  204. return d.name
  205. @webnotes.whitelist()
  206. def export_query():
  207. """export from report builder"""
  208. # TODO: validate use is allowed to export
  209. verify_export_allowed()
  210. ret = webnotes.conn.sql(build_query(), as_dict=1)
  211. columns = [x[0] for x in webnotes.conn.get_description()]
  212. data = [['Sr'] + get_labels(columns),]
  213. # flatten dict
  214. cnt = 1
  215. for row in ret:
  216. flat = [cnt,]
  217. for c in columns:
  218. flat.append(row.get(c))
  219. data.append(flat)
  220. cnt += 1
  221. # convert to csv
  222. from cStringIO import StringIO
  223. import csv
  224. f = StringIO()
  225. writer = csv.writer(f)
  226. from webnotes.utils import cstr
  227. for r in data:
  228. # encode only unicode type strings and not int, floats etc.
  229. writer.writerow(map(lambda v: isinstance(v, unicode) and v.encode('utf-8') or v, r))
  230. f.seek(0)
  231. webnotes.response['result'] = unicode(f.read(), 'utf-8')
  232. webnotes.response['type'] = 'csv'
  233. webnotes.response['doctype'] = [t[4:-1] for t in tables][0]
  234. def verify_export_allowed():
  235. """throw exception if user is not allowed to export"""
  236. global roles
  237. roles = webnotes.get_roles()
  238. if not ('Administrator' in roles or 'System Manager' in roles or 'Report Manager' in roles):
  239. raise webnotes.PermissionError
  240. def get_labels(columns):
  241. """get column labels based on column names"""
  242. label_dict = {}
  243. for doctype in doctypes:
  244. for d in doctypes[doctype]:
  245. if d.doctype=='DocField' and d.fieldname:
  246. label_dict[d.fieldname] = d.label
  247. return map(lambda x: label_dict.get(x, x.title()), columns)
  248. @webnotes.whitelist()
  249. def delete_items():
  250. """delete selected items"""
  251. import json
  252. from webnotes.model import delete_doc
  253. from webnotes.model.code import get_obj
  254. il = json.loads(webnotes.form_dict.get('items'))
  255. doctype = webnotes.form_dict.get('doctype')
  256. for d in il:
  257. try:
  258. dt_obj = get_obj(doctype, d)
  259. if hasattr(dt_obj, 'on_trash'):
  260. dt_obj.on_trash()
  261. delete_doc(doctype, d)
  262. except Exception, e:
  263. pass
  264. @webnotes.whitelist()
  265. def get_stats():
  266. """get tag info"""
  267. import json
  268. tags = json.loads(webnotes.form_dict.get('stats'))
  269. doctype = webnotes.form_dict['doctype']
  270. stats = {}
  271. columns = get_table_columns(doctype)
  272. for tag in tags:
  273. if not tag in columns: continue
  274. tagcount = webnotes.conn.sql("""select %(tag)s, count(*)
  275. from `tab%(doctype)s`
  276. where ifnull(%(tag)s, '')!=''
  277. group by %(tag)s;""" % locals(), as_list=1)
  278. if tag=='_user_tags':
  279. stats[tag] = scrub_user_tags(tagcount)
  280. else:
  281. stats[tag] = tagcount
  282. return stats
  283. def scrub_user_tags(tagcount):
  284. """rebuild tag list for tags"""
  285. rdict = {}
  286. tagdict = dict(tagcount)
  287. for t in tagdict:
  288. alltags = t.split(',')
  289. for tag in alltags:
  290. if tag:
  291. if not tag in rdict:
  292. rdict[tag] = 0
  293. rdict[tag] += tagdict[t]
  294. rlist = []
  295. for tag in rdict:
  296. rlist.append([tag, rdict[tag]])
  297. return rlist
  298. def get_table_columns(table):
  299. res = webnotes.conn.sql("DESC `tab%s`" % table, as_dict=1)
  300. if res: return [r['Field'] for r in res]