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.
 
 
 
 
 
 

470 lines
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_check_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, prefix='tab'):
  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, prefix=prefix)
  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, prefix=prefix)
  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 to_dict(self):
  82. return [d.fields for d in self.doclist]
  83. def check_if_latest(self, method="save"):
  84. from webnotes.model.meta import is_single
  85. conflict = False
  86. if not cint(self.doc.fields.get('__islocal')):
  87. if is_single(self.doc.doctype):
  88. modified = webnotes.conn.get_value(self.doc.doctype, self.doc.name, "modified")
  89. if isinstance(modified, list):
  90. modified = modified[0]
  91. if cstr(modified) and cstr(modified) != cstr(self.doc.modified):
  92. conflict = True
  93. else:
  94. tmp = webnotes.conn.sql("""select modified, docstatus from `tab%s`
  95. where name="%s" for update"""
  96. % (self.doc.doctype, self.doc.name), as_dict=True)
  97. if not tmp:
  98. webnotes.msgprint("""This record does not exist. Please refresh.""", raise_exception=1)
  99. modified = cstr(tmp[0].modified)
  100. if modified and modified != cstr(self.doc.modified):
  101. conflict = True
  102. self.check_docstatus_transition(tmp[0].docstatus, method)
  103. if conflict:
  104. webnotes.msgprint(_("Error: Document has been modified after you have opened it") \
  105. + (" (%s, %s). " % (modified, self.doc.modified)) \
  106. + _("Please refresh to get the latest document."), raise_exception=TimestampMismatchError)
  107. def check_docstatus_transition(self, db_docstatus, method):
  108. valid = {
  109. "save": [0,0],
  110. "submit": [0,1],
  111. "cancel": [1,2],
  112. "update_after_submit": [1,1]
  113. }
  114. labels = {
  115. 0: _("Draft"),
  116. 1: _("Submitted"),
  117. 2: _("Cancelled")
  118. }
  119. if not hasattr(self, "to_docstatus"):
  120. self.to_docstatus = 0
  121. if method != "runserverobj" and [db_docstatus, self.to_docstatus] != valid[method]:
  122. webnotes.msgprint(_("Cannot change from") + ": " + labels[db_docstatus] + " > " + \
  123. labels[self.to_docstatus], raise_exception=DocstatusTransitionError)
  124. def check_links(self):
  125. if self.ignore_check_links:
  126. return
  127. ref, err_list = {}, []
  128. for d in self.doclist:
  129. if not ref.get(d.doctype):
  130. ref[d.doctype] = d.make_link_list()
  131. err_list += d.validate_links(ref[d.doctype])
  132. if err_list:
  133. webnotes.msgprint("""[Link Validation] Could not find the following values: %s.
  134. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1)
  135. def update_timestamps_and_docstatus(self):
  136. from webnotes.utils import now
  137. ts = now()
  138. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  139. for d in self.doclist:
  140. if self.doc.fields.get('__islocal'):
  141. if not d.owner:
  142. d.owner = user
  143. if not d.creation:
  144. d.creation = ts
  145. d.modified_by = user
  146. d.modified = ts
  147. if d.docstatus != 2 and self.to_docstatus >= int(d.docstatus): # don't update deleted
  148. d.docstatus = self.to_docstatus
  149. def prepare_for_save(self, method):
  150. self.check_if_latest(method)
  151. if method != "cancel":
  152. self.check_links()
  153. self.update_timestamps_and_docstatus()
  154. self.update_parent_info()
  155. def update_parent_info(self):
  156. idx_map = {}
  157. is_local = cint(self.doc.fields.get("__islocal"))
  158. if not webnotes.in_import:
  159. parentfields = [d.fieldname for d in self.meta.get({"doctype": "DocField", "fieldtype": "Table"})]
  160. for i, d in enumerate(self.doclist[1:]):
  161. if d.parentfield:
  162. if not webnotes.in_import:
  163. if not d.parentfield in parentfields:
  164. webnotes.msgprint("Bad parentfield %s" % d.parentfield,
  165. raise_exception=True)
  166. d.parenttype = self.doc.doctype
  167. d.parent = self.doc.name
  168. if not d.idx:
  169. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  170. if is_local:
  171. # if parent is new, all children should be new
  172. d.fields["__islocal"] = 1
  173. idx_map[d.parentfield] = d.idx
  174. def run_method(self, method):
  175. self.make_controller()
  176. if hasattr(self.controller, method):
  177. getattr(self.controller, method)()
  178. if hasattr(self.controller, 'custom_' + method):
  179. getattr(self.controller, 'custom_' + method)()
  180. notify(self.controller, method)
  181. self.set_doclist(self.controller.doclist)
  182. def get_method(self, method):
  183. self.make_controller()
  184. return getattr(self.controller, method, None)
  185. def save_main(self):
  186. try:
  187. self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
  188. except NameError, e:
  189. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  190. # prompt if cancelled
  191. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  192. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  193. webnotes.errprint(webnotes.utils.getTraceback())
  194. raise e
  195. def save_children(self):
  196. child_map = {}
  197. for d in self.doclist[1:]:
  198. if d.fields.get("parent") or d.fields.get("parentfield"):
  199. d.parent = self.doc.name # rename if reqd
  200. d.parenttype = self.doc.doctype
  201. d.save(check_links=False, ignore_fields = self.ignore_fields)
  202. child_map.setdefault(d.doctype, []).append(d.name)
  203. # delete all children in database that are not in the child_map
  204. # get all children types
  205. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  206. for dt in tablefields:
  207. if dt[0] not in self.ignore_children_type:
  208. cnames = child_map.get(dt[0]) or []
  209. if cnames:
  210. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  211. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  212. tuple([self.doc.name, self.doc.doctype] + cnames))
  213. else:
  214. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  215. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  216. def insert(self):
  217. self.doc.fields["__islocal"] = 1
  218. self.set_defaults()
  219. if webnotes.in_test:
  220. if self.meta.get_field("naming_series"):
  221. self.doc.naming_series = "_T-" + self.doc.doctype + "-"
  222. return self.save()
  223. def set_defaults(self):
  224. if webnotes.in_import:
  225. return
  226. new_docs = {}
  227. new_doclist = []
  228. for d in self.doclist:
  229. if not d.doctype in new_docs:
  230. new_docs[d.doctype] = webnotes.new_doc(d.doctype)
  231. newd = webnotes.doc(new_docs[d.doctype].fields.copy())
  232. newd.fields.update(d.fields)
  233. new_doclist.append(newd)
  234. self.set_doclist(new_doclist)
  235. def has_read_perm(self):
  236. return webnotes.has_permission(self.doc.doctype, "read", self.doc)
  237. def save(self, check_links=1):
  238. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  239. self.to_docstatus = 0
  240. self.prepare_for_save("save")
  241. if not self.ignore_validate:
  242. self.run_method('validate')
  243. if not self.ignore_mandatory:
  244. self.check_mandatory()
  245. self.save_main()
  246. self.save_children()
  247. self.run_method('on_update')
  248. else:
  249. self.no_permission_to(_("Write"))
  250. return self
  251. def submit(self):
  252. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  253. self.to_docstatus = 1
  254. self.prepare_for_save("submit")
  255. self.run_method('validate')
  256. self.check_mandatory()
  257. self.save_main()
  258. self.save_children()
  259. self.run_method('on_update')
  260. self.run_method('on_submit')
  261. else:
  262. self.no_permission_to(_("Submit"))
  263. return self
  264. def cancel(self):
  265. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  266. self.to_docstatus = 2
  267. self.prepare_for_save("cancel")
  268. self.run_method('before_cancel')
  269. self.save_main()
  270. self.save_children()
  271. self.run_method('on_cancel')
  272. self.check_no_back_links_exist()
  273. else:
  274. self.no_permission_to(_("Cancel"))
  275. return self
  276. def update_after_submit(self):
  277. if self.doc.docstatus != 1:
  278. webnotes.msgprint("Only to called after submit", raise_exception=1)
  279. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  280. self.to_docstatus = 1
  281. self.prepare_for_save("update_after_submit")
  282. self.run_method('before_update_after_submit')
  283. self.save_main()
  284. self.save_children()
  285. self.run_method('on_update_after_submit')
  286. else:
  287. self.no_permission_to(_("Update"))
  288. return self
  289. def delete(self):
  290. webnotes.delete_doc(self.doc.doctype, self.doc.name)
  291. def no_permission_to(self, ptype):
  292. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  293. _("No Permission to ") + ptype, raise_exception=BeanPermissionError)
  294. def check_no_back_links_exist(self):
  295. from webnotes.model.utils import check_if_doc_is_linked
  296. check_if_doc_is_linked(self.doc.doctype, self.doc.name, method="Cancel")
  297. def check_mandatory(self):
  298. missing = []
  299. for doc in self.doclist:
  300. for df in self.meta:
  301. if df.doctype=="DocField" and df.reqd and df.parent==doc.doctype and df.fieldname!="naming_series":
  302. msg = ""
  303. if df.fieldtype == "Table":
  304. if not self.doclist.get({"parentfield": df.fieldname}):
  305. msg = _("Error") + ": " + _("Data missing in table") + ": " + _(df.label)
  306. elif doc.fields.get(df.fieldname) is None:
  307. msg = _("Error") + ": "
  308. if doc.parentfield:
  309. msg += _("Row") + (" # %d: " % doc.idx)
  310. msg += _("Value missing for") + ": " + _(df.label)
  311. if msg:
  312. missing.append([msg, df.fieldname])
  313. if missing:
  314. for msg, fieldname in missing:
  315. msgprint(msg)
  316. raise webnotes.MandatoryError, ", ".join([fieldname for msg, fieldname in missing])
  317. def convert_type(self, doc):
  318. if doc.doctype==doc.name and doc.doctype!="DocType":
  319. for df in self.meta.get({"doctype": "DocField", "parent": doc.doctype}):
  320. if df.fieldtype in ("Int", "Check"):
  321. doc.fields[df.fieldname] = cint(doc.fields.get(df.fieldname))
  322. elif df.fieldtype in ("Float", "Currency"):
  323. doc.fields[df.fieldname] = flt(doc.fields.get(df.fieldname))
  324. doc.docstatus = cint(doc.docstatus)
  325. def clone(source_wrapper):
  326. """ make a clone of a document"""
  327. if isinstance(source_wrapper, list):
  328. source_wrapper = Bean(source_wrapper)
  329. new_wrapper = Bean(source_wrapper.doclist.copy())
  330. if new_wrapper.doc.fields.get("amended_from"):
  331. new_wrapper.doc.fields["amended_from"] = None
  332. if new_wrapper.doc.fields.get("amendment_date"):
  333. new_wrapper.doc.fields["amendment_date"] = None
  334. for d in new_wrapper.doclist:
  335. d.fields.update({
  336. "name": None,
  337. "__islocal": 1,
  338. "docstatus": 0,
  339. })
  340. return new_wrapper
  341. def notify(controller, caller_method):
  342. try:
  343. from startup.observers import observer_map
  344. except ImportError:
  345. return
  346. doctype = controller.doc.doctype
  347. def call_observers(key):
  348. if key in observer_map:
  349. observer_list = observer_map[key]
  350. if isinstance(observer_list, basestring):
  351. observer_list = [observer_list]
  352. for observer_method in observer_list:
  353. webnotes.get_method(observer_method)(controller, caller_method)
  354. call_observers("*:*")
  355. call_observers(doctype + ":*")
  356. call_observers("*:" + caller_method)
  357. call_observers(doctype + ":" + caller_method)
  358. # for bc
  359. def getlist(doclist, parentfield):
  360. """
  361. Return child records of a particular type
  362. """
  363. import webnotes.model.utils
  364. return webnotes.model.utils.getlist(doclist, parentfield)
  365. def copy_doclist(doclist, no_copy = []):
  366. """
  367. Make a copy of the doclist
  368. """
  369. import webnotes.model.utils
  370. return webnotes.model.utils.copy_doclist(doclist, no_copy)