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.
 
 
 
 
 
 

525 regels
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. if not args:
  180. args = []
  181. self.make_controller()
  182. def add_to_response(out, new_response):
  183. if isinstance(new_response, dict):
  184. out.update(new_response)
  185. if hasattr(self.controller, method):
  186. add_to_response(webnotes.local.response,
  187. webnotes.call(getattr(self.controller, method), *args, **kwargs))
  188. if hasattr(self.controller, 'custom_' + method):
  189. add_to_response(webnotes.local.response,
  190. webnotes.call(getattr(self.controller, 'custom_' + method), *args, **kwargs))
  191. args = [self, method] + args
  192. for handler in webnotes.get_hooks("bean_event:" + self.doc.doctype + ":" + method) \
  193. + webnotes.get_hooks("bean_event:*:" + method):
  194. add_to_response(webnotes.local.response, webnotes.call(webnotes.get_attr(handler), *args, **kwargs))
  195. self.set_doclist(self.controller.doclist)
  196. return webnotes.local.response
  197. def get_attr(self, method):
  198. self.make_controller()
  199. return getattr(self.controller, method, None)
  200. def insert(self, ignore_permissions=None):
  201. if ignore_permissions:
  202. self.ignore_permissions = True
  203. self.doc.fields["__islocal"] = 1
  204. self.set_defaults()
  205. if webnotes.flags.in_test:
  206. if self.meta.get_field("naming_series"):
  207. self.doc.naming_series = "_T-" + self.doc.doctype + "-"
  208. return self.save()
  209. def insert_or_update(self):
  210. if self.doc.name and webnotes.conn.exists(self.doc.doctype, self.doc.name):
  211. return self.save()
  212. else:
  213. return self.insert()
  214. def set_defaults(self):
  215. if webnotes.flags.in_import:
  216. return
  217. new_docs = {}
  218. new_doclist = []
  219. for d in self.doclist:
  220. if not d.doctype in new_docs:
  221. new_docs[d.doctype] = webnotes.new_doc(d.doctype)
  222. newd = webnotes.doc(new_docs[d.doctype].fields.copy())
  223. newd.fields.update(d.fields)
  224. new_doclist.append(newd)
  225. self.set_doclist(new_doclist)
  226. def has_read_perm(self):
  227. return self.has_permission("read")
  228. def has_permission(self, permtype):
  229. return webnotes.has_permission(self.doc.doctype, permtype, self.doc)
  230. def save(self, check_links=1, ignore_permissions=None):
  231. if ignore_permissions:
  232. self.ignore_permissions = ignore_permissions
  233. perm_to_check = "write"
  234. if self.doc.fields.get("__islocal"):
  235. perm_to_check = "create"
  236. if not self.doc.owner:
  237. self.doc.owner = webnotes.session.user
  238. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, perm_to_check, 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. self.validate_doclist()
  244. self.save_main()
  245. self.save_children()
  246. self.run_method('on_update')
  247. if perm_to_check=="create":
  248. self.run_method("after_insert")
  249. else:
  250. self.no_permission_to(_(perm_to_check.title()))
  251. return self
  252. def submit(self):
  253. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  254. self.to_docstatus = 1
  255. self.prepare_for_save("submit")
  256. self.run_method('validate')
  257. self.validate_doclist()
  258. self.save_main()
  259. self.save_children()
  260. self.run_method('on_update')
  261. self.run_method('on_submit')
  262. else:
  263. self.no_permission_to(_("Submit"))
  264. return self
  265. def cancel(self):
  266. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  267. self.to_docstatus = 2
  268. self.prepare_for_save("cancel")
  269. self.run_method('before_cancel')
  270. self.save_main()
  271. self.save_children()
  272. self.run_method('on_cancel')
  273. self.check_no_back_links_exist()
  274. else:
  275. self.no_permission_to(_("Cancel"))
  276. return self
  277. def update_after_submit(self):
  278. if self.doc.docstatus != 1:
  279. webnotes.msgprint("Only to called after submit", raise_exception=1)
  280. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  281. self.to_docstatus = 1
  282. self.prepare_for_save("update_after_submit")
  283. self.run_method('validate')
  284. self.run_method('before_update_after_submit')
  285. self.validate_doclist()
  286. self.save_main()
  287. self.save_children()
  288. self.run_method('on_update_after_submit')
  289. else:
  290. self.no_permission_to(_("Update"))
  291. return self
  292. def save_main(self):
  293. try:
  294. self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
  295. except NameError, e:
  296. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  297. # prompt if cancelled
  298. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  299. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  300. webnotes.errprint(webnotes.utils.get_traceback())
  301. raise
  302. def save_children(self):
  303. child_map = {}
  304. for d in self.doclist[1:]:
  305. if d.fields.get("parent") or d.fields.get("parentfield"):
  306. d.parent = self.doc.name # rename if reqd
  307. d.parenttype = self.doc.doctype
  308. d.save(check_links=False, ignore_fields = self.ignore_fields)
  309. child_map.setdefault(d.doctype, []).append(d.name)
  310. # delete all children in database that are not in the child_map
  311. # get all children types
  312. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  313. for dt in tablefields:
  314. if dt[0] not in self.ignore_children_type:
  315. cnames = child_map.get(dt[0]) or []
  316. if cnames:
  317. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  318. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  319. tuple([self.doc.name, self.doc.doctype] + cnames))
  320. else:
  321. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  322. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  323. def delete(self):
  324. webnotes.delete_doc(self.doc.doctype, self.doc.name)
  325. def no_permission_to(self, ptype):
  326. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  327. _("No Permission to ") + ptype, raise_exception=BeanPermissionError)
  328. def check_no_back_links_exist(self):
  329. from webnotes.model.delete_doc import check_if_doc_is_linked
  330. check_if_doc_is_linked(self.doc.doctype, self.doc.name, method="Cancel")
  331. def check_mandatory(self):
  332. if self.ignore_mandatory:
  333. return
  334. missing = []
  335. for doc in self.doclist:
  336. for df in self.meta:
  337. if df.doctype=="DocField" and df.reqd and df.parent==doc.doctype and df.fieldname!="naming_series":
  338. msg = ""
  339. if df.fieldtype == "Table":
  340. if not self.doclist.get({"parentfield": df.fieldname}):
  341. msg = _("Error") + ": " + _("Data missing in table") + ": " + _(df.label)
  342. elif doc.fields.get(df.fieldname) is None:
  343. msg = _("Error") + ": "
  344. if doc.parentfield:
  345. msg += _("Row") + (" # %s: " % (doc.idx,))
  346. msg += _("Value missing for") + ": " + _(df.label)
  347. if msg:
  348. missing.append([msg, df.fieldname])
  349. if missing:
  350. for msg, fieldname in missing:
  351. msgprint(msg)
  352. raise webnotes.MandatoryError, ", ".join([fieldname for msg, fieldname in missing])
  353. def convert_type(self, doc):
  354. if doc.doctype==doc.name and doc.doctype!="DocType":
  355. for df in self.meta.get({"doctype": "DocField", "parent": doc.doctype}):
  356. if df.fieldtype in ("Int", "Check"):
  357. doc.fields[df.fieldname] = cint(doc.fields.get(df.fieldname))
  358. elif df.fieldtype in ("Float", "Currency"):
  359. doc.fields[df.fieldname] = flt(doc.fields.get(df.fieldname))
  360. doc.docstatus = cint(doc.docstatus)
  361. def extract_images_from_text_editor(self):
  362. from webnotes.utils.file_manager import extract_images_from_html
  363. if self.doc.doctype != "DocType":
  364. for df in self.meta.get({"doctype": "DocField", "parent": self.doc.doctype, "fieldtype":"Text Editor"}):
  365. extract_images_from_html(self.doc, df.fieldname)
  366. def validate_doclist(self):
  367. self.check_mandatory()
  368. self.validate_restrictions()
  369. self.check_links()
  370. def check_links(self):
  371. if self.ignore_links:
  372. return
  373. ref, err_list = {}, []
  374. for d in self.doclist:
  375. if not ref.get(d.doctype):
  376. ref[d.doctype] = d.make_link_list()
  377. err_list += d.validate_links(ref[d.doctype])
  378. if err_list:
  379. webnotes.msgprint("""[Link Validation] Could not find the following values: %s.
  380. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1)
  381. def validate_restrictions(self):
  382. if self.ignore_restrictions:
  383. return
  384. has_restricted_data = False
  385. for d in self.doclist:
  386. if not webnotes.permissions.has_unrestricted_access(webnotes.get_doctype(d.doctype), d):
  387. has_restricted_data = True
  388. if has_restricted_data:
  389. raise BeanPermissionError
  390. def clone(source_wrapper):
  391. """ make a clone of a document"""
  392. if isinstance(source_wrapper, list):
  393. source_wrapper = Bean(source_wrapper)
  394. new_wrapper = Bean(source_wrapper.doclist.copy())
  395. if new_wrapper.doc.fields.get("amended_from"):
  396. new_wrapper.doc.fields["amended_from"] = None
  397. if new_wrapper.doc.fields.get("amendment_date"):
  398. new_wrapper.doc.fields["amendment_date"] = None
  399. for d in new_wrapper.doclist:
  400. d.fields.update({
  401. "name": None,
  402. "__islocal": 1,
  403. "docstatus": 0,
  404. })
  405. return new_wrapper
  406. # for bc
  407. def getlist(doclist, parentfield):
  408. import webnotes.model.utils
  409. return webnotes.model.utils.getlist(doclist, parentfield)
  410. def copy_doclist(doclist, no_copy = []):
  411. """
  412. Make a copy of the doclist
  413. """
  414. import webnotes.model.utils
  415. return webnotes.model.utils.copy_doclist(doclist, no_copy)