organization-tree.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * 把扁平的 org 节点数组构造为嵌套树(对齐 PC 端 src/utils/organization-tree.js)。
  3. * 节点形状:{ id, name, type, parentId, sort?, children: [] }
  4. */
  5. const LEGAL_TYPES = new Set(["10", "20", "group", "company"]);
  6. export function buildOrganizationTree(list = []) {
  7. const nodeMap = new Map();
  8. const roots = [];
  9. list.forEach((item) => {
  10. const node = Object.assign({}, item, { children: [] });
  11. nodeMap.set(String(item.id), node);
  12. });
  13. nodeMap.forEach((node) => {
  14. const parentId = node.parentId == null ? "0" : String(node.parentId);
  15. const parent = nodeMap.get(parentId);
  16. if (parent && String(node.id) !== parentId) {
  17. parent.children.push(node);
  18. } else {
  19. roots.push(node);
  20. }
  21. });
  22. const sortNodes = (nodes, level = 0) => {
  23. nodes.sort((a, b) => Number(a.sort || 0) - Number(b.sort || 0));
  24. nodes.forEach((node) => {
  25. node.treeLevel = level;
  26. sortNodes(node.children || [], level + 1);
  27. });
  28. };
  29. sortNodes(roots);
  30. return roots;
  31. }
  32. /**
  33. * 从全量 org 列表里识别法人节点。
  34. */
  35. export function pickLegalEntities(list = []) {
  36. if (!Array.isArray(list) || !list.length) return [];
  37. const parents = new Map(list.map((item) => [String(item.id), item]));
  38. const isLegalType = (item) => LEGAL_TYPES.has(String(item.type));
  39. const hasNoParent = (item) => {
  40. const pid = item.parentId == null ? "0" : String(item.parentId);
  41. return pid === "0" || !parents.has(pid);
  42. };
  43. return list.filter((item) => isLegalType(item) || hasNoParent(item)).map((item) => ({ id: item.id, name: item.name }));
  44. }
  45. /**
  46. * 从全量 org 列表里取出某个法人节点下(含自身)的所有节点,再构树。
  47. */
  48. export function buildDeptTreeUnderLegal(allList = [], legalId) {
  49. if (!legalId) return buildOrganizationTree(allList);
  50. const key = String(legalId);
  51. const root = allList.find((item) => String(item.id) === key);
  52. if (!root) return [];
  53. const picked = [root];
  54. const walk = (parentId) => {
  55. allList.forEach((item) => {
  56. if (String(item.parentId) === String(parentId)) {
  57. picked.push(item);
  58. walk(item.id);
  59. }
  60. });
  61. };
  62. walk(legalId);
  63. return buildOrganizationTree(picked);
  64. }
  65. export { LEGAL_TYPES };