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.

doctype.py 14 KiB

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