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.
 
 
 
 
 
 

406 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. if not d.owner:
  151. d.owner = user
  152. if not d.creation:
  153. d.creation = ts
  154. d.modified_by = user
  155. d.modified = ts
  156. if d.docstatus != 2 and self.to_docstatus >= d.docstatus: # don't update deleted
  157. d.docstatus = self.to_docstatus
  158. def prepare_for_save(self, method):
  159. self.check_if_latest(method)
  160. if method != "cancel":
  161. self.check_links()
  162. self.update_timestamps_and_docstatus()
  163. self.update_parent_info()
  164. def update_parent_info(self):
  165. idx_map = {}
  166. is_local = cint(self.doc.fields.get("__islocal"))
  167. for i, d in enumerate(self.doclist[1:]):
  168. if d.parentfield:
  169. d.parenttype = self.doc.doctype
  170. d.parent = self.doc.name
  171. if not d.idx:
  172. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  173. if is_local:
  174. # if parent is new, all children should be new
  175. d.fields["__islocal"] = 1
  176. idx_map[d.parentfield] = d.idx
  177. def run_method(self, method):
  178. self.make_obj()
  179. if hasattr(self.obj, method):
  180. getattr(self.obj, method)()
  181. if hasattr(self.obj, 'custom_' + method):
  182. getattr(self.obj, 'custom_' + method)()
  183. notify(self.obj, method)
  184. self.set_doclist(self.obj.doclist)
  185. def get_method(self, method):
  186. self.make_obj()
  187. return getattr(self.obj, method, None)
  188. def save_main(self):
  189. try:
  190. self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
  191. except NameError, e:
  192. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  193. # prompt if cancelled
  194. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  195. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  196. webnotes.errprint(webnotes.utils.getTraceback())
  197. raise e
  198. def save_children(self):
  199. child_map = {}
  200. for d in self.children:
  201. if d.fields.get("parent") or d.fields.get("parentfield"):
  202. d.parent = self.doc.name # rename if reqd
  203. d.parenttype = self.doc.doctype
  204. d.save(check_links=False, ignore_fields = self.ignore_fields)
  205. child_map.setdefault(d.doctype, []).append(d.name)
  206. # delete all children in database that are not in the child_map
  207. # get all children types
  208. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  209. for dt in tablefields:
  210. if dt[0] not in self.ignore_children_type:
  211. cnames = child_map.get(dt[0]) or []
  212. if cnames:
  213. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  214. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  215. tuple([self.doc.name, self.doc.doctype] + cnames))
  216. else:
  217. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  218. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  219. def insert(self):
  220. self.doc.fields["__islocal"] = 1
  221. return self.save()
  222. def has_read_perm(self):
  223. return webnotes.has_permission(self.doc.doctype, "read", self.doc)
  224. def save(self, check_links=1):
  225. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  226. self.to_docstatus = 0
  227. self.prepare_for_save("save")
  228. if not self.ignore_validate:
  229. self.run_method('validate')
  230. self.save_main()
  231. self.save_children()
  232. self.run_method('on_update')
  233. else:
  234. self.no_permission_to(_("Write"))
  235. return self
  236. def submit(self):
  237. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  238. self.to_docstatus = 1
  239. self.prepare_for_save("submit")
  240. self.run_method('validate')
  241. self.save_main()
  242. self.save_children()
  243. self.run_method('on_update')
  244. self.run_method('on_submit')
  245. else:
  246. self.no_permission_to(_("Submit"))
  247. return self
  248. def cancel(self):
  249. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  250. self.to_docstatus = 2
  251. self.prepare_for_save("cancel")
  252. self.run_method('before_cancel')
  253. self.save_main()
  254. self.save_children()
  255. self.run_method('on_cancel')
  256. self.check_no_back_links_exist()
  257. else:
  258. self.no_permission_to(_("Cancel"))
  259. return self
  260. def update_after_submit(self):
  261. if self.doc.docstatus != 1:
  262. webnotes.msgprint("Only to called after submit", raise_exception=1)
  263. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  264. self.to_docstatus = 1
  265. self.prepare_for_save("update_after_submit")
  266. self.run_method('before_update_after_submit')
  267. self.save_main()
  268. self.save_children()
  269. self.run_method('on_update_after_submit')
  270. else:
  271. self.no_permission_to(_("Update"))
  272. return self
  273. def delete(self):
  274. webnotes.delete_doc(self.doc.doctype, self.doc.name)
  275. def no_permission_to(self, ptype):
  276. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  277. _("No Permission to ") + ptype, raise_exception=BeanPermissionError)
  278. def check_no_back_links_exist(self):
  279. from webnotes.model.utils import check_if_doc_is_linked
  280. check_if_doc_is_linked(self.doc.doctype, self.doc.name, method="Cancel")
  281. def clone(source_wrapper):
  282. """ make a clone of a document"""
  283. if isinstance(source_wrapper, list):
  284. source_wrapper = Bean(source_wrapper)
  285. new_wrapper = Bean(source_wrapper.doclist.copy())
  286. if new_wrapper.doc.fields.get("amended_from"):
  287. new_wrapper.doc.fields["amended_from"] = None
  288. if new_wrapper.doc.fields.get("amendment_date"):
  289. new_wrapper.doc.fields["amendment_date"] = None
  290. for d in new_wrapper.doclist:
  291. d.fields.update({
  292. "name": None,
  293. "__islocal": 1,
  294. "docstatus": 0,
  295. })
  296. return new_wrapper
  297. def notify(controller, caller_method):
  298. try:
  299. from startup.observers import observer_map
  300. except ImportError:
  301. return
  302. doctype = controller.doc.doctype
  303. def call_observers(key):
  304. if key in observer_map:
  305. observer_list = observer_map[key]
  306. if isinstance(observer_list, basestring):
  307. observer_list = [observer_list]
  308. for observer_method in observer_list:
  309. webnotes.get_method(observer_method)(controller, caller_method)
  310. call_observers("*:*")
  311. call_observers(doctype + ":*")
  312. call_observers("*:" + caller_method)
  313. call_observers(doctype + ":" + caller_method)
  314. # for bc
  315. def getlist(doclist, parentfield):
  316. """
  317. Return child records of a particular type
  318. """
  319. import webnotes.model.utils
  320. return webnotes.model.utils.getlist(doclist, parentfield)
  321. def copy_doclist(doclist, no_copy = []):
  322. """
  323. Make a copy of the doclist
  324. """
  325. import webnotes.model.utils
  326. return webnotes.model.utils.copy_doclist(doclist, no_copy)