76 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
/**
* 更新用户部门
* POST /api/admin/users/update-department
*/
export async function POST(request: NextRequest) {
try {
// 验证管理员权限
const session = await getServerSession(authOptions);
if (!session || !session.user || (session.user as any).role !== 'ADMIN') {
return NextResponse.json(
{ error: '权限不足' },
{ status: 403 }
);
}
const { userId, department } = await request.json();
if (!userId) {
return NextResponse.json(
{ error: '缺少用户ID' },
{ status: 400 }
);
}
// 双写:同时更新 department(旧字段)和 departmentId(新字段)
let updateData: any = {
department: department || '' // 旧字段(向后兼容)
};
// 如果提供了部门名称,查找对应的部门ID
if (department && department.trim() !== '') {
const dept = await prisma.department.findUnique({
where: { name: department.trim() }
});
if (dept) {
updateData.departmentId = dept.id; // 新字段(阶段二新增)
} else {
// 部门不存在,清除 departmentId
updateData.departmentId = null;
}
} else {
// 部门为空,清除 departmentId
updateData.departmentId = null;
}
// 更新用户部门
const user = await prisma.user.update({
where: { id: userId },
data: updateData,
include: {
departmentRef: true // 包含部门关联信息
}
});
console.log('[Update Department] Success:', {
userId: user.id,
username: user.username,
department: user.department
});
return NextResponse.json(user);
} catch (error) {
console.error('[Update Department] Error:', error);
return NextResponse.json(
{ error: '更新部门失败' },
{ status: 500 }
);
}
}