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.7 KiB

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 type(dt) is 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" % self.doc.doctype, raise_exception=1)
  112. def check_links(self):
  113. """
  114. Checks integrity of links (throws exception if links are invalid)
  115. """
  116. ref, err_list = {}, []
  117. for d in self.docs:
  118. if not ref.get(d.doctype):
  119. ref[d.doctype] = d.make_link_list()
  120. err_list += d.validate_links(ref[d.doctype])
  121. if err_list:
  122. webnotes.msgprint("""[Link Validation] Could not find the following values: %s.
  123. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1)
  124. def update_timestamps_and_docstatus(self):
  125. """
  126. Update owner, creation, modified_by, modified, docstatus
  127. """
  128. from webnotes.utils import now
  129. ts = now()
  130. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  131. for d in self.docs:
  132. if self.doc.fields.get('__islocal'):
  133. d.owner = user
  134. d.creation = ts
  135. d.modified_by = user
  136. d.modified = ts
  137. if d.docstatus != 2: # don't update deleted
  138. d.docstatus = self.to_docstatus
  139. def prepare_for_save(self, check_links):
  140. """
  141. Set owner, modified etc before saving
  142. """
  143. self.check_if_latest()
  144. self.check_permission()
  145. if check_links:
  146. self.check_links()
  147. self.update_timestamps_and_docstatus()
  148. def run_method(self, method):
  149. """
  150. Run a method and custom_method
  151. """
  152. self.make_obj()
  153. if hasattr(self.obj, method):
  154. getattr(self.obj, method)()
  155. if hasattr(self.obj, 'custom_' + method):
  156. getattr(self.obj, 'custom_' + method)()
  157. trigger(method, self.obj.doc)
  158. self.set_doclist([self.obj.doc] + self.obj.doclist)
  159. def save_main(self):
  160. """
  161. Save the main doc
  162. """
  163. try:
  164. self.doc.save(cint(self.doc.fields.get('__islocal')))
  165. except NameError, e:
  166. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  167. # prompt if cancelled
  168. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  169. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  170. webnotes.errprint(webnotes.utils.getTraceback())
  171. raise e
  172. def save_children(self):
  173. """
  174. Save Children, with the new parent name
  175. """
  176. child_map = {}
  177. for d in self.children:
  178. if (d.fields.has_key('parent') and d.fields.get('parent')) or \
  179. (d.fields.has_key("parentfield") and d.fields.get("parentfield")):
  180. # if d.parent:
  181. d.parent = self.doc.name # rename if reqd
  182. d.parenttype = self.doc.doctype
  183. d.save(new = cint(d.fields.get('__islocal')))
  184. child_map.setdefault(d.doctype, []).append(d.name)
  185. # delete all children in database that are not in the child_map
  186. # get all children types
  187. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  188. for dt in tablefields:
  189. cnames = child_map.get(dt[0]) or []
  190. if cnames:
  191. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  192. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  193. tuple([self.doc.name, self.doc.doctype] + cnames))
  194. else:
  195. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  196. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  197. def save(self, check_links=1):
  198. """
  199. Save the list
  200. """
  201. self.prepare_for_save(check_links)
  202. self.run_method('validate')
  203. self.save_main()
  204. self.save_children()
  205. self.run_method('on_update')
  206. def submit(self):
  207. """
  208. Save & Submit - set docstatus = 1, run "on_submit"
  209. """
  210. if self.doc.docstatus != 0:
  211. webnotes.msgprint("Only draft can be submitted", raise_exception=1)
  212. self.to_docstatus = 1
  213. self.save()
  214. self.run_method('on_submit')
  215. def cancel(self):
  216. """
  217. Cancel - set docstatus 2, run "on_cancel"
  218. """
  219. if self.doc.docstatus != 1:
  220. webnotes.msgprint("Only submitted can be cancelled", raise_exception=1)
  221. self.to_docstatus = 2
  222. self.prepare_for_save(1)
  223. self.save_main()
  224. self.save_children()
  225. self.run_method('on_cancel')
  226. def update_after_submit(self):
  227. """
  228. Update after submit - some values changed after submit
  229. """
  230. if self.doc.docstatus != 1:
  231. webnotes.msgprint("Only to called after submit", raise_exception=1)
  232. self.to_docstatus = 1
  233. self.prepare_for_save(1)
  234. self.save_main()
  235. self.save_children()
  236. self.run_method('on_update_after_submit')
  237. # clone
  238. def clone(source_doclist):
  239. """ Copy previous invoice and change dates"""
  240. from webnotes.model.doc import Document
  241. new_doclist = []
  242. new_parent = Document(fielddata = source_doclist.doc.fields.copy())
  243. new_parent.name = 'Temp/001'
  244. new_parent.fields['__islocal'] = 1
  245. new_parent.fields['docstatus'] = 0
  246. if new_parent.fields.has_key('amended_from'):
  247. new_parent.fields['amended_from'] = None
  248. new_parent.fields['amendment_date'] = None
  249. new_parent.save(1)
  250. new_doclist.append(new_parent)
  251. for d in source_doclist.doclist[1:]:
  252. newd = Document(fielddata = d.fields.copy())
  253. newd.name = None
  254. newd.fields['__islocal'] = 1
  255. newd.fields['docstatus'] = 0
  256. newd.parent = new_parent.name
  257. new_doclist.append(newd)
  258. doclistobj = ModelWrapper()
  259. doclistobj.docs = new_doclist
  260. doclistobj.doc = new_doclist[0]
  261. doclistobj.doclist = new_doclist
  262. doclistobj.children = new_doclist[1:]
  263. doclistobj.save()
  264. return doclistobj
  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)