25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

wrapper.py 10 KiB

12 yıl önce
12 yıl önce
12 yıl önce
12 yıl önce
12 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 import _
  30. from webnotes.utils import cint
  31. from webnotes.model.doc import Document
  32. class ModelWrapper:
  33. """
  34. Collection of Documents with one parent and multiple children
  35. """
  36. def __init__(self, dt=None, dn=None):
  37. self.docs = []
  38. self.obj = None
  39. self.to_docstatus = 0
  40. self.ignore_permissions = 0
  41. if isinstance(dt, basestring) and not dn:
  42. dn = dt
  43. if dt and dn:
  44. self.load_from_db(dt, dn)
  45. elif isinstance(dt, list):
  46. self.set_doclist(dt)
  47. def load_from_db(self, dt=None, dn=None, prefix='tab'):
  48. """
  49. Load doclist from dt
  50. """
  51. from webnotes.model.doc import Document, getchildren
  52. if not dt: dt = self.doc.doctype
  53. if not dn: dn = self.doc.name
  54. doc = Document(dt, dn, prefix=prefix)
  55. # get all children types
  56. tablefields = webnotes.model.meta.get_table_fields(dt)
  57. # load chilren
  58. doclist = webnotes.doclist([doc,])
  59. for t in tablefields:
  60. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  61. self.set_doclist(doclist)
  62. self.run_method("onload")
  63. def __iter__(self):
  64. """
  65. Make this iterable
  66. """
  67. return self.docs.__iter__()
  68. def from_compressed(self, data, docname):
  69. """
  70. Expand called from client
  71. """
  72. from webnotes.model.utils import expand
  73. self.docs = expand(data)
  74. self.set_doclist(self.docs)
  75. def set_doclist(self, docs):
  76. for i, d in enumerate(docs):
  77. if isinstance(d, dict):
  78. docs[i] = Document(fielddata=d)
  79. self.docs = self.doclist = webnotes.doclist(docs)
  80. self.doc, self.children = self.doclist[0], self.doclist[1:]
  81. if self.obj:
  82. self.obj.doclist = self.doclist
  83. self.obj.doc = self.doc
  84. def make_obj(self):
  85. """
  86. Create a DocType object
  87. """
  88. if self.obj: return self.obj
  89. from webnotes.model.code import get_obj
  90. self.obj = get_obj(doc=self.doc, doclist=self.doclist)
  91. return self.obj
  92. def to_dict(self):
  93. """
  94. return as a list of dictionaries
  95. """
  96. return [d.fields for d in self.docs]
  97. def check_if_latest(self):
  98. """
  99. Raises exception if the modified time is not the same as in the database
  100. """
  101. from webnotes.model.meta import is_single
  102. if (not is_single(self.doc.doctype)) and (not cint(self.doc.fields.get('__islocal'))):
  103. tmp = webnotes.conn.sql("""
  104. SELECT modified FROM `tab%s` WHERE name="%s" for update"""
  105. % (self.doc.doctype, self.doc.name))
  106. if not tmp:
  107. webnotes.msgprint("""This record does not exist. Please refresh.""", raise_exception=1)
  108. if tmp and str(tmp[0][0]) != str(self.doc.modified):
  109. webnotes.msgprint("""
  110. Document has been modified after you have opened it.
  111. To maintain the integrity of the data, you will not be able to save your changes.
  112. Please refresh this document. [%s/%s]""" % (tmp[0][0], self.doc.modified), 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. from webnotes.utils import now
  127. ts = now()
  128. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  129. for d in self.docs:
  130. if self.doc.fields.get('__islocal'):
  131. d.owner = user
  132. d.creation = ts
  133. d.modified_by = user
  134. d.modified = ts
  135. if d.docstatus != 2 and self.to_docstatus >= d.docstatus: # don't update deleted
  136. d.docstatus = self.to_docstatus
  137. def prepare_for_save(self, check_links):
  138. self.check_if_latest()
  139. if check_links:
  140. self.check_links()
  141. self.update_timestamps_and_docstatus()
  142. self.update_parent_info()
  143. def update_parent_info(self):
  144. idx_map = {}
  145. is_local = cint(self.doc.fields.get("__islocal"))
  146. for i, d in enumerate(self.doclist[1:]):
  147. if d.parentfield:
  148. d.parenttype = self.doc.doctype
  149. d.parent = self.doc.name
  150. if not d.idx:
  151. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  152. if is_local:
  153. # if parent is new, all children should be new
  154. d.fields["__islocal"] = 1
  155. idx_map[d.parentfield] = d.idx
  156. def run_method(self, method):
  157. self.make_obj()
  158. if hasattr(self.obj, method):
  159. getattr(self.obj, method)()
  160. if hasattr(self.obj, 'custom_' + method):
  161. getattr(self.obj, 'custom_' + method)()
  162. notify(self.obj, method)
  163. self.set_doclist(self.obj.doclist)
  164. def save_main(self):
  165. try:
  166. self.doc.save(cint(self.doc.fields.get('__islocal')))
  167. except NameError, e:
  168. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  169. # prompt if cancelled
  170. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  171. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  172. webnotes.errprint(webnotes.utils.getTraceback())
  173. raise e
  174. def save_children(self):
  175. child_map = {}
  176. for d in self.children:
  177. if d.fields.get("parent") or d.fields.get("parentfield"):
  178. d.parent = self.doc.name # rename if reqd
  179. d.parenttype = self.doc.doctype
  180. d.save(new = cint(d.fields.get('__islocal')))
  181. child_map.setdefault(d.doctype, []).append(d.name)
  182. # delete all children in database that are not in the child_map
  183. # get all children types
  184. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  185. for dt in tablefields:
  186. cnames = child_map.get(dt[0]) or []
  187. if cnames:
  188. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  189. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  190. tuple([self.doc.name, self.doc.doctype] + cnames))
  191. else:
  192. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  193. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  194. def insert(self):
  195. self.doc.fields["__islocal"] = 1
  196. return self.save()
  197. def save(self, check_links=1):
  198. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  199. self.prepare_for_save(check_links)
  200. self.run_method('validate')
  201. self.save_main()
  202. self.save_children()
  203. self.run_method('on_update')
  204. else:
  205. self.no_permission_to(_("Write"))
  206. return self
  207. def submit(self):
  208. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  209. if self.doc.docstatus != 0:
  210. webnotes.msgprint("Only draft can be submitted", raise_exception=1)
  211. self.to_docstatus = 1
  212. self.save()
  213. self.run_method('on_submit')
  214. else:
  215. self.no_permission_to(_("Submit"))
  216. return self
  217. def cancel(self):
  218. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  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. else:
  227. self.no_permission_to(_("Cancel"))
  228. return self
  229. def update_after_submit(self):
  230. if self.doc.docstatus != 1:
  231. webnotes.msgprint("Only to called after submit", raise_exception=1)
  232. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  233. self.to_docstatus = 1
  234. self.prepare_for_save(1)
  235. self.save_main()
  236. self.save_children()
  237. self.run_method('on_update_after_submit')
  238. else:
  239. self.no_permission_to(_("Update"))
  240. return self
  241. def no_permission_to(self, ptype):
  242. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  243. _("No Permission to ") + ptype, raise_exception=True)
  244. # clone
  245. def clone(source_wrapper):
  246. """ Copy previous invoice and change dates"""
  247. if isinstance(source_wrapper, list):
  248. source_wrapper = ModelWrapper(source_wrapper)
  249. new_wrapper = ModelWrapper(source_wrapper.doclist.copy())
  250. new_wrapper.doc.fields.update({
  251. "amended_from": None,
  252. "amendment_date": None,
  253. })
  254. for d in new_wrapper.doclist:
  255. d.fields.update({
  256. "name": None,
  257. "__islocal": 1,
  258. "docstatus": 0,
  259. })
  260. return new_wrapper
  261. def notify(controller, caller_method):
  262. try:
  263. from startup.observers import observer_map
  264. except ImportError:
  265. return
  266. doctype = controller.doc.doctype
  267. def call_observers(key):
  268. if key in observer_map:
  269. observer_list = observer_map[key]
  270. if isinstance(observer_list, basestring):
  271. observer_list = [observer_list]
  272. for observer_method in observer_list:
  273. webnotes.get_method(observer_method)(controller, caller_method)
  274. call_observers("*:*")
  275. call_observers(doctype + ":*")
  276. call_observers("*:" + caller_method)
  277. call_observers(doctype + ":" + caller_method)
  278. # for bc
  279. def getlist(doclist, parentfield):
  280. """
  281. Return child records of a particular type
  282. """
  283. import webnotes.model.utils
  284. return webnotes.model.utils.getlist(doclist, parentfield)
  285. def copy_doclist(doclist, no_copy = []):
  286. """
  287. Make a copy of the doclist
  288. """
  289. import webnotes.model.utils
  290. return webnotes.model.utils.copy_doclist(doclist, no_copy)