78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
/**
|
||
* 数据迁移脚本:为所有现有部门创建默认权限配置
|
||
*
|
||
* 使用方法:
|
||
* npx tsx scripts/migrate-department-permissions.ts
|
||
*/
|
||
|
||
import { PrismaClient } from '@prisma/client';
|
||
import { getAllMaterialTypes } from '../lib/department-permission';
|
||
|
||
const prisma = new PrismaClient();
|
||
|
||
async function main() {
|
||
console.log('开始迁移部门权限配置...');
|
||
|
||
// 获取所有部门
|
||
const departments = await prisma.department.findMany({
|
||
orderBy: { name: 'asc' },
|
||
});
|
||
|
||
console.log(`找到 ${departments.length} 个部门`);
|
||
|
||
// 获取所有素材类型(从数据库动态获取)
|
||
const allMaterialTypes = await getAllMaterialTypes();
|
||
console.log(`找到 ${allMaterialTypes.length} 种素材类型:`, allMaterialTypes.join(', '));
|
||
|
||
let createdCount = 0;
|
||
let skippedCount = 0;
|
||
|
||
for (const dept of departments) {
|
||
console.log(`处理部门: ${dept.name}`);
|
||
|
||
// 检查是否已有权限配置
|
||
const existingPermissions = await prisma.departmentMaterialPermission.findMany({
|
||
where: { department: dept.name },
|
||
});
|
||
|
||
const existingTypes = new Set(existingPermissions.map((p) => p.materialType));
|
||
|
||
// 为缺失的素材类型创建默认权限配置
|
||
const newPermissions = allMaterialTypes
|
||
.filter((type) => !existingTypes.has(type))
|
||
.map((materialType) => ({
|
||
department: dept.name,
|
||
materialType,
|
||
canView: false, // 默认不允许查看
|
||
canDownload: false, // 默认不允许下载
|
||
canShare: true, // 默认允许分享
|
||
linkedToDepartment: null,
|
||
}));
|
||
|
||
if (newPermissions.length > 0) {
|
||
await prisma.departmentMaterialPermission.createMany({
|
||
data: newPermissions,
|
||
});
|
||
createdCount += newPermissions.length;
|
||
console.log(` 为 ${dept.name} 创建了 ${newPermissions.length} 条权限配置`);
|
||
} else {
|
||
skippedCount++;
|
||
console.log(` ${dept.name} 已有完整权限配置,跳过`);
|
||
}
|
||
}
|
||
|
||
console.log('\n迁移完成!');
|
||
console.log(`创建了 ${createdCount} 条权限配置`);
|
||
console.log(`跳过了 ${skippedCount} 个部门(已有完整配置)`);
|
||
}
|
||
|
||
main()
|
||
.catch((error) => {
|
||
console.error('迁移失败:', error);
|
||
process.exit(1);
|
||
})
|
||
.finally(async () => {
|
||
await prisma.$disconnect();
|
||
});
|
||
|