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.
 
 
 
 
 
 

409 line
12 KiB

  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 _
  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. if isinstance(dt, basestring) and not dn:
  46. dn = dt
  47. if dt and dn:
  48. self.load_from_db(dt, dn)
  49. elif isinstance(dt, list):
  50. self.set_doclist(dt)
  51. elif isinstance(dt, dict):
  52. self.set_doclist([dt])
  53. def load_from_db(self, dt=None, dn=None, prefix='tab'):
  54. """
  55. Load doclist from dt
  56. """
  57. from webnotes.model.doc import Document, getchildren
  58. if not dt: dt = self.doc.doctype
  59. if not dn: dn = self.doc.name
  60. doc = Document(dt, dn, prefix=prefix)
  61. # get all children types
  62. tablefields = webnotes.model.meta.get_table_fields(dt)
  63. # load chilren
  64. doclist = webnotes.doclist([doc,])
  65. for t in tablefields:
  66. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  67. self.set_doclist(doclist)
  68. self.run_method("onload")
  69. def __iter__(self):
  70. return self.doclist.__iter__()
  71. def from_compressed(self, data, docname):
  72. from webnotes.model.utils import expand
  73. self.set_doclist(expand(data))
  74. def set_doclist(self, doclist):
  75. for i, d in enumerate(doclist):
  76. if isinstance(d, dict):
  77. doclist[i] = Document(fielddata=d)
  78. self.doclist = webnotes.doclist(doclist)
  79. self.doc = self.doclist[0]
  80. if self.obj:
  81. self.obj.doclist = self.doclist
  82. self.obj.doc = self.doc
  83. def make_obj(self):
  84. if self.obj:
  85. # update doclist before running any method
  86. self.obj.doclist = self.doclist
  87. return self.obj
  88. self.obj = webnotes.get_obj(doc=self.doc, doclist=self.doclist)
  89. self.obj.bean = self
  90. self.controller = self.obj
  91. return self.obj
  92. def to_dict(self):
  93. return [d.fields for d in self.doclist]
  94. def check_if_latest(self, method="save"):
  95. from webnotes.model.meta import is_single
  96. conflict = False
  97. if not cint(self.doc.fields.get('__islocal')):
  98. if is_single(self.doc.doctype):
  99. modified = webnotes.conn.get_value(self.doc.doctype, self.doc.name, "modified")
  100. if isinstance(modified, list):
  101. modified = modified[0]
  102. if cstr(modified) and cstr(modified) != cstr(self.doc.modified):
  103. conflict = True
  104. else:
  105. tmp = webnotes.conn.sql("""select modified, docstatus from `tab%s`
  106. where name="%s" for update"""
  107. % (self.doc.doctype, self.doc.name), as_dict=True)
  108. if not tmp:
  109. webnotes.msgprint("""This record does not exist. Please refresh.""", raise_exception=1)
  110. modified = cstr(tmp[0].modified)
  111. if modified and modified != cstr(self.doc.modified):
  112. conflict = True
  113. self.check_docstatus_transition(tmp[0].docstatus, method)
  114. if conflict:
  115. webnotes.msgprint(_("Error: Document has been modified after you have opened it") \
  116. + (" (%s, %s). " % (modified, self.doc.modified)) \
  117. + _("Please refresh to get the latest document."), raise_exception=True)
  118. def check_docstatus_transition(self, db_docstatus, method):
  119. valid = {
  120. "save": [0,0],
  121. "submit": [0,1],
  122. "cancel": [1,2],
  123. "update_after_submit": [1,1]
  124. }
  125. labels = {
  126. 0: _("Draft"),
  127. 1: _("Submitted"),
  128. 2: _("Cancelled")
  129. }
  130. if not hasattr(self, "to_docstatus"):
  131. self.to_docstatus = 0
  132. if method != "runserverobj" and [db_docstatus, self.to_docstatus] != valid[method]:
  133. webnotes.msgprint(_("Cannot change from") + ": " + labels[db_docstatus] + " > " + \
  134. labels[self.to_docstatus], raise_exception=DocstatusTransitionError)
  135. def check_links(self):
  136. if self.ignore_check_links:
  137. return
  138. ref, err_list = {}, []
  139. for d in self.doclist:
  140. if not ref.get(d.doctype):
  141. ref[d.doctype] = d.make_link_list()
  142. err_list += d.validate_links(ref[d.doctype])
  143. if err_list:
  144. webnotes.msgprint("""[Link Validation] Could not find the following values: %s.
  145. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1)
  146. def update_timestamps_and_docstatus(self):
  147. from webnotes.utils import now
  148. ts = now()
  149. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  150. for d in self.doclist:
  151. if self.doc.fields.get('__islocal'):
  152. if not d.owner:
  153. d.owner = user
  154. if not d.creation:
  155. d.creation = ts
  156. d.modified_by = user
  157. d.modified = ts
  158. if d.docstatus != 2 and self.to_docstatus >= d.docstatus: # don't update deleted
  159. d.docstatus = self.to_docstatus
  160. def prepare_for_save(self, method):
  161. self.check_if_latest(method)
  162. if method != "cancel":
  163. self.check_links()
  164. self.update_timestamps_and_docstatus()
  165. self.update_parent_info()
  166. def update_parent_info(self):
  167. idx_map = {}
  168. is_local = cint(self.doc.fields.get("__islocal"))
  169. for i, d in enumerate(self.doclist[1:]):
  170. if d.parentfield:
  171. d.parenttype = self.doc.doctype
  172. d.parent = self.doc.name
  173. if not d.idx:
  174. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  175. if is_local:
  176. # if parent is new, all children should be new
  177. d.fields["__islocal"] = 1
  178. idx_map[d.parentfield] = d.idx
  179. def run_method(self, method):
  180. self.make_obj()
  181. if hasattr(self.obj, method):
  182. getattr(self.obj, method)()
  183. if hasattr(self.obj, 'custom_' + method):
  184. getattr(self.obj, 'custom_' + method)()
  185. notify(self.obj, method)
  186. self.doclist = self.obj.doclist
  187. def get_method(self, method):
  188. self.make_obj()
  189. return getattr(self.obj, method, None)
  190. def save_main(self):
  191. try:
  192. self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
  193. except NameError, e:
  194. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  195. # prompt if cancelled
  196. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  197. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  198. webnotes.errprint(webnotes.utils.getTraceback())
  199. raise e
  200. def save_children(self):
  201. child_map = {}
  202. for d in self.doclist[1:]:
  203. if d.fields.get("parent") or d.fields.get("parentfield"):
  204. d.parent = self.doc.name # rename if reqd
  205. d.parenttype = self.doc.doctype
  206. d.save(check_links=False, ignore_fields = self.ignore_fields)
  207. child_map.setdefault(d.doctype, []).append(d.name)
  208. # delete all children in database that are not in the child_map
  209. # get all children types
  210. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  211. for dt in tablefields:
  212. if dt[0] not in self.ignore_children_type:
  213. cnames = child_map.get(dt[0]) or []
  214. if cnames:
  215. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  216. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  217. tuple([self.doc.name, self.doc.doctype] + cnames))
  218. else:
  219. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  220. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  221. def insert(self):
  222. self.doc.fields["__islocal"] = 1
  223. return self.save()
  224. def has_read_perm(self):
  225. return webnotes.has_permission(self.doc.doctype, "read", self.doc)
  226. def save(self, check_links=1):
  227. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", 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.save_main()
  233. self.save_children()
  234. self.run_method('on_update')
  235. else:
  236. self.no_permission_to(_("Write"))
  237. return self
  238. def submit(self):
  239. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  240. self.to_docstatus = 1
  241. self.prepare_for_save("submit")
  242. self.run_method('validate')
  243. self.save_main()
  244. self.save_children()
  245. self.run_method('on_update')
  246. self.run_method('on_submit')
  247. else:
  248. self.no_permission_to(_("Submit"))
  249. return self
  250. def cancel(self):
  251. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  252. self.to_docstatus = 2
  253. self.prepare_for_save("cancel")
  254. self.run_method('before_cancel')
  255. self.save_main()
  256. self.save_children()
  257. self.run_method('on_cancel')
  258. self.check_no_back_links_exist()
  259. else:
  260. self.no_permission_to(_("Cancel"))
  261. return self
  262. def update_after_submit(self):
  263. if self.doc.docstatus != 1:
  264. webnotes.msgprint("Only to called after submit", raise_exception=1)
  265. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  266. self.to_docstatus = 1
  267. self.prepare_for_save("update_after_submit")
  268. self.run_method('before_update_after_submit')
  269. self.save_main()
  270. self.save_children()
  271. self.run_method('on_update_after_submit')
  272. else:
  273. self.no_permission_to(_("Update"))
  274. return self
  275. def delete(self):
  276. webnotes.delete_doc(self.doc.doctype, self.doc.name)
  277. def no_permission_to(self, ptype):
  278. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  279. _("No Permission to ") + ptype, raise_exception=BeanPermissionError)
  280. def check_no_back_links_exist(self):
  281. from webnotes.model.utils import check_if_doc_is_linked
  282. check_if_doc_is_linked(self.doc.doctype, self.doc.name, method="Cancel")
  283. def clone(source_wrapper):
  284. """ make a clone of a document"""
  285. if isinstance(source_wrapper, list):
  286. source_wrapper = Bean(source_wrapper)
  287. new_wrapper = Bean(source_wrapper.doclist.copy())
  288. if new_wrapper.doc.fields.get("amended_from"):
  289. new_wrapper.doc.fields["amended_from"] = None
  290. if new_wrapper.doc.fields.get("amendment_date"):
  291. new_wrapper.doc.fields["amendment_date"] = None
  292. for d in new_wrapper.doclist:
  293. d.fields.update({
  294. "name": None,
  295. "__islocal": 1,
  296. "docstatus": 0,
  297. })
  298. return new_wrapper
  299. def notify(controller, caller_method):
  300. try:
  301. from startup.observers import observer_map
  302. except ImportError:
  303. return
  304. doctype = controller.doc.doctype
  305. def call_observers(key):
  306. if key in observer_map:
  307. observer_list = observer_map[key]
  308. if isinstance(observer_list, basestring):
  309. observer_list = [observer_list]
  310. for observer_method in observer_list:
  311. webnotes.get_method(observer_method)(controller, caller_method)
  312. call_observers("*:*")
  313. call_observers(doctype + ":*")
  314. call_observers("*:" + caller_method)
  315. call_observers(doctype + ":" + caller_method)
  316. # for bc
  317. def getlist(doclist, parentfield):
  318. """
  319. Return child records of a particular type
  320. """
  321. import webnotes.model.utils
  322. return webnotes.model.utils.getlist(doclist, parentfield)
  323. def copy_doclist(doclist, no_copy = []):
  324. """
  325. Make a copy of the doclist
  326. """
  327. import webnotes.model.utils
  328. return webnotes.model.utils.copy_doclist(doclist, no_copy)