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.

12 年之前
12 年之前
12 年之前
12 年之前
12 年之前
12 年之前
12 年之前
12 年之前
12 年之前
12 年之前
12 年之前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. from __future__ import unicode_literals
  23. """
  24. Transactions are defined as collection of classes, a Bean represents collection of Document
  25. objects for a transaction with main and children.
  26. Group actions like save, etc are performed on doclists
  27. """
  28. import webnotes
  29. from webnotes import _, msgprint
  30. from webnotes.utils import cint, cstr
  31. from webnotes.model.doc import Document
  32. class DocstatusTransitionError(webnotes.ValidationError): pass
  33. class BeanPermissionError(webnotes.ValidationError): pass
  34. class Bean:
  35. """
  36. Collection of Documents with one parent and multiple children
  37. """
  38. def __init__(self, dt=None, dn=None):
  39. self.obj = None
  40. self.ignore_permissions = False
  41. self.ignore_children_type = []
  42. self.ignore_check_links = False
  43. self.ignore_validate = False
  44. self.ignore_fields = False
  45. self.ignore_mandatory = False
  46. if isinstance(dt, basestring) and not dn:
  47. dn = dt
  48. if dt and dn:
  49. self.load_from_db(dt, dn)
  50. elif isinstance(dt, list):
  51. self.set_doclist(dt)
  52. elif isinstance(dt, dict):
  53. self.set_doclist([dt])
  54. def load_from_db(self, dt=None, dn=None, prefix='tab'):
  55. """
  56. Load doclist from dt
  57. """
  58. from webnotes.model.doc import getchildren
  59. if not dt: dt = self.doc.doctype
  60. if not dn: dn = self.doc.name
  61. doc = Document(dt, dn, prefix=prefix)
  62. # get all children types
  63. tablefields = webnotes.model.meta.get_table_fields(dt)
  64. # load chilren
  65. doclist = webnotes.doclist([doc,])
  66. for t in tablefields:
  67. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  68. self.set_doclist(doclist)
  69. def __iter__(self):
  70. return self.doclist.__iter__()
  71. @property
  72. def meta(self):
  73. if not hasattr(self, "_meta"):
  74. self._meta = webnotes.get_doctype(self.doc.doctype)
  75. return self._meta
  76. def from_compressed(self, data, docname):
  77. from webnotes.model.utils import expand
  78. self.set_doclist(expand(data))
  79. def set_doclist(self, doclist):
  80. for i, d in enumerate(doclist):
  81. if isinstance(d, dict):
  82. doclist[i] = Document(fielddata=d)
  83. self.doclist = webnotes.doclist(doclist)
  84. self.doc = self.doclist[0]
  85. if self.obj:
  86. self.obj.doclist = self.doclist
  87. self.obj.doc = self.doc
  88. def make_controller(self):
  89. if self.obj:
  90. # update doclist before running any method
  91. self.obj.doclist = self.doclist
  92. return self.obj
  93. self.obj = webnotes.get_obj(doc=self.doc, doclist=self.doclist)
  94. self.obj.bean = self
  95. self.controller = self.obj
  96. return self.obj
  97. def to_dict(self):
  98. return [d.fields for d in self.doclist]
  99. def check_if_latest(self, method="save"):
  100. from webnotes.model.meta import is_single
  101. conflict = False
  102. if not cint(self.doc.fields.get('__islocal')):
  103. if is_single(self.doc.doctype):
  104. modified = webnotes.conn.get_value(self.doc.doctype, self.doc.name, "modified")
  105. if isinstance(modified, list):
  106. modified = modified[0]
  107. if cstr(modified) and cstr(modified) != cstr(self.doc.modified):
  108. conflict = True
  109. else:
  110. tmp = webnotes.conn.sql("""select modified, docstatus from `tab%s`
  111. where name="%s" for update"""
  112. % (self.doc.doctype, self.doc.name), as_dict=True)
  113. if not tmp:
  114. webnotes.msgprint("""This record does not exist. Please refresh.""", raise_exception=1)
  115. modified = cstr(tmp[0].modified)
  116. if modified and modified != cstr(self.doc.modified):
  117. conflict = True
  118. self.check_docstatus_transition(tmp[0].docstatus, method)
  119. if conflict:
  120. webnotes.msgprint(_("Error: Document has been modified after you have opened it") \
  121. + (" (%s, %s). " % (modified, self.doc.modified)) \
  122. + _("Please refresh to get the latest document."), raise_exception=True)
  123. def check_docstatus_transition(self, db_docstatus, method):
  124. valid = {
  125. "save": [0,0],
  126. "submit": [0,1],
  127. "cancel": [1,2],
  128. "update_after_submit": [1,1]
  129. }
  130. labels = {
  131. 0: _("Draft"),
  132. 1: _("Submitted"),
  133. 2: _("Cancelled")
  134. }
  135. if not hasattr(self, "to_docstatus"):
  136. self.to_docstatus = 0
  137. if method != "runserverobj" and [db_docstatus, self.to_docstatus] != valid[method]:
  138. webnotes.msgprint(_("Cannot change from") + ": " + labels[db_docstatus] + " > " + \
  139. labels[self.to_docstatus], raise_exception=DocstatusTransitionError)
  140. def check_links(self):
  141. if self.ignore_check_links:
  142. return
  143. ref, err_list = {}, []
  144. for d in self.doclist:
  145. if not ref.get(d.doctype):
  146. ref[d.doctype] = d.make_link_list()
  147. err_list += d.validate_links(ref[d.doctype])
  148. if err_list:
  149. webnotes.msgprint("""[Link Validation] Could not find the following values: %s.
  150. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1)
  151. def update_timestamps_and_docstatus(self):
  152. from webnotes.utils import now
  153. ts = now()
  154. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  155. for d in self.doclist:
  156. if self.doc.fields.get('__islocal'):
  157. if not d.owner:
  158. d.owner = user
  159. if not d.creation:
  160. d.creation = ts
  161. d.modified_by = user
  162. d.modified = ts
  163. if d.docstatus != 2 and self.to_docstatus >= d.docstatus: # don't update deleted
  164. d.docstatus = self.to_docstatus
  165. def prepare_for_save(self, method):
  166. self.check_if_latest(method)
  167. if method != "cancel":
  168. self.check_links()
  169. self.update_timestamps_and_docstatus()
  170. self.update_parent_info()
  171. def update_parent_info(self):
  172. idx_map = {}
  173. is_local = cint(self.doc.fields.get("__islocal"))
  174. if not webnotes.in_import:
  175. parentfields = [d.fieldname for d in self.meta.get({"doctype": "DocField", "fieldtype": "Table"})]
  176. for i, d in enumerate(self.doclist[1:]):
  177. if d.parentfield:
  178. if not webnotes.in_import:
  179. if not d.parentfield in parentfields:
  180. webnotes.msgprint("Bad parentfield %s" % parentfield,
  181. raise_exception=True)
  182. d.parenttype = self.doc.doctype
  183. d.parent = self.doc.name
  184. if not d.idx:
  185. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  186. if is_local:
  187. # if parent is new, all children should be new
  188. d.fields["__islocal"] = 1
  189. idx_map[d.parentfield] = d.idx
  190. def run_method(self, method):
  191. self.make_controller()
  192. if hasattr(self.controller, method):
  193. getattr(self.controller, method)()
  194. if hasattr(self.controller, 'custom_' + method):
  195. getattr(self.controller, 'custom_' + method)()
  196. notify(self.controller, method)
  197. self.set_doclist(self.controller.doclist)
  198. def get_method(self, method):
  199. self.make_controller()
  200. return getattr(self.controller, method, None)
  201. def save_main(self):
  202. try:
  203. self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
  204. except NameError, e:
  205. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  206. # prompt if cancelled
  207. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  208. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  209. webnotes.errprint(webnotes.utils.getTraceback())
  210. raise e
  211. def save_children(self):
  212. child_map = {}
  213. for d in self.doclist[1:]:
  214. if d.fields.get("parent") or d.fields.get("parentfield"):
  215. d.parent = self.doc.name # rename if reqd
  216. d.parenttype = self.doc.doctype
  217. d.save(check_links=False, ignore_fields = self.ignore_fields)
  218. child_map.setdefault(d.doctype, []).append(d.name)
  219. # delete all children in database that are not in the child_map
  220. # get all children types
  221. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  222. for dt in tablefields:
  223. if dt[0] not in self.ignore_children_type:
  224. cnames = child_map.get(dt[0]) or []
  225. if cnames:
  226. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  227. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  228. tuple([self.doc.name, self.doc.doctype] + cnames))
  229. else:
  230. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  231. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  232. def insert(self):
  233. self.doc.fields["__islocal"] = 1
  234. if webnotes.in_test:
  235. if self.meta.get_field("naming_series"):
  236. self.doc.naming_series = "_T-" + self.doc.doctype + "-"
  237. return self.save()
  238. def has_read_perm(self):
  239. return webnotes.has_permission(self.doc.doctype, "read", self.doc)
  240. def save(self, check_links=1):
  241. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  242. self.to_docstatus = 0
  243. self.prepare_for_save("save")
  244. if not self.ignore_validate:
  245. self.run_method('validate')
  246. if not self.ignore_mandatory:
  247. self.check_mandatory()
  248. self.save_main()
  249. self.save_children()
  250. self.run_method('on_update')
  251. else:
  252. self.no_permission_to(_("Write"))
  253. return self
  254. def submit(self):
  255. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  256. self.to_docstatus = 1
  257. self.prepare_for_save("submit")
  258. self.run_method('validate')
  259. self.check_mandatory()
  260. self.save_main()
  261. self.save_children()
  262. self.run_method('on_update')
  263. self.run_method('on_submit')
  264. else:
  265. self.no_permission_to(_("Submit"))
  266. return self
  267. def cancel(self):
  268. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  269. self.to_docstatus = 2
  270. self.prepare_for_save("cancel")
  271. self.run_method('before_cancel')
  272. self.save_main()
  273. self.save_children()
  274. self.run_method('on_cancel')
  275. self.check_no_back_links_exist()
  276. else:
  277. self.no_permission_to(_("Cancel"))
  278. return self
  279. def update_after_submit(self):
  280. if self.doc.docstatus != 1:
  281. webnotes.msgprint("Only to called after submit", raise_exception=1)
  282. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  283. self.to_docstatus = 1
  284. self.prepare_for_save("update_after_submit")
  285. self.run_method('before_update_after_submit')
  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 delete(self):
  293. webnotes.delete_doc(self.doc.doctype, self.doc.name)
  294. def no_permission_to(self, ptype):
  295. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  296. _("No Permission to ") + ptype, raise_exception=BeanPermissionError)
  297. def check_no_back_links_exist(self):
  298. from webnotes.model.utils import check_if_doc_is_linked
  299. check_if_doc_is_linked(self.doc.doctype, self.doc.name, method="Cancel")
  300. def check_mandatory(self):
  301. missing = []
  302. for doc in self.doclist:
  303. for df in self.meta:
  304. if df.doctype=="DocField" and df.reqd and df.parent==doc.doctype:
  305. msg = ""
  306. if df.fieldtype == "Table":
  307. if not self.doclist.get({"parentfield": df.fieldname}):
  308. msg = _("Error") + ": " + _("Data missing in table") + ": " + _(label)
  309. elif doc.fields.get(df.fieldname) is None:
  310. msg = _("Error") + ": "
  311. if doc.parentfield:
  312. msg += _("Row") + (" # %d: " % doc.idx)
  313. msg += _("Value missing for") + ": " + _(df.label)
  314. if msg:
  315. missing.append([msg, df.fieldname])
  316. if missing:
  317. for msg, fieldname in missing:
  318. msgprint(msg)
  319. raise webnotes.MandatoryError, ", ".join([fieldname for msg, fieldname in missing])
  320. def clone(source_wrapper):
  321. """ make a clone of a document"""
  322. if isinstance(source_wrapper, list):
  323. source_wrapper = Bean(source_wrapper)
  324. new_wrapper = Bean(source_wrapper.doclist.copy())
  325. if new_wrapper.doc.fields.get("amended_from"):
  326. new_wrapper.doc.fields["amended_from"] = None
  327. if new_wrapper.doc.fields.get("amendment_date"):
  328. new_wrapper.doc.fields["amendment_date"] = None
  329. for d in new_wrapper.doclist:
  330. d.fields.update({
  331. "name": None,
  332. "__islocal": 1,
  333. "docstatus": 0,
  334. })
  335. return new_wrapper
  336. def notify(controller, caller_method):
  337. try:
  338. from startup.observers import observer_map
  339. except ImportError:
  340. return
  341. doctype = controller.doc.doctype
  342. def call_observers(key):
  343. if key in observer_map:
  344. observer_list = observer_map[key]
  345. if isinstance(observer_list, basestring):
  346. observer_list = [observer_list]
  347. for observer_method in observer_list:
  348. webnotes.get_method(observer_method)(controller, caller_method)
  349. call_observers("*:*")
  350. call_observers(doctype + ":*")
  351. call_observers("*:" + caller_method)
  352. call_observers(doctype + ":" + caller_method)
  353. # for bc
  354. def getlist(doclist, parentfield):
  355. """
  356. Return child records of a particular type
  357. """
  358. import webnotes.model.utils
  359. return webnotes.model.utils.getlist(doclist, parentfield)
  360. def copy_doclist(doclist, no_copy = []):
  361. """
  362. Make a copy of the doclist
  363. """
  364. import webnotes.model.utils
  365. return webnotes.model.utils.copy_doclist(doclist, no_copy)