From 4f3b5112b099bf317785db044ec3b7c901630b14 Mon Sep 17 00:00:00 2001 From: wangziqi Date: Thu, 9 Jul 2026 16:12:13 +0800 Subject: [PATCH] feat: filter org-tree-with-users to deepest 2 levels --- .../src/integration/dingtalk.service.ts | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/apps/server/src/integration/dingtalk.service.ts b/apps/server/src/integration/dingtalk.service.ts index dd1f99c..112f0c2 100644 --- a/apps/server/src/integration/dingtalk.service.ts +++ b/apps/server/src/integration/dingtalk.service.ts @@ -514,21 +514,37 @@ export class DingTalkService { throw new ServiceUnavailableException('钉钉未配置'); } const token = await this.getAccessToken(); - const deptIds = await this.getAllDeptIds(token, rootDeptId); + + // Compute global depth map (always from rootDeptId=1) + const depthMap = await this.getDeptDepthMap(token); + const maxDepth = Math.max(...depthMap.values()); + + // Get subtree IDs for the user's selected root + const subtreeIds = await this.getAllDeptIds(token, rootDeptId); + + // Filter: only keep departments at the deepest 2 levels of the global tree + const filteredIds = subtreeIds.filter((id) => { + const d = depthMap.get(id) ?? -1; + return d === maxDepth || d === maxDepth - 1; + }); + + if (filteredIds.length === 0) { + return []; + } // 拉每个部门详情 const nodes: DingOrgTreeNodeWithUsers[] = []; // Before dedup: collect deptIds per user const userDeptMap = new Map(); - for (let i = 0; i < deptIds.length; i++) { + for (let i = 0; i < filteredIds.length; i++) { if (i > 0) await this.delay(i); - const detail = await this.getDeptDetail(token, deptIds[i]); + const detail = await this.getDeptDetail(token, filteredIds[i]); if (!detail) continue; // 拉该部门下的用户 - const dingUsers = await this.getDeptUsers(token, deptIds[i]); - this.logger.log(`[dingtalk] dept ${deptIds[i]} (${detail.name}): ${dingUsers.length} users`); + const dingUsers = await this.getDeptUsers(token, filteredIds[i]); + this.logger.log(`[dingtalk] dept ${filteredIds[i]} (${detail.name}): ${dingUsers.length} users`); nodes.push({ id: detail.dept_id, @@ -567,13 +583,13 @@ export class DingTalkService { })); } - // 组装成树 + // 组装成树(父节点可能已被过滤,缺失的父节点 → 节点提升为根) const map = new Map(); nodes.forEach((n) => map.set(n.id, n)); const roots: DingOrgTreeNodeWithUsers[] = []; for (const node of nodes) { const parent = map.get(node.parentId); - if (parent && node.id !== rootDeptId) { + if (parent) { parent.children.push(node); } else { roots.push(node);