gongxiangp2/lib/personnel-salary.ts

160 lines
11 KiB
TypeScript

import { Prisma, type PersonnelSalaryBase } from '@prisma/client'
import { prisma } from '@/lib/prisma'
import { resolvePerformanceSalaryAccess } from '@/lib/performance-salary-access'
import { listEmployedBrandCenterPeople } from '@/lib/employee-directory'
import { createSalarySchema, updateSalarySchema, deleteSalarySchema, type SalaryRecord } from '@/lib/personnel-salary-contract'
import type { z } from 'zod'
import type { PersonnelSalaryExportGroup } from './personnel-salary-export'
import { readSalaryOrganizationDepartments } from './salary-organization-department'
export class SalaryError extends Error {
constructor(message: string, public status: number, public code = 'SALARY_ERROR') { super(message) }
}
export async function requireSalaryAccess(userId: string, write = false, db: Prisma.TransactionClient = prisma) {
const access = await resolvePerformanceSalaryAccess(userId, db)
if (!access.canView || (write && !access.canEdit)) throw new SalaryError(write ? '仅超级管理员可以维护薪资配置。' : '无权访问绩效薪资。', 403)
return access
}
export function serializeSalary(row: PersonnelSalaryBase): SalaryRecord {
return { id: row.id, employeeProfileId: row.employeeProfileId, positionId: row.positionId ?? null, jobGrade: row.jobGrade || '', name: row.name, flowerName: row.flowerName,
department: row.department, brand: row.brand, baseSalary: row.baseSalary.toFixed(2), gradeSalary: row.gradeSalary.toFixed(2),
performanceSalary: row.performanceSalary.toFixed(2), revision: row.revision, updatedAt: row.updatedAt.toISOString(), deletedAt: row.deletedAt?.toISOString() ?? null }
}
const conflict = () => new SalaryError('记录已被修改或删除。请刷新最新数据;你的编辑草稿已保留。', 409, 'REVISION_CONFLICT')
async function writeTransaction<T>(work: (db: Prisma.TransactionClient) => Promise<T>) {
try { return await prisma.$transaction(work, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }) }
catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === 'P2002') throw new SalaryError('该人员已有薪资基础档案,请刷新后查看。', 409, 'DUPLICATE_PERSON')
if (error.code === 'P2034') throw conflict()
}
throw error
}
}
export async function listSalaryRecords(userId: string) {
const access = await requireSalaryAccess(userId)
const rows = await prisma.personnelSalaryBase.findMany({ where: { deletedAt: null }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] })
const departments = await readSalaryOrganizationDepartments(prisma, rows.map(row => row.employeeProfileId))
return { canEdit: access.canEdit, records: rows.map(row => ({ ...serializeSalary(row), organizationDepartment: departments.get(row.employeeProfileId) ?? null })) }
}
export async function readPersonnelSalaryExport(userId: string, position?: string): Promise<PersonnelSalaryExportGroup[]> {
return prisma.$transaction(async db => {
await requireSalaryAccess(userId, false, db)
const positions = await db.salaryPositionConfig.findMany({ where: { deletedAt: null, personnelPositionId: null }, select: { id: true, name: true }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] })
if (position && position !== 'unassigned' && !positions.some(item => item.id === position)) throw new SalaryError('所选岗位已删除或不存在,请刷新后重选。', 404)
const records = await db.personnelSalaryBase.findMany({ where: { deletedAt: null, ...(position === 'unassigned' ? { positionId: null } : position ? { positionId: position } : {}) }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] })
const selected = position === 'unassigned' ? [] : positions.filter(item => !position || item.id === position)
const groups: PersonnelSalaryExportGroup[] = selected.map(item => ({ name: item.name, records: records.filter(row => row.positionId === item.id).map(serializeSalary) }))
const unassigned = records.filter(row => !row.positionId).map(serializeSalary)
if (unassigned.length || position === 'unassigned') groups.push({ name: '未分配', records: unassigned })
return groups
}, { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead })
}
export async function listSalaryCandidates(userId: string) {
await requireSalaryAccess(userId, true)
const people = await listEmployedBrandCenterPeople(prisma)
const records = await prisma.personnelSalaryBase.findMany({ where: { deletedAt: null }, select: { employeeProfileId: true } })
const existing = new Set(records.map(row => row.employeeProfileId))
const candidates = people.filter(person => !existing.has(person.employeeProfileId))
const departments = await readSalaryOrganizationDepartments(prisma, candidates.map(person => person.employeeProfileId))
return candidates.map(person => ({ ...person, organizationDepartment: departments.get(person.employeeProfileId) ?? null }))
}
export async function createSalaryRecord(input: unknown, actorUserId: string) {
const value = createSalarySchema.parse(input)
return writeTransaction(async db => {
await requireSalaryAccess(actorUserId, true, db)
const position = await verifySalaryPosition(value.positionId, db)
const people = await listEmployedBrandCenterPeople(db)
if (!people.some(person => person.employeeProfileId === value.employeeProfileId)) throw new SalaryError('请选择品牌中心当前在职花名册中的人员。', 400)
const department = position?.salaryRole === 'ai-planning' ? await requirePlannerDepartment(db, value.employeeProfileId) : value.department
const saved = await db.personnelSalaryBase.create({ data: { ...value, department, brand: value.brand ?? '', createdByUserId: actorUserId, updatedByUserId: actorUserId } })
const after = serializeSalary(saved)
await db.personnelSalaryBaseAudit.create({ data: { recordId: saved.id, actorUserId, action: 'CREATE', after } })
return after
})
}
export async function updateSalaryRecord(id: string, input: unknown, actorUserId: string) {
const { revision, ...fields } = updateSalarySchema.parse(input)
return writeTransaction(async db => {
await requireSalaryAccess(actorUserId, true, db)
const before = await db.personnelSalaryBase.findUnique({ where: { id } })
if (!before || before.deletedAt || before.revision !== revision) throw conflict()
const position = await verifySalaryPosition(fields.positionId === undefined ? before.positionId : fields.positionId, db)
const department = position?.salaryRole === 'ai-planning' ? await requirePlannerDepartment(db, before.employeeProfileId) : fields.department
const jobGrade = Object.prototype.hasOwnProperty.call(input, 'jobGrade') ? fields.jobGrade : before.jobGrade
const result = await db.personnelSalaryBase.updateMany({ where: { id, revision, deletedAt: null }, data: { ...fields, department, brand: fields.brand ?? before.brand, jobGrade, revision: { increment: 1 }, updatedByUserId: actorUserId } })
if (result.count !== 1) throw conflict()
const saved = await db.personnelSalaryBase.findUniqueOrThrow({ where: { id } })
const after = serializeSalary(saved)
await db.personnelSalaryBaseAudit.create({ data: { recordId: id, actorUserId, action: 'UPDATE', before: serializeSalary(before), after } })
return after
})
}
async function verifySalaryPosition(positionId: string | null | undefined, db: Prisma.TransactionClient) {
if (!positionId) return null
const position = await db.salaryPositionConfig.findFirst({ where: { id: positionId, deletedAt: null, personnelPositionId: null }, select: { id: true, salaryRole: true } })
if (!position) throw new SalaryError('请选择有效的人员岗位;职级绩效方案不能直接配置人员。', 409, 'INVALID_POSITION')
return position
}
async function requirePlannerDepartment(db: Prisma.TransactionClient, employeeProfileId: string) {
const department = (await readSalaryOrganizationDepartments(db, [employeeProfileId])).get(employeeProfileId)
if (!department) throw new SalaryError('无法唯一确认该人员的组织架构部门,请先维护组织架构后重试。', 409, 'SALARY_DEPARTMENT_UNRESOLVED')
return department
}
export async function deleteSalaryRecord(id: string, input: unknown, actorUserId: string) {
const { revision } = deleteSalarySchema.parse(input)
return writeTransaction(async db => {
await requireSalaryAccess(actorUserId, true, db)
const before = await db.personnelSalaryBase.findUnique({ where: { id } })
if (!before || before.deletedAt || before.revision !== revision) throw conflict()
const result = await db.personnelSalaryBase.updateMany({ where: { id, revision, deletedAt: null }, data: { deletedAt: new Date(), revision: { increment: 1 }, updatedByUserId: actorUserId } })
if (result.count !== 1) throw conflict()
const after = serializeSalary(await db.personnelSalaryBase.findUniqueOrThrow({ where: { id } }))
await db.personnelSalaryBaseAudit.create({ data: { recordId: id, actorUserId, action: 'DELETE', before: serializeSalary(before), after } })
return { id }
})
}
export type SalaryInitializationRow = { expectedJobNumber: string; expectedFlowerName: string; value: z.infer<typeof createSalarySchema> }
// No source payroll is compiled into this module. The local import utility supplies a verified manifest.
export async function initializeSalaryRecords(rows: SalaryInitializationRow[], actorUserId: string) {
return writeTransaction(async db => {
await requireSalaryAccess(actorUserId, true, db)
const key = 'personnel-salary-base-initial-v1'
if (await db.personnelSalaryBaseAudit.findUnique({ where: { initializationKey: key } })) return { initialized: false, created: 0, skipped: rows.length }
const people = await listEmployedBrandCenterPeople(db)
const ids = new Set<string>()
// Verify ALL stable IDs again before the first write, even if some rows already exist.
for (const row of rows) {
const person = people.find(person => person.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 SalaryError('初始化人员 ID 与当前花名册不一致或重复,未写入任何数据。', 409)
}
createSalarySchema.parse({ employeeProfileId: row.value.employeeProfileId, name: row.value.name, flowerName: row.value.flowerName, department: row.value.department, brand: row.value.brand,
baseSalary: String(row.value.baseSalary), gradeSalary: String(row.value.gradeSalary), performanceSalary: String(row.value.performanceSalary) })
ids.add(person.employeeProfileId)
}
let created = 0
for (const row of rows) {
if (await db.personnelSalaryBase.findFirst({ where: { employeeProfileId: row.value.employeeProfileId } })) continue
const value = createSalarySchema.parse(row.value)
const saved = await db.personnelSalaryBase.create({ data: { ...value, brand: value.brand ?? '', createdByUserId: actorUserId, updatedByUserId: actorUserId } })
await db.personnelSalaryBaseAudit.create({ data: { recordId: saved.id, actorUserId, action: 'INITIALIZE', after: serializeSalary(saved) } })
created++
}
await db.personnelSalaryBaseAudit.create({ data: { actorUserId, action: 'INITIALIZE_BATCH', initializationKey: key, after: { created, skipped: rows.length - created } } })
return { initialized: true, created, skipped: rows.length - created }
})
}