import { Prisma, type SalaryPositionConfig, type SalaryPerformanceVersion } from '@prisma/client' import { z } from 'zod' import { prisma } from './prisma' import { SalaryError, requireSalaryAccess } from './personnel-salary' import { applicableSalaryGrades, performanceMonthSchema, positionAtMonth, positionFieldsSchema, resolvePersonnelPerformance, type SalaryPosition, type PositionFields } from './salary-position-contract' import { currentSalaryMonth } from './performance-salary-templates' export const positionConflict = () => new SalaryError('岗位配置已被修改或删除,请核对最新配置;当前草稿已保留。', 409, 'REVISION_CONFLICT') export const performanceVersionOrder = { orderBy: { effectiveMonth: 'desc' } } as const type PositionRow = SalaryPositionConfig & { _count?: { people: number }; performanceVersions?: SalaryPerformanceVersion[] } export function serializePosition(row: PositionRow): SalaryPosition { return { id: row.id, name: row.name, salaryRole: row.salaryRole as SalaryPosition['salaryRole'], description: row.description, personnelPositionId: row.personnelPositionId ?? null, jobGrade: row.jobGrade || '', dimensions: row.dimensions as PositionFields['dimensions'], revision: row.revision, updatedAt: row.updatedAt.toISOString(), personnelCount: row._count?.people ?? 0, ...(row.performanceVersions && { performanceVersions: row.performanceVersions.map((version, index, versions) => ({ id: version.id, effectiveMonth: version.effectiveMonth, endsBeforeMonth: versions[index - 1]?.effectiveMonth ?? null, description: version.description, dimensions: version.dimensions as PositionFields['dimensions'], revision: version.revision, })) }), } } const countPeople = { people: { where: { deletedAt: null } } } export async function listSalaryPositions(userId: string, month = currentSalaryMonth()) { const access = await requireSalaryAccess(userId) const positions = await prisma.salaryPositionConfig.findMany({ where: { deletedAt: null }, include: { _count: { select: countPeople }, performanceVersions: performanceVersionOrder }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }], }) const bases = await prisma.personnelSalaryBase.findMany({ where: { deletedAt: null }, select: { positionId: true, jobGrade: true } }) const monthlyPositions = positions.map(row => positionAtMonth(serializePosition(row), month)) const counts = new Map() for (const base of bases) { const match = resolvePersonnelPerformance(base.positionId, base.jobGrade, monthlyPositions, month) if (match?.personnelPositionId) counts.set(match.id, (counts.get(match.id) ?? 0) + 1) } return { canEdit: access.canEdit, positions: monthlyPositions.map(position => position.personnelPositionId ? { ...position, personnelCount: counts.get(position.id) ?? 0 } : position) } } async function validateGradeBinding(value: PositionFields, id: string | undefined, db: Prisma.TransactionClient) { if (value.personnelPositionId) { const parent = await db.salaryPositionConfig.findFirst({ where: { id: value.personnelPositionId, deletedAt: null, personnelPositionId: null } }) if (!parent || parent.id === id || parent.salaryRole !== value.salaryRole) throw new SalaryError('请选择同一薪资入口下的有效人员岗位。', 400) if (id && (await db.personnelSalaryBase.count({ where: { positionId: id, deletedAt: null } }) || await db.salaryPositionConfig.count({ where: { personnelPositionId: id, deletedAt: null } }))) throw new SalaryError('该岗位仍有人员或职级方案,不能改为职级绩效方案。', 409) if (await db.salaryPositionConfig.count({ where: { personnelPositionId: value.personnelPositionId, jobGrade: value.jobGrade, deletedAt: null, ...(id ? { id: { not: id } } : {}) } })) throw new SalaryError('该人员岗位已有相同职级的绩效方案。', 409, 'DUPLICATE_GRADE_SCHEME') } if (id && !value.personnelPositionId) { const children = await db.salaryPositionConfig.findMany({ where: { personnelPositionId: id, deletedAt: null }, select: { salaryRole: true } }) if (children.some(child => child.salaryRole !== value.salaryRole)) throw new SalaryError('请先调整关联职级方案的薪资入口。', 409) } } export async function listSalaryScoreSources(userId: string) { await requireSalaryAccess(userId) return prisma.performanceSurveyTemplate.findMany({ where: { archivedAt: null, isActive: true }, select: { code: true, name: true }, orderBy: [{ name: 'asc' }, { code: 'asc' }] }) } async function validateSources(fields: Pick, db: Prisma.TransactionClient, previous?: PositionFields['dimensions']) { const previousSources = new Map(previous?.flatMap(dimension => dimension.metrics.map(metric => [metric.id, metric.source] as const))) const codes = Array.from(new Set(fields.dimensions.flatMap(dimension => dimension.metrics.flatMap(metric => { if (metric.source.kind !== 'survey') return [] const old = previousSources.get(metric.id) return old?.kind === 'survey' && old.templateCode === metric.source.templateCode ? [] : [metric.source.templateCode] })))) if (!codes.length) return const count = await db.performanceSurveyTemplate.count({ where: { code: { in: codes }, isActive: true, archivedAt: null } }) if (count !== codes.length) throw new SalaryError('所选调研来源已停用或不存在,请重新选择来源。', 400) } export async function positionTransaction(work: (db: Prisma.TransactionClient) => Promise) { try { return await prisma.$transaction(work, { isolationLevel: Prisma.TransactionIsolationLevel.Serializable }) } catch (error) { if (error instanceof Prisma.PrismaClientKnownRequestError) { if (error.code === 'P2002') { const target = JSON.stringify(error.meta?.target ?? '') if (/effective_month|effectiveMonth/.test(target)) throw duplicatePerformanceMonth() if (/job_grade|jobGrade|salary_grade_scheme_live_unique/.test(target)) throw new SalaryError('该人员岗位已有相同职级的绩效方案。', 409, 'DUPLICATE_GRADE_SCHEME') throw new SalaryError('岗位名称已存在,请使用其他名称。', 409, 'DUPLICATE_POSITION') } if (error.code === 'P2034') throw positionConflict() } throw error } } export async function createSalaryPosition(input: unknown, actorUserId: string) { const { effectiveMonth, confirmedImpact, ...fields } = z.object({ effectiveMonth: performanceMonthSchema.optional(), confirmedImpact: impactSchema.optional(), }).passthrough().parse(input) const value = positionFieldsSchema.parse(fields) const month = effectiveMonth ?? currentSalaryMonth() if (value.dimensions.length && effectiveMonth) confirmPerformanceImpact(month, null, confirmedImpact) return positionTransaction(async db => { await requireSalaryAccess(actorUserId, true, db) await validateSources(value, db) await validateGradeBinding(value, undefined, db) const saved = await db.salaryPositionConfig.create({ data: { ...value, createdByUserId: actorUserId, updatedByUserId: actorUserId, ...(value.dimensions.length && { performanceVersions: { create: { effectiveMonth: month, description: value.description, dimensions: value.dimensions } } }), }, include: { performanceVersions: performanceVersionOrder }, }) const after = positionAtMonth(serializePosition(saved), month) await db.salaryPositionConfigAudit.create({ data: { positionId: saved.id, actorUserId, action: 'CREATE', after } }) return after }) } export async function updateSalaryPosition(id: string, input: unknown, actorUserId: string) { const { revision, ...rest } = revisionInput(input) if (rest.operation === 'create-version' || rest.operation === 'update-version') { return savePerformanceVersion(id, revision, rest, actorUserId) } const { operation, ...fields } = rest if (operation !== undefined && operation !== 'update-position') throw new SalaryError('请求格式错误。', 400) const metadataOnly = operation === 'update-position' const value = positionFieldsSchema.parse(fields) if (metadataOnly && value.dimensions.length) throw new SalaryError('请单独保存绩效版本。', 400) return positionTransaction(async db => { await requireSalaryAccess(actorUserId, true, db) const before = await db.salaryPositionConfig.findUnique({ where: { id }, include: { performanceVersions: performanceVersionOrder } }) if (!before || before.deletedAt || before.revision !== revision) throw positionConflict() if (!metadataOnly && before.performanceVersions.length) throw new SalaryError('此岗位已有实施月份版本,请选择对应版本后保存。', 409, 'PERFORMANCE_VERSION_REQUIRED') if (!metadataOnly) await validateSources(value, db) // Older callers cannot accidentally detach a saved grade scheme by omitting its binding. const binding = { ...value, personnelPositionId: value.personnelPositionId === undefined ? before.personnelPositionId : value.personnelPositionId, jobGrade: value.jobGrade === undefined ? before.jobGrade : value.jobGrade } positionFieldsSchema.parse(binding) const previousGrades = applicableSalaryGrades(before) if (previousGrades.length > 1 && (binding.personnelPositionId !== before.personnelPositionId || binding.jobGrade !== before.jobGrade || binding.salaryRole !== before.salaryRole) && await db.personnelSalaryBase.count({ where: { positionId: before.personnelPositionId, jobGrade: { in: previousGrades }, deletedAt: null } })) { throw new SalaryError('仍有 P2/P3 人员使用此方案,请先调整对应人员。', 409, 'POSITION_HAS_PEOPLE') } await validateGradeBinding(binding, id, db) const result = await db.salaryPositionConfig.updateMany({ where: { id, revision, deletedAt: null }, data: { ...binding, ...(metadataOnly && { dimensions: before.dimensions as Prisma.InputJsonValue }), revision: { increment: 1 }, updatedByUserId: actorUserId, } }) if (result.count !== 1) throw positionConflict() if (binding.dimensions.length) await db.salaryPerformanceVersion.create({ data: { positionId: id, effectiveMonth: currentSalaryMonth(), description: binding.description, dimensions: binding.dimensions, } }) const after = positionAtMonth(serializePosition(await db.salaryPositionConfig.findUniqueOrThrow({ where: { id }, include: { performanceVersions: performanceVersionOrder }, })), currentSalaryMonth()) await db.salaryPositionConfigAudit.create({ data: { positionId: id, actorUserId, action: 'UPDATE', before: serializePosition(before), after } }) return after }) } const duplicatePerformanceMonth = () => new SalaryError('该岗位已有同一实施月份的绩效版本。', 409, 'DUPLICATE_PERFORMANCE_MONTH') const impactSchema = z.object({ effectiveMonth: z.string(), endsBeforeMonth: z.string().nullable() }).strict() function confirmPerformanceImpact(effectiveMonth: string, endsBeforeMonth: string | null, confirmation?: z.infer) { if (effectiveMonth <= currentSalaryMonth() && (confirmation?.effectiveMonth !== effectiveMonth || confirmation.endsBeforeMonth !== endsBeforeMonth)) { throw new SalaryError('请先确认本次保存影响的薪资月份。', 409, 'PERFORMANCE_IMPACT_REQUIRED') } } const versionFields = { description: z.string(), dimensions: z.array(z.unknown()).min(1, '请至少设置一个考核维度'), confirmedImpact: impactSchema.optional(), } const versionInput = z.discriminatedUnion('operation', [ z.object({ ...versionFields, operation: z.literal('create-version'), effectiveMonth: performanceMonthSchema, copyFromVersionId: z.string().uuid().optional() }).strict(), z.object({ ...versionFields, operation: z.literal('update-version'), versionId: z.string().uuid(), versionRevision: z.number().int().positive() }).strict(), ]) async function savePerformanceVersion(id: string, revision: number, input: unknown, actorUserId: string) { const request = versionInput.parse(input) return positionTransaction(async db => { await requireSalaryAccess(actorUserId, true, db) const position = await db.salaryPositionConfig.findUnique({ where: { id }, include: { performanceVersions: performanceVersionOrder } }) if (!position || position.deletedAt || position.revision !== revision) throw positionConflict() const before = serializePosition(position) const versions = before.performanceVersions! const updating = request.operation === 'update-version' const target = updating ? versions.find(version => version.id === request.versionId) : undefined if (updating && (!target?.dimensions.length || target.revision !== request.versionRevision)) throw positionConflict() const effectiveMonth = request.operation === 'create-version' ? request.effectiveMonth : target!.effectiveMonth const endsBeforeMonth = target?.endsBeforeMonth ?? versions.filter(version => version.effectiveMonth > effectiveMonth).at(-1)?.effectiveMonth ?? null if (!updating && versions.some(version => version.effectiveMonth === effectiveMonth)) throw duplicatePerformanceMonth() const gradeCutoff = versions.find(version => !version.dimensions.length)?.effectiveMonth if (!updating && !position.personnelPositionId && (gradeCutoff ? effectiveMonth >= gradeCutoff : await db.salaryPositionConfig.count({ where: { personnelPositionId: id, deletedAt: null } }))) { throw new SalaryError('请为对应职级新增绩效版本。', 409, 'GRADE_PERFORMANCE_VERSION_REQUIRED') } confirmPerformanceImpact(effectiveMonth, endsBeforeMonth, request.confirmedImpact) const { description, dimensions } = positionFieldsSchema.parse({ name: position.name, salaryRole: position.salaryRole, personnelPositionId: position.personnelPositionId, jobGrade: position.jobGrade, description: request.description, dimensions: request.dimensions, }) const copied = request.operation === 'create-version' && request.copyFromVersionId ? versions.find(version => version.id === request.copyFromVersionId) : undefined if (request.operation === 'create-version' && request.copyFromVersionId && !copied?.dimensions.length) throw positionConflict() await validateSources({ dimensions }, db, target?.dimensions ?? copied?.dimensions) if (target) { const result = await db.salaryPerformanceVersion.updateMany({ where: { id: target.id, positionId: id, revision: target.revision }, data: { description, dimensions, revision: { increment: 1 } }, }) if (result.count !== 1) throw positionConflict() } else { await db.salaryPerformanceVersion.create({ data: { positionId: id, effectiveMonth, description, dimensions } }) } const changed = await db.salaryPositionConfig.updateMany({ where: { id, revision, deletedAt: null }, data: { revision: { increment: 1 }, updatedByUserId: actorUserId }, }) if (changed.count !== 1) throw positionConflict() const after = positionAtMonth(serializePosition(await db.salaryPositionConfig.findUniqueOrThrow({ where: { id }, include: { performanceVersions: performanceVersionOrder }, })), effectiveMonth) await db.salaryPositionConfigAudit.create({ data: { positionId: id, actorUserId, action: target ? 'UPDATE_PERFORMANCE_VERSION' : 'CREATE_PERFORMANCE_VERSION', before: target ? { ...target } : Prisma.JsonNull, after: { ...after.performanceVersion!, description, dimensions }, } }) return after }) } export function revisionInput(input: unknown): Record & { revision: number } { if (!input || typeof input !== 'object' || Array.isArray(input)) throw new SalaryError('请求格式错误。', 400) const value = input as Record if (!Number.isInteger(value.revision) || Number(value.revision) < 1) throw new SalaryError('缺少有效版本号,请刷新后重试。', 400) return value as Record & { revision: number } } export async function deleteSalaryPosition(id: string, input: unknown, actorUserId: string) { const { revision, ...rest } = revisionInput(input) if (Object.keys(rest).length) throw new SalaryError('请求格式错误。', 400) return positionTransaction(async db => { await requireSalaryAccess(actorUserId, true, db) const before = await db.salaryPositionConfig.findUnique({ where: { id } }) if (!before || before.deletedAt || before.revision !== revision) throw positionConflict() if (await db.salaryPositionConfig.count({ where: { personnelPositionId: id, deletedAt: null } })) throw new SalaryError('该人员岗位仍有关联职级绩效方案,请先移除关联方案。', 409, 'POSITION_HAS_GRADE_SCHEMES') if (await db.personnelSalaryBase.count({ where: { positionId: id, deletedAt: null } })) throw new SalaryError('该岗位仍有人员,请先转移或移除人员薪资档案。', 409, 'POSITION_HAS_PEOPLE') if (before.personnelPositionId && await db.personnelSalaryBase.count({ where: { positionId: before.personnelPositionId, jobGrade: { in: applicableSalaryGrades(before) }, deletedAt: null, } })) throw new SalaryError('仍有人员使用此职级方案,请先调整对应人员职级。', 409, 'POSITION_HAS_PEOPLE') const result = await db.salaryPositionConfig.updateMany({ where: { id, revision, deletedAt: null }, data: { deletedAt: new Date(), revision: { increment: 1 }, updatedByUserId: actorUserId } }) if (result.count !== 1) throw positionConflict() await db.salaryPositionConfigAudit.create({ data: { positionId: id, actorUserId, action: 'DELETE', before: serializePosition(before), after: { deleted: true } } }) return { id } }) }