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.
 
 
 
 
 
 

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