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.
 
 
 
 
 
 

241 line
8.4 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  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 __future__ import unicode_literals
  12. import frappe
  13. from frappe import _
  14. from frappe.model.document import Document
  15. class NestedSetRecursionError(frappe.ValidationError): pass
  16. class NestedSetMultipleRootsError(frappe.ValidationError): pass
  17. class NestedSetChildExistsError(frappe.ValidationError): pass
  18. class NestedSetInvalidMergeError(frappe.ValidationError): pass
  19. # called in the on_update method
  20. def update_nsm(doc):
  21. # get fields, data from the DocType
  22. opf = 'old_parent'
  23. pf = "parent_" + frappe.scrub(doc.doctype)
  24. if hasattr(doc,'nsm_parent_field'):
  25. pf = doc.nsm_parent_field
  26. if hasattr(doc,'nsm_oldparent_field'):
  27. opf = doc.nsm_oldparent_field
  28. p, op = doc.get(pf) or None, doc.get(opf) or None
  29. # has parent changed (?) or parent is None (root)
  30. if not doc.lft and not doc.rgt:
  31. update_add_node(doc, p or '', pf)
  32. elif op != p:
  33. update_move_node(doc, pf)
  34. # set old parent
  35. doc.set(opf, p)
  36. frappe.db.set_value(doc.doctype, doc.name, opf, p or '')
  37. doc.load_from_db()
  38. def update_add_node(doc, parent, parent_field):
  39. """
  40. insert a new node
  41. """
  42. from frappe.utils import now
  43. n = now()
  44. doctype = doc.doctype
  45. name = doc.name
  46. # get the last sibling of the parent
  47. if parent:
  48. left, right = frappe.db.sql("select lft, rgt from `tab%s` where name=%s" \
  49. % (doctype, "%s"), parent)[0]
  50. validate_loop(doc.doctype, doc.name, left, right)
  51. else: # root
  52. right = frappe.db.sql("select ifnull(max(rgt),0)+1 from `tab%s` \
  53. where ifnull(`%s`,'') =''" % (doctype, parent_field))[0][0]
  54. right = right or 1
  55. # update all on the right
  56. frappe.db.sql("update `tab%s` set rgt = rgt+2, modified=%s where rgt >= %s" %
  57. (doctype, '%s', '%s'), (n, right))
  58. frappe.db.sql("update `tab%s` set lft = lft+2, modified=%s where lft >= %s" %
  59. (doctype, '%s', '%s'), (n, right))
  60. # update index of new node
  61. if frappe.db.sql("select * from `tab%s` where lft=%s or rgt=%s"% (doctype, right, right+1)):
  62. frappe.msgprint(_("Nested set error. Please contact the Administrator."))
  63. raise Exception
  64. frappe.db.sql("update `tab{0}` set lft=%s, rgt=%s, modified=%s where name=%s".format(doctype),
  65. (right,right+1,n,name))
  66. return right
  67. def update_move_node(doc, parent_field):
  68. parent = doc.get(parent_field)
  69. if parent:
  70. new_parent = frappe.db.sql("""select lft, rgt from `tab%s`
  71. where name = %s""" % (doc.doctype, '%s'), parent, as_dict=1)[0]
  72. validate_loop(doc.doctype, doc.name, new_parent.lft, new_parent.rgt)
  73. # move to dark side
  74. frappe.db.sql("""update `tab%s` set lft = -lft, rgt = -rgt
  75. where lft >= %s and rgt <= %s"""% (doc.doctype, '%s', '%s'), (doc.lft, doc.rgt))
  76. # shift left
  77. diff = doc.rgt - doc.lft + 1
  78. frappe.db.sql("""update `tab%s` set lft = lft -%s, rgt = rgt - %s
  79. where lft > %s"""% (doc.doctype, '%s', '%s', '%s'), (diff, diff, doc.rgt))
  80. # shift left rgts of ancestors whose only rgts must shift
  81. frappe.db.sql("""update `tab%s` set rgt = rgt - %s
  82. where lft < %s and rgt > %s"""% (doc.doctype, '%s', '%s', '%s'),
  83. (diff, doc.lft, doc.rgt))
  84. if parent:
  85. new_parent = frappe.db.sql("""select lft, rgt from `tab%s`
  86. where name = %s""" % (doc.doctype, '%s'), parent, as_dict=1)[0]
  87. # set parent lft, rgt
  88. frappe.db.sql("""update `tab%s` set rgt = rgt + %s
  89. where name = %s"""% (doc.doctype, '%s', '%s'), (diff, parent))
  90. # shift right at new parent
  91. frappe.db.sql("""update `tab%s` set lft = lft + %s, rgt = rgt + %s
  92. where lft > %s""" % (doc.doctype, '%s', '%s', '%s'),
  93. (diff, diff, new_parent.rgt))
  94. # shift right rgts of ancestors whose only rgts must shift
  95. frappe.db.sql("""update `tab%s` set rgt = rgt + %s
  96. where lft < %s and rgt > %s""" % (doc.doctype, '%s', '%s', '%s'),
  97. (diff, new_parent.lft, new_parent.rgt))
  98. new_diff = new_parent.rgt - doc.lft
  99. else:
  100. # new root
  101. max_rgt = frappe.db.sql("""select max(rgt) from `tab%s`""" % doc.doctype)[0][0]
  102. new_diff = max_rgt + 1 - doc.lft
  103. # bring back from dark side
  104. frappe.db.sql("""update `tab%s` set lft = -lft + %s, rgt = -rgt + %s
  105. where lft < 0"""% (doc.doctype, '%s', '%s'), (new_diff, new_diff))
  106. def rebuild_tree(doctype, parent_field):
  107. """
  108. call rebuild_node for all root nodes
  109. """
  110. # get all roots
  111. frappe.db.auto_commit_on_many_writes = 1
  112. right = 1
  113. result = frappe.db.sql("SELECT name FROM `tab%s` WHERE `%s`='' or `%s` IS NULL ORDER BY name ASC" % (doctype, parent_field, parent_field))
  114. for r in result:
  115. right = rebuild_node(doctype, r[0], right, parent_field)
  116. frappe.db.auto_commit_on_many_writes = 0
  117. def rebuild_node(doctype, parent, left, parent_field):
  118. """
  119. reset lft, rgt and recursive call for all children
  120. """
  121. from frappe.utils import now
  122. n = now()
  123. # the right value of this node is the left value + 1
  124. right = left+1
  125. # get all children of this node
  126. result = frappe.db.sql("SELECT name FROM `tab%s` WHERE `%s`=%s" %
  127. (doctype, parent_field, '%s'), (parent))
  128. for r in result:
  129. right = rebuild_node(doctype, r[0], right, parent_field)
  130. # we've got the left value, and now that we've processed
  131. # the children of this node we also know the right value
  132. frappe.db.sql("""UPDATE `tab{0}` SET lft=%s, rgt=%s, modified=%s
  133. WHERE name=%s""".format(doctype), (left,right,n,parent))
  134. #return the right value of this node + 1
  135. return right+1
  136. def validate_loop(doctype, name, lft, rgt):
  137. """check if item not an ancestor (loop)"""
  138. if name in frappe.db.sql_list("""select name from `tab%s` where lft <= %s and rgt >= %s""" % (doctype,
  139. "%s", "%s"), (lft, rgt)):
  140. frappe.throw(_("Item cannot be added to its own descendents"), NestedSetRecursionError)
  141. class NestedSet(Document):
  142. def on_update(self):
  143. update_nsm(self)
  144. self.validate_ledger()
  145. def on_trash(self):
  146. if not self.nsm_parent_field:
  147. self.nsm_parent_field = frappe.scrub(self.doctype) + "_parent"
  148. parent = self.get(self.nsm_parent_field)
  149. if not parent:
  150. frappe.throw(_("Root {0} cannot be deleted").format(_(self.doctype)))
  151. # cannot delete non-empty group
  152. has_children = frappe.db.sql("""select count(name) from `tab{doctype}`
  153. where `{nsm_parent_field}`=%s""".format(doctype=self.doctype, nsm_parent_field=self.nsm_parent_field),
  154. (self.name,))[0][0]
  155. if has_children:
  156. frappe.throw(_("Cannot delete {0} as it has child nodes").format(self.name), NestedSetChildExistsError)
  157. self.set(self.nsm_parent_field, "")
  158. update_nsm(self)
  159. def before_rename(self, olddn, newdn, merge=False, group_fname="is_group"):
  160. if merge:
  161. is_group = frappe.db.get_value(self.doctype, newdn, group_fname)
  162. if self.get(group_fname) != is_group:
  163. frappe.throw(_("Merging is only possible between Group-to-Group or Leaf Node-to-Leaf Node"), NestedSetInvalidMergeError)
  164. def after_rename(self, olddn, newdn, merge=False):
  165. if merge:
  166. parent_field = "parent_" + self.doctype.replace(" ", "_").lower()
  167. rebuild_tree(self.doctype, parent_field)
  168. def validate_one_root(self):
  169. if not self.get(self.nsm_parent_field):
  170. if frappe.db.sql("""select count(*) from `tab%s` where
  171. ifnull(%s, '')=''""" % (self.doctype, self.nsm_parent_field))[0][0] > 1:
  172. frappe.throw(_("""Multiple root nodes not allowed."""), NestedSetMultipleRootsError)
  173. def validate_ledger(self, group_identifier="is_group"):
  174. if self.get(group_identifier) == "No":
  175. if frappe.db.sql("""select name from `tab%s` where %s=%s and docstatus!=2""" %
  176. (self.doctype, self.nsm_parent_field, '%s'), (self.name)):
  177. frappe.throw(_("{0} {1} cannot be a leaf node as it has children").format(_(self.doctype), self.name))
  178. def get_root_of(doctype):
  179. """Get root element of a DocType with a tree structure"""
  180. return frappe.db.sql("""select t1.name from `tab{0}` t1 where
  181. (select count(*) from `tab{1}` t2 where
  182. t2.lft < t1.lft and t2.rgt > t1.rgt) = 0""".format(doctype, doctype))[0][0]
  183. def get_ancestors_of(doctype, name):
  184. """Get ancestor elements of a DocType with a tree structure"""
  185. lft, rgt = frappe.db.get_value(doctype, name, ["lft", "rgt"])
  186. result = frappe.db.sql_list("""select name from `tab%s`
  187. where lft<%s and rgt>%s order by lft desc""" % (doctype, "%s", "%s"), (lft, rgt))
  188. return result or []