Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

524 lignes
15 KiB

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