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.
 
 
 
 
 
 

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