perf: refactor get_all_nodes in Org Chart

This commit is contained in:
Rucha Mahabal
2023-05-04 04:34:47 +05:30
parent 4a35ff0e57
commit 986a90efe0

View File

@@ -1,4 +1,5 @@
import frappe
from frappe.query_builder.functions import Count
@frappe.whitelist()
@@ -15,31 +16,34 @@ def get_children(parent=None, company=None, exclude_node=None):
if exclude_node:
filters.append(["name", "!=", exclude_node])
employees = frappe.get_list(
employees = frappe.get_all(
"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,
order_by="name",
)
for employee in employees:
is_expandable = frappe.db.count("Employee", filters={"reports_to": employee.get("id")})
employee.connections = get_connections(employee.id)
employee.expandable = 1 if is_expandable else 0
employee.connections = get_connections(employee.id, employee.lft, employee.rgt)
employee.expandable = bool(employee.connections)
return employees
def get_connections(employee):
num_connections = 0
def get_connections(employee: str, lft: int, rgt: int) -> int:
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]])
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
return query[0][0]