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.
 
 
 
 
 
 

520 lines
15 KiB

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