I want to create a hierarchy structure in a custom page from Company, Branch, Department and Designation. I already linked each other from custom fields. Now here are the relation in the hierarchy structure, Company is the main parent. Company’s child is Branch’s(multiple branch’s). Branches child is Department. Department have child department. Each child department’s parent is its parent department. A department may have child department or not. If a parent department have child department, then the parent department have is-group checkbox checked. If a department does not have child department, it will custom_is_single checkbox checked. Now Departments child is designation. Each designation’s parent is a department. Designations parent department may be a Single department(which is custom_is_single checkbox checked) may be a Parent Department (which is is_group checkbox checked) or may be a child department(which is no checkbox checked and which must have a parent department). Now following this data structure I create this code,
import frappe
@frappe.whitelist()
def get_org_structure():
companies = frappe.get_list("Company", fields=["name"])
if not companies:
return {}
company_name = companies[0].name # Assuming you want the first company
branches = frappe.get_all("Branch", filters={"company": company_name}, fields=["name"])
org_structure = {"name": company_name, "children": []}
for branch in branches:
departments = frappe.get_all("Department", filters={"parent_branch": branch.name}, fields=["name", "is_group"])
branch_data = {"name": branch.name, "children": []}
for department in departments:
child_departments = frappe.get_all("Department", filters={"parent_department": department.name}, fields=["name"])
department_data = {"name": department.name, "children": []}
if department["is_group"]:
for child_department in child_departments:
designations = frappe.get_all("Designation", filters={"department": child_department.name}, fields=["name"])
child_department_data = {"name": child_department.name, "children": [{"name": des.name} for des in designations]}
department_data["children"].append(child_department_data)
else:
designations = frappe.get_all("Designation", filters={"department": department.name}, fields=["name"])
department_data["children"] = [{"name": des.name} for des in designations]
branch_data["children"].append(department_data)
org_structure["children"].append(branch_data)
return org_structure
But this code returns child department two time. First one is under the parent department, which is ok. But another same child department showing under the branch. How can I fix this?