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.

doclistview.py 8.5 KiB

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