perf: refactor get_all_nodes in Org Chart
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import frappe
|
import frappe
|
||||||
|
from frappe.query_builder.functions import Count
|
||||||
|
|
||||||
|
|
||||||
@frappe.whitelist()
|
@frappe.whitelist()
|
||||||
@@ -15,31 +16,34 @@ def get_children(parent=None, company=None, exclude_node=None):
|
|||||||
if exclude_node:
|
if exclude_node:
|
||||||
filters.append(["name", "!=", exclude_node])
|
filters.append(["name", "!=", exclude_node])
|
||||||
|
|
||||||
employees = frappe.get_list(
|
employees = frappe.get_all(
|
||||||
"Employee",
|
"Employee",
|
||||||
fields=["employee_name as name", "name as id", "reports_to", "image", "designation as title"],
|
fields=[
|
||||||
|
"employee_name as name",
|
||||||
|
"name as id",
|
||||||
|
"lft",
|
||||||
|
"rgt",
|
||||||
|
"reports_to",
|
||||||
|
"image",
|
||||||
|
"designation as title",
|
||||||
|
],
|
||||||
filters=filters,
|
filters=filters,
|
||||||
order_by="name",
|
order_by="name",
|
||||||
)
|
)
|
||||||
|
|
||||||
for employee in employees:
|
for employee in employees:
|
||||||
is_expandable = frappe.db.count("Employee", filters={"reports_to": employee.get("id")})
|
employee.connections = get_connections(employee.id, employee.lft, employee.rgt)
|
||||||
employee.connections = get_connections(employee.id)
|
employee.expandable = bool(employee.connections)
|
||||||
employee.expandable = 1 if is_expandable else 0
|
|
||||||
|
|
||||||
return employees
|
return employees
|
||||||
|
|
||||||
|
|
||||||
def get_connections(employee):
|
def get_connections(employee: str, lft: int, rgt: int) -> int:
|
||||||
num_connections = 0
|
Employee = frappe.qb.DocType("Employee")
|
||||||
|
query = (
|
||||||
|
frappe.qb.from_(Employee)
|
||||||
|
.select(Count(Employee.name))
|
||||||
|
.where((Employee.lft > lft) & (Employee.rgt < rgt))
|
||||||
|
).run()
|
||||||
|
|
||||||
nodes_to_expand = frappe.get_list("Employee", filters=[["reports_to", "=", employee]])
|
return query[0][0]
|
||||||
num_connections += len(nodes_to_expand)
|
|
||||||
|
|
||||||
while nodes_to_expand:
|
|
||||||
parent = nodes_to_expand.pop(0)
|
|
||||||
descendants = frappe.get_list("Employee", filters=[["reports_to", "=", parent.name]])
|
|
||||||
num_connections += len(descendants)
|
|
||||||
nodes_to_expand.extend(descendants)
|
|
||||||
|
|
||||||
return num_connections
|
|
||||||
|
|||||||
Reference in New Issue
Block a user