Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

424 строки
12 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 = {}
  19. docfield_types = None
  20. def get(doctype, processed=False, cached=True):
  21. """return doclist"""
  22. if cached:
  23. doclist = from_cache(doctype, processed)
  24. if doclist:
  25. if processed:
  26. update_language(doclist)
  27. return DocTypeDocList(doclist)
  28. load_docfield_types()
  29. # main doctype doclist
  30. doclist = get_doctype_doclist(doctype)
  31. # add doctypes of table fields
  32. table_types = [d.options for d in doclist \
  33. if d.doctype=='DocField' and d.fieldtype=='Table']
  34. for table_doctype in table_types:
  35. doclist += get_doctype_doclist(table_doctype)
  36. if processed:
  37. add_code(doctype, doclist)
  38. expand_selects(doclist)
  39. add_print_formats(doclist)
  40. add_search_fields(doclist)
  41. add_workflows(doclist)
  42. add_linked_with(doclist)
  43. to_cache(doctype, processed, doclist)
  44. if processed:
  45. update_language(doclist)
  46. return DocTypeDocList(doclist)
  47. def load_docfield_types():
  48. global docfield_types
  49. docfield_types = dict(webnotes.conn.sql("""select fieldname, fieldtype from tabDocField
  50. where parent='DocField'"""))
  51. def add_workflows(doclist):
  52. from webnotes.model.workflow import get_workflow_name
  53. doctype = doclist[0].name
  54. # get active workflow
  55. workflow_name = get_workflow_name(doctype)
  56. if workflow_name and webnotes.conn.exists("Workflow", workflow_name):
  57. doclist += webnotes.get_doclist("Workflow", workflow_name)
  58. # add workflow states (for icons and style)
  59. for state in map(lambda d: d.state, doclist.get({"doctype":"Workflow Document State"})):
  60. doclist += webnotes.get_doclist("Workflow State", state)
  61. def get_doctype_doclist(doctype):
  62. """get doclist of single doctype"""
  63. doclist = webnotes.get_doclist('DocType', doctype)
  64. add_custom_fields(doctype, doclist)
  65. apply_property_setters(doctype, doclist)
  66. sort_fields(doclist)
  67. return doclist
  68. def sort_fields(doclist):
  69. """sort on basis of previous_field"""
  70. from webnotes.model.doclist import DocList
  71. newlist = DocList([])
  72. pending = filter(lambda d: d.doctype=='DocField', doclist)
  73. maxloops = 20
  74. while (pending and maxloops>0):
  75. maxloops -= 1
  76. for d in pending[:]:
  77. if d.previous_field:
  78. # field already added
  79. for n in newlist:
  80. if n.fieldname==d.previous_field:
  81. newlist.insert(newlist.index(n)+1, d)
  82. pending.remove(d)
  83. break
  84. else:
  85. newlist.append(d)
  86. pending.remove(d)
  87. # recurring at end
  88. if pending:
  89. newlist += pending
  90. # renum
  91. idx = 1
  92. for d in newlist:
  93. d.idx = idx
  94. idx += 1
  95. doclist.get({"doctype":["!=", "DocField"]}).extend(newlist)
  96. def apply_property_setters(doctype, doclist):
  97. for ps in webnotes.conn.sql("""select * from `tabProperty Setter` where
  98. doc_type=%s""", doctype, as_dict=1):
  99. if ps['doctype_or_field']=='DocType':
  100. if ps.get('property_type', None) in ('Int', 'Check'):
  101. ps['value'] = cint(ps['value'])
  102. doclist[0].fields[ps['property']] = ps['value']
  103. else:
  104. docfield = filter(lambda d: d.doctype=="DocField" and d.fieldname==ps['field_name'],
  105. doclist)
  106. if not docfield: continue
  107. if docfield_types.get(ps['property'], None) in ('Int', 'Check'):
  108. ps['value'] = cint(ps['value'])
  109. docfield[0].fields[ps['property']] = ps['value']
  110. def add_custom_fields(doctype, doclist):
  111. try:
  112. res = webnotes.conn.sql("""SELECT * FROM `tabCustom Field`
  113. WHERE dt = %s AND docstatus < 2""", doctype, as_dict=1)
  114. except Exception, e:
  115. if e.args[0]==1146:
  116. return doclist
  117. else:
  118. raise e
  119. for r in res:
  120. custom_field = webnotes.model.doc.Document(fielddata=r)
  121. # convert to DocField
  122. custom_field.fields.update({
  123. 'doctype': 'DocField',
  124. 'parent': doctype,
  125. 'parentfield': 'fields',
  126. 'parenttype': 'DocType',
  127. })
  128. doclist.append(custom_field)
  129. return doclist
  130. def add_linked_with(doclist):
  131. """add list of doctypes this doctype is 'linked' with"""
  132. doctype = doclist[0].name
  133. links = webnotes.conn.sql("""select parent, fieldname from tabDocField
  134. where (fieldtype="Link" and options=%s)
  135. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  136. links += webnotes.conn.sql("""select dt as parent, fieldname from `tabCustom Field`
  137. where (fieldtype="Link" and options=%s)
  138. or (fieldtype="Select" and options=%s)""", (doctype, "link:"+ doctype))
  139. links = dict(links)
  140. if not links:
  141. return {}
  142. ret = {}
  143. for dt in links:
  144. ret[dt] = { "fieldname": links[dt] }
  145. for grand_parent, options in webnotes.conn.sql("""select parent, options from tabDocField
  146. where fieldtype="Table"
  147. and options in (select name from tabDocType
  148. where istable=1 and name in (%s))""" % ", ".join(["%s"] * len(links)) ,tuple(links)):
  149. ret[grand_parent] = {"child_doctype": options, "fieldname": links[options] }
  150. if options in ret:
  151. del ret[options]
  152. doclist[0].fields["__linked_with"] = ret
  153. def from_cache(doctype, processed):
  154. """ load doclist from cache.
  155. sets flag __from_cache in first doc of doclist if loaded from cache"""
  156. global doctype_cache
  157. # from memory
  158. if 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. global doctype_cache
  169. webnotes.cache().set_value(cache_name(doctype, processed),
  170. [d.fields for d in doclist])
  171. if not processed:
  172. doctype_cache[doctype] = doclist
  173. def cache_name(doctype, processed):
  174. """returns cache key"""
  175. suffix = ""
  176. if processed:
  177. suffix = ":Raw"
  178. return "doctype:" + doctype + suffix
  179. def clear_cache(doctype=None):
  180. global doctype_cache
  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 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))