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

122 lines
9.1 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 { readSalaryWorkflowSnapshots } from '../salary-workflow-source'
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('../salary-workflow-source', () => ({ readSalaryWorkflowSnapshots: jest.fn().mockResolvedValue([]) }))
jest.mock('../art-workflow-point-configuration', () => ({
readArtPointDashboard: jest.fn().mockResolvedValue({
generatedAt: '2026-11-26 12:00:00',
workflows: [{ businessId: 'flow', reviewFinishTime: '2026-10-01', scoreContributions: [{ workflowKey: 'flow', name: '测试', finalPoints: 71 }] }],
}),
readArtPointOvertimeExemptions: jest.fn().mockResolvedValue([]),
}))
jest.mock('../personnel-salary', () => ({ requireSalaryAccess: jest.fn().mockResolvedValue({ canEdit: true }) }))
jest.mock('../performance-salary-workflows', () => {
const readSalaryWorkflowMetrics = jest.fn().mockResolvedValue({ points: new Map([['employee', 71]]), artDeliveryCounts: new Map([['employee', { onTime: 1, total: 1 }]]), onTimeRates: new Map([['employee', 100]]) })
return { readSalaryWorkflowMetrics, readSalaryWorkflowMetricsBatch: async (months: string[], people: import('../art-workflow-points').ArtPointPerson[]) => new Map(await Promise.all(months.map(async month => [month, await readSalaryWorkflowMetrics(month, people)] as const))) }
})
jest.mock('../salary-market-intent', () => {
const readSalaryMarketIntent = jest.fn()
return { readSalaryMarketIntent, readSalaryMarketIntentBatch: async (months: string[], people: import('../art-workflow-points').ArtPointPerson[], ids: string[]) => new Map(await Promise.all(months.map(async month => [month, await readSalaryMarketIntent(month, people, ids)] as const))) }
})
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 = ''
let versioned = false
const configuredPositions = () => versioned ? positions.map(position => ({
...position,
performanceVersions: position.personnelPositionId
? [{ id: position.id + '-future', effectiveMonth: '2027-01', description: '', dimensions: INITIAL_SALARY_POSITIONS[1].value.dimensions, revision: 1 },
{ id: position.id + '-nov', effectiveMonth: '2026-11', description: '', dimensions: position.dimensions, revision: 1 }]
: [{ id: 'closed', effectiveMonth: '2026-11', description: '', dimensions: [], revision: 1 },
{ id: 'baseline', effectiveMonth: '0000-00', description: '', dimensions: INITIAL_SALARY_POSITIONS[1].value.dimensions, revision: 1 }],
})) : positions
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 = ''; versioned = false; jest.clearAllMocks()
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['employee', { rawScore: 100 }]]))
const db = {
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 () => configuredPositions() },
}
Object.assign(prisma, db)
;(prisma.$transaction as jest.Mock).mockImplementation(work => work(db))
})
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, previousTotal: null, salaryDifference: null })
expect(result.positionGroups.find(p => p.rows.length)?.position.dimensions).toEqual([])
expect(readSalaryMarketIntent).not.toHaveBeenCalled()
})
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' })
})
test('P2 与 P3 按月共用配置及权重,保留实际职级并跨历史与未来版本比较工资', async () => {
versioned = true
const months = ['2026-10', '2026-11', '2026-12', '2027-01']
const results = []
for (const month of months) {
grade = 'P2'
const p2 = await getPerformanceSalaryDetails('admin', month)
grade = 'P3'
const p3 = await getPerformanceSalaryDetails('admin', month)
const row = p2.roles['ai-planning'][0]
const comparison = p3.roles['ai-planning'][0]
expect(row.jobGrade).toBe('P2')
expect(row.performancePositionId).toBe(month === '2026-10' ? rootId : 'scheme-P3')
expect(row.totalScore).toBe(comparison.totalScore)
expect(row.values.performanceCoefficient).not.toBeNull()
expect(row.values.performanceCoefficient).toBe(comparison.values.performanceCoefficient)
expect(row.values.currentTotal).toBe(comparison.values.currentTotal)
const group = p2.positionGroups.find(group => group.rows.length)
expect(group?.position.performanceVersion?.id).toBe(month === '2026-10' ? 'baseline' : month === '2027-01' ? 'scheme-P3-future' : 'scheme-P3-nov')
results.push(row.values)
}
for (let i = 1; i < results.length; i++) expect(results[i].previousTotal).toBe(results[i - 1].currentTotal)
grade = 'P4'
const p4 = await getPerformanceSalaryDetails('admin', '2026-11')
expect(p4.roles['ai-planning'][0].performancePositionId).toBe('scheme-P4')
expect(p4.roles['ai-planning'][0].values.performanceCoefficient).not.toBe(results[1].performanceCoefficient)
})