您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

501 行
14 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. """
  5. Transactions are defined as collection of classes, a Bean represents collection of Document
  6. objects for a transaction with main and children.
  7. Group actions like save, etc are performed on doclists
  8. """
  9. import webnotes
  10. from webnotes import _, msgprint
  11. from webnotes.utils import cint, cstr, flt
  12. from webnotes.model.doc import Document
  13. class DocstatusTransitionError(webnotes.ValidationError): pass
  14. class BeanPermissionError(webnotes.ValidationError): pass
  15. class TimestampMismatchError(webnotes.ValidationError): pass
  16. class Bean:
  17. """
  18. Collection of Documents with one parent and multiple children
  19. """
  20. def __init__(self, dt=None, dn=None):
  21. self.obj = None
  22. self.ignore_permissions = False
  23. self.ignore_children_type = []
  24. self.ignore_links = False
  25. self.ignore_validate = False
  26. self.ignore_fields = False
  27. self.ignore_mandatory = False
  28. if isinstance(dt, basestring) and not dn:
  29. dn = dt
  30. if dt and dn:
  31. self.load_from_db(dt, dn)
  32. elif isinstance(dt, list):
  33. self.set_doclist(dt)
  34. elif isinstance(dt, dict):
  35. self.set_doclist([dt])
  36. def load_from_db(self, dt=None, dn=None):
  37. """
  38. Load doclist from dt
  39. """
  40. from webnotes.model.doc import getchildren
  41. if not dt: dt = self.doc.doctype
  42. if not dn: dn = self.doc.name
  43. doc = Document(dt, dn)
  44. # get all children types
  45. tablefields = webnotes.model.meta.get_table_fields(dt)
  46. # load chilren
  47. doclist = webnotes.doclist([doc,])
  48. for t in tablefields:
  49. doclist += getchildren(doc.name, t[0], t[1], dt)
  50. self.set_doclist(doclist)
  51. if dt == dn:
  52. self.convert_type(self.doc)
  53. def __iter__(self):
  54. return self.doclist.__iter__()
  55. @property
  56. def meta(self):
  57. if not hasattr(self, "_meta"):
  58. self._meta = webnotes.get_doctype(self.doc.doctype)
  59. return self._meta
  60. def from_compressed(self, data, docname):
  61. from webnotes.model.utils import expand
  62. self.set_doclist(expand(data))
  63. def set_doclist(self, doclist):
  64. for i, d in enumerate(doclist):
  65. if isinstance(d, dict):
  66. doclist[i] = Document(fielddata=d)
  67. self.doclist = webnotes.doclist(doclist)
  68. self.doc = self.doclist[0]
  69. if self.obj:
  70. self.obj.doclist = self.doclist
  71. self.obj.doc = self.doc
  72. def make_controller(self):
  73. if self.obj:
  74. # update doclist before running any method
  75. self.obj.doclist = self.doclist
  76. return self.obj
  77. self.obj = webnotes.get_obj(doc=self.doc, doclist=self.doclist)
  78. self.obj.bean = self
  79. self.controller = self.obj
  80. return self.obj
  81. def get_controller(self):
  82. return self.make_controller()
  83. def to_dict(self):
  84. return [d.fields for d in self.doclist]
  85. def check_if_latest(self, method="save"):
  86. from webnotes.model.meta import is_single
  87. conflict = False
  88. if not cint(self.doc.fields.get('__islocal')):
  89. if is_single(self.doc.doctype):
  90. modified = webnotes.conn.get_value(self.doc.doctype, self.doc.name, "modified")
  91. if isinstance(modified, list):
  92. modified = modified[0]
  93. if cstr(modified) and cstr(modified) != cstr(self.doc.modified):
  94. conflict = True
  95. else:
  96. tmp = webnotes.conn.sql("""select modified, docstatus from `tab%s`
  97. where name="%s" for update"""
  98. % (self.doc.doctype, self.doc.name), as_dict=True)
  99. if not tmp:
  100. webnotes.msgprint("""This record does not exist. Please refresh.""", raise_exception=1)
  101. modified = cstr(tmp[0].modified)
  102. if modified and modified != cstr(self.doc.modified):
  103. conflict = True
  104. self.check_docstatus_transition(tmp[0].docstatus, method)
  105. if conflict:
  106. webnotes.msgprint(_("Error: Document has been modified after you have opened it") \
  107. + (" (%s, %s). " % (modified, self.doc.modified)) \
  108. + _("Please refresh to get the latest document."), raise_exception=TimestampMismatchError)
  109. def check_docstatus_transition(self, db_docstatus, method):
  110. valid = {
  111. "save": [0,0],
  112. "submit": [0,1],
  113. "cancel": [1,2],
  114. "update_after_submit": [1,1]
  115. }
  116. labels = {
  117. 0: _("Draft"),
  118. 1: _("Submitted"),
  119. 2: _("Cancelled")
  120. }
  121. if not hasattr(self, "to_docstatus"):
  122. self.to_docstatus = 0
  123. if method != "runserverobj" and [db_docstatus, self.to_docstatus] != valid[method]:
  124. webnotes.msgprint(_("Cannot change from") + ": " + labels[db_docstatus] + " > " + \
  125. labels[self.to_docstatus], raise_exception=DocstatusTransitionError)
  126. def check_links(self):
  127. if self.ignore_links:
  128. return
  129. ref, err_list = {}, []
  130. for d in self.doclist:
  131. if not ref.get(d.doctype):
  132. ref[d.doctype] = d.make_link_list()
  133. err_list += d.validate_links(ref[d.doctype])
  134. if err_list:
  135. webnotes.msgprint("""[Link Validation] Could not find the following values: %s.
  136. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1)
  137. def update_timestamps_and_docstatus(self):
  138. from webnotes.utils import now
  139. ts = now()
  140. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  141. for d in self.doclist:
  142. if self.doc.fields.get('__islocal'):
  143. if not d.owner:
  144. d.owner = user
  145. if not d.creation:
  146. d.creation = ts
  147. d.modified_by = user
  148. d.modified = ts
  149. if d.docstatus != 2 and self.to_docstatus >= int(d.docstatus): # don't update deleted
  150. d.docstatus = self.to_docstatus
  151. def prepare_for_save(self, method):
  152. self.check_if_latest(method)
  153. if method != "cancel":
  154. self.extract_images_from_text_editor()
  155. self.check_links()
  156. self.update_timestamps_and_docstatus()
  157. self.update_parent_info()
  158. def update_parent_info(self):
  159. idx_map = {}
  160. is_local = cint(self.doc.fields.get("__islocal"))
  161. if not webnotes.flags.in_import:
  162. parentfields = [d.fieldname for d in self.meta.get({"doctype": "DocField", "fieldtype": "Table"})]
  163. for i, d in enumerate(self.doclist[1:]):
  164. if d.parentfield:
  165. if not webnotes.flags.in_import:
  166. if not d.parentfield in parentfields:
  167. webnotes.msgprint("Bad parentfield %s" % d.parentfield,
  168. raise_exception=True)
  169. d.parenttype = self.doc.doctype
  170. d.parent = self.doc.name
  171. if not d.idx:
  172. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  173. else:
  174. d.idx = cint(d.idx)
  175. if is_local:
  176. # if parent is new, all children should be new
  177. d.fields["__islocal"] = 1
  178. d.name = None
  179. idx_map[d.parentfield] = d.idx
  180. def run_method(self, method, *args, **kwargs):
  181. self.make_controller()
  182. if hasattr(self.controller, method):
  183. getattr(self.controller, method)(*args, **kwargs)
  184. if hasattr(self.controller, 'custom_' + method):
  185. getattr(self.controller, 'custom_' + method)(*args, **kwargs)
  186. notify(self.controller, method)
  187. self.set_doclist(self.controller.doclist)
  188. def get_method(self, method):
  189. self.make_controller()
  190. return getattr(self.controller, method, None)
  191. def insert(self):
  192. self.doc.fields["__islocal"] = 1
  193. self.set_defaults()
  194. if webnotes.flags.in_test:
  195. if self.meta.get_field("naming_series"):
  196. self.doc.naming_series = "_T-" + self.doc.doctype + "-"
  197. return self.save()
  198. def insert_or_update(self):
  199. if webnotes.conn.exists( self.doc.doctype, self.doc.name):
  200. return self.save()
  201. else:
  202. return self.insert()
  203. def set_defaults(self):
  204. if webnotes.flags.in_import:
  205. return
  206. new_docs = {}
  207. new_doclist = []
  208. for d in self.doclist:
  209. if not d.doctype in new_docs:
  210. new_docs[d.doctype] = webnotes.new_doc(d.doctype)
  211. newd = webnotes.doc(new_docs[d.doctype].fields.copy())
  212. newd.fields.update(d.fields)
  213. new_doclist.append(newd)
  214. self.set_doclist(new_doclist)
  215. def has_read_perm(self):
  216. return webnotes.has_permission(self.doc.doctype, "read", self.doc)
  217. def save(self, check_links=1):
  218. perm_to_check = "write"
  219. if self.doc.fields.get("__islocal"):
  220. perm_to_check = "create"
  221. if not self.doc.owner:
  222. self.doc.owner = webnotes.session.user
  223. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, perm_to_check, self.doc):
  224. self.to_docstatus = 0
  225. self.prepare_for_save("save")
  226. if self.doc.fields.get("__islocal"):
  227. # set name before validate
  228. self.doc.set_new_name()
  229. self.run_method('before_insert')
  230. if not self.ignore_validate:
  231. self.run_method('validate')
  232. if not self.ignore_mandatory:
  233. self.check_mandatory()
  234. self.save_main()
  235. self.save_children()
  236. self.run_method('on_update')
  237. else:
  238. self.no_permission_to(_(perm_to_check.title()))
  239. return self
  240. def submit(self):
  241. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  242. self.to_docstatus = 1
  243. self.prepare_for_save("submit")
  244. self.run_method('validate')
  245. self.check_mandatory()
  246. self.save_main()
  247. self.save_children()
  248. self.run_method('on_update')
  249. self.run_method('on_submit')
  250. else:
  251. self.no_permission_to(_("Submit"))
  252. return self
  253. def cancel(self):
  254. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  255. self.to_docstatus = 2
  256. self.prepare_for_save("cancel")
  257. self.run_method('before_cancel')
  258. self.save_main()
  259. self.save_children()
  260. self.run_method('on_cancel')
  261. self.check_no_back_links_exist()
  262. else:
  263. self.no_permission_to(_("Cancel"))
  264. return self
  265. def update_after_submit(self):
  266. if self.doc.docstatus != 1:
  267. webnotes.msgprint("Only to called after submit", raise_exception=1)
  268. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  269. self.to_docstatus = 1
  270. self.prepare_for_save("update_after_submit")
  271. self.run_method('before_update_after_submit')
  272. self.save_main()
  273. self.save_children()
  274. self.run_method('on_update_after_submit')
  275. else:
  276. self.no_permission_to(_("Update"))
  277. return self
  278. def save_main(self):
  279. try:
  280. self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
  281. except NameError, e:
  282. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  283. # prompt if cancelled
  284. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  285. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  286. webnotes.errprint(webnotes.utils.getTraceback())
  287. raise e
  288. def save_children(self):
  289. child_map = {}
  290. for d in self.doclist[1:]:
  291. if d.fields.get("parent") or d.fields.get("parentfield"):
  292. d.parent = self.doc.name # rename if reqd
  293. d.parenttype = self.doc.doctype
  294. d.save(check_links=False, ignore_fields = self.ignore_fields)
  295. child_map.setdefault(d.doctype, []).append(d.name)
  296. # delete all children in database that are not in the child_map
  297. # get all children types
  298. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  299. for dt in tablefields:
  300. if dt[0] not in self.ignore_children_type:
  301. cnames = child_map.get(dt[0]) or []
  302. if cnames:
  303. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  304. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  305. tuple([self.doc.name, self.doc.doctype] + cnames))
  306. else:
  307. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  308. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  309. def delete(self):
  310. webnotes.delete_doc(self.doc.doctype, self.doc.name)
  311. def no_permission_to(self, ptype):
  312. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  313. _("No Permission to ") + ptype, raise_exception=BeanPermissionError)
  314. def check_no_back_links_exist(self):
  315. from webnotes.model.utils import check_if_doc_is_linked
  316. check_if_doc_is_linked(self.doc.doctype, self.doc.name, method="Cancel")
  317. def check_mandatory(self):
  318. missing = []
  319. for doc in self.doclist:
  320. for df in self.meta:
  321. if df.doctype=="DocField" and df.reqd and df.parent==doc.doctype and df.fieldname!="naming_series":
  322. msg = ""
  323. if df.fieldtype == "Table":
  324. if not self.doclist.get({"parentfield": df.fieldname}):
  325. msg = _("Error") + ": " + _("Data missing in table") + ": " + _(df.label)
  326. elif doc.fields.get(df.fieldname) is None:
  327. msg = _("Error") + ": "
  328. if doc.parentfield:
  329. msg += _("Row") + (" # %s: " % (doc.idx,))
  330. msg += _("Value missing for") + ": " + _(df.label)
  331. if msg:
  332. missing.append([msg, df.fieldname])
  333. if missing:
  334. for msg, fieldname in missing:
  335. msgprint(msg)
  336. raise webnotes.MandatoryError, ", ".join([fieldname for msg, fieldname in missing])
  337. def convert_type(self, doc):
  338. if doc.doctype==doc.name and doc.doctype!="DocType":
  339. for df in self.meta.get({"doctype": "DocField", "parent": doc.doctype}):
  340. if df.fieldtype in ("Int", "Check"):
  341. doc.fields[df.fieldname] = cint(doc.fields.get(df.fieldname))
  342. elif df.fieldtype in ("Float", "Currency"):
  343. doc.fields[df.fieldname] = flt(doc.fields.get(df.fieldname))
  344. doc.docstatus = cint(doc.docstatus)
  345. def extract_images_from_text_editor(self):
  346. from webnotes.utils.file_manager import extract_images_from_html
  347. if self.doc.doctype != "DocType":
  348. for df in self.meta.get({"doctype": "DocField", "parent": self.doc.doctype, "fieldtype":"Text Editor"}):
  349. extract_images_from_html(self.doc, df.fieldname)
  350. def clone(source_wrapper):
  351. """ make a clone of a document"""
  352. if isinstance(source_wrapper, list):
  353. source_wrapper = Bean(source_wrapper)
  354. new_wrapper = Bean(source_wrapper.doclist.copy())
  355. if new_wrapper.doc.fields.get("amended_from"):
  356. new_wrapper.doc.fields["amended_from"] = None
  357. if new_wrapper.doc.fields.get("amendment_date"):
  358. new_wrapper.doc.fields["amendment_date"] = None
  359. for d in new_wrapper.doclist:
  360. d.fields.update({
  361. "name": None,
  362. "__islocal": 1,
  363. "docstatus": 0,
  364. })
  365. return new_wrapper
  366. def notify(controller, caller_method):
  367. try:
  368. from startup.observers import observer_map
  369. except ImportError:
  370. return
  371. doctype = controller.doc.doctype
  372. def call_observers(key):
  373. if key in observer_map:
  374. observer_list = observer_map[key]
  375. if isinstance(observer_list, basestring):
  376. observer_list = [observer_list]
  377. for observer_method in observer_list:
  378. webnotes.get_method(observer_method)(controller, caller_method)
  379. call_observers("*:*")
  380. call_observers(doctype + ":*")
  381. call_observers("*:" + caller_method)
  382. call_observers(doctype + ":" + caller_method)
  383. # for bc
  384. def getlist(doclist, parentfield):
  385. """
  386. Return child records of a particular type
  387. """
  388. import webnotes.model.utils
  389. return webnotes.model.utils.getlist(doclist, parentfield)
  390. def copy_doclist(doclist, no_copy = []):
  391. """
  392. Make a copy of the doclist
  393. """
  394. import webnotes.model.utils
  395. return webnotes.model.utils.copy_doclist(doclist, no_copy)