You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

315 lines
10 KiB

  1. # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
  2. # License: MIT. See LICENSE
  3. # Tree (Hierarchical) Nested Set Model (nsm)
  4. #
  5. # To use the nested set model,
  6. # use the following pattern
  7. # 1. name your parent field as "parent_item_group" if not have a property nsm_parent_field as your field name in the document class
  8. # 2. have a field called "old_parent" in your fields list - this identifies whether the parent has been changed
  9. # 3. call update_nsm(doc_obj) in the on_upate method
  10. # ------------------------------------------
  11. from typing import Iterator
  12. import frappe
  13. from frappe import _
  14. from frappe.model.document import Document
  15. from frappe.query_builder import DocType, Order
  16. class NestedSetRecursionError(frappe.ValidationError): pass
  17. class NestedSetMultipleRootsError(frappe.ValidationError): pass
  18. class NestedSetChildExistsError(frappe.ValidationError): pass
  19. class NestedSetInvalidMergeError(frappe.ValidationError): pass
  20. # called in the on_update method
  21. def update_nsm(doc):
  22. # get fields, data from the DocType
  23. old_parent_field = 'old_parent'
  24. parent_field = "parent_" + frappe.scrub(doc.doctype)
  25. if hasattr(doc,'nsm_parent_field'):
  26. parent_field = doc.nsm_parent_field
  27. if hasattr(doc,'nsm_oldparent_field'):
  28. old_parent_field = doc.nsm_oldparent_field
  29. parent, old_parent = doc.get(parent_field) or None, doc.get(old_parent_field) or None
  30. # has parent changed (?) or parent is None (root)
  31. if not doc.lft and not doc.rgt:
  32. update_add_node(doc, parent or '', parent_field)
  33. elif old_parent != parent:
  34. update_move_node(doc, parent_field)
  35. # set old parent
  36. doc.set(old_parent_field, parent)
  37. frappe.db.set_value(doc.doctype, doc.name, old_parent_field, parent or '', update_modified=False)
  38. doc.reload()
  39. def update_add_node(doc, parent, parent_field):
  40. """
  41. insert a new node
  42. """
  43. doctype = doc.doctype
  44. name = doc.name
  45. # get the last sibling of the parent
  46. if parent:
  47. left, right = frappe.db.sql("select lft, rgt from `tab{0}` where name=%s for update"
  48. .format(doctype), parent)[0]
  49. validate_loop(doc.doctype, doc.name, left, right)
  50. else: # root
  51. right = frappe.db.sql("""
  52. SELECT COALESCE(MAX(rgt), 0) + 1 FROM `tab{0}`
  53. WHERE COALESCE(`{1}`, '') = ''
  54. """.format(doctype, parent_field))[0][0]
  55. right = right or 1
  56. # update all on the right
  57. frappe.db.sql("update `tab{0}` set rgt = rgt+2 where rgt >= %s"
  58. .format(doctype), (right,))
  59. frappe.db.sql("update `tab{0}` set lft = lft+2 where lft >= %s"
  60. .format(doctype), (right,))
  61. # update index of new node
  62. if frappe.db.sql("select * from `tab{0}` where lft=%s or rgt=%s".format(doctype), (right, right+1)):
  63. frappe.msgprint(_("Nested set error. Please contact the Administrator."))
  64. raise Exception
  65. frappe.db.sql("update `tab{0}` set lft=%s, rgt=%s where name=%s".format(doctype),
  66. (right,right+1, name))
  67. return right
  68. def update_move_node(doc, parent_field):
  69. parent = doc.get(parent_field)
  70. if parent:
  71. new_parent = frappe.db.sql("""select lft, rgt from `tab{0}`
  72. where name = %s for update""".format(doc.doctype), parent, as_dict=1)[0]
  73. validate_loop(doc.doctype, doc.name, new_parent.lft, new_parent.rgt)
  74. # move to dark side
  75. frappe.db.sql("""update `tab{0}` set lft = -lft, rgt = -rgt
  76. where lft >= %s and rgt <= %s""".format(doc.doctype), (doc.lft, doc.rgt))
  77. # shift left
  78. diff = doc.rgt - doc.lft + 1
  79. frappe.db.sql("""update `tab{0}` set lft = lft -%s, rgt = rgt - %s
  80. where lft > %s""".format(doc.doctype), (diff, diff, doc.rgt))
  81. # shift left rgts of ancestors whose only rgts must shift
  82. frappe.db.sql("""update `tab{0}` set rgt = rgt - %s
  83. where lft < %s and rgt > %s""".format(doc.doctype), (diff, doc.lft, doc.rgt))
  84. if parent:
  85. new_parent = frappe.db.sql("""select lft, rgt from `tab%s`
  86. where name = %s for update""" % (doc.doctype, '%s'), parent, as_dict=1)[0]
  87. # set parent lft, rgt
  88. frappe.db.sql("""update `tab{0}` set rgt = rgt + %s
  89. where name = %s""".format(doc.doctype), (diff, parent))
  90. # shift right at new parent
  91. frappe.db.sql("""update `tab{0}` set lft = lft + %s, rgt = rgt + %s
  92. where lft > %s""".format(doc.doctype), (diff, diff, new_parent.rgt))
  93. # shift right rgts of ancestors whose only rgts must shift
  94. frappe.db.sql("""update `tab{0}` set rgt = rgt + %s
  95. where lft < %s and rgt > %s""".format(doc.doctype),
  96. (diff, new_parent.lft, new_parent.rgt))
  97. new_diff = new_parent.rgt - doc.lft
  98. else:
  99. # new root
  100. max_rgt = frappe.db.sql("""select max(rgt) from `tab{0}`""".format(doc.doctype))[0][0]
  101. new_diff = max_rgt + 1 - doc.lft
  102. # bring back from dark side
  103. frappe.db.sql("""update `tab{0}` set lft = -lft + %s, rgt = -rgt + %s
  104. where lft < 0""".format(doc.doctype), (new_diff, new_diff))
  105. @frappe.whitelist()
  106. def rebuild_tree(doctype, parent_field):
  107. """
  108. call rebuild_node for all root nodes
  109. """
  110. # Check for perm if called from client-side
  111. if frappe.request and frappe.local.form_dict.cmd == 'rebuild_tree':
  112. frappe.only_for('System Manager')
  113. # get all roots
  114. right = 1
  115. table = DocType(doctype)
  116. column = getattr(table, parent_field)
  117. result = (
  118. frappe.qb.from_(table)
  119. .where(
  120. (column == "") | (column.isnull())
  121. )
  122. .orderby(table.name, order=Order.asc)
  123. .select(table.name)
  124. ).run()
  125. frappe.db.auto_commit_on_many_writes = 1
  126. for r in result:
  127. right = rebuild_node(doctype, r[0], right, parent_field)
  128. frappe.db.auto_commit_on_many_writes = 0
  129. def rebuild_node(doctype, parent, left, parent_field):
  130. """
  131. reset lft, rgt and recursive call for all children
  132. """
  133. # the right value of this node is the left value + 1
  134. right = left+1
  135. # get all children of this node
  136. table = DocType(doctype)
  137. column = getattr(table, parent_field)
  138. result = (
  139. frappe.qb.from_(table).where(column == parent).select(table.name)
  140. ).run()
  141. for r in result:
  142. right = rebuild_node(doctype, r[0], right, parent_field)
  143. # we've got the left value, and now that we've processed
  144. # the children of this node we also know the right value
  145. frappe.db.set_value(doctype, parent, {"lft": left, "rgt": right}, for_update=False, update_modified=False)
  146. #return the right value of this node + 1
  147. return right+1
  148. def validate_loop(doctype, name, lft, rgt):
  149. """check if item not an ancestor (loop)"""
  150. if name in frappe.db.sql_list("""select name from `tab{0}` where lft <= %s and rgt >= %s"""
  151. .format(doctype), (lft, rgt)):
  152. frappe.throw(_("Item cannot be added to its own descendents"), NestedSetRecursionError)
  153. class NestedSet(Document):
  154. def __setup__(self):
  155. if self.meta.get("nsm_parent_field"):
  156. self.nsm_parent_field = self.meta.nsm_parent_field
  157. def on_update(self):
  158. update_nsm(self)
  159. self.validate_ledger()
  160. def on_trash(self, allow_root_deletion=False):
  161. if not getattr(self, 'nsm_parent_field', None):
  162. self.nsm_parent_field = frappe.scrub(self.doctype) + "_parent"
  163. parent = self.get(self.nsm_parent_field)
  164. if not parent and not allow_root_deletion:
  165. frappe.throw(_("Root {0} cannot be deleted").format(_(self.doctype)))
  166. # cannot delete non-empty group
  167. self.validate_if_child_exists()
  168. self.set(self.nsm_parent_field, "")
  169. try:
  170. update_nsm(self)
  171. except frappe.DoesNotExistError:
  172. if self.flags.on_rollback:
  173. pass
  174. frappe.message_log.pop()
  175. else:
  176. raise
  177. def validate_if_child_exists(self):
  178. has_children = frappe.db.sql("""select count(name) from `tab{doctype}`
  179. where `{nsm_parent_field}`=%s""".format(doctype=self.doctype, nsm_parent_field=self.nsm_parent_field),
  180. (self.name,))[0][0]
  181. if has_children:
  182. frappe.throw(_("Cannot delete {0} as it has child nodes").format(self.name), NestedSetChildExistsError)
  183. def before_rename(self, olddn, newdn, merge=False, group_fname="is_group"):
  184. if merge and hasattr(self, group_fname):
  185. is_group = frappe.db.get_value(self.doctype, newdn, group_fname)
  186. if self.get(group_fname) != is_group:
  187. frappe.throw(_("Merging is only possible between Group-to-Group or Leaf Node-to-Leaf Node"), NestedSetInvalidMergeError)
  188. def after_rename(self, olddn, newdn, merge=False):
  189. if not self.nsm_parent_field:
  190. parent_field = "parent_" + self.doctype.replace(" ", "_").lower()
  191. else:
  192. parent_field = self.nsm_parent_field
  193. # set old_parent for children
  194. frappe.db.sql("update `tab{0}` set old_parent=%s where {1}=%s"
  195. .format(self.doctype, parent_field), (newdn, newdn))
  196. if merge:
  197. rebuild_tree(self.doctype, parent_field)
  198. def validate_one_root(self):
  199. if not self.get(self.nsm_parent_field):
  200. if self.get_root_node_count() > 1:
  201. frappe.throw(_("""Multiple root nodes not allowed."""), NestedSetMultipleRootsError)
  202. def get_root_node_count(self):
  203. return frappe.db.count(self.doctype, {
  204. self.nsm_parent_field: ''
  205. })
  206. def validate_ledger(self, group_identifier="is_group"):
  207. if hasattr(self, group_identifier) and not bool(self.get(group_identifier)):
  208. if frappe.db.sql("""select name from `tab{0}` where {1}=%s and docstatus!=2"""
  209. .format(self.doctype, self.nsm_parent_field), (self.name)):
  210. frappe.throw(_("{0} {1} cannot be a leaf node as it has children").format(_(self.doctype), self.name))
  211. def get_ancestors(self):
  212. return get_ancestors_of(self.doctype, self.name)
  213. def get_parent(self) -> "NestedSet":
  214. """Return the parent Document."""
  215. parent_name = self.get(self.nsm_parent_field)
  216. if parent_name:
  217. return frappe.get_doc(self.doctype, parent_name)
  218. def get_children(self) -> Iterator["NestedSet"]:
  219. """Return a generator that yields child Documents."""
  220. child_names = frappe.get_list(self.doctype, filters={self.nsm_parent_field: self.name}, pluck="name")
  221. for name in child_names:
  222. yield frappe.get_doc(self.doctype, name)
  223. def get_root_of(doctype):
  224. """Get root element of a DocType with a tree structure"""
  225. result = frappe.db.sql("""select t1.name from `tab{0}` t1 where
  226. (select count(*) from `tab{1}` t2 where
  227. t2.lft < t1.lft and t2.rgt > t1.rgt) = 0
  228. and t1.rgt > t1.lft""".format(doctype, doctype))
  229. return result[0][0] if result else None
  230. def get_ancestors_of(doctype, name, order_by="lft desc", limit=None):
  231. """Get ancestor elements of a DocType with a tree structure"""
  232. lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
  233. result = [d["name"] for d in frappe.db.get_all(doctype, {"lft": ["<", lft], "rgt": [">", rgt]},
  234. "name", order_by=order_by, limit_page_length=limit)]
  235. return result or []
  236. def get_descendants_of(doctype, name, order_by="lft desc", limit=None,
  237. ignore_permissions=False):
  238. '''Return descendants of the current record'''
  239. lft, rgt = frappe.db.get_value(doctype, name, ['lft', 'rgt'])
  240. result = [d["name"] for d in frappe.db.get_list(doctype, {"lft": [">", lft], "rgt": ["<", rgt]},
  241. "name", order_by=order_by, limit_page_length=limit, ignore_permissions=ignore_permissions)]
  242. return result or []