Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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