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

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