105 lines
2.9 KiB
TypeScript

// 切换用户激活状态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 === 'pending' ? 'suspended' : status;
targetIsActive = status === 'active';
} else if (isActive !== undefined) {
// 旧格式:使用 isActive 参数(向后兼容)
if (typeof isActive !== 'boolean') {
return NextResponse.json(
{ error: '参数错误' },
{ status: 400 }
);
}
targetIsActive = isActive;
targetStatus = isActive ? 'active' : 'suspended';
} 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 }
);
}
const now = new Date()
await prisma.user.update({
where: { id: userId },
data: {
isActive: targetIsActive,
status: targetStatus,
archivedAt: targetStatus === 'archived' ? now : null,
statusChangedAt: now,
statusChangedBy: sessionUserId,
},
});
const statusMessages: Record<string, string> = {
'active': '用户已激活',
'suspended': '用户已暂停',
'archived': '用户已归档',
};
return NextResponse.json({
message: statusMessages[targetStatus] || (targetIsActive ? '用户已激活' : '用户已禁用'),
});
} catch (error) {
console.error('Toggle active error:', error);
return NextResponse.json(
{ error: '操作失败' },
{ status: 500 }
);
}
}