GuDingZiChan/backend/src/controllers/departmentController.ts
2026-03-23 11:54:41 +08:00

771 lines
22 KiB
TypeScript

import { Request, Response } from 'express'
import prisma from '../utils/prisma'
import { successResponse, errorResponse } from '../utils/response'
import { buildBusinessDepartmentWhere } from '../utils/organization'
const baseSelect = {
id: true,
name: true,
status: true,
parent_id: true,
source_group_id: true,
source_parent_group_id: true,
source_system: true,
last_synced_at: true,
created_at: true,
updated_at: true
}
const departmentCollator = new Intl.Collator('zh-CN', {
numeric: true,
sensitivity: 'base'
})
const personCollator = new Intl.Collator('zh-CN', {
numeric: true,
sensitivity: 'base'
})
const resolveBusinessDepartmentIdsForPerson = (
person: {
main_department_id: number | null
personDepartments: Array<{
department: {
id: number
} | null
}>
},
departmentIdSet: Set<number>
) => {
const ids = new Set<number>()
if (person.main_department_id && departmentIdSet.has(person.main_department_id)) {
ids.add(person.main_department_id)
}
person.personDepartments.forEach((item) => {
if (item.department && departmentIdSet.has(item.department.id)) {
ids.add(item.department.id)
}
})
return [...ids]
}
const hasAnyLinkedDepartment = (person: {
main_department_id: number | null
personDepartments: Array<{
department: {
id: number
} | null
}>
}) => Boolean(person.main_department_id) || person.personDepartments.some((item) => Boolean(item.department))
const buildDepartmentLevelMap = (departments: Array<{ id: number; parent_id: number | null }>) => {
const byId = new Map(departments.map((dept) => [dept.id, dept]))
const cache = new Map<number, number>()
const resolveLevel = (id: number): number => {
if (cache.has(id)) {
return cache.get(id)!
}
const current = byId.get(id)
if (!current || !current.parent_id) {
cache.set(id, 0)
return 0
}
const level = resolveLevel(current.parent_id) + 1
cache.set(id, level)
return level
}
departments.forEach((dept) => resolveLevel(dept.id))
return cache
}
const buildDepartmentTree = (
departments: Array<{
id: number
name: string
status: string
parent_id: number | null
source_system?: string | null
created_at: Date
updated_at: Date
_count: { equipments: number; children: number; personDepartments: number }
}>
) => {
const compareDepartments = (
a: typeof departments[number],
b: typeof departments[number]
) => {
if (a.status !== b.status) {
return a.status === 'active' ? -1 : 1
}
const aHasChildren = a._count.children > 0
const bHasChildren = b._count.children > 0
if (aHasChildren !== bHasChildren) {
return aHasChildren ? -1 : 1
}
const aInUse = a._count.personDepartments > 0 || a._count.equipments > 0
const bInUse = b._count.personDepartments > 0 || b._count.equipments > 0
if (aInUse !== bInUse) {
return aInUse ? -1 : 1
}
const aSynced = Boolean(a.source_system)
const bSynced = Boolean(b.source_system)
if (aSynced !== bSynced) {
return aSynced ? -1 : 1
}
if (a._count.personDepartments !== b._count.personDepartments) {
return b._count.personDepartments - a._count.personDepartments
}
if (a._count.equipments !== b._count.equipments) {
return b._count.equipments - a._count.equipments
}
return departmentCollator.compare(a.name, b.name)
}
const childrenMap = new Map<number | null, typeof departments>()
for (const department of departments) {
const siblings = childrenMap.get(department.parent_id) || []
siblings.push(department)
childrenMap.set(department.parent_id, siblings)
}
childrenMap.forEach((siblings, key) => {
childrenMap.set(key, [...siblings].sort(compareDepartments))
})
const buildNode = (department: typeof departments[number]): any => ({
...department,
equipment_count: department._count.equipments,
children_count: department._count.children,
person_count: department._count.personDepartments,
children: (childrenMap.get(department.id) || []).map(buildNode)
})
return (childrenMap.get(null) || []).map(buildNode)
}
const buildOrganizationTree = (
departments: Array<{
id: number
name: string
status: string
parent_id: number | null
source_system?: string | null
created_at: Date
updated_at: Date
last_synced_at?: Date | null
source_group_id?: number | null
source_parent_group_id?: number | null
_count: { equipments: number; children: number; personDepartments: number }
}>,
people: Array<{
id: number
nickname: string
real_name: string
id_number: string | null
department: string | null
main_department_id: number | null
position: string | null
phone: string | null
email: string | null
status: string
remarks: string | null
source_userid: string | null
source_system: string | null
source_main_department_id: number | null
source_dept_ids: string | null
source_department_name: string | null
source_main_department_name: string | null
department_sync_bucket: string | null
manager_source_userid: string | null
source_employee_status: string | null
last_synced_at: Date | null
created_at: Date
updated_at: Date
mainDepartment: {
id: number
name: string
status: string
parent_id: number | null
source_group_id: number | null
source_system: string | null
last_synced_at: Date | null
} | null
personDepartments: Array<{
department: {
id: number
name: string
status: string
parent_id: number | null
source_group_id: number | null
source_system: string | null
last_synced_at: Date | null
} | null
}>
}>
) => {
const compareDepartments = (
a: typeof departments[number],
b: typeof departments[number]
) => {
if (a.status !== b.status) {
return a.status === 'active' ? -1 : 1
}
const aHasChildren = a._count.children > 0
const bHasChildren = b._count.children > 0
if (aHasChildren !== bHasChildren) {
return aHasChildren ? -1 : 1
}
const aInUse = a._count.personDepartments > 0 || a._count.equipments > 0
const bInUse = b._count.personDepartments > 0 || b._count.equipments > 0
if (aInUse !== bInUse) {
return aInUse ? -1 : 1
}
const aSynced = Boolean(a.source_system)
const bSynced = Boolean(b.source_system)
if (aSynced !== bSynced) {
return aSynced ? -1 : 1
}
if (a._count.personDepartments !== b._count.personDepartments) {
return b._count.personDepartments - a._count.personDepartments
}
if (a._count.equipments !== b._count.equipments) {
return b._count.equipments - a._count.equipments
}
return departmentCollator.compare(a.name, b.name)
}
const comparePeople = (a: typeof people[number], b: typeof people[number]) => {
if (a.status !== b.status) {
return a.status === 'active' ? -1 : 1
}
const aSynced = Boolean(a.source_system)
const bSynced = Boolean(b.source_system)
if (aSynced !== bSynced) {
return aSynced ? -1 : 1
}
return personCollator.compare(`${a.nickname} ${a.real_name}`, `${b.nickname} ${b.real_name}`)
}
const childrenMap = new Map<number | null, typeof departments>()
for (const department of departments) {
const siblings = childrenMap.get(department.parent_id) || []
siblings.push(department)
childrenMap.set(department.parent_id, siblings)
}
childrenMap.forEach((siblings, key) => {
childrenMap.set(key, [...siblings].sort(compareDepartments))
})
const departmentIdSet = new Set(departments.map((department) => department.id))
const peopleByDepartmentId = new Map<number, typeof people>()
const unassignedPeople: typeof people = []
for (const person of people) {
const departmentIds = resolveBusinessDepartmentIdsForPerson(person, departmentIdSet)
if (departmentIds.length === 0) {
if (!hasAnyLinkedDepartment(person)) {
unassignedPeople.push(person)
}
continue
}
departmentIds.forEach((departmentId) => {
const bucket = peopleByDepartmentId.get(departmentId) || []
bucket.push(person)
peopleByDepartmentId.set(departmentId, bucket)
})
}
peopleByDepartmentId.forEach((bucket, departmentId) => {
peopleByDepartmentId.set(departmentId, [...bucket].sort(comparePeople))
})
const serializeOrganizationPerson = (person: typeof people[number]) => {
const departments = Array.from(
new Map(
person.personDepartments
.map((item) => item.department)
.filter(
(
department
): department is NonNullable<(typeof person.personDepartments)[number]['department']> => Boolean(department)
)
.map((department) => [department.id, department] as const)
).values()
)
return {
id: person.id,
nickname: person.nickname,
real_name: person.real_name,
id_number: person.id_number,
department: person.mainDepartment?.name || person.department || departments[0]?.name || null,
main_department_id: person.main_department_id,
main_department: person.mainDepartment
? {
id: person.mainDepartment.id,
name: person.mainDepartment.name,
status: person.mainDepartment.status,
parent_id: person.mainDepartment.parent_id,
source_group_id: person.mainDepartment.source_group_id,
source_system: person.mainDepartment.source_system,
last_synced_at: person.mainDepartment.last_synced_at
}
: null,
departments,
department_names: departments.map((department) => department.name),
position: person.position,
phone: person.phone,
email: person.email,
status: person.status,
remarks: person.remarks,
source_userid: person.source_userid,
source_system: person.source_system,
source_main_department_id: person.source_main_department_id,
source_dept_ids: person.source_dept_ids,
source_department_name: person.source_department_name,
source_main_department_name: person.source_main_department_name,
department_sync_bucket: person.department_sync_bucket,
manager_source_userid: person.manager_source_userid,
source_employee_status: person.source_employee_status,
last_synced_at: person.last_synced_at,
is_synced: Boolean(person.source_system),
created_at: person.created_at,
updated_at: person.updated_at
}
}
const normalizedUnassignedPeople = [...unassignedPeople].sort(comparePeople).map(serializeOrganizationPerson)
const buildNode = (department: typeof departments[number]): any => {
const normalizedPeople = (peopleByDepartmentId.get(department.id) || []).map(serializeOrganizationPerson)
const childNodes = (childrenMap.get(department.id) || []).map(buildNode)
const totalPersonCount =
normalizedPeople.length + childNodes.reduce((sum: number, child: any) => sum + child.total_person_count, 0)
return {
...department,
equipment_count: department._count.equipments,
children_count: department._count.children,
person_count: department._count.personDepartments,
direct_person_count: normalizedPeople.length,
total_person_count: totalPersonCount,
people: normalizedPeople,
children: childNodes
}
}
const tree = (childrenMap.get(null) || []).map(buildNode)
return {
departments: tree,
unassigned_people: normalizedUnassignedPeople
}
}
// 获取启用的部门列表(下拉选项,含层级信息)
export const getDepartmentOptions = async (_req: Request, res: Response) => {
try {
const departments = await prisma.department.findMany({
where: {
AND: [
buildBusinessDepartmentWhere(),
{ status: 'active' }
]
},
orderBy: [{ parent_id: 'asc' }, { name: 'asc' }],
select: {
...baseSelect,
parent: {
select: { id: true, name: true }
}
}
})
const levelMap = buildDepartmentLevelMap(departments)
const options = departments.map(dept => ({
...dept,
parent_name: dept.parent?.name || null,
level: levelMap.get(dept.id) || 0
}))
successResponse(res, options, '获取成功')
} catch (error: any) {
errorResponse(res, error.message || '获取部门列表失败')
}
}
// 获取部门树形结构
export const getDepartmentTree = async (_req: Request, res: Response) => {
try {
const departments = await prisma.department.findMany({
where: buildBusinessDepartmentWhere(),
orderBy: [{ parent_id: 'asc' }, { name: 'asc' }],
select: {
...baseSelect,
_count: {
select: { equipments: true, children: true, personDepartments: true }
}
}
})
const tree = buildDepartmentTree(departments)
successResponse(res, tree, '获取成功')
} catch (error: any) {
errorResponse(res, error.message || '获取部门树失败')
}
}
export const getOrganizationTree = async (_req: Request, res: Response) => {
try {
const [departments, allPeople] = await Promise.all([
prisma.department.findMany({
where: buildBusinessDepartmentWhere(),
orderBy: [{ parent_id: 'asc' }, { name: 'asc' }],
select: {
...baseSelect,
_count: {
select: { equipments: true, children: true, personDepartments: true }
}
}
}),
prisma.person.findMany({
orderBy: [{ status: 'asc' }, { nickname: 'asc' }, { real_name: 'asc' }],
include: {
mainDepartment: {
select: {
id: true,
name: true,
status: true,
parent_id: true,
source_group_id: true,
source_system: true,
last_synced_at: true
}
},
personDepartments: {
select: {
department: {
select: {
id: true,
name: true,
status: true,
parent_id: true,
source_group_id: true,
source_system: true,
last_synced_at: true
}
}
}
}
}
})
])
const businessDepartmentIdSet = new Set(departments.map((department) => department.id))
const people = allPeople.filter((person) => {
const businessDepartmentIds = resolveBusinessDepartmentIdsForPerson(person, businessDepartmentIdSet)
if (businessDepartmentIds.length > 0) {
return true
}
return !hasAnyLinkedDepartment(person)
})
const tree = buildOrganizationTree(departments, people as any)
const activePersonTotal = people.filter((person) => person.status === 'active').length
const syncedPersonTotal = people.filter((person) => Boolean(person.source_system)).length
successResponse(
res,
{
...tree,
summary: {
department_total: departments.length,
active_department_total: departments.filter((department) => department.status === 'active').length,
person_total: people.length,
active_person_total: activePersonTotal,
inactive_person_total: people.length - activePersonTotal,
synced_person_total: syncedPersonTotal,
local_person_total: people.length - syncedPersonTotal,
unassigned_person_total: tree.unassigned_people.length
}
},
'获取成功'
)
} catch (error: any) {
errorResponse(res, error.message || '获取组织架构失败')
}
}
// 获取部门列表(分页)
export const getDepartmentList = async (req: Request, res: Response) => {
try {
const { page = 1, pageSize = 10, keyword, status } = req.query
const where: any = {
AND: [buildBusinessDepartmentWhere()]
}
if (status) {
where.AND.push({ status })
}
if (keyword) {
where.AND.push({ name: { contains: keyword as string } })
}
const skip = (Number(page) - 1) * Number(pageSize)
const [list, total] = await Promise.all([
prisma.department.findMany({
where,
skip,
take: Number(pageSize),
orderBy: [{ parent_id: 'asc' }, { updated_at: 'desc' }],
select: {
...baseSelect,
parent: {
select: { id: true, name: true }
},
_count: {
select: { equipments: true, children: true, personDepartments: true }
}
}
}),
prisma.department.count({ where })
])
const levelMap = buildDepartmentLevelMap(list)
const formattedList = list.map(dept => ({
...dept,
parent_name: dept.parent?.name || null,
level: levelMap.get(dept.id) || 0,
equipment_count: dept._count.equipments,
children_count: dept._count.children,
person_count: dept._count.personDepartments
}))
successResponse(
res,
{
list: formattedList,
total,
page: Number(page),
pageSize: Number(pageSize)
},
'获取成功'
)
} catch (error: any) {
errorResponse(res, error.message || '获取部门列表失败')
}
}
// 验证父部门有效性
const validateParentDepartment = async (parentId: number | null | undefined, currentId?: number): Promise<string | null> => {
if (!parentId) return null
const parent = await prisma.department.findFirst({
where: {
id: parentId,
...buildBusinessDepartmentWhere()
},
select: { id: true, parent_id: true, status: true }
})
if (!parent) {
return '指定的父部门不存在'
}
if (parent.status !== 'active') {
return '父部门已禁用,无法设置'
}
// 检查是否设置自己为父部门
if (currentId && parentId === currentId) {
return '不能将部门设为自己的子部门'
}
if (currentId) {
let cursor = parent
while (cursor.parent_id) {
if (cursor.parent_id === currentId) {
return '不能将部门设为自己的子部门'
}
cursor = await prisma.department.findUnique({
where: { id: cursor.parent_id },
select: { id: true, parent_id: true, status: true }
}) as any
if (!cursor) break
}
}
return null
}
// 创建部门
export const createDepartment = async (req: Request, res: Response) => {
try {
const { name, parent_id } = req.body as { name?: string; parent_id?: number | null }
if (!name || !name.trim()) {
return errorResponse(res, '部门名称不能为空', 422)
}
// 验证父部门
const parentError = await validateParentDepartment(parent_id)
if (parentError) {
return errorResponse(res, parentError, 400)
}
const department = await prisma.department.create({
data: {
name: name.trim(),
parent_id: parent_id || null
},
select: {
...baseSelect,
parent: {
select: { id: true, name: true }
}
}
})
successResponse(res, {
...department,
parent_name: department.parent?.name || null,
level: department.parent_id ? 1 : 0
}, '新增部门成功')
} catch (error: any) {
if (error.code === 'P2002') {
return errorResponse(res, '部门名称已存在')
}
errorResponse(res, error.message || '新增部门失败')
}
}
// 更新部门
export const updateDepartment = async (req: Request, res: Response) => {
try {
const { id } = req.params
const { name, status, parent_id } = req.body as { name?: string; status?: string; parent_id?: number | null }
const existing = await prisma.department.findFirst({
where: {
id: Number(id),
...buildBusinessDepartmentWhere()
},
include: {
_count: { select: { children: true } }
}
})
if (!existing) {
return errorResponse(res, '部门不存在', 404)
}
if (name !== undefined && !name.trim()) {
return errorResponse(res, '部门名称不能为空', 422)
}
// 如果要设置父部门,验证有效性
if (parent_id !== undefined) {
const parentError = await validateParentDepartment(parent_id, Number(id))
if (parentError) {
return errorResponse(res, parentError, 400)
}
}
const updated = await prisma.department.update({
where: { id: Number(id) },
data: {
name: name?.trim() || existing.name,
status: status || existing.status,
parent_id: parent_id !== undefined ? (parent_id || null) : existing.parent_id
},
select: {
...baseSelect,
parent: {
select: { id: true, name: true }
}
}
})
successResponse(res, {
...updated,
parent_name: updated.parent?.name || null,
level: updated.parent_id ? 1 : 0
}, '更新部门成功')
} catch (error: any) {
if (error.code === 'P2002') {
return errorResponse(res, '部门名称已存在')
}
errorResponse(res, error.message || '更新部门失败')
}
}
// 删除部门
export const deleteDepartment = async (req: Request, res: Response) => {
try {
const { id } = req.params
const existing = await prisma.department.findFirst({
where: {
id: Number(id),
...buildBusinessDepartmentWhere()
},
include: {
_count: {
select: { equipments: true, children: true, mainPersons: true, personDepartments: true }
}
}
})
if (!existing) {
return errorResponse(res, '部门不存在', 404)
}
// 检查是否有子部门
if (existing._count.children > 0) {
return errorResponse(res, '该部门下存在子部门,请先删除或转移子部门', 400)
}
if (existing._count.equipments > 0) {
return errorResponse(res, '该部门已被资产使用,无法删除')
}
if (existing._count.mainPersons > 0 || existing._count.personDepartments > 0) {
return errorResponse(res, '该部门已被人员主数据使用,无法删除')
}
await prisma.department.delete({
where: { id: Number(id) }
})
successResponse(res, null, '删除部门成功')
} catch (error: any) {
errorResponse(res, error.message || '删除部门失败')
}
}