import { NextRequest, NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/lib/auth'; import { prisma } from '@/lib/prisma'; import { isSystemAdmin } from '@/lib/department-permission'; /** * 设置部门管理员 * POST /api/admin/users/set-department-manager */ export async function POST(request: NextRequest) { try { // 验证管理员权限 const session = await getServerSession(authOptions); if (!session || !session.user || !isSystemAdmin((session.user as any).role)) { return NextResponse.json( { error: '需要管理员权限' }, { status: 403 } ); } const { userId, departmentName } = await request.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 } ); } // 设置部门管理员(同时提升为管理员角色) const user = await prisma.user.update({ where: { id: userId }, data: { managedDepartment: departmentName, role: 'ADMIN' } }); return NextResponse.json({ message: '部门管理员设置成功', user }); } catch (error) { console.error('Set department manager error:', error); return NextResponse.json( { error: '设置失败' }, { status: 500 } ); } } /** * 取消部门管理员 * DELETE /api/admin/users/set-department-manager?userId=xxx */ export async function DELETE(request: NextRequest) { try { // 验证管理员权限 const session = await getServerSession(authOptions); if (!session || !session.user || !isSystemAdmin((session.user as any).role)) { return NextResponse.json( { error: '需要管理员权限' }, { status: 403 } ); } const { searchParams } = new URL(request.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 } ); } }