82 lines
5.7 KiB
TypeScript
82 lines
5.7 KiB
TypeScript
import { Prisma, type SalaryPositionConfig } from '@prisma/client'
|
|
import { prisma } from './prisma'
|
|
import { SalaryError, requireSalaryAccess } from './personnel-salary'
|
|
import { positionFieldsSchema, type SalaryPosition, type PositionFields } from './salary-position-contract'
|
|
|
|
export const positionConflict = () => new SalaryError('岗位配置已被修改或删除,请核对最新配置;当前草稿已保留。', 409, 'REVISION_CONFLICT')
|
|
export function serializePosition(row: SalaryPositionConfig & { _count?: { people: number } }): SalaryPosition {
|
|
return { id: row.id, name: row.name, salaryRole: row.salaryRole as SalaryPosition['salaryRole'], description: row.description,
|
|
dimensions: row.dimensions as PositionFields['dimensions'], revision: row.revision, updatedAt: row.updatedAt.toISOString(), personnelCount: row._count?.people ?? 0 }
|
|
}
|
|
const countPeople = { people: { where: { deletedAt: null } } }
|
|
export async function listSalaryPositions(userId: string) {
|
|
const access = await requireSalaryAccess(userId)
|
|
const positions = await prisma.salaryPositionConfig.findMany({ where: { deletedAt: null }, include: { _count: { select: countPeople } }, orderBy: [{ createdAt: 'asc' }, { id: 'asc' }] })
|
|
return { canEdit: access.canEdit, positions: positions.map(serializePosition) }
|
|
}
|
|
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: PositionFields, db: Prisma.TransactionClient) {
|
|
const codes = Array.from(new Set(fields.dimensions.flatMap(dimension => dimension.metrics.flatMap(metric => metric.source.kind === 'survey' ? [metric.source.templateCode] : []))))
|
|
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<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_POSITION')
|
|
if (error.code === 'P2034') throw positionConflict()
|
|
}
|
|
throw error
|
|
}
|
|
}
|
|
export async function createSalaryPosition(input: unknown, actorUserId: string) {
|
|
const value = positionFieldsSchema.parse(input)
|
|
return positionTransaction(async db => {
|
|
await requireSalaryAccess(actorUserId, true, db)
|
|
await validateSources(value, db)
|
|
const saved = await db.salaryPositionConfig.create({ data: { ...value, createdByUserId: actorUserId, updatedByUserId: actorUserId } })
|
|
const after = serializePosition(saved)
|
|
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)
|
|
const value = positionFieldsSchema.parse(rest)
|
|
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()
|
|
await validateSources(value, db)
|
|
const result = await db.salaryPositionConfig.updateMany({ where: { id, revision, deletedAt: null }, data: { ...value, revision: { increment: 1 }, updatedByUserId: actorUserId } })
|
|
if (result.count !== 1) throw positionConflict()
|
|
const after = serializePosition(await db.salaryPositionConfig.findUniqueOrThrow({ where: { id } }))
|
|
await db.salaryPositionConfigAudit.create({ data: { positionId: id, actorUserId, action: 'UPDATE', before: serializePosition(before), after } })
|
|
return after
|
|
})
|
|
}
|
|
export function revisionInput(input: unknown): Record<string, unknown> & { revision: number } {
|
|
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new SalaryError('请求格式错误。', 400)
|
|
const value = input as Record<string, unknown>
|
|
if (!Number.isInteger(value.revision) || Number(value.revision) < 1) throw new SalaryError('缺少有效版本号,请刷新后重试。', 400)
|
|
return value as Record<string, unknown> & { 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.personnelSalaryBase.count({ where: { positionId: id, 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 }
|
|
})
|
|
}
|