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

1016 строки
31 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import frappe
  5. from frappe import _, msgprint
  6. from frappe.utils import flt, cstr, now, get_datetime_str
  7. from frappe.utils.background_jobs import enqueue
  8. from frappe.model.base_document import BaseDocument, get_controller
  9. from frappe.model.naming import set_new_name
  10. from werkzeug.exceptions import NotFound, Forbidden
  11. import hashlib, json
  12. from frappe.model import optional_fields
  13. # once_only validation
  14. # methods
  15. def get_doc(arg1, arg2=None):
  16. """returns a frappe.model.Document object.
  17. :param arg1: Document dict or DocType name.
  18. :param arg2: [optional] document name.
  19. There are two ways to call `get_doc`
  20. # will fetch the latest user object (with child table) from the database
  21. user = get_doc("User", "test@example.com")
  22. # create a new object
  23. user = get_doc({
  24. "doctype":"User"
  25. "email_id": "test@example.com",
  26. "user_roles: [
  27. {"role": "System Manager"}
  28. ]
  29. })
  30. """
  31. if isinstance(arg1, BaseDocument):
  32. return arg1
  33. elif isinstance(arg1, basestring):
  34. doctype = arg1
  35. else:
  36. doctype = arg1.get("doctype")
  37. controller = get_controller(doctype)
  38. if controller:
  39. return controller(arg1, arg2)
  40. raise ImportError, arg1
  41. class Document(BaseDocument):
  42. """All controllers inherit from `Document`."""
  43. def __init__(self, arg1, arg2=None):
  44. """Constructor.
  45. :param arg1: DocType name as string or document **dict**
  46. :param arg2: Document name, if `arg1` is DocType name.
  47. If DocType name and document name are passed, the object will load
  48. all values (including child documents) from the database.
  49. """
  50. self.doctype = self.name = None
  51. self._default_new_docs = {}
  52. self.flags = frappe._dict()
  53. if arg1 and isinstance(arg1, basestring):
  54. if not arg2:
  55. # single
  56. self.doctype = self.name = arg1
  57. else:
  58. self.doctype = arg1
  59. if isinstance(arg2, dict):
  60. # filter
  61. self.name = frappe.db.get_value(arg1, arg2, "name")
  62. if self.name is None:
  63. frappe.throw(_("{0} {1} not found").format(_(arg1), arg2), frappe.DoesNotExistError)
  64. else:
  65. self.name = arg2
  66. self.load_from_db()
  67. elif isinstance(arg1, dict):
  68. super(Document, self).__init__(arg1)
  69. self.init_valid_columns()
  70. else:
  71. # incorrect arguments. let's not proceed.
  72. raise frappe.DataError("Document({0}, {1})".format(arg1, arg2))
  73. def reload(self):
  74. """Reload document from database"""
  75. self.load_from_db()
  76. def load_from_db(self):
  77. """Load document and children from database and create properties
  78. from fields"""
  79. if not getattr(self, "_metaclass", False) and self.meta.issingle:
  80. single_doc = frappe.db.get_singles_dict(self.doctype)
  81. if not single_doc:
  82. single_doc = frappe.new_doc(self.doctype).as_dict()
  83. single_doc["name"] = self.doctype
  84. del single_doc["__islocal"]
  85. super(Document, self).__init__(single_doc)
  86. self.init_valid_columns()
  87. self._fix_numeric_types()
  88. else:
  89. d = frappe.db.get_value(self.doctype, self.name, "*", as_dict=1)
  90. if not d:
  91. frappe.throw(_("{0} {1} not found").format(_(self.doctype), self.name), frappe.DoesNotExistError)
  92. super(Document, self).__init__(d)
  93. if self.name=="DocType" and self.doctype=="DocType":
  94. from frappe.model.meta import doctype_table_fields
  95. table_fields = doctype_table_fields
  96. else:
  97. table_fields = self.meta.get_table_fields()
  98. for df in table_fields:
  99. children = frappe.db.get_values(df.options,
  100. {"parent": self.name, "parenttype": self.doctype, "parentfield": df.fieldname},
  101. "*", as_dict=True, order_by="idx asc")
  102. if children:
  103. self.set(df.fieldname, children)
  104. else:
  105. self.set(df.fieldname, [])
  106. # sometimes __setup__ can depend on child values, hence calling again at the end
  107. if hasattr(self, "__setup__"):
  108. self.__setup__()
  109. def get_latest(self):
  110. if not getattr(self, "latest", None):
  111. self.latest = frappe.get_doc(self.doctype, self.name)
  112. return self.latest
  113. def check_permission(self, permtype, permlabel=None):
  114. """Raise `frappe.PermissionError` if not permitted"""
  115. if not self.has_permission(permtype):
  116. self.raise_no_permission_to(permlabel or permtype)
  117. def has_permission(self, permtype="read", verbose=False):
  118. """Call `frappe.has_permission` if `self.flags.ignore_permissions`
  119. is not set.
  120. :param permtype: one of `read`, `write`, `submit`, `cancel`, `delete`"""
  121. if self.flags.ignore_permissions:
  122. return True
  123. return frappe.has_permission(self.doctype, permtype, self, verbose=verbose)
  124. def has_website_permission(self, permtype="read", verbose=False):
  125. """Call `frappe.has_website_permission` if `self.flags.ignore_permissions`
  126. is not set.
  127. :param permtype: one of `read`, `write`, `submit`, `cancel`, `delete`"""
  128. if self.flags.ignore_permissions:
  129. return True
  130. return (frappe.has_website_permission(self.doctype, permtype, self, verbose=verbose)
  131. or self.has_permission(permtype, verbose=verbose))
  132. def raise_no_permission_to(self, perm_type):
  133. """Raise `frappe.PermissionError`."""
  134. msg = _("No permission to {0} {1} {2}".format(perm_type, self.doctype, self.name or ""))
  135. frappe.msgprint(msg)
  136. raise frappe.PermissionError(msg)
  137. def lock(self):
  138. '''Will set docstatus to 3 + the current docstatus and mark it as queued
  139. 3 = queued for saving
  140. 4 = queued for submission
  141. 5 = queued for cancellation
  142. '''
  143. self.db_set('docstatus', 3 + self.docstatus, update_modified = False)
  144. def unlock(self):
  145. '''set the original docstatus at the time it was locked in the controller'''
  146. current_docstatus = self.db_get('docstatus') - 4
  147. if current_docstatus < 0:
  148. current_docstatus = 0
  149. self.db_set('docstatus', current_docstatus, update_modified = False)
  150. def insert(self, ignore_permissions=None):
  151. """Insert the document in the database (as a new document).
  152. This will check for user permissions and execute `before_insert`,
  153. `validate`, `on_update`, `after_insert` methods if they are written.
  154. :param ignore_permissions: Do not check permissions if True."""
  155. if self.flags.in_print:
  156. return
  157. if ignore_permissions!=None:
  158. self.flags.ignore_permissions = ignore_permissions
  159. self.set("__islocal", True)
  160. self.check_permission("create")
  161. self._set_defaults()
  162. self.set_user_and_timestamp()
  163. self.set_docstatus()
  164. self.check_if_latest()
  165. self.run_method("before_insert")
  166. self.set_new_name()
  167. self.set_parent_in_children()
  168. self.validate_higher_perm_levels()
  169. self.flags.in_insert = True
  170. self.run_before_save_methods()
  171. self._validate()
  172. self.set_docstatus()
  173. self.flags.in_insert = False
  174. # run validate, on update etc.
  175. # parent
  176. if getattr(self.meta, "issingle", 0):
  177. self.update_single(self.get_valid_dict())
  178. else:
  179. self.db_insert()
  180. # children
  181. for d in self.get_all_children():
  182. d.db_insert()
  183. self.run_method("after_insert")
  184. self.flags.in_insert = True
  185. self.run_post_save_methods()
  186. self.flags.in_insert = False
  187. # delete __islocal
  188. if hasattr(self, "__islocal"):
  189. delattr(self, "__islocal")
  190. return self
  191. def save(self, *args, **kwargs):
  192. """Wrapper for _save"""
  193. return self._save(*args, **kwargs)
  194. def _save(self, ignore_permissions=None):
  195. """Save the current document in the database in the **DocType**'s table or
  196. `tabSingles` (for single types).
  197. This will check for user permissions and execute
  198. `validate` before updating, `on_update` after updating triggers.
  199. :param ignore_permissions: Do not check permissions if True."""
  200. if self.flags.in_print:
  201. return
  202. if ignore_permissions!=None:
  203. self.flags.ignore_permissions = ignore_permissions
  204. if self.get("__islocal") or not self.get("name"):
  205. self.insert()
  206. return
  207. self.check_permission("write", "save")
  208. self.set_user_and_timestamp()
  209. self.set_docstatus()
  210. self.check_if_latest()
  211. self.set_parent_in_children()
  212. self.validate_higher_perm_levels()
  213. self.run_before_save_methods()
  214. if self._action != "cancel":
  215. self._validate()
  216. if self._action == "update_after_submit":
  217. self.validate_update_after_submit()
  218. self.set_docstatus()
  219. # parent
  220. if self.meta.issingle:
  221. self.update_single(self.get_valid_dict())
  222. else:
  223. self.db_update()
  224. self.update_children()
  225. self.run_post_save_methods()
  226. return self
  227. def update_children(self):
  228. '''update child tables'''
  229. for df in self.meta.get_table_fields():
  230. self.update_child_table(df.fieldname, df)
  231. def update_child_table(self, fieldname, df=None):
  232. '''sync child table for given fieldname'''
  233. rows = []
  234. if not df:
  235. df = self.meta.get_field(fieldname)
  236. for d in self.get(df.fieldname):
  237. d.db_update()
  238. rows.append(d.name)
  239. if df.options in (self.flags.ignore_children_type or []):
  240. # do not delete rows for this because of flags
  241. # hack for docperm :(
  242. return
  243. if rows:
  244. # delete rows that do not match the ones in the
  245. # document
  246. frappe.db.sql("""delete from `tab{0}` where parent=%s
  247. and parenttype=%s and parentfield=%s
  248. and name not in ({1})""".format(df.options, ','.join(['%s'] * len(rows))),
  249. [self.name, self.doctype, fieldname] + rows)
  250. else:
  251. # no rows found, delete all rows
  252. frappe.db.sql("""delete from `tab{0}` where parent=%s
  253. and parenttype=%s and parentfield=%s""".format(df.options),
  254. (self.name, self.doctype, fieldname))
  255. def set_new_name(self):
  256. """Calls `frappe.naming.se_new_name` for parent and child docs."""
  257. set_new_name(self)
  258. # set name for children
  259. for d in self.get_all_children():
  260. set_new_name(d)
  261. def set_title_field(self):
  262. """Set title field based on template"""
  263. def get_values():
  264. values = self.as_dict()
  265. # format values
  266. for key, value in values.iteritems():
  267. if value==None:
  268. values[key] = ""
  269. return values
  270. if self.meta.get("title_field")=="title":
  271. df = self.meta.get_field(self.meta.title_field)
  272. if df.options:
  273. self.set(df.fieldname, df.options.format(**get_values()))
  274. elif self.is_new() and not self.get(df.fieldname) and df.default:
  275. # set default title for new transactions (if default)
  276. self.set(df.fieldname, df.default.format(**get_values()))
  277. def update_single(self, d):
  278. """Updates values for Single type Document in `tabSingles`."""
  279. frappe.db.sql("""delete from tabSingles where doctype=%s""", self.doctype)
  280. for field, value in d.iteritems():
  281. if field != "doctype":
  282. frappe.db.sql("""insert into tabSingles(doctype, field, value)
  283. values (%s, %s, %s)""", (self.doctype, field, value))
  284. if self.doctype in frappe.db.value_cache:
  285. del frappe.db.value_cache[self.doctype]
  286. def set_user_and_timestamp(self):
  287. self._original_modified = self.modified
  288. self.modified = now()
  289. self.modified_by = frappe.session.user
  290. if not self.creation:
  291. self.creation = self.modified
  292. if not self.owner:
  293. self.owner = self.modified_by
  294. for d in self.get_all_children():
  295. d.modified = self.modified
  296. d.modified_by = self.modified_by
  297. if not d.owner:
  298. d.owner = self.owner
  299. if not d.creation:
  300. d.creation = self.creation
  301. frappe.flags.currently_saving.append((self.doctype, self.name))
  302. def set_docstatus(self):
  303. if self.docstatus==None:
  304. self.docstatus=0
  305. for d in self.get_all_children():
  306. d.docstatus = self.docstatus
  307. def _validate(self):
  308. self._validate_mandatory()
  309. self._validate_links()
  310. self._validate_selects()
  311. self._validate_constants()
  312. self._validate_length()
  313. self._sanitize_content()
  314. self._save_passwords()
  315. children = self.get_all_children()
  316. for d in children:
  317. d._validate_selects()
  318. d._validate_constants()
  319. d._validate_length()
  320. d._sanitize_content()
  321. d._save_passwords()
  322. if self.is_new():
  323. # don't set fields like _assign, _comments for new doc
  324. for fieldname in optional_fields:
  325. self.set(fieldname, None)
  326. # extract images after validations to save processing if some validation error is raised
  327. self._extract_images_from_text_editor()
  328. for d in children:
  329. d._extract_images_from_text_editor()
  330. def apply_fieldlevel_read_permissions(self):
  331. '''Remove values the user is not allowed to read (called when loading in desk)'''
  332. has_higher_permlevel = False
  333. for p in self.get_permissions():
  334. if p.permlevel > 0:
  335. has_higher_permlevel = True
  336. break
  337. if not has_higher_permlevel:
  338. return
  339. has_access_to = self.get_permlevel_access('read')
  340. for df in self.meta.fields:
  341. if df.permlevel and not df.permlevel in has_access_to:
  342. self.set(df.fieldname, None)
  343. for table_field in self.meta.get_table_fields():
  344. for df in frappe.get_meta(table_field.options).fields or []:
  345. if df.permlevel and not df.permlevel in has_access_to:
  346. for child in self.get(table_field.fieldname) or []:
  347. child.set(df.fieldname, None)
  348. def validate_higher_perm_levels(self):
  349. """If the user does not have permissions at permlevel > 0, then reset the values to original / default"""
  350. if self.flags.ignore_permissions or frappe.flags.in_install:
  351. return
  352. has_access_to = self.get_permlevel_access()
  353. high_permlevel_fields = self.meta.get_high_permlevel_fields()
  354. if high_permlevel_fields:
  355. self.reset_values_if_no_permlevel_access(has_access_to, high_permlevel_fields)
  356. # check for child tables
  357. for df in self.meta.get_table_fields():
  358. high_permlevel_fields = frappe.get_meta(df.options).meta.get_high_permlevel_fields()
  359. if high_permlevel_fields:
  360. for d in self.get(df.fieldname):
  361. d.reset_values_if_no_permlevel_access(has_access_to, high_permlevel_fields)
  362. def get_permlevel_access(self, permission_type='write'):
  363. if not hasattr(self, "_has_access_to"):
  364. user_roles = frappe.get_roles()
  365. self._has_access_to = []
  366. for perm in self.get_permissions():
  367. if perm.role in user_roles and perm.permlevel > 0 and perm.get(permission_type):
  368. if perm.permlevel not in self._has_access_to:
  369. self._has_access_to.append(perm.permlevel)
  370. return self._has_access_to
  371. def has_permlevel_access_to(self, fieldname, df=None, permission_type='read'):
  372. if not df:
  373. df = self.meta.get_field(fieldname)
  374. return df.permlevel in self.get_permlevel_access()
  375. def get_permissions(self):
  376. if self.meta.istable:
  377. # use parent permissions
  378. permissions = frappe.get_meta(self.parenttype).permissions
  379. else:
  380. permissions = self.meta.permissions
  381. return permissions
  382. def _set_defaults(self):
  383. if frappe.flags.in_import:
  384. return
  385. new_doc = frappe.new_doc(self.doctype, as_dict=True)
  386. self.update_if_missing(new_doc)
  387. # children
  388. for df in self.meta.get_table_fields():
  389. new_doc = frappe.new_doc(df.options, as_dict=True)
  390. value = self.get(df.fieldname)
  391. if isinstance(value, list):
  392. for d in value:
  393. d.update_if_missing(new_doc)
  394. def check_if_latest(self):
  395. """Checks if `modified` timestamp provided by document being updated is same as the
  396. `modified` timestamp in the database. If there is a different, the document has been
  397. updated in the database after the current copy was read. Will throw an error if
  398. timestamps don't match.
  399. Will also validate document transitions (Save > Submit > Cancel) calling
  400. `self.check_docstatus_transition`."""
  401. conflict = False
  402. self._action = "save"
  403. if not self.get('__islocal'):
  404. if self.meta.issingle:
  405. modified = frappe.db.get_value(self.doctype, self.name, "modified")
  406. if cstr(modified) and cstr(modified) != cstr(self._original_modified):
  407. conflict = True
  408. else:
  409. tmp = frappe.db.sql("""select modified, docstatus from `tab{0}`
  410. where name = %s for update""".format(self.doctype), self.name, as_dict=True)
  411. if not tmp:
  412. frappe.throw(_("Record does not exist"))
  413. else:
  414. tmp = tmp[0]
  415. modified = cstr(tmp.modified)
  416. if modified and modified != cstr(self._original_modified):
  417. conflict = True
  418. self.check_docstatus_transition(tmp.docstatus)
  419. if conflict:
  420. frappe.msgprint(_("Error: Document has been modified after you have opened it") \
  421. + (" (%s, %s). " % (modified, self.modified)) \
  422. + _("Please refresh to get the latest document."),
  423. raise_exception=frappe.TimestampMismatchError)
  424. else:
  425. self.check_docstatus_transition(0)
  426. def check_docstatus_transition(self, docstatus):
  427. """Ensures valid `docstatus` transition.
  428. Valid transitions are (number in brackets is `docstatus`):
  429. - Save (0) > Save (0)
  430. - Save (0) > Submit (1)
  431. - Submit (1) > Submit (1)
  432. - Submit (1) > Cancel (2)
  433. If docstatus is > 2, it will throw exception as document is deemed queued
  434. """
  435. if self.docstatus > 2:
  436. frappe.throw(_('This document is currently queued for execution. Please try again'),
  437. title=_('Document Queued'), indicator='red')
  438. if not self.docstatus:
  439. self.docstatus = 0
  440. if docstatus==0:
  441. if self.docstatus==0:
  442. self._action = "save"
  443. elif self.docstatus==1:
  444. self._action = "submit"
  445. self.check_permission("submit")
  446. else:
  447. raise frappe.DocstatusTransitionError, _("Cannot change docstatus from 0 to 2")
  448. elif docstatus==1:
  449. if self.docstatus==1:
  450. self._action = "update_after_submit"
  451. self.check_permission("submit")
  452. elif self.docstatus==2:
  453. self._action = "cancel"
  454. self.check_permission("cancel")
  455. else:
  456. raise frappe.DocstatusTransitionError, _("Cannot change docstatus from 1 to 0")
  457. elif docstatus==2:
  458. raise frappe.ValidationError, _("Cannot edit cancelled document")
  459. def set_parent_in_children(self):
  460. """Updates `parent` and `parenttype` property in all children."""
  461. for d in self.get_all_children():
  462. d.parent = self.name
  463. d.parenttype = self.doctype
  464. def validate_update_after_submit(self):
  465. if self.flags.ignore_validate_update_after_submit:
  466. return
  467. self._validate_update_after_submit()
  468. for d in self.get_all_children():
  469. if d.is_new() and self.meta.get_field(d.parentfield).allow_on_submit:
  470. # in case of a new row, don't validate allow on submit, if table is allow on submit
  471. continue
  472. d._validate_update_after_submit()
  473. # TODO check only allowed values are updated
  474. def _validate_mandatory(self):
  475. if self.flags.ignore_mandatory:
  476. return
  477. missing = self._get_missing_mandatory_fields()
  478. for d in self.get_all_children():
  479. missing.extend(d._get_missing_mandatory_fields())
  480. if not missing:
  481. return
  482. for fieldname, msg in missing:
  483. msgprint(msg)
  484. if frappe.flags.print_messages:
  485. print self.as_json().encode("utf-8")
  486. raise frappe.MandatoryError('[{doctype}, {name}]: {fields}'.format(
  487. fields=", ".join((each[0] for each in missing)),
  488. doctype=self.doctype,
  489. name=self.name))
  490. def _validate_links(self):
  491. if self.flags.ignore_links:
  492. return
  493. invalid_links, cancelled_links = self.get_invalid_links()
  494. for d in self.get_all_children():
  495. result = d.get_invalid_links(is_submittable=self.meta.is_submittable)
  496. invalid_links.extend(result[0])
  497. cancelled_links.extend(result[1])
  498. if invalid_links:
  499. msg = ", ".join((each[2] for each in invalid_links))
  500. frappe.throw(_("Could not find {0}").format(msg),
  501. frappe.LinkValidationError)
  502. if cancelled_links:
  503. msg = ", ".join((each[2] for each in cancelled_links))
  504. frappe.throw(_("Cannot link cancelled document: {0}").format(msg),
  505. frappe.CancelledLinkError)
  506. def get_all_children(self, parenttype=None):
  507. """Returns all children documents from **Table** type field in a list."""
  508. ret = []
  509. for df in self.meta.get("fields", {"fieldtype": "Table"}):
  510. if parenttype:
  511. if df.options==parenttype:
  512. return self.get(df.fieldname)
  513. value = self.get(df.fieldname)
  514. if isinstance(value, list):
  515. ret.extend(value)
  516. return ret
  517. def run_method(self, method, *args, **kwargs):
  518. """run standard triggers, plus those in hooks"""
  519. if "flags" in kwargs:
  520. del kwargs["flags"]
  521. if hasattr(self, method) and hasattr(getattr(self, method), "__call__"):
  522. fn = lambda self, *args, **kwargs: getattr(self, method)(*args, **kwargs)
  523. else:
  524. # hack! to run hooks even if method does not exist
  525. fn = lambda self, *args, **kwargs: None
  526. fn.__name__ = method.encode("utf-8")
  527. return Document.hook(fn)(self, *args, **kwargs)
  528. @staticmethod
  529. def whitelist(f):
  530. f.whitelisted = True
  531. return f
  532. @whitelist.__func__
  533. def _submit(self):
  534. """Submit the document. Sets `docstatus` = 1, then saves."""
  535. self.docstatus = 1
  536. self.save()
  537. @whitelist.__func__
  538. def _cancel(self):
  539. """Cancel the document. Sets `docstatus` = 2, then saves."""
  540. self.docstatus = 2
  541. self.save()
  542. @whitelist.__func__
  543. def submit(self):
  544. """Submit the document. Sets `docstatus` = 1, then saves."""
  545. self._submit()
  546. @whitelist.__func__
  547. def cancel(self):
  548. """Cancel the document. Sets `docstatus` = 2, then saves."""
  549. self._cancel()
  550. def delete(self):
  551. """Delete document."""
  552. frappe.delete_doc(self.doctype, self.name, flags=self.flags)
  553. def run_before_save_methods(self):
  554. """Run standard methods before `INSERT` or `UPDATE`. Standard Methods are:
  555. - `validate`, `before_save` for **Save**.
  556. - `validate`, `before_submit` for **Submit**.
  557. - `before_cancel` for **Cancel**
  558. - `before_update_after_submit` for **Update after Submit**
  559. Will also update title_field if set"""
  560. self.set_title_field()
  561. self.reset_seen()
  562. if self.flags.ignore_validate:
  563. return
  564. if self._action=="save":
  565. self.run_method("validate")
  566. self.run_method("before_save")
  567. elif self._action=="submit":
  568. self.run_method("validate")
  569. self.run_method("before_submit")
  570. elif self._action=="cancel":
  571. self.run_method("before_cancel")
  572. elif self._action=="update_after_submit":
  573. self.run_method("before_update_after_submit")
  574. def run_post_save_methods(self):
  575. """Run standard methods after `INSERT` or `UPDATE`. Standard Methods are:
  576. - `on_update` for **Save**.
  577. - `on_update`, `on_submit` for **Submit**.
  578. - `on_cancel` for **Cancel**
  579. - `update_after_submit` for **Update after Submit**"""
  580. if self._action=="save":
  581. self.run_method("on_update")
  582. elif self._action=="submit":
  583. self.run_method("on_update")
  584. self.run_method("on_submit")
  585. if not self.flags.ignore_submit_comment:
  586. self.add_comment("Submitted")
  587. elif self._action=="cancel":
  588. self.run_method("on_cancel")
  589. self.check_no_back_links_exist()
  590. if not self.flags.ignore_submit_comment:
  591. self.add_comment("Cancelled")
  592. elif self._action=="update_after_submit":
  593. self.run_method("on_update_after_submit")
  594. self.run_method('on_change')
  595. self.update_timeline_doc()
  596. self.clear_cache()
  597. self.notify_update()
  598. if (self.doctype, self.name) in frappe.flags.currently_saving:
  599. frappe.flags.currently_saving.remove((self.doctype, self.name))
  600. self.latest = None
  601. def clear_cache(self):
  602. frappe.cache().hdel("last_modified", self.doctype)
  603. self.clear_linked_with_cache()
  604. def clear_linked_with_cache(self):
  605. cache = frappe.cache()
  606. def _clear_cache(d):
  607. for df in (d.meta.get_link_fields() + d.meta.get_dynamic_link_fields()):
  608. if d.get(df.fieldname):
  609. doctype = df.options if df.fieldtype=="Link" else d.get(df.options)
  610. name = d.get(df.fieldname)
  611. if df.fieldtype=="Dynamic Link":
  612. # clear linked doctypes list
  613. cache.hdel("linked_doctypes", doctype)
  614. # for all users, delete linked with cache and per doctype linked with cache
  615. cache.delete_value("user:*:linked_with:{doctype}:{name}".format(doctype=doctype, name=name))
  616. cache.delete_value("user:*:linked_with:{doctype}:{name}:*".format(doctype=doctype, name=name))
  617. _clear_cache(self)
  618. for d in self.get_all_children():
  619. _clear_cache(d)
  620. def reset_seen(self):
  621. '''Clear _seen property and set current user as seen'''
  622. if getattr(self.meta, 'track_seen', False):
  623. self._seen = json.dumps([frappe.session.user])
  624. def notify_update(self):
  625. """Publish realtime that the current document is modified"""
  626. frappe.publish_realtime("doc_update", {"modified": self.modified, "doctype": self.doctype, "name": self.name},
  627. doctype=self.doctype, docname=self.name, after_commit=True)
  628. if not self.meta.get("read_only") and not self.meta.get("issingle") and \
  629. not self.meta.get("istable"):
  630. frappe.publish_realtime("list_update", {"doctype": self.doctype}, after_commit=True)
  631. def check_no_back_links_exist(self):
  632. """Check if document links to any active document before Cancel."""
  633. from frappe.model.delete_doc import check_if_doc_is_linked, check_if_doc_is_dynamically_linked
  634. if not self.flags.ignore_links:
  635. check_if_doc_is_linked(self, method="Cancel")
  636. check_if_doc_is_dynamically_linked(self, method="Cancel")
  637. @staticmethod
  638. def whitelist(f):
  639. """Decorator: Whitelist method to be called remotely via REST API."""
  640. f.whitelisted = True
  641. return f
  642. @staticmethod
  643. def hook(f):
  644. """Decorator: Make method `hookable` (i.e. extensible by another app).
  645. Note: If each hooked method returns a value (dict), then all returns are
  646. collated in one dict and returned. Ideally, don't return values in hookable
  647. methods, set properties in the document."""
  648. def add_to_return_value(self, new_return_value):
  649. if isinstance(new_return_value, dict):
  650. if not self.get("_return_value"):
  651. self._return_value = {}
  652. self._return_value.update(new_return_value)
  653. else:
  654. self._return_value = new_return_value or self.get("_return_value")
  655. def compose(fn, *hooks):
  656. def runner(self, method, *args, **kwargs):
  657. add_to_return_value(self, fn(self, *args, **kwargs))
  658. for f in hooks:
  659. add_to_return_value(self, f(self, method, *args, **kwargs))
  660. return self._return_value
  661. return runner
  662. def composer(self, *args, **kwargs):
  663. hooks = []
  664. method = f.__name__
  665. doc_events = frappe.get_doc_hooks()
  666. for handler in doc_events.get(self.doctype, {}).get(method, []) \
  667. + doc_events.get("*", {}).get(method, []):
  668. hooks.append(frappe.get_attr(handler))
  669. composed = compose(f, *hooks)
  670. return composed(self, method, *args, **kwargs)
  671. return composer
  672. def is_whitelisted(self, method):
  673. fn = getattr(self, method, None)
  674. if not fn:
  675. raise NotFound("Method {0} not found".format(method))
  676. elif not getattr(fn, "whitelisted", False):
  677. raise Forbidden("Method {0} not whitelisted".format(method))
  678. def validate_value(self, fieldname, condition, val2, doc=None, raise_exception=None):
  679. """Check that value of fieldname should be 'condition' val2
  680. else throw Exception."""
  681. error_condition_map = {
  682. "in": _("one of"),
  683. "not in": _("none of"),
  684. "^": _("beginning with"),
  685. }
  686. if not doc:
  687. doc = self
  688. val1 = doc.get_value(fieldname)
  689. df = doc.meta.get_field(fieldname)
  690. val2 = doc.cast(val2, df)
  691. if not frappe.compare(val1, condition, val2):
  692. label = doc.meta.get_label(fieldname)
  693. condition_str = error_condition_map.get(condition, condition)
  694. if doc.parentfield:
  695. msg = _("Incorrect value in row {0}: {1} must be {2} {3}".format(doc.idx, label, condition_str, val2))
  696. else:
  697. msg = _("Incorrect value: {0} must be {1} {2}".format(label, condition_str, val2))
  698. # raise passed exception or True
  699. msgprint(msg, raise_exception=raise_exception or True)
  700. def validate_table_has_rows(self, parentfield, raise_exception=None):
  701. """Raise exception if Table field is empty."""
  702. if not (isinstance(self.get(parentfield), list) and len(self.get(parentfield)) > 0):
  703. label = self.meta.get_label(parentfield)
  704. frappe.throw(_("Table {0} cannot be empty").format(label), raise_exception or frappe.EmptyTableError)
  705. def round_floats_in(self, doc, fieldnames=None):
  706. """Round floats for all `Currency`, `Float`, `Percent` fields for the given doc.
  707. :param doc: Document whose numeric properties are to be rounded.
  708. :param fieldnames: [Optional] List of fields to be rounded."""
  709. if not fieldnames:
  710. fieldnames = (df.fieldname for df in
  711. doc.meta.get("fields", {"fieldtype": ["in", ["Currency", "Float", "Percent"]]}))
  712. for fieldname in fieldnames:
  713. doc.set(fieldname, flt(doc.get(fieldname), self.precision(fieldname, doc.parentfield)))
  714. def get_url(self):
  715. """Returns Desk URL for this document. `/desk#Form/{doctype}/{name}`"""
  716. return "/desk#Form/{doctype}/{name}".format(doctype=self.doctype, name=self.name)
  717. def add_comment(self, comment_type, text=None, comment_by=None, link_doctype=None, link_name=None):
  718. """Add a comment to this document.
  719. :param comment_type: e.g. `Comment`. See Communication for more info."""
  720. comment = frappe.get_doc({
  721. "doctype":"Communication",
  722. "communication_type": "Comment",
  723. "sender": comment_by or frappe.session.user,
  724. "comment_type": comment_type,
  725. "reference_doctype": self.doctype,
  726. "reference_name": self.name,
  727. "content": text or comment_type,
  728. "link_doctype": link_doctype,
  729. "link_name": link_name
  730. }).insert(ignore_permissions=True)
  731. return comment
  732. def add_seen(self, user=None):
  733. '''add the given/current user to list of users who have seen this document (_seen)'''
  734. if not user:
  735. user = frappe.session.user
  736. if self.meta.track_seen:
  737. if self._seen:
  738. _seen = json.loads(self._seen)
  739. else:
  740. _seen = []
  741. if user not in _seen:
  742. _seen.append(user)
  743. self.db_set('_seen', json.dumps(_seen), update_modified=False)
  744. frappe.local.flags.commit = True
  745. def get_signature(self):
  746. """Returns signature (hash) for private URL."""
  747. return hashlib.sha224(get_datetime_str(self.creation)).hexdigest()
  748. def get_liked_by(self):
  749. liked_by = getattr(self, "_liked_by", None)
  750. if liked_by:
  751. return json.loads(liked_by)
  752. else:
  753. return []
  754. def set_onload(self, key, value):
  755. if not self.get("__onload"):
  756. self.set("__onload", frappe._dict())
  757. self.get("__onload")[key] = value
  758. def update_timeline_doc(self):
  759. if frappe.flags.in_install or not self.meta.get("timeline_field"):
  760. return
  761. timeline_doctype = self.meta.get_link_doctype(self.meta.timeline_field)
  762. timeline_name = self.get(self.meta.timeline_field)
  763. if not (timeline_doctype and timeline_name):
  764. return
  765. # update timeline doc in communication if it is different than current timeline doc
  766. frappe.db.sql("""update `tabCommunication`
  767. set timeline_doctype=%(timeline_doctype)s, timeline_name=%(timeline_name)s
  768. where
  769. reference_doctype=%(doctype)s and reference_name=%(name)s
  770. and (timeline_doctype is null or timeline_doctype != %(timeline_doctype)s
  771. or timeline_name is null or timeline_name != %(timeline_name)s)""",
  772. {
  773. "doctype": self.doctype,
  774. "name": self.name,
  775. "timeline_doctype": timeline_doctype,
  776. "timeline_name": timeline_name
  777. })
  778. def queue_action(self, action, **kwargs):
  779. '''Run an action in background. If the action has an inner function,
  780. like _submit for submit, it will call that instead'''
  781. if action in ('save', 'submit', 'cancel'):
  782. # set docstatus explicitly again due to inconsistent action
  783. self.docstatus = {'save':0, 'submit':1, 'cancel': 2}[action]
  784. else:
  785. raise 'Action must be one of save, submit, cancel'
  786. # call _submit instead of submit, so you can override submit to call
  787. # run_delayed based on some action
  788. # See: Stock Reconciliation
  789. if hasattr(self, '_' + action):
  790. action = '_' + action
  791. self.lock()
  792. enqueue('frappe.model.document.execute_action', doctype=self.doctype, name=self.name,
  793. action=action, **kwargs)
  794. def execute_action(doctype, name, action, **kwargs):
  795. '''Execute an action on a document (called by background worker)'''
  796. doc = frappe.get_doc(doctype, name)
  797. doc.unlock()
  798. try:
  799. getattr(doc, action)(**kwargs)
  800. except frappe.ValidationError:
  801. # add a comment (?)
  802. if frappe.local.message_log:
  803. msg = json.loads(frappe.local.message_log[-1]).get('message')
  804. else:
  805. msg = '<pre><code>' + frappe.get_traceback() + '</pre></code>'
  806. doc.add_comment('Comment', _('Action Failed') + '<br><br>' + msg)
  807. doc.notify_update()
  808. except Exception:
  809. # add a comment (?)
  810. doc.add_comment('Comment',
  811. _('Action Failed') + '<pre><code>' + frappe.get_traceback() + '</pre></code>')
  812. doc.notify_update()