import { createHash, randomUUID } from 'node:crypto' import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from 'node:fs' import { dirname, resolve } from 'node:path' import { Prisma } from '@prisma/client' import { prisma } from '../lib/prisma' import { requireSalaryAccess } from '../lib/personnel-salary' import { INITIAL_SALARY_POSITIONS } from '../lib/salary-position-seeds' import { PERFORMANCE_BASELINE, percentageBasisPoints, positionFieldsSchema, type PositionDimension } from '../lib/salary-position-contract' type Version = { id: string; effectiveMonth: string; description: string; dimensions: PositionDimension[]; revision: number } type Operation = { id: string; revision: number; fingerprint: string; versions: Version[] } type Manifest = { id: string; database: string; generatedAt: string; actor: string snapshot: unknown; operations: Operation[] } const mode = process.argv[2] ?? 'audit' const manifestPath = resolve(process.argv[3] ?? '.private/salary-performance-versions/manifest.json') const actor = process.env.SALARY_VERSION_ACTOR_ID ?? '' const target = new URL(process.env.DATABASE_URL ?? '') const local = ['127.0.0.1', 'localhost'].includes(target.hostname) && target.pathname.startsWith('/salary_isolated_') const digest = (value: unknown): string => createHash('sha256').update(JSON.stringify(value)).digest('hex') const canonical = (value: unknown): unknown => value instanceof Date ? value.toISOString() : Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value const equal = (a: unknown, b: unknown) => digest(canonical(a)) === digest(canonical(b)) const save = (path: string, value: unknown) => { mkdirSync(dirname(path), { recursive: true, mode: 0o700 }) writeFileSync(path + '.next', JSON.stringify(value, null, 2), { mode: 0o600 }) renameSync(path + '.next', path) } const cleanDescription = (value: string) => value.replace(/[;;]?最新配置适用于所有月份/g, '') const normalize = (versions: Array<{ id: string; effectiveMonth: string; description: string; dimensions: unknown; revision: number }>) => versions.map(version => ({ id: version.id, effectiveMonth: version.effectiveMonth, description: version.description, dimensions: version.dimensions, revision: version.revision })) .sort((a, b) => a.effectiveMonth.localeCompare(b.effectiveMonth)) async function main() { if (!['audit', 'apply', 'restore'].includes(mode)) throw Error('使用 audit、apply 或 restore') if (!actor) throw Error('请指定当前有效超管 SALARY_VERSION_ACTOR_ID') if (!local && process.env.SALARY_VERSION_EXPECTED_DATABASE !== target.pathname.slice(1)) throw Error('请明确设置目标数据库 SALARY_VERSION_EXPECTED_DATABASE') await requireSalaryAccess(actor, true) if (mode === 'audit' && existsSync(manifestPath)) throw Error('快照已存在,请使用原清单或选择新路径') if (mode === 'audit') { const manifest = await prisma.$transaction(async db => { await db.$executeRawUnsafe('SET TRANSACTION READ ONLY') await requireSalaryAccess(actor, true, db) const positions = await db.salaryPositionConfig.findMany({ where: { deletedAt: null }, include: { performanceVersions: { orderBy: { effectiveMonth: 'asc' } } }, orderBy: { id: 'asc' }, }) const audits = await db.salaryPositionConfigAudit.findMany({ where: { positionId: { in: positions.map(position => position.id) } }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] }) const operations: Operation[] = positions.map(position => { if (position.performanceVersions.length) throw Error(`岗位已有版本,请先核对现有清单 ${position.id}`) const seed = INITIAL_SALARY_POSITIONS.find(seed => seed.id === position.id) const history = audits.filter(audit => audit.positionId === position.id).flatMap(audit => [audit.before, audit.after]) .flatMap(snapshot => { if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) return [] // Audit snapshots can contain identity fields. Validate only the saved business fields. const record = snapshot as Record const parsed = positionFieldsSchema.safeParse({ name: record.name, salaryRole: record.salaryRole ?? position.salaryRole, description: record.description, dimensions: record.dimensions, }) return parsed.success ? [parsed.data] : [] }) const versions: Version[] = [] if (seed) { const weights = (dimensions: PositionDimension[]) => dimensions.map(d => [d.id, percentageBasisPoints(d.weight), d.metrics.map(m => [m.id, percentageBasisPoints(m.weight)])]) const previous = history.find(snapshot => equal(weights(snapshot.dimensions), weights(seed.value.dimensions))) if (!previous) throw Error(`缺少可信历史方案 ${position.id}`) const latest = [ ...history.map(snapshot => snapshot.dimensions), position.dimensions as PositionDimension[] ] .flatMap(dimensions => dimensions.flatMap(d => d.metrics)) const sources = new Map(latest.map(metric => [metric.id, metric.source])) const dimensions = structuredClone(previous.dimensions) for (const dimension of dimensions) for (const metric of dimension.metrics) { const source = sources.get(metric.id) if (source) metric.source = source } positionFieldsSchema.parse({ ...previous, dimensions }) versions.push({ id: randomUUID(), effectiveMonth: PERFORMANCE_BASELINE, description: cleanDescription(previous.description), dimensions, revision: 1 }) } versions.push({ id: randomUUID(), effectiveMonth: '2026-11', description: cleanDescription(position.description), dimensions: position.dimensions as PositionDimension[], revision: 1, }) return { id: position.id, revision: position.revision, fingerprint: digest(canonical(position)), versions } }) return { id: randomUUID(), database: target.pathname.slice(1), generatedAt: new Date().toISOString(), actor, snapshot: { positions, audits }, operations } }, { isolationLevel: 'RepeatableRead', timeout: 20000 }) save(manifestPath, manifest) console.log(JSON.stringify({ mode, positions: manifest.operations.length, versions: manifest.operations.reduce((n, operation) => n + operation.versions.length, 0), privateSnapshot: manifestPath })) return } const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Manifest if (manifest.database !== target.pathname.slice(1) || !manifest.id || !manifest.operations?.length) throw Error('清单与目标库不匹配') const results = await prisma.$transaction(async db => { await requireSalaryAccess(actor, true, db) await db.$executeRawUnsafe('SELECT pg_advisory_xact_lock(8261126)') const results: Array<{ id: string; status: string }> = [] for (const operation of manifest.operations) { const row = await db.salaryPositionConfig.findUniqueOrThrow({ where: { id: operation.id }, include: { performanceVersions: { orderBy: { effectiveMonth: 'asc' } } } }) const receipt = await db.salaryPositionConfigAudit.findFirst({ where: { positionId: row.id, action: 'INITIALIZE_PERFORMANCE_VERSIONS', after: { path: ['manifestId'], equals: manifest.id } }, }) const restored = await db.salaryPositionConfigAudit.findFirst({ where: { positionId: row.id, action: 'RESTORE_PERFORMANCE_VERSIONS', after: { path: ['manifestId'], equals: manifest.id } }, }) if (mode === 'apply' && receipt) { if (restored || row.revision !== operation.revision + 1 || !equal(normalize(row.performanceVersions), normalize(operation.versions))) throw Error('初始化后出现修改,请重新核对') results.push({ id: row.id, status: 'skipped' }) continue } if (mode === 'restore') { if (!receipt) throw Error('缺少本次初始化审计') if (restored) { if (row.revision !== operation.revision + 2 || row.performanceVersions.length) throw Error('恢复后存在后续修改') results.push({ id: row.id, status: 'skipped' }) continue } if (row.revision !== operation.revision + 1 || !equal(normalize(row.performanceVersions), normalize(operation.versions))) throw Error('配置已修改,停止恢复') await db.salaryPerformanceVersion.deleteMany({ where: { positionId: row.id, id: { in: operation.versions.map(version => version.id) } } }) } else { if (digest(canonical(row)) !== operation.fingerprint) throw Error('配置或修订已变化,停止初始化') await db.salaryPerformanceVersion.createMany({ data: operation.versions.map(version => ({ ...version, positionId: row.id })) }) } const changed = await db.salaryPositionConfig.updateMany({ where: { id: row.id, revision: row.revision, deletedAt: null }, data: { revision: { increment: 1 }, updatedByUserId: actor, } }) if (changed.count !== 1) throw Error('岗位修订冲突') await db.salaryPositionConfigAudit.create({ data: { positionId: row.id, actorUserId: actor, action: mode === 'restore' ? 'RESTORE_PERFORMANCE_VERSIONS' : 'INITIALIZE_PERFORMANCE_VERSIONS', before: { revision: row.revision, versions: normalize(row.performanceVersions) } as Prisma.InputJsonValue, after: { manifestId: manifest.id, revision: row.revision + 1, versions: mode === 'restore' ? [] : operation.versions } as Prisma.InputJsonValue, } }) results.push({ id: row.id, status: mode === 'restore' ? 'restored' : 'applied' }) } return results }, { isolationLevel: 'Serializable', timeout: 20000 }) save(manifestPath + '.' + mode + '.json', { manifestId: manifest.id, generatedAt: new Date().toISOString(), actor, results }) console.log(JSON.stringify({ mode, results, privateReceipt: manifestPath + '.' + mode + '.json' })) } main().catch(error => { console.error(error instanceof Error ? error.message : '配置维护失败'); process.exitCode = 1 }).finally(() => prisma.$disconnect())