您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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