diff --git a/app/api/organization/route.ts b/app/api/organization/route.ts index ac93df58..75dc5d43 100644 --- a/app/api/organization/route.ts +++ b/app/api/organization/route.ts @@ -5,11 +5,14 @@ * - 只统计"在素材库开过账号(User)且已建立活跃绑定(UserEmployeeBinding)"的人; * - 花名册里有、但没有素材库账号的人(仓储/物流等约 1200 人)不纳入; * - 无钉钉 ID 无法绑定的活跃账号单独归入"未绑定/待人工确认"组; - * - 绑定档案部门路径为"未确定"的单独归入"未确定"组。 + * - 绑定档案部门路径为"未确定"的单独归入"未确定"组; + * - 默认只展示花名册在职(employmentState 非 RESIGNED)。离职档案仍留在库里做托管/作者追溯, + * 不进日常组织树;?includeInactive=true 才把离职的人加回名单; + * - 一人多部门:按全部任职路径显示,A 同时在 1、2 部门时两边名单都有 A;上级节点仍按人去重。 * * 返回: * - tree:真实组织树(OrganizationUnit,isActive),节点带该部门直接+间接人员数; - * - employees:全部已采纳人员的明细(含 M/P 等级、归属、直属主管、在职状态); + * - employees:当前可见人员的明细(含 M/P 等级、归属、直属主管、在职状态); * - unbound:未绑定账号;unclassified:部门未确定的人。 */ @@ -18,6 +21,13 @@ import { getServerSession } from 'next-auth' import { authOptions } from '@/lib/auth' import { prisma } from '@/lib/prisma' import { isSystemAdmin, isDepartmentAdmin, isAdmin } from '@/lib/department-permission' +import { isRosterEmployed, selectVisibleOrganizationPeople } from '@/lib/auto-personnel-rules' +import { + collectEmployeeOrganizationPaths, + countUniquePeopleOnOrganizationPaths, + parseOrganizationDepartmentIds, + personBelongsToOrganizationPath, +} from '@/lib/organization-material-permissions' interface OrgNode { id: string @@ -37,6 +47,7 @@ interface EmployeeRow { displayName: string | null jobNumber: string | null departmentPath: string | null + departmentPaths: string[] departmentName: string | null positionTitle: string | null positionLevel: string | null @@ -106,6 +117,15 @@ export async function GET(request: NextRequest) { managerName: true, isLeadership: true, employmentState: true, + sourcePayload: true, + departmentMemberships: { + select: { + sourceDeptId: true, + departmentPath: true, + departmentName: true, + isPrimary: true, + }, + }, }, }, }, @@ -114,9 +134,32 @@ export async function GET(request: NextRequest) { // 2. 组织树(全部有效节点) const units = await prisma.organizationUnit.findMany({ where: { isActive: true }, - select: { id: true, name: true, path: true, level: true, parentId: true }, + select: { id: true, name: true, path: true, level: true, parentId: true, sourceDeptId: true }, orderBy: [{ level: 'asc' }, { name: 'asc' }], }) + const pathBySourceDeptId = new Map(units.map((unit) => [String(unit.sourceDeptId), unit.path])) + + const resolveEmployeePaths = (profile: { + departmentPath: string | null + sourcePayload: unknown + departmentMemberships: Array<{ sourceDeptId: string; departmentPath: string | null }> + } | null | undefined): string[] => { + if (!profile) return [] + const synced = ((profile.sourcePayload as { syncedFields?: Record } | null)?.syncedFields || + {}) as Record + const extraIds = [ + ...parseOrganizationDepartmentIds(synced.departmentIds), + ...parseOrganizationDepartmentIds(synced.employeeDeptIdList), + ...parseOrganizationDepartmentIds(synced.registerDeptIds), + ...parseOrganizationDepartmentIds(synced.flowerBookDeptId), + ] + return collectEmployeeOrganizationPaths([ + profile.departmentPath, + ...profile.departmentMemberships.map((membership) => membership.departmentPath), + ...profile.departmentMemberships.map((membership) => pathBySourceDeptId.get(String(membership.sourceDeptId))), + ...extraIds.map((id) => pathBySourceDeptId.get(id)), + ]) + } // 3. 无钉钉 ID 的活跃账号(未绑定组) const unboundUsers = await prisma.user.findMany({ @@ -125,37 +168,35 @@ export async function GET(request: NextRequest) { orderBy: { createdAt: 'asc' }, }) - // 组装人员行 - const employees: EmployeeRow[] = bindings.map((b) => ({ - userId: b.userId, - username: b.user?.username ?? null, - realName: b.user?.realName ?? null, - displayName: b.employeeProfile?.displayName ?? null, - jobNumber: b.employeeProfile?.jobNumber ?? null, - departmentPath: b.employeeProfile?.departmentPath ?? null, - departmentName: b.employeeProfile?.departmentName ?? null, - positionTitle: b.employeeProfile?.positionTitle ?? null, - positionLevel: b.employeeProfile?.positionLevel ?? null, - levelType: b.employeeProfile?.levelType ?? null, - managerName: b.employeeProfile?.managerName ?? null, - isLeadership: Boolean(b.employeeProfile?.isLeadership), - employmentState: b.employeeProfile?.employmentState ?? null, - isActive: Boolean(b.user?.isActive), - })) - - // 统计每个部门路径前缀下的人数(用于树节点计数) - // 若为部门管理员,只统计本部门分支 - const pathCount = new Map() - const scopeEmployees = scopePrefix ? employees.filter((e) => e.departmentPath?.startsWith(scopePrefix)) : employees - for (const e of scopeEmployees) { - if (!e.departmentPath) continue - const parts = e.departmentPath.split('/') - let acc = '' - for (const part of parts) { - acc = acc ? `${acc}/${part}` : part - pathCount.set(acc, (pathCount.get(acc) ?? 0) + 1) + // 组装人员行(一人多部门:departmentPaths 含全部任职路径,departmentPath 仍是主部门) + const employees: EmployeeRow[] = bindings.map((b) => { + const departmentPaths = resolveEmployeePaths(b.employeeProfile) + return { + userId: b.userId, + username: b.user?.username ?? null, + realName: b.user?.realName ?? null, + displayName: b.employeeProfile?.displayName ?? null, + jobNumber: b.employeeProfile?.jobNumber ?? null, + departmentPath: b.employeeProfile?.departmentPath ?? departmentPaths[0] ?? null, + departmentPaths, + departmentName: b.employeeProfile?.departmentName ?? null, + positionTitle: b.employeeProfile?.positionTitle ?? null, + positionLevel: b.employeeProfile?.positionLevel ?? null, + levelType: b.employeeProfile?.levelType ?? null, + managerName: b.employeeProfile?.managerName ?? null, + isLeadership: Boolean(b.employeeProfile?.isLeadership), + employmentState: b.employeeProfile?.employmentState ?? null, + isActive: Boolean(b.user?.isActive), } - } + }) + + // 统计每个部门路径前缀下的人数(本级+子孙,每人只计一次) + // 若为部门管理员,只统计本部门分支 + const scopeEmployees = scopePrefix + ? employees.filter((e) => personBelongsToOrganizationPath(e.departmentPaths, scopePrefix)) + : employees + const visibleEmployees = selectVisibleOrganizationPeople(scopeEmployees, includeInactive) + const pathCount = countUniquePeopleOnOrganizationPaths(visibleEmployees.map((e) => e.departmentPaths)) // 构建组织树(只保留有人的分支 + 未确定组) const unitMap = new Map() @@ -179,14 +220,7 @@ export async function GET(request: NextRequest) { } } - // 统计每个节点的总人数(含子孙) - const totalCount = (node: OrgNode): number => { - let c = node.count - for (const child of node.children) c += totalCount(child) - node.count = c - return c - } - for (const root of roots) totalCount(root) + // pathCount 已按路径前缀累计,节点人数本身含子孙,不必再滚加一层。 // 只保留有人的子树(count > 0),无人的分支剪掉 const prune = (node: OrgNode): OrgNode | null => { @@ -197,8 +231,10 @@ export async function GET(request: NextRequest) { const tree = roots.map(prune).filter((n): n is OrgNode => n !== null) // 未确定组(有绑定但部门路径缺失或以"未确定"开头) - const unclassified = scopeEmployees.filter( - (e) => !e.departmentPath || e.departmentPath.startsWith('未确定'), + const unclassified = visibleEmployees.filter( + (e) => + e.departmentPaths.length === 0 || + e.departmentPaths.every((path) => path.startsWith('未确定')), ) // 未绑定组(无钉钉 ID 的活跃账号) @@ -209,12 +245,10 @@ export async function GET(request: NextRequest) { oldDepartment: u.department, })) - const visibleEmployees = includeInactive ? scopeEmployees : scopeEmployees.filter((e) => e.isActive) - const summary = { totalEmployees: employees.length, - activeEmployees: employees.filter((e) => e.isActive).length, - inactiveEmployees: employees.filter((e) => !e.isActive).length, + activeEmployees: employees.filter((e) => isRosterEmployed(e.employmentState)).length, + inactiveEmployees: employees.filter((e) => !isRosterEmployed(e.employmentState)).length, unboundCount: unbound.length, unclassifiedCount: unclassified.length, visibleCount: visibleEmployees.length, diff --git a/components/organization/OrganizationWorkspace.tsx b/components/organization/OrganizationWorkspace.tsx index 20959f04..6c7bc630 100644 --- a/components/organization/OrganizationWorkspace.tsx +++ b/components/organization/OrganizationWorkspace.tsx @@ -18,6 +18,10 @@ import { useEffect, useMemo, useState, useCallback } from 'react' import { useSession } from 'next-auth/react' import { useRouter } from 'next/navigation' import BoardShell from '@/components/board/BoardShell' +import { + lastOrganizationPathSegment, + personBelongsToOrganizationPath, +} from '@/lib/organization-material-permissions' // ---------- 类型 ---------- interface OrgNode { @@ -37,6 +41,7 @@ interface EmployeeRow { displayName: string | null jobNumber: string | null departmentPath: string | null + departmentPaths?: string[] departmentName: string | null positionTitle: string | null positionLevel: string | null @@ -171,9 +176,28 @@ export default function OrganizationWorkspace({ embedded = false }: Organization if (selectedGroup === 'unclassified') return data.unclassified if (selectedGroup === 'unbound') return [] if (!selectedPath) return [] - return data.employees.filter((e) => e.departmentPath === selectedPath) + return data.employees.filter((e) => + personBelongsToOrganizationPath(e.departmentPaths?.length ? e.departmentPaths : [e.departmentPath], selectedPath), + ) }, [data, selectedPath, selectedGroup]) + const employeePaths = (e: EmployeeRow) => + e.departmentPaths?.length ? e.departmentPaths : e.departmentPath ? [e.departmentPath] : [] + + const descendantCount = selectedEmployees.filter( + (e) => !employeePaths(e).some((path) => path === selectedPath), + ).length + + const matchingDepartmentLabel = (e: EmployeeRow) => { + const matching = selectedPath + ? employeePaths(e).filter((path) => personBelongsToOrganizationPath([path], selectedPath)) + : employeePaths(e) + const names = (matching.length > 0 ? matching : employeePaths(e)).map( + (path) => lastOrganizationPathSegment(path) || path, + ) + return names.filter(Boolean).join('、') || '—' + } + // 部门负责人计数(当前选中列表) const leaderCount = selectedEmployees.filter((e) => e.isLeadership).length @@ -228,7 +252,7 @@ export default function OrganizationWorkspace({ embedded = false }: Organization

组织架构

- 品牌中心人员全景 · 数据源:HR 花名册(每日 02:00 自动同步) + 品牌中心在职人员 · 数据源:HR 花名册(每日 02:00 自动同步)

@@ -237,7 +261,7 @@ export default function OrganizationWorkspace({ embedded = false }: Organization 共 {data.summary.visibleCount} 人 {isSuperAdmin && ( - (在职 {data.summary.activeEmployees} / 含离职 {data.summary.inactiveEmployees}) + (在职 {data.summary.activeEmployees} / 离职 {data.summary.inactiveEmployees}) )} @@ -395,7 +419,10 @@ export default function OrganizationWorkspace({ embedded = false }: Organization
{selectedGroup === 'org' && selectedPath && ( -

{selectedPath}

+

+ {selectedPath} + {descendantCount > 0 ? ` · 含下级 ${descendantCount} 人` : ''} +

)} @@ -461,6 +488,7 @@ export default function OrganizationWorkspace({ embedded = false }: Organization 人员 工号 + 所属部门 职位 等级 直属主管 @@ -483,9 +511,17 @@ export default function OrganizationWorkspace({ embedded = false }: Organization 负责人 )} + {employeePaths(e).length > 1 && ( + + 兼任 + + )} {e.jobNumber ?? '—'} + + {matchingDepartmentLabel(e)} + {e.positionTitle ?? '—'} {e.positionLevel ? ( diff --git a/lib/__tests__/auto-personnel-rules.test.ts b/lib/__tests__/auto-personnel-rules.test.ts new file mode 100644 index 00000000..80acf000 --- /dev/null +++ b/lib/__tests__/auto-personnel-rules.test.ts @@ -0,0 +1,38 @@ +import { + isRosterEmployed, + selectVisibleOrganizationPeople, + shouldAutoActivate, +} from '@/lib/auto-personnel-rules' + +describe('花名册在职判定', () => { + it('只有明确离职才不算在职', () => { + expect(isRosterEmployed('RESIGNED')).toBe(false) + expect(isRosterEmployed('ACTIVE')).toBe(true) + expect(isRosterEmployed('UNKNOWN')).toBe(true) + expect(isRosterEmployed(null)).toBe(true) + expect(isRosterEmployed(undefined)).toBe(true) + }) + + it('自动激活跟花名册在职走同一口径', () => { + expect(shouldAutoActivate({ employmentState: 'RESIGNED' })).toBe(false) + expect(shouldAutoActivate({ employmentState: 'UNKNOWN' })).toBe(true) + expect(shouldAutoActivate(null)).toBe(false) + }) + + it('组织架构默认名单不带离职的人,也不看账号是否还启用', () => { + const people = [ + { name: '在职且账号启用', employmentState: 'ACTIVE', isActive: true }, + { name: '离职但账号还没归档', employmentState: 'RESIGNED', isActive: true }, + { name: '离职且账号已关', employmentState: 'RESIGNED', isActive: false }, + { name: '在职但账号停用', employmentState: 'ACTIVE', isActive: false }, + { name: '状态未知', employmentState: 'UNKNOWN', isActive: true }, + ] + + expect(selectVisibleOrganizationPeople(people).map((p) => p.name)).toEqual([ + '在职且账号启用', + '在职但账号停用', + '状态未知', + ]) + expect(selectVisibleOrganizationPeople(people, true)).toHaveLength(5) + }) +}) diff --git a/lib/__tests__/organization-material-permissions.test.ts b/lib/__tests__/organization-material-permissions.test.ts index 5d3a9599..0cb068ed 100644 --- a/lib/__tests__/organization-material-permissions.test.ts +++ b/lib/__tests__/organization-material-permissions.test.ts @@ -1,7 +1,14 @@ import { + collectEmployeeOrganizationPaths, collectOccupiedOrganizationPaths, + countPeopleOnOrganizationPaths, + countUniquePeopleOnOrganizationPaths, findOrganizationPermissionStorageKey, + isUnderOrganizationPath, + normalizeOrganizationPath, organizationPathChain, + parseOrganizationDepartmentIds, + personBelongsToOrganizationPath, pruneOrganizationTree, resolveOrganizationPermissionKey, } from '@/lib/organization-material-permissions' @@ -151,3 +158,86 @@ describe('organization material permission keys', () => { }) }) }) + +describe('organization people counts', () => { + const company = '江苏简尚品牌管理有限公司' + const planning = `${company}/品牌中心/商品企划部` + const shelf = `${planning}/架类` + const support = `${company}/业务支持` + const visual = `${support}/视觉支持` + + test('normalize keeps the original path, it does not join the prefix chain', () => { + expect(normalizeOrganizationPath(` ${company}/ 总经理室 / `)).toBe(`${company}/总经理室`) + }) + + test('a person belongs to their own dept and every ancestor, not a sibling', () => { + expect(isUnderOrganizationPath(shelf, planning)).toBe(true) + expect(isUnderOrganizationPath(shelf, company)).toBe(true) + expect(isUnderOrganizationPath(planning, planning)).toBe(true) + expect(isUnderOrganizationPath(planning, shelf)).toBe(false) + expect(isUnderOrganizationPath(visual, planning)).toBe(false) + expect(isUnderOrganizationPath(null, planning)).toBe(false) + }) + + test('tree numbers count each person once per ancestor, never roll children up again', () => { + const counts = countPeopleOnOrganizationPaths([shelf, visual, `${company}/人力行政中心`]) + + expect(counts.get(company)).toBe(3) + expect(counts.get(`${company}/品牌中心`)).toBe(1) + expect(counts.get(planning)).toBe(1) + expect(counts.get(shelf)).toBe(1) + expect(counts.get(support)).toBe(1) + expect(counts.get(visual)).toBe(1) + expect(counts.get(`${company}/人力行政中心`)).toBe(1) + }) + + test('clicking 商品企划部 includes the person sitting in 架类', () => { + const people = [ + { name: '涂涂', departmentPath: shelf }, + { name: '香樟', departmentPath: `${company}/品牌中心/品牌设计部` }, + ] + expect( + people.filter((person) => isUnderOrganizationPath(person.departmentPath, planning)).map((p) => p.name), + ).toEqual(['涂涂']) + }) + + test('一人兼多个部门时,每个部门名单都有他,公司人数仍只计一次', () => { + const office = `${company}/总经理室` + const brand = `${company}/品牌中心` + const ops = `${company}/运营中心G` + const jiangling = collectEmployeeOrganizationPaths([office, brand, ops, office]) + + expect(jiangling).toEqual([office, brand, ops]) + expect(personBelongsToOrganizationPath(jiangling, brand)).toBe(true) + expect(personBelongsToOrganizationPath(jiangling, office)).toBe(true) + expect(personBelongsToOrganizationPath(jiangling, `${company}/运营中心A`)).toBe(false) + + const counts = countUniquePeopleOnOrganizationPaths([ + jiangling, + [`${company}/人力行政中心`], + ]) + expect(counts.get(company)).toBe(2) + expect(counts.get(brand)).toBe(1) + expect(counts.get(office)).toBe(1) + expect(counts.get(`${company}/人力行政中心`)).toBe(1) + }) + + test('只保留最深任职,上级部门不另算一个职位', () => { + expect( + collectEmployeeOrganizationPaths([ + `${company}/品牌中心`, + `${company}/品牌中心/品牌创意A部`, + `${company}/品牌中心`, + ]), + ).toEqual([`${company}/品牌中心/品牌创意A部`]) + }) + + test('花名册部门 ID 列表会拆出全部任职部门', () => { + expect(parseOrganizationDepartmentIds('[22787301,909676348]')).toEqual(['22787301', '909676348']) + expect(parseOrganizationDepartmentIds('22802296|911666246|32221130')).toEqual([ + '22802296', + '911666246', + '32221130', + ]) + }) +}) diff --git a/lib/auto-personnel-rules.ts b/lib/auto-personnel-rules.ts index 00d033fb..c394f8fc 100644 --- a/lib/auto-personnel-rules.ts +++ b/lib/auto-personnel-rules.ts @@ -53,6 +53,25 @@ export async function getAuthoritativePersonnelForUser(userId: string): Promise< } } +/** + * 花名册是否按在职计:UNKNOWN/空视为在职,宁可多留;只有明确 RESIGNED 才算离职。 + */ +export function isRosterEmployed(employmentState: string | null | undefined): boolean { + return employmentState !== 'RESIGNED' +} + +/** + * 组织架构默认名单:只看花名册在职。 + * includeResigned 打开后才把离职的人加回来,供核对托管/交接。 + */ +export function selectVisibleOrganizationPeople( + people: T[], + includeResigned = false, +): T[] { + if (includeResigned) return people + return people.filter((person) => isRosterEmployed(person.employmentState)) +} + /** * 判断账号是否应自动激活: * 有活跃绑定 + 花名册在职(employmentState 非 RESIGNED;UNKNOWN/空视为在职,宁可多留)。 @@ -61,7 +80,7 @@ export function shouldAutoActivate(personnel: { employmentState: string | null } | null): boolean { if (!personnel) return false - return personnel.employmentState !== 'RESIGNED' + return isRosterEmployed(personnel.employmentState) } /** diff --git a/lib/organization-material-permissions.ts b/lib/organization-material-permissions.ts index 53f96210..38fddba3 100644 --- a/lib/organization-material-permissions.ts +++ b/lib/organization-material-permissions.ts @@ -55,6 +55,110 @@ export function lastOrganizationPathSegment(path: string): string { return slash >= 0 ? last.slice(slash + 1) : last } +export function normalizeOrganizationPath(path: string | null | undefined): string { + return String(path || '') + .split('/') + .map((part) => part.trim()) + .filter(Boolean) + .join('/') +} + +/** 人是否在这个部门:本级,或挂在它下面的子部门。 */ +export function isUnderOrganizationPath( + employeePath: string | null | undefined, + departmentPath: string | null | undefined, +): boolean { + const employee = normalizeOrganizationPath(employeePath) + const department = normalizeOrganizationPath(departmentPath) + if (!employee || !department) return false + return employee === department || employee.startsWith(`${department}/`) +} + +export function collectEmployeeOrganizationPaths( + candidates: Array, +): string[] { + const unique: string[] = [] + const seen = new Set() + for (const candidate of candidates) { + const path = normalizeOrganizationPath(candidate) + if (!path || seen.has(path)) continue + seen.add(path) + unique.push(path) + } + return collapseNestedOrganizationPaths(unique) +} + +/** 花名册常同时给上级和本组。只留最深的任职,避免「品牌创意A部 + 品牌中心」被当成两个职位。 */ +export function collapseNestedOrganizationPaths(paths: string[]): string[] { + return paths.filter( + (path) => !paths.some((other) => other !== path && isUnderOrganizationPath(other, path)), + ) +} + +export function personBelongsToOrganizationPath( + employeePaths: Array, + departmentPath: string | null | undefined, +): boolean { + return employeePaths.some((path) => isUnderOrganizationPath(path, departmentPath)) +} + +export function parseOrganizationDepartmentIds(value: unknown): string[] { + if (value == null) return [] + if (Array.isArray(value)) { + return Array.from(new Set(value.flatMap((item) => parseOrganizationDepartmentIds(item)))) + } + const text = String(value).trim() + if (!text) return [] + if (text.startsWith('[')) { + try { + const parsed = JSON.parse(text) + if (Array.isArray(parsed)) return parseOrganizationDepartmentIds(parsed) + } catch { + // 花名册有时是半截 JSON,继续按分隔符拆。 + } + } + return Array.from( + new Set( + text + .split(/[/>||,,;;\s\[\]]+/) + .map((item) => item.trim()) + .filter((item) => /^\d+$/.test(item)), + ), + ) +} + +/** + * 每个部门路径上的人数(含子孙)。 + * 一个人只加一次到每个祖先,禁止再按子节点滚加,否则公司节点会被加出三四倍。 + */ +export function countPeopleOnOrganizationPaths( + employeePaths: Array, +): Map { + return countUniquePeopleOnOrganizationPaths(employeePaths.map((path) => [path])) +} + +/** + * 一人多部门时:每个任职部门及其祖先都计他一次; + * 两个部门共用的上级(比如公司)仍然只计一个人。 + */ +export function countUniquePeopleOnOrganizationPaths( + peoplePaths: Array>, +): Map { + const counts = new Map() + for (const paths of peoplePaths) { + const prefixes = new Set() + for (const path of paths) { + for (const prefix of organizationPathChain(path || '')) { + prefixes.add(prefix) + } + } + for (const prefix of prefixes) { + counts.set(prefix, (counts.get(prefix) ?? 0) + 1) + } + } + return counts +} + export function findOrganizationPermissionStorageKey( path: string, storedKeys: Iterable,