import fs from 'node:fs/promises' import path from 'node:path' import { prisma } from '../lib/prisma' import { isSuperAdmin } from '../lib/department-permission' import { getTeamFunctions, saveTeamFunction } from '../lib/team-functions' // One department per invocation; explicit IDs only, dry run by default, never overwrite an existing config. async function main() { const args = process.argv.slice(2) const option = (key: string) => args[args.indexOf(key) + 1] for (const key of ['--department-id', '--template', '--actor-user-id']) { if (!args.includes(key) || !option(key) || option(key).startsWith('--')) throw new Error(`缺少 ${key}`) } const actorUserId = option('--actor-user-id') if (!(await isSuperAdmin(actorUserId))) throw new Error('操作人必须是数据库中的超级管理员。') const { teams } = await getTeamFunctions(true) const team = teams.find(row => row.organizationUnitId === option('--department-id')) if (!team) throw new Error('未找到有效的品牌中心部门 ID。') if (team.revision !== 0) throw new Error('该部门已有配置,拒绝覆盖;请在页面中编辑。') const templates = JSON.parse(await fs.readFile(path.join(process.cwd(), 'data/team-function-initial-content.json'), 'utf8')) const template = templates.find((row: { name: string }) => row.name === option('--template')) if (!template) throw new Error('未找到职责模板。') const leadId = args.includes('--lead-profile-id') ? option('--lead-profile-id') : null if (leadId && !team.candidates.some(person => person.employeeProfileId === leadId)) throw new Error('负责人 ID 不在该部门在职花名册内。') const input = { organizationUnitId: team.organizationUnitId, revision: 0, leadEmployeeProfileId: leadId, description: template.description, branches: template.branches } console.log(JSON.stringify({ apply: args.includes('--apply'), department: { id: team.organizationUnitId, name: team.name, path: team.path }, template: template.name, lead: team.candidates.find(person => person.employeeProfileId === leadId) ?? null, content: input }, null, 2)) if (args.includes('--apply')) console.log(await saveTeamFunction(input, actorUserId)) } main().catch(error => { console.error(error.message); process.exitCode = 1 }).finally(() => prisma.$disconnect())