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.

пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 12 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 12 година
пре 13 година
пре 12 година
пре 13 година
пре 13 година
пре 12 година
пре 12 година
пре 12 година
пре 13 година
пре 13 година
пре 12 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 12 година
пре 12 година
пре 13 година
пре 12 година
пре 13 година
пре 12 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
пре 13 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. if query:
  45. return run_custom_query(query)
  46. if not filters: filters = []
  47. if not docstatus: docstatus = []
  48. args = prepare_args(doctype, filters, fields, docstatus, group_by, order_by)
  49. args.limit = add_limit(limit_start, limit_page_length)
  50. query = """select %(fields)s from %(tables)s where %(conditions)s
  51. %(group_by)s order by %(order_by)s %(limit)s""" % args
  52. return webnotes.conn.sql(query, as_dict=1)
  53. def prepare_args(doctype, filters, fields, docstatus, group_by, order_by):
  54. global tables
  55. tables = get_tables(doctype, fields)
  56. load_doctypes()
  57. remove_user_tags(doctype, fields)
  58. conditions = build_conditions(doctype, fields, filters, docstatus)
  59. args = webnotes._dict()
  60. # query dict
  61. args.tables = ', '.join(tables)
  62. args.conditions = ' and '.join(conditions)
  63. args.fields = ', '.join(fields)
  64. args.order_by = order_by or tables[0] + '.modified desc'
  65. args.group_by = group_by and (" group by " + group_by) or ""
  66. check_sort_by_table(args.order_by)
  67. return args
  68. def compress(data):
  69. """separate keys and values"""
  70. if not data: return data
  71. values = []
  72. keys = data[0].keys()
  73. for row in data:
  74. new_row = []
  75. for key in keys:
  76. new_row.append(row[key])
  77. values.append(new_row)
  78. return {
  79. "keys": keys,
  80. "values": values
  81. }
  82. def check_sort_by_table(sort_by):
  83. """check atleast 1 column selected from the sort by table """
  84. tbl = sort_by.split('.')[0]
  85. if tbl not in tables:
  86. if tbl.startswith('`'):
  87. tbl = tbl[4:-1]
  88. webnotes.msgprint("Please select atleast 1 column from '%s' to sort"\
  89. % tbl, raise_exception=1)
  90. def run_custom_query(query):
  91. """run custom query"""
  92. if '%(key)s' in query:
  93. query = query.replace('%(key)s', 'name')
  94. return webnotes.conn.sql(query, as_dict=1)
  95. def load_doctypes():
  96. """load all doctypes and roles"""
  97. global doctypes, roles
  98. import webnotes.model.doctype
  99. roles = webnotes.get_roles()
  100. for t in tables:
  101. if t.startswith('`'):
  102. doctype = t[4:-1]
  103. if not webnotes.has_permission(doctype):
  104. webnotes.response['403'] = 1
  105. raise webnotes.PermissionError, doctype
  106. doctypes[doctype] = webnotes.model.doctype.get(doctype)
  107. def remove_user_tags(doctype, fields):
  108. """remove column _user_tags if not in table"""
  109. for fld in fields:
  110. if '_user_tags' in fld:
  111. if not '_user_tags' in get_table_columns(doctype):
  112. del fields[fields.index(fld)]
  113. break
  114. def add_limit(limit_start, limit_page_length):
  115. if limit_page_length:
  116. return 'limit %s, %s' % (limit_start, limit_page_length)
  117. else:
  118. return ''
  119. def build_conditions(doctype, fields, filters, docstatus):
  120. """build conditions"""
  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(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. match_conditions = build_match_conditions(doctype, fields)
  133. if match_conditions:
  134. conditions.append(match_conditions)
  135. return conditions
  136. def build_filter_conditions(filters, conditions):
  137. """build conditions from user filters"""
  138. from webnotes.utils import cstr
  139. for f in filters:
  140. tname = ('`tab' + f[0] + '`')
  141. if not tname in tables:
  142. tables.append(tname)
  143. # prepare in condition
  144. if f[2]=='in':
  145. opts = ["'" + t.strip().replace("'", "\'") + "'" for t in f[3].split(',')]
  146. f[3] = "(" + ', '.join(opts) + ")"
  147. conditions.append(tname + '.' + f[1] + " " + f[2] + " " + f[3])
  148. else:
  149. if isinstance(f[3], basestring):
  150. f[3] = "'" + f[3].replace("'", "\'") + "'"
  151. conditions.append(tname + '.' + f[1] + " " + f[2] + " " + f[3])
  152. else:
  153. conditions.append('ifnull(' + tname + '.' + f[1] + ",0) " + f[2] \
  154. + " " + cstr(f[3]))
  155. def build_match_conditions(doctype, fields=None):
  156. """add match conditions if applicable"""
  157. match_conditions = []
  158. match = True
  159. if not tables or not doctypes:
  160. global tables
  161. tables = get_tables(doctype, fields)
  162. load_doctypes()
  163. for d in doctypes[doctype]:
  164. if d.doctype == 'DocPerm' and d.parent == doctype:
  165. if d.role in roles:
  166. if d.match: # role applicable
  167. if ':' in d.match:
  168. document_key, default_key = d.match.split(":")
  169. else:
  170. default_key = document_key = d.match
  171. for v in webnotes.defaults.get_user_default_as_list(default_key) or ["** No Match **"]:
  172. match_conditions.append('`tab%s`.%s="%s"' % (doctype,
  173. document_key, v))
  174. elif d.read == 1 and d.permlevel == 0:
  175. # don't restrict if another read permission at level 0
  176. # exists without a match restriction
  177. match = False
  178. if match_conditions and match:
  179. return '('+ ' or '.join(match_conditions) +')'
  180. else:
  181. return ""
  182. def get_tables(doctype, fields):
  183. """extract tables from fields"""
  184. tables = ['`tab' + doctype + '`']
  185. # add tables from fields
  186. for f in fields or []:
  187. if "." not in f: continue
  188. table_name = f.split('.')[0]
  189. if table_name.lower().startswith('group_concat('):
  190. table_name = table_name[13:]
  191. # check if ifnull function is used
  192. if table_name.lower().startswith('ifnull('):
  193. table_name = table_name[7:]
  194. if not table_name[0]=='`':
  195. table_name = '`' + table_name + '`'
  196. if not table_name in tables:
  197. tables.append(table_name)
  198. return tables
  199. @webnotes.whitelist()
  200. def save_report():
  201. """save report"""
  202. from webnotes.model.doc import Document
  203. data = webnotes.form_dict
  204. if webnotes.conn.exists('Report', data['name']):
  205. d = Document('Report', data['name'])
  206. else:
  207. d = Document('Report')
  208. d.report_name = data['name']
  209. d.ref_doctype = data['doctype']
  210. d.report_type = "Report Builder"
  211. d.json = data['json']
  212. webnotes.bean([d]).save()
  213. webnotes.msgprint("%s saved." % d.name)
  214. return d.name
  215. @webnotes.whitelist()
  216. def export_query():
  217. """export from report builder"""
  218. # TODO: validate use is allowed to export
  219. verify_export_allowed()
  220. ret = execute(**get_form_params())
  221. columns = [x[0] for x in webnotes.conn.get_description()]
  222. data = [['Sr'] + get_labels(columns),]
  223. # flatten dict
  224. cnt = 1
  225. for row in ret:
  226. flat = [cnt,]
  227. for c in columns:
  228. flat.append(row.get(c))
  229. data.append(flat)
  230. cnt += 1
  231. # convert to csv
  232. from cStringIO import StringIO
  233. import csv
  234. f = StringIO()
  235. writer = csv.writer(f)
  236. from webnotes.utils import cstr
  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 = webnotes.conn.sql("""select %(tag)s, count(*)
  285. from `tab%(doctype)s`
  286. where ifnull(%(tag)s, '')!=''
  287. group by %(tag)s;""" % locals(), as_list=1)
  288. if tag=='_user_tags':
  289. stats[tag] = scrub_user_tags(tagcount)
  290. else:
  291. stats[tag] = tagcount
  292. return stats
  293. def scrub_user_tags(tagcount):
  294. """rebuild tag list for tags"""
  295. rdict = {}
  296. tagdict = dict(tagcount)
  297. for t in tagdict:
  298. alltags = t.split(',')
  299. for tag in alltags:
  300. if tag:
  301. if not tag in rdict:
  302. rdict[tag] = 0
  303. rdict[tag] += tagdict[t]
  304. rlist = []
  305. for tag in rdict:
  306. rlist.append([tag, rdict[tag]])
  307. return rlist
  308. def get_table_columns(table):
  309. res = webnotes.conn.sql("DESC `tab%s`" % table, as_dict=1)
  310. if res: return [r['Field'] for r in res]