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.
 
 
 
 
 
 

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