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.
 
 
 
 
 
 

434 lines
13 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. """
  4. Get metadata (main doctype with fields and permissions with all table doctypes)
  5. - if exists in cache, get it from cache
  6. - add custom fields
  7. - override properties from PropertySetter
  8. - sort based on prev_field
  9. - optionally, post process (add js, css, select fields), or without
  10. """
  11. from __future__ import unicode_literals
  12. # imports
  13. import webnotes
  14. import webnotes.model
  15. import webnotes.model.doc
  16. import webnotes.model.doclist
  17. from webnotes.utils import cint, get_base_path
  18. doctype_cache = webnotes.local('doctype_doctype_cache')
  19. docfield_types = webnotes.local('doctype_docfield_types')
  20. # doctype_cache = {}
  21. # docfield_types = None
  22. def get(doctype, processed=False, cached=True):
  23. """return doclist"""
  24. if cached:
  25. doclist = from_cache(doctype, processed)
  26. if doclist:
  27. if processed:
  28. update_language(doclist)
  29. return DocTypeDocList(doclist)
  30. load_docfield_types()
  31. # main doctype doclist
  32. doclist = get_doctype_doclist(doctype)
  33. # add doctypes of table fields
  34. table_types = [d.options for d in doclist \
  35. if d.doctype=='DocField' and d.fieldtype=='Table']
  36. for table_doctype in table_types:
  37. doclist += get_doctype_doclist(table_doctype)
  38. if processed:
  39. add_code(doctype, doclist)
  40. expand_selects(doclist)
  41. add_print_formats(doclist)
  42. add_search_fields(doclist)
  43. add_workflows(doclist)
  44. add_linked_with(doclist)
  45. to_cache(doctype, processed, doclist)
  46. if processed:
  47. update_language(doclist)
  48. return DocTypeDocList(doclist)
  49. def load_docfield_types():
  50. webnotes.local.doctype_docfield_types = dict(webnotes.conn.sql("""select fieldname, fieldtype from tabDocField
  51. where parent='DocField'"""))
  52. def add_workflows(doclist):
  53. from webnotes.model.workflow import get_workflow_name
  54. doctype = doclist[0].name
  55. # get active workflow
  56. workflow_name = get_workflow_name(doctype)
  57. if workflow_name and webnotes.conn.exists("Workflow", workflow_name):
  58. doclist += webnotes.get_doclist("Workflow", workflow_name)
  59. # add workflow states (for icons and style)
  60. for state in map(lambda d: d.state, doclist.get({"doctype":"Workflow Document State"})):
  61. doclist += webnotes.get_doclist("Workflow State", state)
  62. def get_doctype_doclist(doctype):
  63. """get doclist of single doctype"""
  64. doclist = webnotes.get_doclist('DocType', doctype)
  65. add_custom_fields(doctype, doclist)
  66. apply_property_setters(doctype, doclist)
  67. sort_fields(doclist)
  68. return doclist
  69. def sort_fields(doclist):
  70. """sort on basis of previous_field"""
  71. from webnotes.model.doclist import DocList
  72. newlist = DocList([])
  73. pending = filter(lambda d: d.doctype=='DocField', doclist)
  74. maxloops = 20
  75. while (pending and maxloops>0):
  76. maxloops -= 1
  77. for d in pending[:]:
  78. if d.previous_field:
  79. # field already added
  80. for n in newlist:
  81. if n.fieldname==d.previous_field:
  82. newlist.insert(newlist.index(n)+1, d)
  83. pending.remove(d)
  84. break
  85. else:
  86. newlist.append(d)
  87. pending.remove(d)
  88. # recurring at end
  89. if pending:
  90. newlist += pending
  91. # renum
  92. idx = 1
  93. for d in newlist:
  94. d.idx = idx
  95. idx += 1
  96. doclist.get({"doctype":["!=", "DocField"]}).extend(newlist)
  97. def apply_property_setters(doctype, doclist):
  98. for ps in webnotes.conn.sql("""select * from `tabProperty Setter` where
  99. doc_type=%s""", doctype, as_dict=1):
  100. if ps['doctype_or_field']=='DocType':
  101. if ps.get('property_type', None) in ('Int', 'Check'):
  102. ps['value'] = cint(ps['value'])
  103. doclist[0].fields[ps['property']] = ps['value']
  104. else:
  105. docfield = filter(lambda d: d.doctype=="DocField" and d.fieldname==ps['field_name'],
  106. doclist)
  107. if not docfield: continue
  108. if docfield_types.get(ps['property'], None) in ('Int', 'Check'):
  109. ps['value'] = cint(ps['value'])
  110. docfield[0].fields[ps['property']] = ps['value']
  111. def add_custom_fields(doctype, doclist):
  112. try:
  113. res = webnotes.conn.sql("""SELECT * FROM `tabCustom Field`
  114. WHERE dt = %s AND docstatus < 2""", doctype, as_dict=1)
  115. except Exception, e:
  116. if e.args[0]==1146:
  117. return doclist
  118. else:
  119. raise
  120. for r in res:
  121. custom_field = webnotes.model.doc.Document(fielddata=r)
  122. # convert to DocField
  123. custom_field.fields.update({
  124. 'doctype': 'DocField',
  125. 'parent': doctype,
  126. 'parentfield': 'fields',
  127. 'parenttype': 'DocType',
  128. '__custom_field': 1
  129. })
  130. doclist.append(custom_field)
  131. return doclist
  132. def add_linked_with(doclist):
  133. """add list of doctypes this doctype is 'linked' with"""
  134. doctype = doclist[0].name
  135. links = webnotes.conn.sql("""select parent, fieldname from tabDocField
  136. where (fieldtype="Link" and options=%s)
  137. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  138. links += webnotes.conn.sql("""select dt as parent, fieldname from `tabCustom Field`
  139. where (fieldtype="Link" and options=%s)
  140. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  141. links = dict(links)
  142. if not links:
  143. return {}
  144. ret = {}
  145. for dt in links:
  146. ret[dt] = { "fieldname": links[dt] }
  147. for grand_parent, options in webnotes.conn.sql("""select parent, options from tabDocField
  148. where fieldtype="Table"
  149. and options in (select name from tabDocType
  150. where istable=1 and name in (%s))""" % ", ".join(["%s"] * len(links)) ,tuple(links)):
  151. ret[grand_parent] = {"child_doctype": options, "fieldname": links[options] }
  152. if options in ret:
  153. del ret[options]
  154. doclist[0].fields["__linked_with"] = ret
  155. def from_cache(doctype, processed):
  156. """ load doclist from cache.
  157. sets flag __from_cache in first doc of doclist if loaded from cache"""
  158. # from memory
  159. if doctype_cache and not processed and doctype in doctype_cache:
  160. return doctype_cache[doctype]
  161. doclist = webnotes.cache().get_value(cache_name(doctype, processed))
  162. if doclist:
  163. from webnotes.model.doclist import DocList
  164. doclist = DocList([webnotes.model.doc.Document(fielddata=d)
  165. for d in doclist])
  166. doclist[0].fields["__from_cache"] = 1
  167. return doclist
  168. def to_cache(doctype, processed, doclist):
  169. if not doctype_cache:
  170. webnotes.local.doctype_doctype_cache = {}
  171. webnotes.cache().set_value(cache_name(doctype, processed),
  172. [d.fields for d in doclist])
  173. if not processed:
  174. doctype_cache[doctype] = doclist
  175. def cache_name(doctype, processed):
  176. """returns cache key"""
  177. suffix = ""
  178. if processed:
  179. suffix = ":Raw"
  180. return "doctype:" + doctype + suffix
  181. def clear_cache(doctype=None):
  182. import webnotes.plugins
  183. def clear_single(dt):
  184. webnotes.cache().delete_value(cache_name(dt, False))
  185. webnotes.cache().delete_value(cache_name(dt, True))
  186. webnotes.plugins.clear_cache("DocType", dt)
  187. if doctype_cache and doctype in doctype_cache:
  188. del doctype_cache[dt]
  189. if doctype:
  190. clear_single(doctype)
  191. # clear all parent doctypes
  192. for dt in webnotes.conn.sql("""select parent from tabDocField
  193. where fieldtype="Table" and options=%s""", doctype):
  194. clear_single(dt[0])
  195. # clear all notifications
  196. from core.doctype.notification_count.notification_count import delete_notification_count_for
  197. delete_notification_count_for(doctype)
  198. else:
  199. # clear all
  200. for dt in webnotes.conn.sql("""select name from tabDocType"""):
  201. clear_single(dt[0])
  202. def add_code(doctype, doclist):
  203. import os
  204. from webnotes.modules import scrub, get_module_path
  205. doc = doclist[0]
  206. path = os.path.join(get_module_path(doc.module), 'doctype', scrub(doc.name))
  207. def _add_code(fname, fieldname):
  208. fpath = os.path.join(path, fname)
  209. if os.path.exists(fpath):
  210. with open(fpath, 'r') as f:
  211. doc.fields[fieldname] = f.read()
  212. _add_code(scrub(doc.name) + '.js', '__js')
  213. _add_code(scrub(doc.name) + '.css', '__css')
  214. _add_code('%s_list.js' % scrub(doc.name), '__list_js')
  215. _add_code('%s_calendar.js' % scrub(doc.name), '__calendar_js')
  216. _add_code('%s_map.js' % scrub(doc.name), '__map_js')
  217. add_embedded_js(doc)
  218. def add_embedded_js(doc):
  219. """embed all require files"""
  220. import re, os
  221. from webnotes import conf
  222. # custom script
  223. custom = webnotes.conn.get_value("Custom Script", {"dt": doc.name,
  224. "script_type": "Client"}, "script") or ""
  225. doc.fields['__js'] = ((doc.fields.get('__js') or '') + '\n' + custom).encode("utf-8")
  226. def _sub(match):
  227. require_path = re.search('["\'][^"\']*["\']', match.group(0)).group(0)[1:-1]
  228. fpath = os.path.join(get_base_path(), require_path)
  229. if os.path.exists(fpath):
  230. with open(fpath, 'r') as f:
  231. return '\n' + unicode(f.read(), "utf-8") + '\n'
  232. else:
  233. return 'wn.require("%s")' % require_path
  234. if doc.fields.get('__js'):
  235. doc.fields['__js'] = re.sub('(wn.require\([^\)]*.)', _sub, doc.fields['__js'])
  236. def expand_selects(doclist):
  237. for d in filter(lambda d: d.fieldtype=='Select' \
  238. and (d.options or '').startswith('link:'), doclist):
  239. doctype = d.options.split("\n")[0][5:]
  240. d.link_doctype = doctype
  241. d.options = '\n'.join([''] + [o.name for o in webnotes.conn.sql("""select
  242. name from `tab%s` where docstatus<2 order by name asc""" % doctype, as_dict=1)])
  243. def add_print_formats(doclist):
  244. print_formats = webnotes.conn.sql("""select * FROM `tabPrint Format`
  245. WHERE doc_type=%s AND docstatus<2""", doclist[0].name, as_dict=1)
  246. for pf in print_formats:
  247. doclist.append(webnotes.model.doc.Document('Print Format', fielddata=pf))
  248. def get_property(dt, prop, fieldname=None):
  249. """get a doctype property"""
  250. doctypelist = get(dt)
  251. if fieldname:
  252. field = doctypelist.get_field(fieldname)
  253. return field and field.fields.get(prop) or None
  254. else:
  255. return doctypelist[0].fields.get(prop)
  256. def get_link_fields(doctype):
  257. """get docfields of links and selects with "link:" """
  258. doctypelist = get(doctype)
  259. return doctypelist.get({"fieldtype":"Link"}).extend(doctypelist.get({"fieldtype":"Select",
  260. "options": "^link:"}))
  261. def add_validators(doctype, doclist):
  262. for validator in webnotes.conn.sql("""select name from `tabDocType Validator` where
  263. for_doctype=%s""", doctype, as_dict=1):
  264. doclist.extend(webnotes.get_doclist('DocType Validator', validator.name))
  265. def add_search_fields(doclist):
  266. """add search fields found in the doctypes indicated by link fields' options"""
  267. for lf in doclist.get({"fieldtype": "Link", "options":["!=", "[Select]"]}):
  268. if lf.options:
  269. search_fields = get(lf.options)[0].search_fields
  270. if search_fields:
  271. lf.search_fields = map(lambda sf: sf.strip(), search_fields.split(","))
  272. def update_language(doclist):
  273. """update language"""
  274. if webnotes.lang != 'en':
  275. from webnotes.modules import get_doc_path
  276. if not hasattr(webnotes.local, 'translations'):
  277. webnotes.local.translations = {}
  278. translations = webnotes.local.translations
  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 translations:
  292. translations[webnotes.lang] = webnotes._dict({})
  293. translations[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))