2026-05-14 14:58:12 +08:00

93 lines
2.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { isSuperAdmin } from '@/lib/department-permission';
/**
* POST - 批量更新权限配置
*/
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
const userId = (session?.user as any)?.id;
if (!session || !(await isSuperAdmin(userId))) {
return NextResponse.json({ error: '需要超级管理员权限' }, { status: 403 });
}
const body = await request.json();
const { department } = body || {};
const permissions: Array<{
materialType: string;
canView?: boolean;
canDownload?: boolean;
canDownloadSource?: boolean;
canShare?: boolean;
}> = body?.permissions || [];
if (!department || !Array.isArray(permissions) || permissions.length === 0) {
return NextResponse.json(
{ error: '部门名称和素材类型列表不能为空' },
{ status: 400 }
);
}
const materialTypes = permissions.map((p) => p.materialType).filter(Boolean);
// 检查是否有关联部门
const existing = await prisma.departmentMaterialPermission.findFirst({
where: {
department,
materialType: { in: materialTypes },
linkedToDepartment: { not: null },
},
});
if (existing) {
return NextResponse.json(
{ error: '该部门已关联到其他部门,请先取消关联' },
{ status: 400 }
);
}
// 批量更新权限配置
const updates = permissions.map((perm) =>
prisma.departmentMaterialPermission.upsert({
where: {
department_materialType: {
department,
materialType: perm.materialType,
},
},
update: {
canView: perm.canView ?? false,
canDownload: perm.canDownload ?? false,
canDownloadSource: perm.canDownloadSource ?? false,
canShare: perm.canShare ?? true,
linkedToDepartment: null,
},
create: {
department,
materialType: perm.materialType,
canView: perm.canView ?? false,
canDownload: perm.canDownload ?? false,
canDownloadSource: perm.canDownloadSource ?? false,
canShare: perm.canShare ?? true,
linkedToDepartment: null,
},
})
);
await Promise.all(updates);
return NextResponse.json({
message: '批量更新成功',
updatedCount: permissions.length,
});
} catch (error) {
console.error('[Department Permissions Batch] Error:', error);
return NextResponse.json({ error: '批量更新失败' }, { status: 500 });
}
}