2026-06-03 18:41:52 +08:00

254 lines
7.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { canUseDepartmentIsolation, planDepartmentStructureChangeWithPaidCore } from '@/lib/license'
import { isCurrentSuperAdmin } from '@/lib/admin-permissions'
function departmentPlanResponse(plan: {
valid: boolean
allowed: boolean
statusCode?: number
error?: string
errorCode?: string
response?: Record<string, unknown>
details?: Record<string, unknown>
}) {
if (plan.response) {
return NextResponse.json(plan.response, { status: plan.statusCode || 200 })
}
return NextResponse.json(
{
error: plan.error || '付费增强包无法规划部门结构变更',
errorCode: plan.errorCode,
details: plan.details,
},
{ status: plan.statusCode || 503 }
)
}
async function loadDepartmentPlanSnapshot() {
return prisma.department.findMany({
select: { id: true, name: true },
orderBy: { createdAt: 'asc' },
})
}
// Get all departments
export async function GET() {
try {
const departments = await prisma.department.findMany({
orderBy: {
createdAt: 'asc',
},
})
return NextResponse.json(departments)
} catch (error) {
console.error('Error fetching departments:', error)
return NextResponse.json(
{ error: '获取部门列表失败' },
{ status: 500 }
)
}
}
// Create a new department (super admin only)
export async function POST(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || !(await isCurrentSuperAdmin(session))) {
return NextResponse.json(
{ error: '仅最高权限账号可维护部门结构' },
{ status: 403 }
)
}
// 检查部门隔离功能是否可用
if (!(await canUseDepartmentIsolation())) {
return NextResponse.json(
{ error: '当前许可证未包含部门隔离功能,请联系管理员处理授权' },
{ status: 403 }
)
}
const { name } = await req.json()
const departments = await loadDepartmentPlanSnapshot()
const plan = await planDepartmentStructureChangeWithPaidCore({
action: 'create',
target: { name },
departments,
})
if (!plan.valid || !plan.allowed) {
return departmentPlanResponse(plan)
}
const createOp = plan.departmentOps.find((op) => op.type === 'create') as any
if (!createOp?.data) {
return NextResponse.json({ error: '部门创建计划无效' }, { status: 503 })
}
const department = await prisma.department.create({
data: createOp.data,
})
return NextResponse.json(department, { status: 201 })
} catch (error) {
console.error('Error creating department:', error)
return NextResponse.json(
{ error: '创建部门失败' },
{ status: 500 }
)
}
}
// Rename a department (super admin only)
export async function PATCH(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || !(await isCurrentSuperAdmin(session))) {
return NextResponse.json(
{ error: '仅最高权限账号可维护部门结构' },
{ status: 403 }
)
}
if (!(await canUseDepartmentIsolation())) {
return NextResponse.json(
{ error: '当前许可证未包含部门隔离功能,请联系管理员处理授权' },
{ status: 403 }
)
}
const { id, name } = await req.json()
const [departments, users] = await Promise.all([
loadDepartmentPlanSnapshot(),
prisma.user.findMany({
select: {
id: true,
department: true,
managedDepartment: true,
},
}),
])
const plan = await planDepartmentStructureChangeWithPaidCore({
action: 'rename',
target: { id, name },
departments,
users,
})
if (!plan.valid || !plan.allowed) {
return departmentPlanResponse(plan)
}
await prisma.$transaction(async (tx) => {
for (const item of plan.departmentOps.filter((op) => op.type === 'rename') as any[]) {
await tx.department.update({
where: { id: item.id },
data: { name: item.newName },
})
}
for (const userOp of plan.userOps.filter((op) => op.type === 'update') as any[]) {
if (userOp.id && userOp.data && Object.keys(userOp.data).length > 0) {
await tx.user.update({
where: { id: userOp.id },
data: userOp.data,
})
}
}
})
const refreshedDepartment = await prisma.department.findUnique({
where: { id },
})
return NextResponse.json(refreshedDepartment)
} catch (error) {
console.error('Error updating department:', error)
return NextResponse.json(
{ error: '更新部门失败' },
{ status: 500 }
)
}
}
// Delete a department (super admin only)
export async function DELETE(req: NextRequest) {
try {
const session = await getServerSession(authOptions)
if (!session || !(await isCurrentSuperAdmin(session))) {
return NextResponse.json(
{ error: '仅最高权限账号可维护部门结构' },
{ status: 403 }
)
}
if (!(await canUseDepartmentIsolation())) {
return NextResponse.json(
{ error: '当前许可证未包含部门隔离功能,请联系管理员处理授权' },
{ status: 403 }
)
}
const { searchParams } = new URL(req.url)
const id = searchParams.get('id')
const departments = await loadDepartmentPlanSnapshot()
const plan = await planDepartmentStructureChangeWithPaidCore({
action: 'delete',
target: { id },
departments,
})
if (!plan.valid || !plan.allowed) {
return departmentPlanResponse(plan)
}
const deleteOp = plan.departmentOps.find((op) => op.type === 'deleteMany') as any
const targetIds = Array.isArray(deleteOp?.ids) ? deleteOp.ids : []
const targetNames = Array.isArray(deleteOp?.names) ? deleteOp.names : []
await prisma.$transaction(async (tx) => {
for (const userOp of plan.userOps as any[]) {
if (userOp.type === 'clearDepartmentIn' && Array.isArray(userOp.names) && userOp.names.length > 0) {
await tx.user.updateMany({
where: { department: { in: userOp.names } },
data: { department: '' },
})
}
if (userOp.type === 'clearManagedDepartmentIn' && Array.isArray(userOp.names) && userOp.names.length > 0) {
await tx.user.updateMany({
where: { managedDepartment: { in: userOp.names } },
data: { managedDepartment: null },
})
}
}
if (targetIds.length > 0) {
await tx.department.deleteMany({
where: { id: { in: targetIds } },
})
}
})
return NextResponse.json({
message: `已删除 ${targetIds.length} 个分支`,
removedDepartments: targetNames,
})
} catch (error) {
console.error('Error deleting department:', error)
return NextResponse.json(
{ error: '删除失败' },
{ status: 500 }
)
}
}