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.
 
 
 
 
 
 

448 lines
14 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. """
  23. Get metadata (main doctype with fields and permissions with all table doctypes)
  24. - if exists in cache, get it from cache
  25. - add custom fields
  26. - override properties from PropertySetter
  27. - sort based on prev_field
  28. - optionally, post process (add js, css, select fields), or without
  29. """
  30. from __future__ import unicode_literals
  31. # imports
  32. import conf
  33. import webnotes
  34. import webnotes.model
  35. import webnotes.model.doc
  36. import webnotes.model.doclist
  37. doctype_cache = {}
  38. docfield_types = None
  39. def get(doctype, processed=False, cached=True):
  40. """return doclist"""
  41. if cached:
  42. doclist = from_cache(doctype, processed)
  43. if doclist:
  44. if processed:
  45. add_linked_with(doclist)
  46. return DocTypeDocList(doclist)
  47. load_docfield_types()
  48. # main doctype doclist
  49. doclist = get_doctype_doclist(doctype)
  50. # add doctypes of table fields
  51. table_types = [d.options for d in doclist \
  52. if d.doctype=='DocField' and d.fieldtype=='Table']
  53. for table_doctype in table_types:
  54. doclist += get_doctype_doclist(table_doctype)
  55. if processed:
  56. add_code(doctype, doclist)
  57. expand_selects(doclist)
  58. add_print_formats(doclist)
  59. add_search_fields(doclist)
  60. add_workflows(doclist)
  61. update_language(doclist)
  62. # add validators
  63. #add_validators(doctype, doclist)
  64. # add precision
  65. add_precision(doctype, doclist)
  66. to_cache(doctype, processed, doclist)
  67. if processed:
  68. add_linked_with(doclist)
  69. return DocTypeDocList(doclist)
  70. def load_docfield_types():
  71. global docfield_types
  72. docfield_types = dict(webnotes.conn.sql("""select fieldname, fieldtype from tabDocField
  73. where parent='DocField'"""))
  74. def add_workflows(doclist):
  75. from webnotes.model.workflow import get_workflow_name
  76. doctype = doclist[0].name
  77. # get active workflow
  78. workflow_name = get_workflow_name(doctype)
  79. if workflow_name and webnotes.conn.exists("Workflow", workflow_name):
  80. doclist += webnotes.get_doclist("Workflow", workflow_name)
  81. # add workflow states (for icons and style)
  82. for state in map(lambda d: d.state, doclist.get({"doctype":"Workflow Document State"})):
  83. doclist += webnotes.get_doclist("Workflow State", state)
  84. def get_doctype_doclist(doctype):
  85. """get doclist of single doctype"""
  86. doclist = webnotes.get_doclist('DocType', doctype)
  87. add_custom_fields(doctype, doclist)
  88. apply_property_setters(doctype, doclist)
  89. sort_fields(doclist)
  90. return doclist
  91. def sort_fields(doclist):
  92. """sort on basis of previous_field"""
  93. from webnotes.model.doclist import DocList
  94. newlist = DocList([])
  95. pending = filter(lambda d: d.doctype=='DocField', doclist)
  96. maxloops = 20
  97. while (pending and maxloops>0):
  98. maxloops -= 1
  99. for d in pending[:]:
  100. if d.previous_field:
  101. # field already added
  102. for n in newlist:
  103. if n.fieldname==d.previous_field:
  104. newlist.insert(newlist.index(n)+1, d)
  105. pending.remove(d)
  106. break
  107. else:
  108. newlist.append(d)
  109. pending.remove(d)
  110. # recurring at end
  111. if pending:
  112. newlist += pending
  113. # renum
  114. idx = 1
  115. for d in newlist:
  116. d.idx = idx
  117. idx += 1
  118. doclist.get({"doctype":["!=", "DocField"]}).extend(newlist)
  119. def apply_property_setters(doctype, doclist):
  120. from webnotes.utils import cint
  121. for ps in webnotes.conn.sql("""select * from `tabProperty Setter` where
  122. doc_type=%s""", doctype, as_dict=1):
  123. if ps['doctype_or_field']=='DocType':
  124. if ps.get('property_type', None) in ('Int', 'Check'):
  125. ps['value'] = cint(ps['value'])
  126. doclist[0].fields[ps['property']] = ps['value']
  127. else:
  128. docfield = filter(lambda d: d.doctype=="DocField" and d.fieldname==ps['field_name'],
  129. doclist)
  130. if not docfield: continue
  131. if docfield_types.get(ps['property'], None) in ('Int', 'Check'):
  132. ps['value'] = cint(ps['value'])
  133. docfield[0].fields[ps['property']] = ps['value']
  134. def add_custom_fields(doctype, doclist):
  135. try:
  136. res = webnotes.conn.sql("""SELECT * FROM `tabCustom Field`
  137. WHERE dt = %s AND docstatus < 2""", doctype, as_dict=1)
  138. except Exception, e:
  139. if e.args[0]==1146:
  140. return doclist
  141. else:
  142. raise e
  143. for r in res:
  144. custom_field = webnotes.model.doc.Document(fielddata=r)
  145. # convert to DocField
  146. custom_field.fields.update({
  147. 'doctype': 'DocField',
  148. 'parent': doctype,
  149. 'parentfield': 'fields',
  150. 'parenttype': 'DocType',
  151. })
  152. doclist.append(custom_field)
  153. return doclist
  154. def add_linked_with(doclist):
  155. """add list of doctypes this doctype is 'linked' with"""
  156. doctype = doclist[0].name
  157. links = webnotes.conn.sql("""select parent, fieldname from tabDocField
  158. where (fieldtype="Link" and options=%s)
  159. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  160. links += webnotes.conn.sql("""select dt, fieldname from `tabCustom Field`
  161. where (fieldtype="Link" and options=%s)
  162. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  163. doclist[0].fields["__linked_with"] = dict(list(set(links)))
  164. def from_cache(doctype, processed):
  165. """ load doclist from cache.
  166. sets flag __from_cache in first doc of doclist if loaded from cache"""
  167. global doctype_cache
  168. # from memory
  169. if not processed and doctype in doctype_cache:
  170. return doctype_cache[doctype]
  171. doclist = webnotes.cache().get_value(cache_name(doctype, processed))
  172. if doclist:
  173. import json
  174. from webnotes.model.doclist import DocList
  175. doclist = DocList([webnotes.model.doc.Document(fielddata=d)
  176. for d in doclist])
  177. doclist[0].fields["__from_cache"] = 1
  178. return doclist
  179. def to_cache(doctype, processed, doclist):
  180. global doctype_cache
  181. import json
  182. from webnotes.handler import json_handler
  183. webnotes.cache().set_value(cache_name(doctype, processed),
  184. [d.fields for d in doclist])
  185. if not processed:
  186. doctype_cache[doctype] = doclist
  187. def cache_name(doctype, processed):
  188. """returns cache key"""
  189. suffix = ""
  190. if processed:
  191. suffix = ":Raw"
  192. return "doctype:" + doctype + suffix
  193. def clear_cache(doctype):
  194. global doctype_cache
  195. def clear_single(dt):
  196. webnotes.cache().delete_value(cache_name(dt, False))
  197. webnotes.cache().delete_value(cache_name(dt, True))
  198. if doctype in doctype_cache:
  199. del doctype_cache[dt]
  200. clear_single(doctype)
  201. # clear all parent doctypes
  202. for dt in webnotes.conn.sql("""select parent from tabDocField
  203. where fieldtype="Table" and options=%s""", doctype):
  204. clear_single(dt[0])
  205. def add_code(doctype, doclist):
  206. import os, conf
  207. from webnotes.modules import scrub, get_module_path
  208. doc = doclist[0]
  209. path = os.path.join(get_module_path(doc.module), 'doctype', scrub(doc.name))
  210. def _add_code(fname, fieldname):
  211. fpath = os.path.join(path, fname)
  212. if os.path.exists(fpath):
  213. with open(fpath, 'r') as f:
  214. doc.fields[fieldname] = f.read()
  215. _add_code(scrub(doc.name) + '.js', '__js')
  216. _add_code(scrub(doc.name) + '.css', '__css')
  217. _add_code('%s_list.js' % scrub(doc.name), '__listjs')
  218. add_embedded_js(doc)
  219. def add_embedded_js(doc):
  220. """embed all require files"""
  221. import re, os, conf
  222. # custom script
  223. custom = webnotes.conn.get_value("Custom Script", {"dt": doc.name,
  224. "script_type": "Client"}, "script") or ""
  225. doc.fields['__js'] = (doc.fields.get('__js') or '') + '\n' + custom
  226. def _sub(match):
  227. fpath = os.path.join(os.path.dirname(conf.__file__), \
  228. re.search('["\'][^"\']*["\']', match.group(0)).group(0)[1:-1])
  229. if os.path.exists(fpath):
  230. with open(fpath, 'r') as f:
  231. return '\n' + f.read() + '\n'
  232. else:
  233. return '\n// no file "%s" found \n' % fpath
  234. if doc.fields.get('__js'):
  235. doc.fields['__js'] = re.sub('(wn.require\([^\)]*.)', _sub, doc.fields['__js'])
  236. def expand_selects(doclist):
  237. for d in filter(lambda d: d.fieldtype=='Select' \
  238. and (d.options or '').startswith('link:'), doclist):
  239. doctype = d.options.split("\n")[0][5:]
  240. d.link_doctype = doctype
  241. d.options = '\n'.join([''] + [o.name for o in webnotes.conn.sql("""select
  242. name from `tab%s` where docstatus<2 order by name asc""" % doctype, as_dict=1)])
  243. def add_print_formats(doclist):
  244. print_formats = webnotes.conn.sql("""select * FROM `tabPrint Format`
  245. WHERE doc_type=%s AND docstatus<2""", doclist[0].name, as_dict=1)
  246. for pf in print_formats:
  247. doclist.append(webnotes.model.doc.Document('Print Format', fielddata=pf))
  248. def get_property(dt, prop, fieldname=None):
  249. """get a doctype property"""
  250. doctypelist = get(dt)
  251. if fieldname:
  252. field = doctypelist.get_field(fieldname)
  253. return field and field.fields.get(prop) or None
  254. else:
  255. return doctypelist[0].fields.get(prop)
  256. def get_link_fields(doctype):
  257. """get docfields of links and selects with "link:" """
  258. doctypelist = get(doctype)
  259. return doctypelist.get({"fieldtype":"Link"}).extend(doctypelist.get({"fieldtype":"Select",
  260. "options": "^link:"}))
  261. def add_validators(doctype, doclist):
  262. for validator in webnotes.conn.sql("""select name from `tabDocType Validator` where
  263. for_doctype=%s""", doctype, as_dict=1):
  264. doclist.extend(webnotes.get_doclist('DocType Validator', validator.name))
  265. def add_search_fields(doclist):
  266. """add search fields found in the doctypes indicated by link fields' options"""
  267. for lf in doclist.get({"fieldtype": "Link", "options":["!=", "[Select]"]}):
  268. if lf.options:
  269. search_fields = get(lf.options)[0].search_fields
  270. if search_fields:
  271. lf.search_fields = map(lambda sf: sf.strip(), search_fields.split(","))
  272. def update_language(doclist):
  273. """update language"""
  274. if webnotes.lang != 'en':
  275. from webnotes.translate import messages
  276. from webnotes.modules import get_doc_path
  277. # load languages for each doctype
  278. from webnotes.translate import get_lang_data
  279. _messages = {}
  280. for d in doclist:
  281. if d.doctype=='DocType':
  282. _messages.update(get_lang_data(get_doc_path(d.module, d.doctype, d.name),
  283. webnotes.lang, 'doc'))
  284. _messages.update(get_lang_data(get_doc_path(d.module, d.doctype, d.name),
  285. webnotes.lang, 'js'))
  286. doc = doclist[0]
  287. # attach translations to client
  288. doc.fields["__messages"] = _messages
  289. if not webnotes.lang in messages:
  290. messages[webnotes.lang] = webnotes._dict({})
  291. messages[webnotes.lang].update(_messages)
  292. def add_precision(doctype, doclist):
  293. type_precision_map = {
  294. "Currency": 2,
  295. "Float": 6
  296. }
  297. for df in doclist.get({"doctype": "DocField",
  298. "fieldtype": ["in", type_precision_map.keys()]}):
  299. df.precision = type_precision_map[df.fieldtype]
  300. class DocTypeDocList(webnotes.model.doclist.DocList):
  301. def get_field(self, fieldname, parent=None, parentfield=None):
  302. filters = {"doctype":"DocField"}
  303. if isinstance(fieldname, dict):
  304. filters.update(fieldname)
  305. else:
  306. filters["fieldname"] = fieldname
  307. # if parentfield, get the name of the parent table
  308. if parentfield:
  309. parent = self.get_options(parentfield)
  310. if parent:
  311. filters["parent"] = parent
  312. else:
  313. filters["parent"] = self[0].name
  314. fields = self.get(filters)
  315. if fields:
  316. return fields[0]
  317. def get_fieldnames(self, filters=None):
  318. if not filters: filters = {}
  319. filters.update({"doctype": "DocField", "parent": self[0].name})
  320. return map(lambda df: df.fieldname, self.get(filters))
  321. def get_options(self, fieldname, parent=None, parentfield=None):
  322. return self.get_field(fieldname, parent, parentfield).options
  323. def get_label(self, fieldname, parent=None, parentfield=None):
  324. return self.get_field(fieldname, parent, parentfield).label
  325. def get_table_fields(self):
  326. return self.get({"doctype": "DocField", "fieldtype": "Table"})
  327. def get_precision_map(self, parent=None, parentfield=None):
  328. """get a map of fields of type 'currency' or 'float' with precision values"""
  329. filters = {"doctype": "DocField", "fieldtype": ["in", ["Currency", "Float"]]}
  330. if parentfield:
  331. parent = self.get_options(parentfield)
  332. if parent:
  333. filters["parent"] = parent
  334. else:
  335. filters["parent"] = self[0].name
  336. from webnotes import _dict
  337. return _dict((f.fieldname, f.precision) for f in self.get(filters))
  338. def get_parent_doclist(self):
  339. return webnotes.doclist([self[0]] + self.get({"parent": self[0].name}))
  340. def rename_field(doctype, old_fieldname, new_fieldname, lookup_field=None):
  341. """this function assumes that sync is NOT performed"""
  342. import webnotes.model
  343. doctype_list = get(doctype)
  344. old_field = doctype_list.get_field(lookup_field or old_fieldname)
  345. if not old_field:
  346. print "rename_field: " + (lookup_field or old_fieldname) + " not found."
  347. if old_field.fieldtype == "Table":
  348. # change parentfield of table mentioned in options
  349. webnotes.conn.sql("""update `tab%s` set parentfield=%s
  350. where parentfield=%s""" % (old_field.options.split("\n")[0], "%s", "%s"),
  351. (new_fieldname, old_fieldname))
  352. elif old_field.fieldtype not in webnotes.model.no_value_fields:
  353. # copy
  354. if doctype_list[0].issingle:
  355. webnotes.conn.sql("""update `tabSingles` set field=%s
  356. where doctype=%s and field=%s""",
  357. (new_fieldname, doctype, old_fieldname))
  358. else:
  359. webnotes.conn.sql("""update `tab%s` set `%s`=`%s`""" % \
  360. (doctype, new_fieldname, old_fieldname))