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.
 
 
 
 
 
 

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