您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

456 行
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_embedded_js(doc)
  226. def add_embedded_js(doc):
  227. """embed all require files"""
  228. import re, os, conf
  229. # custom script
  230. custom = webnotes.conn.get_value("Custom Script", {"dt": doc.name,
  231. "script_type": "Client"}, "script") or ""
  232. doc.fields['__js'] = (doc.fields.get('__js') or '') + '\n' + custom
  233. def _sub(match):
  234. fpath = os.path.join(os.path.dirname(conf.__file__), \
  235. re.search('["\'][^"\']*["\']', match.group(0)).group(0)[1:-1])
  236. if os.path.exists(fpath):
  237. with open(fpath, 'r') as f:
  238. return '\n' + f.read() + '\n'
  239. else:
  240. return '\n// no file "%s" found \n' % fpath
  241. if doc.fields.get('__js'):
  242. doc.fields['__js'] = re.sub('(wn.require\([^\)]*.)', _sub, doc.fields['__js'])
  243. def expand_selects(doclist):
  244. for d in filter(lambda d: d.fieldtype=='Select' \
  245. and (d.options or '').startswith('link:'), doclist):
  246. doctype = d.options.split("\n")[0][5:]
  247. d.link_doctype = doctype
  248. d.options = '\n'.join([''] + [o.name for o in webnotes.conn.sql("""select
  249. name from `tab%s` where docstatus<2 order by name asc""" % doctype, as_dict=1)])
  250. def add_print_formats(doclist):
  251. print_formats = webnotes.conn.sql("""select * FROM `tabPrint Format`
  252. WHERE doc_type=%s AND docstatus<2""", doclist[0].name, as_dict=1)
  253. for pf in print_formats:
  254. doclist.append(webnotes.model.doc.Document('Print Format', fielddata=pf))
  255. def get_property(dt, prop, fieldname=None):
  256. """get a doctype property"""
  257. doctypelist = get(dt)
  258. if fieldname:
  259. field = doctypelist.get_field(fieldname)
  260. return field and field.fields.get(prop) or None
  261. else:
  262. return doctypelist[0].fields.get(prop)
  263. def get_link_fields(doctype):
  264. """get docfields of links and selects with "link:" """
  265. doctypelist = get(doctype)
  266. return doctypelist.get({"fieldtype":"Link"}).extend(doctypelist.get({"fieldtype":"Select",
  267. "options": "^link:"}))
  268. def add_validators(doctype, doclist):
  269. for validator in webnotes.conn.sql("""select name from `tabDocType Validator` where
  270. for_doctype=%s""", doctype, as_dict=1):
  271. doclist.extend(webnotes.get_doclist('DocType Validator', validator.name))
  272. def add_search_fields(doclist):
  273. """add search fields found in the doctypes indicated by link fields' options"""
  274. for lf in doclist.get({"fieldtype": "Link", "options":["!=", "[Select]"]}):
  275. if lf.options:
  276. search_fields = get(lf.options)[0].search_fields
  277. if search_fields:
  278. lf.search_fields = map(lambda sf: sf.strip(), search_fields.split(","))
  279. def update_language(doclist):
  280. """update language"""
  281. if webnotes.lang != 'en':
  282. from webnotes.translate import messages
  283. from webnotes.modules import get_doc_path
  284. # load languages for each doctype
  285. from webnotes.translate import get_lang_data
  286. _messages = {}
  287. for d in doclist:
  288. if d.doctype=='DocType':
  289. _messages.update(get_lang_data(get_doc_path(d.module, d.doctype, d.name),
  290. webnotes.lang, 'doc'))
  291. _messages.update(get_lang_data(get_doc_path(d.module, d.doctype, d.name),
  292. webnotes.lang, 'js'))
  293. doc = doclist[0]
  294. # attach translations to client
  295. doc.fields["__messages"] = _messages
  296. if not webnotes.lang in messages:
  297. messages[webnotes.lang] = webnotes._dict({})
  298. messages[webnotes.lang].update(_messages)
  299. def add_precision(doctype, doclist):
  300. type_precision_map = {
  301. "Currency": 2,
  302. "Float": 6
  303. }
  304. for df in doclist.get({"doctype": "DocField",
  305. "fieldtype": ["in", type_precision_map.keys()]}):
  306. df.precision = type_precision_map[df.fieldtype]
  307. class DocTypeDocList(webnotes.model.doclist.DocList):
  308. def get_field(self, fieldname, parent=None, parentfield=None):
  309. filters = {"doctype":"DocField"}
  310. if isinstance(fieldname, dict):
  311. filters.update(fieldname)
  312. else:
  313. filters["fieldname"] = fieldname
  314. # if parentfield, get the name of the parent table
  315. if parentfield:
  316. parent = self.get_options(parentfield)
  317. if parent:
  318. filters["parent"] = parent
  319. else:
  320. filters["parent"] = self[0].name
  321. fields = self.get(filters)
  322. if fields:
  323. return fields[0]
  324. def get_fieldnames(self, filters=None):
  325. if not filters: filters = {}
  326. filters.update({"doctype": "DocField", "parent": self[0].name})
  327. return map(lambda df: df.fieldname, self.get(filters))
  328. def get_options(self, fieldname, parent=None, parentfield=None):
  329. return self.get_field(fieldname, parent, parentfield).options
  330. def get_label(self, fieldname, parent=None, parentfield=None):
  331. return self.get_field(fieldname, parent, parentfield).label
  332. def get_table_fields(self):
  333. return self.get({"doctype": "DocField", "fieldtype": "Table"})
  334. def get_precision_map(self, parent=None, parentfield=None):
  335. """get a map of fields of type 'currency' or 'float' with precision values"""
  336. filters = {"doctype": "DocField", "fieldtype": ["in", ["Currency", "Float"]]}
  337. if parentfield:
  338. parent = self.get_options(parentfield)
  339. if parent:
  340. filters["parent"] = parent
  341. else:
  342. filters["parent"] = self[0].name
  343. from webnotes import _dict
  344. return _dict((f.fieldname, f.precision) for f in self.get(filters))
  345. def get_parent_doclist(self):
  346. return webnotes.doclist([self[0]] + self.get({"parent": self[0].name}))
  347. def rename_field(doctype, old_fieldname, new_fieldname, lookup_field=None):
  348. """this function assumes that sync is NOT performed"""
  349. import webnotes.model
  350. doctype_list = get(doctype)
  351. old_field = doctype_list.get_field(lookup_field or old_fieldname)
  352. if not old_field:
  353. print "rename_field: " + (lookup_field or old_fieldname) + " not found."
  354. if old_field.fieldtype == "Table":
  355. # change parentfield of table mentioned in options
  356. webnotes.conn.sql("""update `tab%s` set parentfield=%s
  357. where parentfield=%s""" % (old_field.options.split("\n")[0], "%s", "%s"),
  358. (new_fieldname, old_fieldname))
  359. elif old_field.fieldtype not in webnotes.model.no_value_fields:
  360. # copy
  361. if doctype_list[0].issingle:
  362. webnotes.conn.sql("""update `tabSingles` set field=%s
  363. where doctype=%s and field=%s""",
  364. (new_fieldname, doctype, old_fieldname))
  365. else:
  366. webnotes.conn.sql("""update `tab%s` set `%s`=`%s`""" % \
  367. (doctype, new_fieldname, old_fieldname))