Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

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