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

489 строки
14 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd.
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. """
  5. Transactions are defined as collection of classes, a Bean represents collection of Document
  6. objects for a transaction with main and children.
  7. Group actions like save, etc are performed on doclists
  8. """
  9. import webnotes
  10. from webnotes import _, msgprint
  11. from webnotes.utils import cint, cstr, flt
  12. from webnotes.model.doc import Document
  13. class DocstatusTransitionError(webnotes.ValidationError): pass
  14. class BeanPermissionError(webnotes.ValidationError): pass
  15. class TimestampMismatchError(webnotes.ValidationError): pass
  16. class Bean:
  17. """
  18. Collection of Documents with one parent and multiple children
  19. """
  20. def __init__(self, dt=None, dn=None):
  21. self.obj = None
  22. self.ignore_permissions = False
  23. self.ignore_children_type = []
  24. self.ignore_links = False
  25. self.ignore_validate = False
  26. self.ignore_fields = False
  27. self.ignore_mandatory = False
  28. if isinstance(dt, basestring) and not dn:
  29. dn = dt
  30. if dt and dn:
  31. self.load_from_db(dt, dn)
  32. elif isinstance(dt, list):
  33. self.set_doclist(dt)
  34. elif isinstance(dt, dict):
  35. self.set_doclist([dt])
  36. def load_from_db(self, dt=None, dn=None, prefix='tab'):
  37. """
  38. Load doclist from dt
  39. """
  40. from webnotes.model.doc import getchildren
  41. if not dt: dt = self.doc.doctype
  42. if not dn: dn = self.doc.name
  43. doc = Document(dt, dn, prefix=prefix)
  44. # get all children types
  45. tablefields = webnotes.model.meta.get_table_fields(dt)
  46. # load chilren
  47. doclist = webnotes.doclist([doc,])
  48. for t in tablefields:
  49. doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix)
  50. self.set_doclist(doclist)
  51. if dt == dn:
  52. self.convert_type(self.doc)
  53. def __iter__(self):
  54. return self.doclist.__iter__()
  55. @property
  56. def meta(self):
  57. if not hasattr(self, "_meta"):
  58. self._meta = webnotes.get_doctype(self.doc.doctype)
  59. return self._meta
  60. def from_compressed(self, data, docname):
  61. from webnotes.model.utils import expand
  62. self.set_doclist(expand(data))
  63. def set_doclist(self, doclist):
  64. for i, d in enumerate(doclist):
  65. if isinstance(d, dict):
  66. doclist[i] = Document(fielddata=d)
  67. self.doclist = webnotes.doclist(doclist)
  68. self.doc = self.doclist[0]
  69. if self.obj:
  70. self.obj.doclist = self.doclist
  71. self.obj.doc = self.doc
  72. def make_controller(self):
  73. if self.obj:
  74. # update doclist before running any method
  75. self.obj.doclist = self.doclist
  76. return self.obj
  77. self.obj = webnotes.get_obj(doc=self.doc, doclist=self.doclist)
  78. self.obj.bean = self
  79. self.controller = self.obj
  80. return self.obj
  81. def get_controller(self):
  82. return self.make_controller()
  83. def to_dict(self):
  84. return [d.fields for d in self.doclist]
  85. def check_if_latest(self, method="save"):
  86. from webnotes.model.meta import is_single
  87. conflict = False
  88. if not cint(self.doc.fields.get('__islocal')):
  89. if is_single(self.doc.doctype):
  90. modified = webnotes.conn.get_value(self.doc.doctype, self.doc.name, "modified")
  91. if isinstance(modified, list):
  92. modified = modified[0]
  93. if cstr(modified) and cstr(modified) != cstr(self.doc.modified):
  94. conflict = True
  95. else:
  96. tmp = webnotes.conn.sql("""select modified, docstatus from `tab%s`
  97. where name="%s" for update"""
  98. % (self.doc.doctype, self.doc.name), as_dict=True)
  99. if not tmp:
  100. webnotes.msgprint("""This record does not exist. Please refresh.""", raise_exception=1)
  101. modified = cstr(tmp[0].modified)
  102. if modified and modified != cstr(self.doc.modified):
  103. conflict = True
  104. self.check_docstatus_transition(tmp[0].docstatus, method)
  105. if conflict:
  106. webnotes.msgprint(_("Error: Document has been modified after you have opened it") \
  107. + (" (%s, %s). " % (modified, self.doc.modified)) \
  108. + _("Please refresh to get the latest document."), raise_exception=TimestampMismatchError)
  109. def check_docstatus_transition(self, db_docstatus, method):
  110. valid = {
  111. "save": [0,0],
  112. "submit": [0,1],
  113. "cancel": [1,2],
  114. "update_after_submit": [1,1]
  115. }
  116. labels = {
  117. 0: _("Draft"),
  118. 1: _("Submitted"),
  119. 2: _("Cancelled")
  120. }
  121. if not hasattr(self, "to_docstatus"):
  122. self.to_docstatus = 0
  123. if method != "runserverobj" and [db_docstatus, self.to_docstatus] != valid[method]:
  124. webnotes.msgprint(_("Cannot change from") + ": " + labels[db_docstatus] + " > " + \
  125. labels[self.to_docstatus], raise_exception=DocstatusTransitionError)
  126. def check_links(self):
  127. if self.ignore_links:
  128. return
  129. ref, err_list = {}, []
  130. for d in self.doclist:
  131. if not ref.get(d.doctype):
  132. ref[d.doctype] = d.make_link_list()
  133. err_list += d.validate_links(ref[d.doctype])
  134. if err_list:
  135. webnotes.msgprint("""[Link Validation] Could not find the following values: %s.
  136. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1)
  137. def update_timestamps_and_docstatus(self):
  138. from webnotes.utils import now
  139. ts = now()
  140. user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator'
  141. for d in self.doclist:
  142. if self.doc.fields.get('__islocal'):
  143. if not d.owner:
  144. d.owner = user
  145. if not d.creation:
  146. d.creation = ts
  147. d.modified_by = user
  148. d.modified = ts
  149. if d.docstatus != 2 and self.to_docstatus >= int(d.docstatus): # don't update deleted
  150. d.docstatus = self.to_docstatus
  151. def prepare_for_save(self, method):
  152. self.check_if_latest(method)
  153. if method != "cancel":
  154. self.check_links()
  155. self.update_timestamps_and_docstatus()
  156. self.update_parent_info()
  157. def update_parent_info(self):
  158. idx_map = {}
  159. is_local = cint(self.doc.fields.get("__islocal"))
  160. if not webnotes.in_import:
  161. parentfields = [d.fieldname for d in self.meta.get({"doctype": "DocField", "fieldtype": "Table"})]
  162. for i, d in enumerate(self.doclist[1:]):
  163. if d.parentfield:
  164. if not webnotes.in_import:
  165. if not d.parentfield in parentfields:
  166. webnotes.msgprint("Bad parentfield %s" % d.parentfield,
  167. raise_exception=True)
  168. d.parenttype = self.doc.doctype
  169. d.parent = self.doc.name
  170. if not d.idx:
  171. d.idx = idx_map.setdefault(d.parentfield, 0) + 1
  172. else:
  173. d.idx = cint(d.idx)
  174. if is_local:
  175. # if parent is new, all children should be new
  176. d.fields["__islocal"] = 1
  177. d.name = None
  178. idx_map[d.parentfield] = d.idx
  179. def run_method(self, method, *args, **kwargs):
  180. self.make_controller()
  181. if hasattr(self.controller, method):
  182. getattr(self.controller, method)(*args, **kwargs)
  183. if hasattr(self.controller, 'custom_' + method):
  184. getattr(self.controller, 'custom_' + method)(*args, **kwargs)
  185. notify(self.controller, method)
  186. self.set_doclist(self.controller.doclist)
  187. def get_method(self, method):
  188. self.make_controller()
  189. return getattr(self.controller, method, None)
  190. def save_main(self):
  191. try:
  192. self.doc.save(check_links = False, ignore_fields = self.ignore_fields)
  193. except NameError, e:
  194. webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name))
  195. # prompt if cancelled
  196. if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2:
  197. webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name))
  198. webnotes.errprint(webnotes.utils.getTraceback())
  199. raise e
  200. def save_children(self):
  201. child_map = {}
  202. for d in self.doclist[1:]:
  203. if d.fields.get("parent") or d.fields.get("parentfield"):
  204. d.parent = self.doc.name # rename if reqd
  205. d.parenttype = self.doc.doctype
  206. d.save(check_links=False, ignore_fields = self.ignore_fields)
  207. child_map.setdefault(d.doctype, []).append(d.name)
  208. # delete all children in database that are not in the child_map
  209. # get all children types
  210. tablefields = webnotes.model.meta.get_table_fields(self.doc.doctype)
  211. for dt in tablefields:
  212. if dt[0] not in self.ignore_children_type:
  213. cnames = child_map.get(dt[0]) or []
  214. if cnames:
  215. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s and
  216. name not in (%s)""" % (dt[0], '%s', '%s', ','.join(['%s'] * len(cnames))),
  217. tuple([self.doc.name, self.doc.doctype] + cnames))
  218. else:
  219. webnotes.conn.sql("""delete from `tab%s` where parent=%s and parenttype=%s""" \
  220. % (dt[0], '%s', '%s'), (self.doc.name, self.doc.doctype))
  221. def insert(self):
  222. self.doc.fields["__islocal"] = 1
  223. self.set_defaults()
  224. if webnotes.in_test:
  225. if self.meta.get_field("naming_series"):
  226. self.doc.naming_series = "_T-" + self.doc.doctype + "-"
  227. return self.save()
  228. def insert_or_update(self):
  229. if webnotes.conn.exists( self.doc.doctype, self.doc.name):
  230. return self.save()
  231. else:
  232. return self.insert()
  233. def set_defaults(self):
  234. if webnotes.in_import:
  235. return
  236. new_docs = {}
  237. new_doclist = []
  238. for d in self.doclist:
  239. if not d.doctype in new_docs:
  240. new_docs[d.doctype] = webnotes.new_doc(d.doctype)
  241. newd = webnotes.doc(new_docs[d.doctype].fields.copy())
  242. newd.fields.update(d.fields)
  243. new_doclist.append(newd)
  244. self.set_doclist(new_doclist)
  245. def has_read_perm(self):
  246. return webnotes.has_permission(self.doc.doctype, "read", self.doc)
  247. def save(self, check_links=1):
  248. perm_to_check = "write"
  249. if self.doc.fields.get("__islocal"):
  250. perm_to_check = "create"
  251. if not self.doc.owner:
  252. self.doc.owner = webnotes.session.user
  253. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, perm_to_check, self.doc):
  254. self.to_docstatus = 0
  255. self.prepare_for_save("save")
  256. if not self.ignore_validate:
  257. self.run_method('validate')
  258. if not self.ignore_mandatory:
  259. self.check_mandatory()
  260. self.save_main()
  261. self.save_children()
  262. self.run_method('on_update')
  263. else:
  264. self.no_permission_to(_(perm_to_check.title()))
  265. return self
  266. def submit(self):
  267. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc):
  268. self.to_docstatus = 1
  269. self.prepare_for_save("submit")
  270. self.run_method('validate')
  271. self.check_mandatory()
  272. self.save_main()
  273. self.save_children()
  274. self.run_method('on_update')
  275. self.run_method('on_submit')
  276. else:
  277. self.no_permission_to(_("Submit"))
  278. return self
  279. def cancel(self):
  280. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc):
  281. self.to_docstatus = 2
  282. self.prepare_for_save("cancel")
  283. self.run_method('before_cancel')
  284. self.save_main()
  285. self.save_children()
  286. self.run_method('on_cancel')
  287. self.check_no_back_links_exist()
  288. else:
  289. self.no_permission_to(_("Cancel"))
  290. return self
  291. def update_after_submit(self):
  292. if self.doc.docstatus != 1:
  293. webnotes.msgprint("Only to called after submit", raise_exception=1)
  294. if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc):
  295. self.to_docstatus = 1
  296. self.prepare_for_save("update_after_submit")
  297. self.run_method('before_update_after_submit')
  298. self.save_main()
  299. self.save_children()
  300. self.run_method('on_update_after_submit')
  301. else:
  302. self.no_permission_to(_("Update"))
  303. return self
  304. def delete(self):
  305. webnotes.delete_doc(self.doc.doctype, self.doc.name)
  306. def no_permission_to(self, ptype):
  307. webnotes.msgprint(("%s (%s): " % (self.doc.name, _(self.doc.doctype))) + \
  308. _("No Permission to ") + ptype, raise_exception=BeanPermissionError)
  309. def check_no_back_links_exist(self):
  310. from webnotes.model.utils import check_if_doc_is_linked
  311. check_if_doc_is_linked(self.doc.doctype, self.doc.name, method="Cancel")
  312. def check_mandatory(self):
  313. missing = []
  314. for doc in self.doclist:
  315. for df in self.meta:
  316. if df.doctype=="DocField" and df.reqd and df.parent==doc.doctype and df.fieldname!="naming_series":
  317. msg = ""
  318. if df.fieldtype == "Table":
  319. if not self.doclist.get({"parentfield": df.fieldname}):
  320. msg = _("Error") + ": " + _("Data missing in table") + ": " + _(df.label)
  321. elif doc.fields.get(df.fieldname) is None:
  322. msg = _("Error") + ": "
  323. if doc.parentfield:
  324. msg += _("Row") + (" # %s: " % (doc.idx,))
  325. msg += _("Value missing for") + ": " + _(df.label)
  326. if msg:
  327. missing.append([msg, df.fieldname])
  328. if missing:
  329. for msg, fieldname in missing:
  330. msgprint(msg)
  331. raise webnotes.MandatoryError, ", ".join([fieldname for msg, fieldname in missing])
  332. def convert_type(self, doc):
  333. if doc.doctype==doc.name and doc.doctype!="DocType":
  334. for df in self.meta.get({"doctype": "DocField", "parent": doc.doctype}):
  335. if df.fieldtype in ("Int", "Check"):
  336. doc.fields[df.fieldname] = cint(doc.fields.get(df.fieldname))
  337. elif df.fieldtype in ("Float", "Currency"):
  338. doc.fields[df.fieldname] = flt(doc.fields.get(df.fieldname))
  339. doc.docstatus = cint(doc.docstatus)
  340. def clone(source_wrapper):
  341. """ make a clone of a document"""
  342. if isinstance(source_wrapper, list):
  343. source_wrapper = Bean(source_wrapper)
  344. new_wrapper = Bean(source_wrapper.doclist.copy())
  345. if new_wrapper.doc.fields.get("amended_from"):
  346. new_wrapper.doc.fields["amended_from"] = None
  347. if new_wrapper.doc.fields.get("amendment_date"):
  348. new_wrapper.doc.fields["amendment_date"] = None
  349. for d in new_wrapper.doclist:
  350. d.fields.update({
  351. "name": None,
  352. "__islocal": 1,
  353. "docstatus": 0,
  354. })
  355. return new_wrapper
  356. def notify(controller, caller_method):
  357. try:
  358. from startup.observers import observer_map
  359. except ImportError:
  360. return
  361. doctype = controller.doc.doctype
  362. def call_observers(key):
  363. if key in observer_map:
  364. observer_list = observer_map[key]
  365. if isinstance(observer_list, basestring):
  366. observer_list = [observer_list]
  367. for observer_method in observer_list:
  368. webnotes.get_method(observer_method)(controller, caller_method)
  369. call_observers("*:*")
  370. call_observers(doctype + ":*")
  371. call_observers("*:" + caller_method)
  372. call_observers(doctype + ":" + caller_method)
  373. # for bc
  374. def getlist(doclist, parentfield):
  375. """
  376. Return child records of a particular type
  377. """
  378. import webnotes.model.utils
  379. return webnotes.model.utils.getlist(doclist, parentfield)
  380. def copy_doclist(doclist, no_copy = []):
  381. """
  382. Make a copy of the doclist
  383. """
  384. import webnotes.model.utils
  385. return webnotes.model.utils.copy_doclist(doclist, no_copy)