gongxiangp2/lib/salary-department-maintenance.ts

80 lines
5.6 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import type { Prisma } from '@prisma/client'
import { requireSalaryAccess, serializeSalary } from './personnel-salary'
import { readSalaryOrganizationDepartments } from './salary-organization-department'
type Snapshot = ReturnType<typeof serializeSalary>
export type DepartmentManifest = {
schemaVersion: 1
target: string
actorUserId: string
people: Snapshot[]
operations: Array<{ before: Snapshot; department: string; applyAuditId: string; restoreAuditId: string }>
}
const equal = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
const conflict = () => new Error('SALARY_DEPARTMENT_CONFLICT: re-audit before writing')
const plannerWhere = { deletedAt: null, position: { deletedAt: null, salaryRole: 'ai-planning', personnelPositionId: null } }
/** Caller supplies a read-only snapshot transaction for audit, or a serializable write transaction. */
export async function prepareDepartmentManifest(db: Prisma.TransactionClient, actorUserId: string, target: string): Promise<DepartmentManifest> {
await requireSalaryAccess(actorUserId, true, db)
const rows = await db.personnelSalaryBase.findMany({ where: plannerWhere, orderBy: { id: 'asc' } })
const departments = await readSalaryOrganizationDepartments(db, rows.map(row => row.employeeProfileId))
if (rows.some(row => !departments.get(row.employeeProfileId))) throw new Error('SALARY_DEPARTMENT_UNRESOLVED: no writes started')
const people = rows.map(serializeSalary)
return { schemaVersion: 1, target, actorUserId, people, operations: people.filter(row => row.department !== departments.get(row.employeeProfileId)).map(before => ({
before, department: departments.get(before.employeeProfileId)!, applyAuditId: randomUUID(), restoreAuditId: randomUUID(),
})) }
}
/** Department-only CAS and existing payroll audit storage; deterministic audit IDs survive lost responses. */
export async function applyDepartmentManifest(db: Prisma.TransactionClient, manifest: DepartmentManifest, actorUserId: string, target: string, restore = false) {
await requireSalaryAccess(actorUserId, true, db)
if (manifest.schemaVersion !== 1 || manifest.target !== target || manifest.actorUserId !== actorUserId) throw new Error('MANIFEST_TARGET_MISMATCH')
if (new Set(manifest.people.map(row => row.id)).size !== manifest.people.length || new Set(manifest.operations.map(op => op.before.id)).size !== manifest.operations.length) throw conflict()
const rows = await db.personnelSalaryBase.findMany({ where: plannerWhere, orderBy: { id: 'asc' } })
if (!equal(rows.map(row => row.id), manifest.people.map(row => row.id))) throw conflict()
const departments = restore ? new Map<string, string | null>() : await readSalaryOrganizationDepartments(db, rows.map(row => row.employeeProfileId))
const changes: Array<{ id: string; before: Snapshot; department: string; auditId: string }> = []
let skipped = 0
// Validate every target and its current revision before the first write.
for (const row of rows) {
const current = serializeSalary(row), original = manifest.people.find(p => p.id === row.id)!
const op = manifest.operations.find(item => item.before.id === row.id)
if (!op) { if (!equal(current, original)) throw conflict(); continue }
if (!equal(op.before, original) || !op.department || op.department === original.department) throw conflict()
const applied = await db.personnelSalaryBaseAudit.findUnique({ where: { id: op.applyAuditId } })
const restored = await db.personnelSalaryBaseAudit.findUnique({ where: { id: op.restoreAuditId } })
const checkAudit = (audit: NonNullable<typeof applied>, action: string) => {
if (audit.recordId !== row.id || audit.actorUserId !== actorUserId || audit.action !== action) throw conflict()
// JSONB key order is not significant; compare through serialization below.
const after = audit.after as unknown as Snapshot
if (!after || Object.keys(current).some(key => !equal(current[key as keyof Snapshot], after[key as keyof Snapshot]))) throw conflict()
}
if (restored) {
if (!restore) throw new Error('MANIFEST_ALREADY_RESTORED')
checkAudit(restored, 'RESTORE_ORGANIZATION_DEPARTMENT'); skipped++; continue
}
if (restore) {
if (!applied) { if (!equal(current, original)) throw conflict(); skipped++; continue }
checkAudit(applied, 'SYNC_ORGANIZATION_DEPARTMENT')
changes.push({ id: row.id, before: current, department: original.department, auditId: op.restoreAuditId })
} else {
if (departments.get(row.employeeProfileId) !== op.department) throw new Error('ORGANIZATION_CHANGED: re-audit before writing')
if (applied) { checkAudit(applied, 'SYNC_ORGANIZATION_DEPARTMENT'); skipped++; continue }
if (!equal(current, original)) throw conflict()
changes.push({ id: row.id, before: current, department: op.department, auditId: op.applyAuditId })
}
}
for (const change of changes) {
const updated = await db.personnelSalaryBase.updateMany({ where: { id: change.id, revision: change.before.revision, deletedAt: null }, data: {
department: change.department, revision: { increment: 1 }, updatedByUserId: actorUserId,
} })
if (updated.count !== 1) throw conflict()
const after = serializeSalary(await db.personnelSalaryBase.findUniqueOrThrow({ where: { id: change.id } }))
await db.personnelSalaryBaseAudit.create({ data: { id: change.auditId, recordId: change.id, actorUserId,
action: restore ? 'RESTORE_ORGANIZATION_DEPARTMENT' : 'SYNC_ORGANIZATION_DEPARTMENT', before: change.before, after } })
}
return { changed: changes.length, skipped, people: rows.length }
}