Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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