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.
 
 
 
 
 
 

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