// 切换用户激活状态API 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 - 切换用户激活状态(仅管理员) export async function POST(request: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.user || !(session.user as any).id) { return NextResponse.json( { error: '未登录' }, { status: 401 } ); } const userRole = (session.user as any).role; if (!isSystemAdmin(userRole)) { return NextResponse.json( { error: '无权限' }, { status: 403 } ); } const { userId, isActive, status } = await request.json(); // 支持新旧两种参数格式 let targetStatus: string; let targetIsActive: boolean; if (status !== undefined) { // 新格式:使用 status 参数 if (!['pending', 'active', 'suspended', 'archived'].includes(status)) { return NextResponse.json( { error: '无效的状态值' }, { status: 400 } ); } targetStatus = status; targetIsActive = status === 'active'; } else if (isActive !== undefined) { // 旧格式:使用 isActive 参数(向后兼容) if (typeof isActive !== 'boolean') { return NextResponse.json( { error: '参数错误' }, { status: 400 } ); } targetIsActive = isActive; targetStatus = isActive ? 'active' : 'pending'; } else { return NextResponse.json( { error: '缺少参数:需要 isActive 或 status' }, { status: 400 } ); } if (!userId) { return NextResponse.json( { error: '缺少用户ID' }, { status: 400 } ); } const sessionUserId = (session.user as any).id; // 不能禁用自己 if (userId === sessionUserId) { return NextResponse.json( { error: '不能禁用自己' }, { status: 400 } ); } // 双写:同时更新 status 和 isActive const updateData: any = { isActive: targetIsActive, // 旧字段(向后兼容) status: targetStatus, // 新字段(阶段一新增) }; // 如果状态为 archived,设置 archivedAt if (targetStatus === 'archived') { updateData.archivedAt = new Date(); } else if (targetStatus !== 'archived') { // 如果从 archived 状态恢复,清除 archivedAt updateData.archivedAt = null; } await prisma.user.update({ where: { id: userId }, data: updateData, }); const statusMessages: Record = { 'pending': '用户已设置为待激活', 'active': '用户已激活', 'suspended': '用户已暂停', 'archived': '用户已归档', }; return NextResponse.json({ message: statusMessages[targetStatus] || (targetIsActive ? '用户已激活' : '用户已禁用'), }); } catch (error) { console.error('Toggle active error:', error); return NextResponse.json( { error: '操作失败' }, { status: 500 } ); } }