Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

362 строки
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. is_local = cint(self.doc.fields.get("__islocal"))
  158. for i, d in enumerate(self.doclist[1:]):
  159. if d.parentfield:
  160. d.parenttype = self.doc.doctype
  161. d.parent = self.doc.name
  162. if not d.idx:
  163. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  164. if is_local:
  165. # if parent is new, all children should be new
  166. d.fields["__islocal"] = 1
  167. idx_map[d.parentfield] = d.idx
  168. def run_method(self, method):
  169. """
  170. Run a method and custom_method
  171. """
  172. self.make_obj()
  173. if hasattr(self.obj, method):
  174. getattr(self.obj, method)()
  175. if hasattr(self.obj, 'custom_' + method):
  176. getattr(self.obj, 'custom_' + method)()
  177. notify(self.obj, method)
  178. self.set_doclist(self.obj.doclist)
  179. def save_main(self):
  180. """
  181. Save the main doc
  182. """
  183. try:
  184. self.doc.save(cint(self.doc.fields.get('__islocal')))
  185. except NameError, e:
  186. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  187. # prompt if cancelled
  188. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  189. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  190. webnotes.errprint(webnotes.utils.getTraceback())
  191. raise e
  192. def save_children(self):
  193. """
  194. Save Children, with the new parent name
  195. """
  196. child_map = {}
  197. for d in self.children:
  198. if d.fields.get("parent") or d.fields.get("parentfield"):
  199. d.parent = self.doc.name # rename if reqd
  200. d.parenttype = self.doc.doctype
  201. d.save(new = cint(d.fields.get('__islocal')))
  202. child_map.setdefault(d.doctype, []).append(d.name)
  203. # delete all children in database that are not in the child_map
  204. # get all children types
  205. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  206. for dt in tablefields:
  207. cnames = child_map.get(dt[0]) or []
  208. if cnames:
  209. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  210. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  211. tuple([self.doc.name, self.doc.doctype] + cnames))
  212. else:
  213. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  214. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  215. def save(self, check_links=1):
  216. """
  217. Save the list
  218. """
  219. self.prepare_for_save(check_links)
  220. self.run_method('validate')
  221. self.save_main()
  222. self.save_children()
  223. self.run_method('on_update')
  224. def submit(self):
  225. """
  226. Save & Submit - set docstatus = 1, run "on_submit"
  227. """
  228. if self.doc.docstatus != 0:
  229. webnotes.msgprint("Only draft can be submitted", raise_exception=1)
  230. self.to_docstatus = 1
  231. self.save()
  232. self.run_method('on_submit')
  233. def cancel(self):
  234. """
  235. Cancel - set docstatus 2, run "on_cancel"
  236. """
  237. if self.doc.docstatus != 1:
  238. webnotes.msgprint("Only submitted can be cancelled", raise_exception=1)
  239. self.to_docstatus = 2
  240. self.prepare_for_save(1)
  241. self.save_main()
  242. self.save_children()
  243. self.run_method('on_cancel')
  244. def update_after_submit(self):
  245. """
  246. Update after submit - some values changed after submit
  247. """
  248. if self.doc.docstatus != 1:
  249. webnotes.msgprint("Only to called after submit", raise_exception=1)
  250. self.to_docstatus = 1
  251. self.prepare_for_save(1)
  252. self.save_main()
  253. self.save_children()
  254. self.run_method('on_update_after_submit')
  255. # clone
  256. def clone(source_wrapper):
  257. """ Copy previous invoice and change dates"""
  258. if isinstance(source_wrapper, list):
  259. source_wrapper = ModelWrapper(source_wrapper)
  260. new_wrapper = ModelWrapper(source_wrapper.doclist.copy())
  261. new_wrapper.doc.fields.update({
  262. "amended_from": None,
  263. "amendment_date": None,
  264. })
  265. for d in new_wrapper.doclist:
  266. d.fields.update({
  267. "name": None,
  268. "__islocal": 1,
  269. "docstatus": 0,
  270. })
  271. return new_wrapper
  272. def notify(controller, caller_method):
  273. try:
  274. from startup.observers import observer_map
  275. except ImportError:
  276. return
  277. doctype = controller.doc.doctype
  278. def call_observers(key):
  279. if key in observer_map:
  280. observer_list = observer_map[key]
  281. if isinstance(observer_list, basestring):
  282. observer_list = [observer_list]
  283. for observer_method in observer_list:
  284. webnotes.get_method(observer_method)(controller, caller_method)
  285. call_observers("*:*")
  286. call_observers(doctype + ":*")
  287. call_observers("*:" + caller_method)
  288. call_observers(doctype + ":" + caller_method)
  289. # for bc
  290. def getlist(doclist, parentfield):
  291. """
  292. Return child records of a particular type
  293. """
  294. import webnotes.model.utils
  295. return webnotes.model.utils.getlist(doclist, parentfield)
  296. def copy_doclist(doclist, no_copy = []):
  297. """
  298. Make a copy of the doclist
  299. """
  300. import webnotes.model.utils
  301. return webnotes.model.utils.copy_doclist(doclist, no_copy)