Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

425 wiersze
13 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  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
  18. doctype_cache = webnotes.local('doctype_doctype_cache')
  19. docfield_types = webnotes.local('doctype_doctype_cache')
  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 e
  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. })
  129. doclist.append(custom_field)
  130. return doclist
  131. def add_linked_with(doclist):
  132. """add list of doctypes this doctype is 'linked' with"""
  133. doctype = doclist[0].name
  134. links = webnotes.conn.sql("""select parent, fieldname from tabDocField
  135. where (fieldtype="Link" and options=%s)
  136. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  137. links += webnotes.conn.sql("""select dt as parent, fieldname from `tabCustom Field`
  138. where (fieldtype="Link" and options=%s)
  139. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  140. links = dict(links)
  141. if not links:
  142. return {}
  143. ret = {}
  144. for dt in links:
  145. ret[dt] = { "fieldname": links[dt] }
  146. for grand_parent, options in webnotes.conn.sql("""select parent, options from tabDocField
  147. where fieldtype="Table"
  148. and options in (select name from tabDocType
  149. where istable=1 and name in (%s))""" % ", ".join(["%s"] * len(links)) ,tuple(links)):
  150. ret[grand_parent] = {"child_doctype": options, "fieldname": links[options] }
  151. if options in ret:
  152. del ret[options]
  153. doclist[0].fields["__linked_with"] = ret
  154. def from_cache(doctype, processed):
  155. """ load doclist from cache.
  156. sets flag __from_cache in first doc of doclist if loaded from cache"""
  157. # from memory
  158. if doctype_cache and not processed and doctype in doctype_cache:
  159. return doctype_cache[doctype]
  160. doclist = webnotes.cache().get_value(cache_name(doctype, processed))
  161. if doclist:
  162. from webnotes.model.doclist import DocList
  163. doclist = DocList([webnotes.model.doc.Document(fielddata=d)
  164. for d in doclist])
  165. doclist[0].fields["__from_cache"] = 1
  166. return doclist
  167. def to_cache(doctype, processed, doclist):
  168. if not doctype_cache:
  169. webnotes.local.doctype_doctype_cache = {}
  170. webnotes.cache().set_value(cache_name(doctype, processed),
  171. [d.fields for d in doclist])
  172. if not processed:
  173. doctype_cache[doctype] = doclist
  174. def cache_name(doctype, processed):
  175. """returns cache key"""
  176. suffix = ""
  177. if processed:
  178. suffix = ":Raw"
  179. return "doctype:" + doctype + suffix
  180. def clear_cache(doctype=None):
  181. def clear_single(dt):
  182. webnotes.cache().delete_value(cache_name(dt, False))
  183. webnotes.cache().delete_value(cache_name(dt, True))
  184. if doctype_cache and doctype in doctype_cache:
  185. del doctype_cache[dt]
  186. if doctype:
  187. clear_single(doctype)
  188. # clear all parent doctypes
  189. for dt in webnotes.conn.sql("""select parent from tabDocField
  190. where fieldtype="Table" and options=%s""", doctype):
  191. clear_single(dt[0])
  192. else:
  193. # clear all
  194. for dt in webnotes.conn.sql("""select name from tabDocType"""):
  195. clear_single(dt[0])
  196. def add_code(doctype, doclist):
  197. import os
  198. from webnotes.modules import scrub, get_module_path
  199. doc = doclist[0]
  200. path = os.path.join(get_module_path(doc.module), 'doctype', scrub(doc.name))
  201. def _add_code(fname, fieldname):
  202. fpath = os.path.join(path, fname)
  203. if os.path.exists(fpath):
  204. with open(fpath, 'r') as f:
  205. doc.fields[fieldname] = f.read()
  206. _add_code(scrub(doc.name) + '.js', '__js')
  207. _add_code(scrub(doc.name) + '.css', '__css')
  208. _add_code('%s_list.js' % scrub(doc.name), '__list_js')
  209. _add_code('%s_calendar.js' % scrub(doc.name), '__calendar_js')
  210. _add_code('%s_map.js' % scrub(doc.name), '__map_js')
  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).encode("utf-8")
  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' + unicode(f.read(), "utf-8") + '\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.link_doctype = doctype
  234. d.options = '\n'.join([''] + [o.name for o in webnotes.conn.sql("""select
  235. name from `tab%s` where docstatus<2 order by name asc""" % doctype, as_dict=1)])
  236. def add_print_formats(doclist):
  237. print_formats = webnotes.conn.sql("""select * FROM `tabPrint Format`
  238. WHERE doc_type=%s AND docstatus<2""", doclist[0].name, as_dict=1)
  239. for pf in print_formats:
  240. doclist.append(webnotes.model.doc.Document('Print Format', fielddata=pf))
  241. def get_property(dt, prop, fieldname=None):
  242. """get a doctype property"""
  243. doctypelist = get(dt)
  244. if fieldname:
  245. field = doctypelist.get_field(fieldname)
  246. return field and field.fields.get(prop) or None
  247. else:
  248. return doctypelist[0].fields.get(prop)
  249. def get_link_fields(doctype):
  250. """get docfields of links and selects with "link:" """
  251. doctypelist = get(doctype)
  252. return doctypelist.get({"fieldtype":"Link"}).extend(doctypelist.get({"fieldtype":"Select",
  253. "options": "^link:"}))
  254. def add_validators(doctype, doclist):
  255. for validator in webnotes.conn.sql("""select name from `tabDocType Validator` where
  256. for_doctype=%s""", doctype, as_dict=1):
  257. doclist.extend(webnotes.get_doclist('DocType Validator', validator.name))
  258. def add_search_fields(doclist):
  259. """add search fields found in the doctypes indicated by link fields' options"""
  260. for lf in doclist.get({"fieldtype": "Link", "options":["!=", "[Select]"]}):
  261. if lf.options:
  262. search_fields = get(lf.options)[0].search_fields
  263. if search_fields:
  264. lf.search_fields = map(lambda sf: sf.strip(), search_fields.split(","))
  265. def update_language(doclist):
  266. """update language"""
  267. if webnotes.lang != 'en':
  268. from webnotes.translate import messages
  269. from webnotes.modules import get_doc_path
  270. # load languages for each doctype
  271. from webnotes.translate import get_lang_data
  272. _messages = {}
  273. for d in doclist:
  274. if d.doctype=='DocType':
  275. _messages.update(get_lang_data(get_doc_path(d.module, d.doctype, d.name),
  276. webnotes.lang, 'doc'))
  277. _messages.update(get_lang_data(get_doc_path(d.module, d.doctype, d.name),
  278. webnotes.lang, 'js'))
  279. doc = doclist[0]
  280. # attach translations to client
  281. doc.fields["__messages"] = _messages
  282. if not webnotes.lang in messages:
  283. messages[webnotes.lang] = webnotes._dict({})
  284. messages[webnotes.lang].update(_messages)
  285. class DocTypeDocList(webnotes.model.doclist.DocList):
  286. def get_field(self, fieldname, parent=None, parentfield=None):
  287. filters = {"doctype":"DocField"}
  288. if isinstance(fieldname, dict):
  289. filters.update(fieldname)
  290. else:
  291. filters["fieldname"] = fieldname
  292. # if parentfield, get the name of the parent table
  293. if parentfield:
  294. parent = self.get_options(parentfield)
  295. if parent:
  296. filters["parent"] = parent
  297. else:
  298. filters["parent"] = self[0].name
  299. fields = self.get(filters)
  300. if fields:
  301. return fields[0]
  302. def get_fieldnames(self, filters=None):
  303. if not filters: filters = {}
  304. filters.update({"doctype": "DocField", "parent": self[0].name})
  305. return map(lambda df: df.fieldname, self.get(filters))
  306. def get_options(self, fieldname, parent=None, parentfield=None):
  307. return self.get_field(fieldname, parent, parentfield).options
  308. def get_label(self, fieldname, parent=None, parentfield=None):
  309. return self.get_field(fieldname, parent, parentfield).label
  310. def get_table_fields(self):
  311. return self.get({"doctype": "DocField", "fieldtype": "Table"})
  312. def get_parent_doclist(self):
  313. return webnotes.doclist([self[0]] + self.get({"parent": self[0].name}))
  314. def rename_field(doctype, old_fieldname, new_fieldname, lookup_field=None):
  315. """this function assumes that sync is NOT performed"""
  316. import webnotes.model
  317. doctype_list = get(doctype)
  318. old_field = doctype_list.get_field(lookup_field or old_fieldname)
  319. if not old_field:
  320. print "rename_field: " + (lookup_field or old_fieldname) + " not found."
  321. if old_field.fieldtype == "Table":
  322. # change parentfield of table mentioned in options
  323. webnotes.conn.sql("""update `tab%s` set parentfield=%s
  324. where parentfield=%s""" % (old_field.options.split("\n")[0], "%s", "%s"),
  325. (new_fieldname, old_fieldname))
  326. elif old_field.fieldtype not in webnotes.model.no_value_fields:
  327. # copy
  328. if doctype_list[0].issingle:
  329. webnotes.conn.sql("""update `tabSingles` set field=%s
  330. where doctype=%s and field=%s""",
  331. (new_fieldname, doctype, old_fieldname))
  332. else:
  333. webnotes.conn.sql("""update `tab%s` set `%s`=`%s`""" % \
  334. (doctype, new_fieldname, old_fieldname))