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.

bean.py 15 KiB

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