gongxiangp2/scripts/initialize-personnel-salary-production.ts

46 lines
3.8 KiB
TypeScript

/** One-shot production seed. Payroll is supplied privately, never included in the image. */
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { z } from 'zod'
import { prisma } from '../lib/prisma'
import { initializeSalaryRecords, requireSalaryAccess } from '../lib/personnel-salary'
import { createSalarySchema } from '../lib/personnel-salary-contract'
import { listEmployedBrandCenterPeople } from '../lib/employee-directory'
const inputSchema = z.object({ actorUserId: z.string().uuid(), rows: z.array(z.object({
expectedJobNumber: z.string().min(1), expectedFlowerName: z.string(), value: createSalarySchema,
}).strict()).length(7) }).strict()
async function main() {
const args = process.argv.slice(2)
if (args.some(arg => !['--audit', '--apply'].includes(arg)) || args.length !== 1) throw new Error('Choose --audit or --apply')
const apply = args[0] === '--apply'
// @ts-ignore The shared deployment verifier is an ESM operational tool.
const { assertExpectedDatabaseIdentity, assertBackupReceipt, requireExactCommit } = await import('./safe-production-migrate.mjs')
const expectedCommit = requireExactCommit(process.env.EXPECTED_COMMIT_SHA, 'EXPECTED_COMMIT_SHA')
if (requireExactCommit(await readFile('/app/DEPLOYMENT_COMMIT', 'utf8'), 'image commit') !== expectedCommit) throw new Error('Image commit mismatch')
const databaseUrl = new URL(process.env.DATABASE_URL || '')
const identity = await prisma.$queryRaw<Array<{ database: string; user: string; server_address: string; server_port: string }>>`
SELECT current_database() AS database, current_user AS "user", inet_server_addr()::text AS server_address, inet_server_port()::text AS server_port`
const fingerprint = assertExpectedDatabaseIdentity(databaseUrl, identity[0])
const migration = await prisma.$queryRaw<Array<{ checksum: string }>>`SELECT checksum FROM "_prisma_migrations" WHERE migration_name = '20261023130000_personnel_salary_base' AND finished_at IS NOT NULL AND rolled_back_at IS NULL`
const sql = await readFile('/app/prisma/migrations/20261023130000_personnel_salary_base/migration.sql')
if (migration.length !== 1 || migration[0].checksum !== createHash('sha256').update(sql).digest('hex')) throw new Error('Salary migration not verified')
const bytes = await readFile(process.env.SALARY_INITIALIZATION_INPUT || '')
if (!/^[a-f0-9]{64}$/.test(process.env.EXPECTED_SALARY_INPUT_SHA256 || '') || createHash('sha256').update(bytes).digest('hex') !== process.env.EXPECTED_SALARY_INPUT_SHA256) throw new Error('Private input checksum mismatch')
const input = inputSchema.parse(JSON.parse(bytes.toString('utf8')))
await requireSalaryAccess(input.actorUserId, true)
const candidates = await listEmployedBrandCenterPeople(prisma)
const ids = new Set<string>()
for (const row of input.rows) {
const person = candidates.find(candidate => candidate.employeeProfileId === row.value.employeeProfileId)
if (!person || person.name !== row.value.name || person.flowerName !== row.expectedFlowerName || person.jobNumber !== row.expectedJobNumber || ids.has(person.employeeProfileId)) throw new Error('Roster identity mismatch')
ids.add(person.employeeProfileId)
}
if (!apply) { console.log(JSON.stringify({ dryRun: true, verifiedPeople: ids.size })); return }
if (process.env.ALLOW_PRODUCTION_SALARY_INITIALIZATION !== 'INITIALIZE_ONCE') throw new Error('Explicit initialization flag required')
await assertBackupReceipt({ expectedCommit, database: fingerprint })
console.log(JSON.stringify(await initializeSalaryRecords(input.rows, input.actorUserId)))
}
main().catch(() => { console.error('薪资初始化未完成;请核验提交、数据库、备份、权限和人员身份。未输出薪资明细。'); process.exitCode = 1 }).finally(() => prisma.$disconnect())