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.

wrapper.py 9.6 KiB

12 vuotta sitten
12 vuotta sitten
12 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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.children)
  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 tmp and str(tmp[0][0]) != str(self.doc.modified):
  102. webnotes.msgprint("""
  103. Document has been modified after you have opened it.
  104. To maintain the integrity of the data, you will not be able to save your changes.
  105. Please refresh this document. [%s/%s]""" % (tmp[0][0], self.doc.modified), raise_exception=1)
  106. def check_permission(self):
  107. """
  108. Raises exception if permission is not valid
  109. """
  110. if not self.doc.check_perm(verbose=1):
  111. webnotes.msgprint("Not enough permission to save %s" %
  112. self.doc.doctype, raise_exception=1)
  113. def check_links(self):
  114. """
  115. Checks integrity of links (throws exception if links are invalid)
  116. """
  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. """
  127. Update owner, creation, modified_by, modified, docstatus
  128. """
  129. from webnotes.utils import now
  130. ts = now()
  131. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  132. for d in self.docs:
  133. if self.doc.fields.get('__islocal'):
  134. d.owner = user
  135. d.creation = ts
  136. d.modified_by = user
  137. d.modified = ts
  138. if d.docstatus != 2: # don't update deleted
  139. d.docstatus = self.to_docstatus
  140. def prepare_for_save(self, check_links):
  141. """
  142. Set owner, modified etc before saving
  143. """
  144. self.check_if_latest()
  145. self.check_permission()
  146. if check_links:
  147. self.check_links()
  148. self.update_timestamps_and_docstatus()
  149. self.update_parent_info()
  150. def update_parent_info(self):
  151. idx_map = {}
  152. for i, d in enumerate(self.doclist[1:]):
  153. if d.parentfield:
  154. d.parenttype = self.doc.doctype
  155. d.parent = self.doc.name
  156. if not d.idx:
  157. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  158. idx_map[d.parentfield] = d.idx
  159. def run_method(self, method):
  160. """
  161. Run a method and custom_method
  162. """
  163. self.make_obj()
  164. if hasattr(self.obj, method):
  165. getattr(self.obj, method)()
  166. if hasattr(self.obj, 'custom_' + method):
  167. getattr(self.obj, 'custom_' + method)()
  168. trigger(method, self.obj.doc)
  169. self.set_doclist([self.obj.doc] + self.obj.doclist)
  170. def save_main(self):
  171. """
  172. Save the main doc
  173. """
  174. try:
  175. self.doc.save(cint(self.doc.fields.get('__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. child_map = {}
  188. for d in self.children:
  189. if (d.fields.has_key('parent') and d.fields.get('parent')) or \
  190. (d.fields.has_key("parentfield") and d.fields.get("parentfield")):
  191. # if d.parent:
  192. d.parent = self.doc.name # rename if reqd
  193. d.parenttype = self.doc.doctype
  194. d.save(new = cint(d.fields.get('__islocal')))
  195. child_map.setdefault(d.doctype, []).append(d.name)
  196. # delete all children in database that are not in the child_map
  197. # get all children types
  198. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  199. for dt in tablefields:
  200. cnames = child_map.get(dt[0]) or []
  201. if cnames:
  202. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  203. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  204. tuple([self.doc.name, self.doc.doctype] + cnames))
  205. else:
  206. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  207. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  208. def save(self, check_links=1):
  209. """
  210. Save the list
  211. """
  212. self.prepare_for_save(check_links)
  213. self.run_method('validate')
  214. self.save_main()
  215. self.save_children()
  216. self.run_method('on_update')
  217. def submit(self):
  218. """
  219. Save & Submit - set docstatus = 1, run "on_submit"
  220. """
  221. if self.doc.docstatus != 0:
  222. webnotes.msgprint("Only draft can be submitted", raise_exception=1)
  223. self.to_docstatus = 1
  224. self.save()
  225. self.run_method('on_submit')
  226. def cancel(self):
  227. """
  228. Cancel - set docstatus 2, run "on_cancel"
  229. """
  230. if self.doc.docstatus != 1:
  231. webnotes.msgprint("Only submitted can be cancelled", raise_exception=1)
  232. self.to_docstatus = 2
  233. self.prepare_for_save(1)
  234. self.save_main()
  235. self.save_children()
  236. self.run_method('on_cancel')
  237. def update_after_submit(self):
  238. """
  239. Update after submit - some values changed after submit
  240. """
  241. if self.doc.docstatus != 1:
  242. webnotes.msgprint("Only to called after submit", raise_exception=1)
  243. self.to_docstatus = 1
  244. self.prepare_for_save(1)
  245. self.save_main()
  246. self.save_children()
  247. self.run_method('on_update_after_submit')
  248. # clone
  249. def clone(source_wrapper):
  250. """ Copy previous invoice and change dates"""
  251. if isinstance(source_wrapper, list):
  252. source_wrapper = ModelWrapper(source_wrapper)
  253. new_wrapper = ModelWrapper(source_wrapper.doclist.copy())
  254. new_wrapper.doc.fields.update({
  255. "amended_from": None,
  256. "amendment_date": None,
  257. })
  258. for d in new_wrapper.doclist:
  259. d.fields.update({
  260. "name": None,
  261. "__islocal": 1,
  262. "docstatus": 0,
  263. })
  264. return new_wrapper
  265. def trigger(method, doc):
  266. """trigger doctype events"""
  267. try:
  268. import startup.event_handlers
  269. except ImportError:
  270. return
  271. if hasattr(startup.event_handlers, method):
  272. getattr(startup.event_handlers, method)(doc)
  273. if hasattr(startup.event_handlers, 'doclist_all'):
  274. startup.event_handlers.doclist_all(doc, method)
  275. # for bc
  276. def getlist(doclist, parentfield):
  277. """
  278. Return child records of a particular type
  279. """
  280. import webnotes.model.utils
  281. return webnotes.model.utils.getlist(doclist, parentfield)
  282. def copy_doclist(doclist, no_copy = []):
  283. """
  284. Make a copy of the doclist
  285. """
  286. import webnotes.model.utils
  287. return webnotes.model.utils.copy_doclist(doclist, no_copy)