您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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