106 lines
3.1 KiB
TypeScript
106 lines
3.1 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
||
import { getServerSession } from 'next-auth'
|
||
import { authOptions } from '@/lib/auth'
|
||
import { prisma } from '@/lib/prisma'
|
||
|
||
export async function POST(req: NextRequest) {
|
||
try {
|
||
const session = await getServerSession(authOptions)
|
||
|
||
if (!session || session.user.role !== 'ADMIN') {
|
||
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
|
||
}
|
||
|
||
const { userId, departmentName } = await req.json()
|
||
|
||
if (!userId || !departmentName) {
|
||
return NextResponse.json({ error: '用户ID和部门名称不能为空' }, { status: 400 })
|
||
}
|
||
|
||
// 检查该部门是否已经有管理员
|
||
const existingManager = await prisma.user.findFirst({
|
||
where: {
|
||
managedDepartment: departmentName,
|
||
NOT: { id: userId }
|
||
}
|
||
})
|
||
|
||
if (existingManager) {
|
||
return NextResponse.json({
|
||
error: `部门"${departmentName}"已有管理员:${existingManager.username}`
|
||
}, { status: 400 })
|
||
}
|
||
|
||
// 更新用户为部门管理员
|
||
// 同时将用户的department字段设置为该部门,确保部门管理员显示在部门列表中
|
||
// 并将该部门下其他用户的直属上级设置为新管理员
|
||
const user = await prisma.$transaction(async (tx) => {
|
||
// 更新用户为部门管理员
|
||
const updatedUser = await tx.user.update({
|
||
where: { id: userId },
|
||
data: {
|
||
managedDepartment: departmentName,
|
||
department: departmentName, // 确保部门管理员也属于该部门
|
||
role: 'ADMIN' // 设置为管理员角色
|
||
}
|
||
})
|
||
|
||
// 将该部门下其他用户的直属上级设置为新管理员
|
||
await tx.user.updateMany({
|
||
where: {
|
||
department: departmentName,
|
||
id: { not: userId }, // 排除新管理员自己
|
||
},
|
||
data: {
|
||
parentId: userId
|
||
}
|
||
})
|
||
|
||
return updatedUser
|
||
})
|
||
|
||
return NextResponse.json({
|
||
message: '部门管理员设置成功',
|
||
user
|
||
})
|
||
} catch (error) {
|
||
console.error('Set department manager error:', error)
|
||
return NextResponse.json({ error: '设置失败' }, { status: 500 })
|
||
}
|
||
}
|
||
|
||
// 取消部门管理员
|
||
export async function DELETE(req: NextRequest) {
|
||
try {
|
||
const session = await getServerSession(authOptions)
|
||
|
||
if (!session || session.user.role !== 'ADMIN') {
|
||
return NextResponse.json({ error: '需要管理员权限' }, { status: 403 })
|
||
}
|
||
|
||
const { searchParams } = new URL(req.url)
|
||
const userId = searchParams.get('userId')
|
||
|
||
if (!userId) {
|
||
return NextResponse.json({ error: '用户ID不能为空' }, { status: 400 })
|
||
}
|
||
|
||
// 取消部门管理员
|
||
const user = await prisma.user.update({
|
||
where: { id: userId },
|
||
data: {
|
||
managedDepartment: null
|
||
}
|
||
})
|
||
|
||
return NextResponse.json({
|
||
message: '已取消部门管理员',
|
||
user
|
||
})
|
||
} catch (error) {
|
||
console.error('Remove department manager error:', error)
|
||
return NextResponse.json({ error: '取消失败' }, { status: 500 })
|
||
}
|
||
}
|
||
|