25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

275 satır
9.8 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. import frappe.model.meta
  6. from frappe.model.dynamic_links import get_dynamic_link_map
  7. import frappe.defaults
  8. from frappe.utils.file_manager import remove_all
  9. from frappe.utils.password import delete_all_passwords_for
  10. from frappe import _
  11. from frappe.model.naming import revert_series_if_last
  12. def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False,
  13. ignore_permissions=False, flags=None, ignore_on_trash=False):
  14. """
  15. Deletes a doc(dt, dn) and validates if it is not submitted and not linked in a live record
  16. """
  17. if not ignore_doctypes: ignore_doctypes = []
  18. # get from form
  19. if not doctype:
  20. doctype = frappe.form_dict.get('dt')
  21. name = frappe.form_dict.get('dn')
  22. names = name
  23. if isinstance(name, basestring):
  24. names = [name]
  25. for name in names or []:
  26. # already deleted..?
  27. if not frappe.db.exists(doctype, name):
  28. return
  29. # delete passwords
  30. delete_all_passwords_for(doctype, name)
  31. doc = None
  32. if doctype=="DocType":
  33. if for_reload:
  34. try:
  35. doc = frappe.get_doc(doctype, name)
  36. except frappe.DoesNotExistError:
  37. pass
  38. else:
  39. doc.run_method("before_reload")
  40. else:
  41. doc = frappe.get_doc(doctype, name)
  42. update_flags(doc, flags, ignore_permissions)
  43. check_permission_and_not_submitted(doc)
  44. frappe.db.sql("delete from `tabCustom Field` where dt = %s", name)
  45. frappe.db.sql("delete from `tabCustom Script` where dt = %s", name)
  46. frappe.db.sql("delete from `tabProperty Setter` where doc_type = %s", name)
  47. frappe.db.sql("delete from `tabReport` where ref_doctype=%s", name)
  48. delete_from_table(doctype, name, ignore_doctypes, None)
  49. else:
  50. doc = frappe.get_doc(doctype, name)
  51. if not for_reload:
  52. update_flags(doc, flags, ignore_permissions)
  53. check_permission_and_not_submitted(doc)
  54. if not ignore_on_trash:
  55. doc.run_method("on_trash")
  56. doc.run_method('on_change')
  57. frappe.enqueue('frappe.model.delete_doc.delete_dynamic_links', doctype=doc.doctype, name=doc.name,
  58. async=False if frappe.flags.in_test else True)
  59. # check if links exist
  60. if not force:
  61. check_if_doc_is_linked(doc)
  62. check_if_doc_is_dynamically_linked(doc)
  63. update_naming_series(doc)
  64. delete_from_table(doctype, name, ignore_doctypes, doc)
  65. doc.run_method("after_delete")
  66. # delete attachments
  67. remove_all(doctype, name, from_delete=True)
  68. if doc and not frappe.flags.in_patch:
  69. try:
  70. doc.notify_update()
  71. insert_feed(doc)
  72. except ImportError:
  73. pass
  74. if doc:
  75. add_to_deleted_document(doc)
  76. # delete user_permissions
  77. frappe.defaults.clear_default(parenttype="User Permission", key=doctype, value=name)
  78. def add_to_deleted_document(doc):
  79. '''Add this document to Deleted Document table. Called after delete'''
  80. if doc.doctype != 'Deleted Document' and frappe.flags.in_install != 'frappe':
  81. frappe.get_doc(dict(
  82. doctype='Deleted Document',
  83. deleted_doctype=doc.doctype,
  84. deleted_name=doc.name,
  85. data=doc.as_json()
  86. )).db_insert()
  87. def update_naming_series(doc):
  88. if doc.meta.autoname:
  89. if doc.meta.autoname.startswith("naming_series:") \
  90. and getattr(doc, "naming_series", None):
  91. revert_series_if_last(doc.naming_series, doc.name)
  92. elif doc.meta.autoname.split(":")[0] not in ("Prompt", "field", "hash"):
  93. revert_series_if_last(doc.meta.autoname, doc.name)
  94. def delete_from_table(doctype, name, ignore_doctypes, doc):
  95. if doctype!="DocType" and doctype==name:
  96. frappe.db.sql("delete from `tabSingles` where doctype=%s", name)
  97. else:
  98. frappe.db.sql("delete from `tab%s` where name=%s" % (frappe.db.escape(doctype), "%s"), (name,))
  99. # get child tables
  100. if doc:
  101. tables = [d.options for d in doc.meta.get_table_fields()]
  102. else:
  103. def get_table_fields(field_doctype):
  104. return frappe.db.sql_list("""select options from `tab{}` where fieldtype='Table'
  105. and parent=%s""".format(field_doctype), doctype)
  106. tables = get_table_fields("DocField")
  107. if not frappe.flags.in_install=="frappe":
  108. tables += get_table_fields("Custom Field")
  109. # delete from child tables
  110. for t in list(set(tables)):
  111. if t not in ignore_doctypes:
  112. frappe.db.sql("delete from `tab%s` where parenttype=%s and parent = %s" % (t, '%s', '%s'), (doctype, name))
  113. def update_flags(doc, flags=None, ignore_permissions=False):
  114. if ignore_permissions:
  115. if not flags: flags = {}
  116. flags["ignore_permissions"] = ignore_permissions
  117. if flags:
  118. doc.flags.update(flags)
  119. def check_permission_and_not_submitted(doc):
  120. # permission
  121. if not doc.flags.ignore_permissions and frappe.session.user!="Administrator" and (not doc.has_permission("delete") or (doc.doctype=="DocType" and not doc.custom)):
  122. frappe.msgprint(_("User not allowed to delete {0}: {1}").format(doc.doctype, doc.name), raise_exception=True)
  123. # check if submitted
  124. if doc.docstatus == 1:
  125. frappe.msgprint(_("{0} {1}: Submitted Record cannot be deleted.").format(doc.doctype, doc.name),
  126. raise_exception=True)
  127. def check_if_doc_is_linked(doc, method="Delete"):
  128. """
  129. Raises excption if the given doc(dt, dn) is linked in another record.
  130. """
  131. from frappe.model.rename_doc import get_link_fields
  132. link_fields = get_link_fields(doc.doctype)
  133. link_fields = [[lf['parent'], lf['fieldname'], lf['issingle']] for lf in link_fields]
  134. for link_dt, link_field, issingle in link_fields:
  135. if not issingle:
  136. for item in frappe.db.get_values(link_dt, {link_field:doc.name},
  137. ["name", "parent", "parenttype", "docstatus"], as_dict=True):
  138. if item and ((item.parent or item.name) != doc.name) \
  139. and ((method=="Delete" and item.docstatus<2) or (method=="Cancel" and item.docstatus==1)):
  140. # raise exception only if
  141. # linked to an non-cancelled doc when deleting
  142. # or linked to a submitted doc when cancelling
  143. frappe.throw(_('Cannot delete or cancel because {0} <a href="#Form/{0}/{1}">{1}</a> is linked with {2} <a href="#Form/{2}/{3}">{3}</a>')
  144. .format(doc.doctype, doc.name, item.parenttype if item.parent else link_dt,
  145. item.parent or item.name), frappe.LinkExistsError)
  146. def check_if_doc_is_dynamically_linked(doc, method="Delete"):
  147. '''Raise `frappe.LinkExistsError` if the document is dynamically linked'''
  148. for df in get_dynamic_link_map().get(doc.doctype, []):
  149. if df.parent in ("Communication", "ToDo", "DocShare", "Email Unsubscribe", 'File', 'Version'):
  150. # don't check for communication and todo!
  151. continue
  152. meta = frappe.get_meta(df.parent)
  153. if meta.issingle:
  154. # dynamic link in single doc
  155. refdoc = frappe.db.get_singles_dict(df.parent)
  156. if (refdoc.get(df.options)==doc.doctype
  157. and refdoc.get(df.fieldname)==doc.name
  158. and ((method=="Delete" and refdoc.docstatus < 2)
  159. or (method=="Cancel" and refdoc.docstatus==1))
  160. ):
  161. # raise exception only if
  162. # linked to an non-cancelled doc when deleting
  163. # or linked to a submitted doc when cancelling
  164. frappe.throw(_('Cannot delete or cancel because {0} <a href="#Form/{0}/{1}">{1}</a> is linked with {2} <a href="#Form/{2}/{3}">{3}</a>').format(doc.doctype,
  165. doc.name, df.parent, ""), frappe.LinkExistsError)
  166. else:
  167. # dynamic link in table
  168. df["table"] = ", parent, parenttype, idx" if meta.istable else ""
  169. for refdoc in frappe.db.sql("""select name, docstatus{table} from `tab{parent}` where
  170. {options}=%s and {fieldname}=%s""".format(**df), (doc.doctype, doc.name), as_dict=True):
  171. if ((method=="Delete" and refdoc.docstatus < 2) or (method=="Cancel" and refdoc.docstatus==1)):
  172. # raise exception only if
  173. # linked to an non-cancelled doc when deleting
  174. # or linked to a submitted doc when cancelling
  175. frappe.throw(_('Cannot delete or cancel because {0} <a href="#Form/{0}/{1}">{1}</a> is linked with {2} <a href="#Form/{2}/{3}">{3}</a> {4}')\
  176. .format(doc.doctype, doc.name, refdoc.parenttype if meta.istable else df.parent,
  177. refdoc.parent if meta.istable else refdoc.name,"Row: {0}".format(refdoc.idx) if meta.istable else ""), frappe.LinkExistsError)
  178. def delete_dynamic_links(doctype, name):
  179. delete_doc("ToDo", frappe.db.sql_list("""select name from `tabToDo`
  180. where reference_type=%s and reference_name=%s""", (doctype, name)),
  181. ignore_permissions=True, force=True)
  182. frappe.db.sql('''delete from `tabEmail Unsubscribe`
  183. where reference_doctype=%s and reference_name=%s''', (doctype, name))
  184. # delete comments
  185. frappe.db.sql("""delete from `tabCommunication`
  186. where
  187. communication_type = 'Comment'
  188. and reference_doctype=%s and reference_name=%s""", (doctype, name))
  189. # unlink communications
  190. frappe.db.sql("""update `tabCommunication`
  191. set reference_doctype=null, reference_name=null
  192. where
  193. communication_type = 'Communication'
  194. and reference_doctype=%s
  195. and reference_name=%s""", (doctype, name))
  196. # unlink secondary references
  197. frappe.db.sql("""update `tabCommunication`
  198. set link_doctype=null, link_name=null
  199. where link_doctype=%s and link_name=%s""", (doctype, name))
  200. # unlink feed
  201. frappe.db.sql("""update `tabCommunication`
  202. set timeline_doctype=null, timeline_name=null
  203. where timeline_doctype=%s and timeline_name=%s""", (doctype, name))
  204. # delete shares
  205. delete_doc("DocShare", frappe.db.sql_list("""select name from `tabDocShare`
  206. where share_doctype=%s and share_name=%s""", (doctype, name)),
  207. ignore_on_trash=True, force=True)
  208. # delete versions
  209. frappe.db.sql('delete from tabVersion where ref_doctype=%s and docname=%s', (doctype, name))
  210. def insert_feed(doc):
  211. from frappe.utils import get_fullname
  212. if frappe.flags.in_install or frappe.flags.in_import or getattr(doc, "no_feed_on_delete", False):
  213. return
  214. frappe.get_doc({
  215. "doctype": "Communication",
  216. "communication_type": "Comment",
  217. "comment_type": "Deleted",
  218. "reference_doctype": doc.doctype,
  219. "subject": "{0} {1}".format(_(doc.doctype), doc.name),
  220. "full_name": get_fullname(doc.owner)
  221. }).insert(ignore_permissions=True)