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.
 
 
 
 
 
 

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