gongxiangp2/lib/__tests__/salary-grade-details.test.ts

67 lines
5.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** @jest-environment node */
import { Prisma } from '@prisma/client'
import { prisma } from '../prisma'
import { getPerformanceSalaryDetails } from '../performance-salary-details'
import { readSalaryMarketIntent } from '../salary-market-intent'
import { INITIAL_SALARY_POSITIONS } from '../salary-position-seeds'
import { personnelPositions, performancePositions, resolvePersonnelPerformance } from '../salary-position-contract'
jest.mock('../prisma', () => ({ prisma: { $transaction: jest.fn() } }))
jest.mock('../personnel-salary', () => ({ requireSalaryAccess: jest.fn().mockResolvedValue({ canEdit: true }) }))
jest.mock('../performance-salary-workflows', () => ({ readSalaryWorkflowMetrics: jest.fn().mockResolvedValue({ points: new Map([['employee', 71]]), onTimeRates: new Map([['employee', 100]]) }) }))
jest.mock('../salary-market-intent', () => ({ readSalaryMarketIntent: jest.fn() }))
const rootId = INITIAL_SALARY_POSITIONS[1].id
const positions = [
{ ...INITIAL_SALARY_POSITIONS[1].value, id: rootId, name: '策划师岗', personnelPositionId: null, jobGrade: '', dimensions: [] },
...['P3', 'P4'].map((grade, i) => ({ ...INITIAL_SALARY_POSITIONS[1].value, id: `scheme-${grade}`, personnelPositionId: rootId, jobGrade: grade, dimensions: INITIAL_SALARY_POSITIONS[1].value.dimensions.map((d, index) => ({ ...d, weight: index === 0 ? String(i ? 30 : 20) : index === 1 ? String(i ? 60 : 70) : '10' })) })),
].map(p => ({ ...p, revision: 2, personnelCount: 0, updatedAt: new Date(), deletedAt: null }))
let grade = ''
const base = () => ({ id: 'base', employeeProfileId: 'employee', positionId: rootId, jobGrade: grade, name: '测试', flowerName: '测试', department: '测试部门', brand: '', baseSalary: new Prisma.Decimal('2500'), gradeSalary: new Prisma.Decimal('1000'), performanceSalary: new Prisma.Decimal('1500') })
beforeEach(() => {
grade = ''; jest.clearAllMocks()
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['employee', { rawScore: 100 }]]))
;(prisma.$transaction as jest.Mock).mockImplementation(work => work({
performanceSurveyResponse: { count: async () => 1, findMany: async () => ['visual_brand_tone', 'cross_department', 'course_share', 'work_cooperation'].flatMap(templateCode => [80, 100].map(totalScore => ({ id: `${templateCode}-${totalScore}`, totalScore, scores: {}, createdAt: new Date(), assignment: { workflowStageKey: 'review' }, target: { employeeProfileId: 'employee' }, survey: { templateCode, templateSnapshot: { code: templateCode, questions: [], workflow: { scoring: { mode: 'average_reviewers', stageKeys: ['review'] } } } } }))) },
organizationUnit: { findMany: async () => [] }, performanceSurveyEmployeeProfile: { findMany: async () => [{ id: 'employee', realName: '测试', flowerName: '测试' }] }, personnelSalaryBase: { findMany: async () => [base()] }, salaryPositionConfig: { findMany: async () => positions },
}))
})
test('人员入口只含父岗,绩效入口只含职级方案;匹配稳定ID,不按岗位名推断', () => {
const config = positions.map(p => ({ ...p, updatedAt: p.updatedAt.toISOString() }))
expect(personnelPositions(config).map(p => p.id)).toEqual([rootId])
expect(performancePositions(config).map(p => p.id)).toEqual(['scheme-P3', 'scheme-P4'])
expect(resolvePersonnelPerformance(rootId, 'P3', config)?.id).toBe('scheme-P3')
expect(resolvePersonnelPerformance(rootId, '', config)).toBeNull()
expect(resolvePersonnelPerformance(rootId, 'P2', config)).toBeNull()
expect(resolvePersonnelPerformance('scheme-P3', 'P3', config)).toBeNull()
expect(resolvePersonnelPerformance(rootId, 'P4', config.map(p => ({ ...p, name: '更名' })))?.id).toBe('scheme-P4')
expect(resolvePersonnelPerformance(rootId, 'P3', config.slice(0, 1))).toBeNull()
})
test.each(['', 'P2'])('职级%s未匹配保留基础工资积分,禁止套用旧策划绩效或计算工资', async value => {
grade = value
const result = await getPerformanceSalaryDetails('admin', '2026-10')
const row = result.roles['ai-planning'][0]
expect(row).toMatchObject({ positionId: rootId, jobGrade: value, performanceMatch: 'unmatched', performancePositionId: null, metrics: {}, totalScore: null })
expect(row.values).toMatchObject({ baseSalary: '2500.00', gradeSalary: '1000.00', performanceSalary: '1500.00', points: 71, performanceCoefficient: null, currentTotal: null })
expect(result.positionGroups.find(p => p.rows.length)?.position.dimensions).toEqual([])
expect(readSalaryMarketIntent).toHaveBeenCalledWith('2026-09', expect.any(Array), [])
})
test.each(['2026-09', '2026-10'])('职级调整对%s即时生效,按职级分表且重复调研取均值', async month => {
grade = 'P3'
const p3 = await getPerformanceSalaryDetails('admin', month)
grade = 'P4'
const p4 = await getPerformanceSalaryDetails('admin', month)
for (const [data, expected] of [[p3, 'P3'], [p4, 'P4']] as const) {
const row = data.roles['ai-planning'][0]
expect(row.performancePositionId).toBe(`scheme-${expected}`)
expect(row.positionId).toBe(rootId)
expect(row.performanceMatch).toBe('matched')
expect(row.metrics[INITIAL_SALARY_POSITIONS[1].value.dimensions[0].metrics[0].id]).toBe(90)
expect(row.values.performanceCoefficient).not.toBeNull()
expect(row.values.currentTotal).not.toBeNull()
expect(data.positionGroups.find(group => group.rows.length)?.position.jobGrade).toBe(expected)
}
expect(p3.roles['ai-planning'][0].totalScore).not.toBe(p4.roles['ai-planning'][0].totalScore)
expect(readSalaryMarketIntent).toHaveBeenLastCalledWith(month === '2026-09' ? '2026-08' : '2026-09', expect.any(Array), ['employee'])
expect(prisma.$transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: 'RepeatableRead' })
})