444 lines
36 KiB
TypeScript
444 lines
36 KiB
TypeScript
/** @jest-environment node */
|
||
import { Prisma } from '@prisma/client'
|
||
import { prisma } from '../prisma'
|
||
import { requireSalaryAccess } from '../personnel-salary'
|
||
import { getPerformanceSalaryDetails } from '../performance-salary-details'
|
||
import type { ArtPointPerson } from '../art-workflow-points'
|
||
import { readSalaryWorkflowMetrics } from '../performance-salary-workflows'
|
||
import { readSalaryMarketIntent, readSalaryMarketIntentBatch } from '../salary-market-intent'
|
||
import { readSalaryWorkflowSnapshots } from '../salary-workflow-source'
|
||
import { readArtPointDashboard, readArtPointOvertimeExemptions } from '../art-workflow-point-configuration'
|
||
import { INITIAL_SALARY_POSITIONS } from '../salary-position-seeds'
|
||
import { summarizeMarketIntent, type MarketIntentCandidate } from '../salary-market-intent-contract'
|
||
|
||
jest.mock('../prisma', () => ({ prisma: { $transaction: jest.fn(), organizationUnit: { findMany: jest.fn() }, salaryPositionConfig: { findMany: jest.fn() }, performanceSurveyEmployeeProfile: { findMany: jest.fn() }, personnelSalaryBase: { findMany: jest.fn() }, performanceSurveyResponse: { count: jest.fn(), findMany: jest.fn() } } }))
|
||
jest.mock('../salary-workflow-source', () => ({ readSalaryWorkflowSnapshots: jest.fn().mockResolvedValue([]) }))
|
||
jest.mock('../art-workflow-point-configuration', () => ({ readArtPointDashboard: jest.fn(), readArtPointOvertimeExemptions: jest.fn() }))
|
||
jest.mock('../personnel-salary', () => ({ ...jest.requireActual('../personnel-salary'), requireSalaryAccess: jest.fn() }))
|
||
jest.mock('../performance-salary-workflows', () => {
|
||
const readSalaryWorkflowMetrics = jest.fn()
|
||
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: jest.fn() }
|
||
})
|
||
const db = prisma as unknown as Record<string, any>
|
||
const workflow = readSalaryWorkflowMetrics as jest.Mock
|
||
const dashboard = readArtPointDashboard as jest.Mock
|
||
const pointPayload = (points: number, name = '档案名字') => ({
|
||
generatedAt: '2026-11-26 12:00:00',
|
||
workflows: ['2026-09', '2026-10', '2027-01'].map(month => ({
|
||
businessId: month, reviewFinishTime: `${month}-01 12:00:00`,
|
||
scoreContributions: [{ workflowKey: month, name, finalPoints: points }],
|
||
})),
|
||
})
|
||
let responseSequence = 0
|
||
const response = (id: string, code: string, totalScore: number) => ({ id: `response-${++responseSequence}`, totalScore, createdAt: new Date(), scores: {}, assignment: { workflowStageKey: 'review' }, target: { employeeProfileId: id }, survey: { templateCode: code, templateSnapshot: { code, questions: [], workflow: { scoring: { mode: 'average_reviewers', stageKeys: ['review'] } } } } })
|
||
const oldEnv = process.env.NODE_ENV
|
||
const positions = () => INITIAL_SALARY_POSITIONS.map((item, index) => ({ ...JSON.parse(JSON.stringify(item.value)), id: `job${index}`, revision: 1, updatedAt: new Date(), createdAt: new Date(), deletedAt: null }))
|
||
beforeEach(() => {
|
||
jest.resetAllMocks()
|
||
dashboard.mockResolvedValue(pointPayload(71))
|
||
;(readArtPointOvertimeExemptions as jest.Mock).mockResolvedValue([])
|
||
;(readSalaryMarketIntentBatch as jest.Mock).mockImplementation(async (months: string[], people: ArtPointPerson[], ids: string[]) => new Map(await Promise.all(months.map(async month => [month, await readSalaryMarketIntent(month, people, ids)] as const))))
|
||
;(readSalaryWorkflowSnapshots as jest.Mock).mockResolvedValue([])
|
||
Object.assign(process.env, { NODE_ENV: 'development', PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK: 'false' })
|
||
db.$transaction.mockImplementation((work: any) => work(prisma))
|
||
db.performanceSurveyResponse.count.mockResolvedValue(0)
|
||
db.performanceSurveyResponse.findMany.mockResolvedValue([response('p1', 'visual_brand_tone', 80), response('p1', 'visual_brand_tone', 100), response('p1', 'work_cooperation', 60), response('p1', 'project_result_validation', 100)])
|
||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([{ id: 'p1', realName: '档案名字', flowerName: '档案花名', displayName: 'HR名字', employmentState: 'ACTIVE', departmentPath: '公司/配置部门' }, { id: 'not-configured' }])
|
||
db.organizationUnit.findMany.mockResolvedValue([{ sourceDeptId: 1, name: '配置部门', path: '公司/配置部门' }])
|
||
db.salaryPositionConfig.findMany.mockResolvedValue(positions())
|
||
db.personnelSalaryBase.findMany.mockResolvedValue([{ positionId: 'job1', employeeProfileId: 'p1', name: '档案名字', flowerName: '档案花名', department: '配置部门', brand: '自由品牌', baseSalary: new Prisma.Decimal('100.01'), gradeSalary: new Prisma.Decimal('20'), performanceSalary: new Prisma.Decimal('30') }])
|
||
workflow.mockResolvedValue({ sourceMonth: '2026-10', points: new Map([['p1', 71]]), deliveryCounts: new Map([['p1', { onTime: 9, total: 10 }]]), onTimeRates: new Map([['p1', 90]]) })
|
||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['p1', { rawScore: 100, selected: [], averageChange: 0, validCount: 1 }]]))
|
||
})
|
||
afterAll(() => { Object.assign(process.env, { NODE_ENV: oldEnv }); delete process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK })
|
||
|
||
function singleMetricPosition(role: string, source: Record<string, string> = { kind: 'survey', templateCode: 'visual_brand_tone' }) {
|
||
const job = positions()[1]
|
||
job.salaryRole = role
|
||
job.dimensions = [{ ...job.dimensions[0], weight: '100', metrics: [{ ...job.dimensions[0].metrics[0], weight: '100', source }] }]
|
||
db.salaryPositionConfig.findMany.mockResolvedValue([job])
|
||
return job
|
||
}
|
||
|
||
test.each(['ai-planning', 'management', 'photography', 'spatial-visual', 'ai-technical'] as const)('%s上月金额与切换上月一致,两个月共用人员和配置快照', async role => {
|
||
singleMetricPosition(role)
|
||
db.performanceSurveyResponse.findMany.mockImplementation(async ({ where }: any) => [response('p1', 'visual_brand_tone', where.survey.assessmentMonth === '2026-10' ? 100 : 80)])
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10')
|
||
const row = data.roles[role][0]
|
||
expect(row.values).toMatchObject({ currentTotal: '150.01', previousTotal: '144.01', salaryDifference: '6.00' })
|
||
for (const model of ['personnelSalaryBase', 'salaryPositionConfig', 'performanceSurveyEmployeeProfile', 'organizationUnit']) expect(db[model].findMany).toHaveBeenCalledTimes(1)
|
||
expect(readSalaryWorkflowSnapshots).toHaveBeenCalledTimes(1)
|
||
const previous = await getPerformanceSalaryDetails('reader', '2026-09')
|
||
expect(row.values.previousTotal).toBe(previous.roles[role].find(item => item.employeeProfileId === row.employeeProfileId)!.values.currentTotal)
|
||
})
|
||
|
||
test.each([
|
||
[100, null, '150.01', null, null],
|
||
[null, 100, null, '150.01', null],
|
||
[null, null, null, null, null],
|
||
[0, 100, '120.01', '150.01', '-30.00'],
|
||
[100, 0, '150.01', '120.01', '30.00'],
|
||
[0, 0, '120.01', '120.01', '0.00'],
|
||
])('本月%s上月%s:另一月薪资独立保留,零分及负差不丢失', async (currentScore, previousScore, currentTotal, previousTotal, salaryDifference) => {
|
||
singleMetricPosition('ai-planning')
|
||
db.performanceSurveyResponse.findMany.mockImplementation(async ({ where }: any) => {
|
||
const score = where.survey.assessmentMonth === '2026-10' ? currentScore : previousScore
|
||
return score === null ? [] : [response('p1', 'visual_brand_tone', score)]
|
||
})
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-10')).roles['ai-planning'][0].values).toMatchObject({ currentTotal, previousTotal, salaryDifference })
|
||
})
|
||
|
||
test('跨年按各自正式月份和交付率计算;市场批次只读12月与11月完结流程', async () => {
|
||
const job = singleMetricPosition('ai-planning')
|
||
job.dimensions[0].metrics = [
|
||
{ ...job.dimensions[0].metrics[0], id: 'survey', weight: '50' },
|
||
{ ...job.dimensions[0].metrics[0], id: 'delivery', weight: '50', source: { kind: 'on-time' } },
|
||
]
|
||
db.performanceSurveyResponse.findMany.mockImplementation(async ({ where }: any) => [response('p1', 'visual_brand_tone', where.survey.assessmentMonth === '2027-01' ? 100 : 80)])
|
||
workflow.mockImplementation(async month => ({ sourceMonth: month, points: new Map(), deliveryCounts: new Map(), onTimeRates: new Map([['p1', month === '2027-01' ? 60 : 20]]) }))
|
||
const row = (await getPerformanceSalaryDetails('reader', '2027-01')).roles['ai-planning'][0]
|
||
expect(row.values).toMatchObject({ currentTotal: '144.01', previousTotal: '135.01', salaryDifference: '9.00' })
|
||
expect(db.performanceSurveyResponse.findMany.mock.calls.map(([query]: any) => query.where.survey.assessmentMonth)).toEqual(['2027-01', '2026-12'])
|
||
expect(workflow.mock.calls.map(([month]) => month)).toEqual(['2026-12', '2027-01'])
|
||
expect((readSalaryMarketIntent as jest.Mock).mock.calls.map(([month]) => month)).toEqual(['2026-11', '2026-12'])
|
||
})
|
||
|
||
test('市场来源上月与上上月独立计分;先得到两位小数工资,再精确相减', async () => {
|
||
singleMetricPosition('ai-planning', { kind: 'market-intent-top3' })
|
||
const base = (await db.personnelSalaryBase.findMany())[0]
|
||
db.personnelSalaryBase.findMany.mockResolvedValue([{ ...base, baseSalary: new Prisma.Decimal('.10'), gradeSalary: new Prisma.Decimal('.20'), performanceSalary: new Prisma.Decimal('.50') }])
|
||
;(readSalaryMarketIntent as jest.Mock).mockImplementation(async month => new Map([['p1', { rawScore: month === '2026-12' ? 100.5 : 0 }]]))
|
||
const row = (await getPerformanceSalaryDetails('reader', '2027-01')).roles['ai-planning'][0]
|
||
expect(row.values).toMatchObject({ performanceCoefficient: 1.01, currentTotal: '0.81', previousTotal: '0.30', salaryDifference: '0.51' })
|
||
})
|
||
|
||
test('上月来源失败必须整体失败,不返回仅本月结果;权限失败不读任何来源', async () => {
|
||
workflow.mockImplementation(async month => {
|
||
if (month === '2026-09') throw Object.assign(new Error('source unavailable'), { status: 503 })
|
||
return { points: new Map(), deliveryCounts: new Map(), onTimeRates: new Map() }
|
||
})
|
||
await expect(getPerformanceSalaryDetails('reader', '2026-10')).rejects.toMatchObject({ status: 503 })
|
||
jest.clearAllMocks()
|
||
;(requireSalaryAccess as jest.Mock).mockRejectedValueOnce(Object.assign(new Error('forbidden'), { status: 403 }))
|
||
await expect(getPerformanceSalaryDetails('reader', '2026-10')).rejects.toMatchObject({ status: 403 })
|
||
expect(db.$transaction).not.toHaveBeenCalled()
|
||
expect(readSalaryWorkflowSnapshots).not.toHaveBeenCalled()
|
||
})
|
||
|
||
test('配置快照关联人员、重复已提交调研取平均、工资及积分不变', async () => {
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10')
|
||
expect(requireSalaryAccess).toHaveBeenCalledWith('reader')
|
||
expect(data).toMatchObject({ displayMonth: '2026-10', sourceMonth: '2026-10', marketSourceMonth: '2026-09', isFallback: false })
|
||
expect(db.$transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: 'RepeatableRead' })
|
||
expect(db.performanceSurveyResponse.findMany.mock.calls[0][0].where).toEqual({ survey: { assessmentMonth: '2026-10', status: { notIn: ['draft', 'cancelled'] } }, assignment: { status: 'submitted' } })
|
||
expect(Object.values(data.roles).flat()).toHaveLength(1)
|
||
expect(data.roles['ai-planning'][0]).toMatchObject({ totalScore: 89.2, values: { name: '档案名字', baseSalary: '100.01', points: 71, performanceScore: 89.2, performanceCoefficient: .89, currentTotal: '146.71' } })
|
||
expect(data.positionGroups[1].position.revision).toBe(1)
|
||
const row = data.roles['ai-planning'][0]
|
||
const dimensions = data.positionGroups[1].position.dimensions
|
||
expect(row.metrics[dimensions[0].metrics[0].id]).toBe(90)
|
||
expect(row.values[`${dimensions[0].metrics[0].id}RawValue`]).toBe(90)
|
||
expect(row.values[`${dimensions[0].metrics[0].id}Score`]).toBe(22.5)
|
||
expect(row.values[`${dimensions[1].metrics[1].id}RawValue`]).toBe(90)
|
||
expect(row.values[`${dimensions[1].metrics[1].id}Score`]).toBe(56.7)
|
||
for (const [key, rawValue] of Object.entries(row.metrics)) expect(row.values[`${key}RawValue`]).toBe(rawValue)
|
||
expect(Object.keys(row.values).some(key => key.endsWith('Weighted'))).toBe(false)
|
||
})
|
||
test('只展示有基础档案且关联有效薪资岗位的人,无岗位人员不显示', async () => {
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-09')).roles['ai-planning'][0].employeeProfileId).toBe('p1')
|
||
db.personnelSalaryBase.findMany.mockResolvedValue([{ positionId: null }, { positionId: 'deleted' }])
|
||
expect(Object.values((await getPerformanceSalaryDetails('reader', '2026-09')).roles).flat()).toEqual([])
|
||
})
|
||
test('最新权重、岗位改名及转岗对历史月份生效,多个方案保持独立', async () => {
|
||
const jobs = positions()
|
||
jobs[1].name = '编导策划'; jobs[1].revision = 2
|
||
jobs[1].dimensions[0].weight = '100'; jobs[1].dimensions[1].weight = '0'; jobs[1].dimensions[2].weight = '0'
|
||
jobs[1].salaryRole = 'ai-technical'
|
||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs)
|
||
const data = await getPerformanceSalaryDetails('reader', '2025-01')
|
||
expect(data.roles['ai-planning']).toEqual([])
|
||
expect(data.roles['ai-technical'][0].totalScore).toBe(90)
|
||
expect(data.positionGroups[1].template.title).toBe('编导策划')
|
||
expect(data.positionGroups).toHaveLength(3)
|
||
expect(workflow).toHaveBeenLastCalledWith('2025-01', expect.any(Array))
|
||
expect(dashboard).not.toHaveBeenCalled()
|
||
})
|
||
test('正权重缺失阻断总分;空配置仍列出基础档案', async () => {
|
||
db.performanceSurveyResponse.findMany.mockResolvedValue([])
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-09')).roles['ai-planning'][0]).toMatchObject({ totalScore: null, values: { performanceScore: null, performanceCoefficient: null, currentTotal: null } })
|
||
const jobs = positions(); jobs[1].dimensions = []
|
||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs)
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-09')).roles['ai-planning'][0]).toMatchObject({ totalScore: null, metrics: {}, values: { baseSalary: '100.01', performanceCoefficient: null, currentTotal: null } })
|
||
})
|
||
test('原始零分正常保留,零权重缺失不阻断,贡献与总分不重复加权', async () => {
|
||
db.performanceSurveyResponse.findMany.mockResolvedValue([response('p1', 'visual_brand_tone', 0), response('p1', 'work_cooperation', 60), response('p1', 'project_result_validation', 100)])
|
||
workflow.mockResolvedValue({ sourceMonth: '2026-10', points: new Map([['p1', 71]]), onTimeRates: new Map([['p1', 100]]) })
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10')
|
||
const row = data.roles['ai-planning'][0]
|
||
const dimensions = data.positionGroups[1].position.dimensions
|
||
expect(row.values[`${dimensions[0].metrics[0].id}RawValue`]).toBe(0)
|
||
expect(row.values[`${dimensions[0].metrics[0].id}Score`]).toBe(0)
|
||
expect(row.values[`${dimensions[0].metrics[1].id}RawValue`]).toBeNull()
|
||
expect(row.values[`${dimensions[0].metrics[1].id}Score`]).toBeNull()
|
||
expect(row.values[`${dimensions[1].metrics[1].id}RawValue`]).toBe(100)
|
||
expect(row.values[`${dimensions[1].metrics[1].id}Score`]).toBe(63)
|
||
expect(row.totalScore).toBe(73)
|
||
expect(row.values).toMatchObject({ performanceCoefficient: .73, currentTotal: '141.91' })
|
||
})
|
||
|
||
test.each(['ai-planning', 'photography', 'spatial-visual', 'management', 'ai-technical'])('%s统一按表中贡献之和、两位系数计算当月薪资', async salaryRole => {
|
||
const jobs = positions(); jobs[1].salaryRole = salaryRole
|
||
if (salaryRole === 'management') jobs[1].dimensions[1].metrics[0].source = { kind: 'survey', templateCode: 'project_result_validation' }
|
||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs)
|
||
db.performanceSurveyResponse.findMany.mockResolvedValue([response('p1', 'visual_brand_tone', 88.885), response('p1', 'work_cooperation', 88.885), response('p1', 'project_result_validation', 88.885)])
|
||
workflow.mockResolvedValue({ sourceMonth: '2026-09', points: new Map([['p1', 71]]), deliveryCounts: new Map([['p1', { onTime: 88885, total: 100000 }]]), onTimeRates: new Map([['p1', 88.885]]) })
|
||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['p1', { rawScore: 88.885, selected: [] }]]))
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-09')
|
||
const row = Object.values(data.roles).flat()[0]
|
||
expect(row).toMatchObject({ totalScore: 88.88, values: { performanceScore: 88.88, performanceCoefficient: .89, currentTotal: '146.71' } })
|
||
expect(db.personnelSalaryBase.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { deletedAt: null } }))
|
||
expect(row.values.previousTotal).toBe('146.71')
|
||
expect(row.values.salaryDifference).toBe('0.00')
|
||
expect(data.positionGroups[1].template.columns.filter(c => c.key === 'performanceCoefficient')).toHaveLength(1)
|
||
})
|
||
test('本地调研回退不造成市场月份二次前移,生产和有提交时禁止回退', async () => {
|
||
process.env.PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK = 'true'
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-10')).sourceMonth).toBe('2026-09')
|
||
expect(workflow).toHaveBeenLastCalledWith('2026-09', expect.any(Array))
|
||
expect(readSalaryMarketIntent).toHaveBeenLastCalledWith('2026-09', expect.any(Array), ['p1'])
|
||
db.performanceSurveyResponse.count.mockResolvedValue(1)
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-10')).isFallback).toBe(false)
|
||
Object.assign(process.env, { NODE_ENV: 'production' }); db.performanceSurveyResponse.count.mockResolvedValue(0)
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-10')).isFallback).toBe(false)
|
||
})
|
||
test('权限失败不读取业务数据', async () => {
|
||
;(requireSalaryAccess as jest.Mock).mockRejectedValue(new Error('denied'))
|
||
await expect(getPerformanceSalaryDetails('forged-admin', '2026-10')).rejects.toThrow('denied')
|
||
expect(db.$transaction).not.toHaveBeenCalled()
|
||
expect(readSalaryMarketIntent).not.toHaveBeenCalled()
|
||
})
|
||
|
||
test('市场验证原始分由环比映射,按7%计分;没有经营数据不回退调研分', async () => {
|
||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['p1', { rawScore: 108.74, averageChange: .0874, validCount: 2, selected: [] }]]))
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-09'), row = data.roles['ai-planning'][0]
|
||
const metric = data.positionGroups[1].position.dimensions[1].metrics[0]
|
||
expect(row.metrics[metric.id]).toBe(108.74)
|
||
expect(row.values[`${metric.id}RawValue`]).toBe(108.74)
|
||
expect(row.values[`${metric.id}Score`]).toBe(7.61)
|
||
expect(row.totalScore).toBe(89.81)
|
||
expect(row.metricEvidence?.[metric.id]).toMatchObject({ averageChange: .0874 })
|
||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map())
|
||
expect((await getPerformanceSalaryDetails('reader', '2026-09')).roles['ai-planning'][0].totalScore).toBeNull()
|
||
})
|
||
|
||
// Month selection belongs to the aggregation layer; the conversion service receives the actual completed month.
|
||
test.each([['2026-10', '2026-09'], ['2026-09', '2026-08'], ['2027-01', '2026-12']])('%s仅市场验证取%s完结流程,其余来源及基础工资保持当月', async (month, previous) => {
|
||
;(readSalaryMarketIntent as jest.Mock).mockImplementation(async sourceMonth => new Map([['p1', { month: sourceMonth, rawScore: 120, selected: [], validCount: 1 }]]))
|
||
const data = await getPerformanceSalaryDetails('reader', month), row = data.roles['ai-planning'][0]
|
||
const dimensions = data.positionGroups[1].position.dimensions, marketMetric = dimensions[1].metrics[0]
|
||
expect(data).toMatchObject({ displayMonth: month, sourceMonth: month, marketSourceMonth: previous, isFallback: false })
|
||
expect(readSalaryMarketIntent).toHaveBeenCalledTimes(2)
|
||
expect(readSalaryMarketIntent).toHaveBeenCalledWith(previous, expect.any(Array), ['p1'])
|
||
expect(workflow).toHaveBeenCalledWith(month, expect.any(Array))
|
||
expect(db.performanceSurveyResponse.findMany.mock.calls[0][0].where.survey.assessmentMonth).toBe(month)
|
||
expect(row.metricEvidence?.[marketMetric.id]).toMatchObject({ month: previous })
|
||
expect(row.values).toMatchObject({ points: 71, baseSalary: '100.01', gradeSalary: '20.00', performanceSalary: '30.00', performanceCoefficient: .91, currentTotal: '147.31' })
|
||
expect(row.totalScore).toBe(90.6)
|
||
expect(row.values[`${marketMetric.id}Score`]).toBe(8.4)
|
||
expect(row.values[`${dimensions[1].metrics[1].id}RawValue`]).toBe(90)
|
||
})
|
||
test('上月来源失败不返回部分得分,也不读取更早月份兜底', async () => {
|
||
;(readSalaryMarketIntent as jest.Mock).mockRejectedValue(Object.assign(new Error('经营数据暂不可用'), { status: 503 }))
|
||
await expect(getPerformanceSalaryDetails('reader', '2026-10')).rejects.toMatchObject({ status: 503 })
|
||
expect(readSalaryMarketIntent).toHaveBeenCalledTimes(2)
|
||
expect(readSalaryMarketIntent).toHaveBeenCalledWith('2026-09', expect.any(Array), ['p1'])
|
||
})
|
||
|
||
test('姓名或花名冲突时调研留空并列入核对清单,积分、交付率及工资基础值不变', async () => {
|
||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([{ id: 'p1', realName: '档案名字' }, { id: 'other', flowerName: '档案花名' }])
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10')
|
||
const row = data.roles['ai-planning'][0], dimensions = data.positionGroups[1].position.dimensions
|
||
expect(data.surveyMatchIssues).toEqual([{ employeeProfileId: 'p1', employeeLabel: '档案花名', salaryRole: 'ai-planning', reason: 'name-conflict', message: '姓名和花名对应不同人员' }])
|
||
expect(row.values[`${dimensions[0].metrics[0].id}RawValue`]).toBeNull()
|
||
expect(row.values[`${dimensions[1].metrics[1].id}RawValue`]).toBe(90)
|
||
expect(row.values).toMatchObject({ points: 71, baseSalary: '100.01', performanceCoefficient: null, currentTotal: null })
|
||
})
|
||
|
||
test('主管终评102先按正式规则汇总,自评103及其他人员109不混入;无同人记录保持缺失', async () => {
|
||
const jobs = positions(); db.salaryPositionConfig.findMany.mockResolvedValue(jobs)
|
||
const base = (await db.personnelSalaryBase.findMany())[0]; base.positionId = 'job0'
|
||
db.personnelSalaryBase.findMany.mockResolvedValue([base])
|
||
const code = 'supervisor-visual'; jobs[0].dimensions[0].metrics[0].source = { kind: 'survey', templateCode: code }
|
||
jobs[0].dimensions[0].weight = '50'
|
||
const official = (id: string, score: number, stage: string) => ({ ...response(id, code, score), assignment: { workflowStageKey: stage, reviewerSource: stage === 'self_review' ? 'self' : 'fixed_employee' }, survey: { templateCode: code, templateSnapshot: { code, questions: [], workflow: { scoring: { mode: 'final_reviewer', stageKey: 'final_review', reviewerSource: 'fixed_employee' } } } } })
|
||
db.performanceSurveyResponse.findMany.mockResolvedValue([official('p1', 103, 'self_review'), official('p1', 102, 'final_review'), official('other', 109, 'final_review')])
|
||
let data = await getPerformanceSalaryDetails('reader', '2026-08')
|
||
const metric = jobs[0].dimensions[0].metrics[0]
|
||
expect(data.roles.management[0].values[`${metric.id}RawValue`]).toBe(102)
|
||
expect(data.roles.management[0].values[`${metric.id}Score`]).toBe(40.8)
|
||
db.performanceSurveyResponse.findMany.mockResolvedValue([official('other', 109, 'final_review')])
|
||
data = await getPerformanceSalaryDetails('reader', '2026-09')
|
||
expect(data.roles.management[0].values[`${metric.id}RawValue`]).toBeNull()
|
||
expect(data.surveyMatchIssues).toEqual([])
|
||
})
|
||
|
||
test('主管两项使用主部门汇总;批量读取包含未匹配职级的策划成员,其他部门隔离', async () => {
|
||
const jobs = positions()
|
||
jobs[0].dimensions[0].weight = '50'; jobs[0].dimensions[1].weight = '40'
|
||
jobs[0].dimensions[1].metrics[0].source = { kind: 'market-intent-top3' }
|
||
jobs[0].dimensions[1].metrics[1].weight = '30'; jobs[0].dimensions[1].metrics[2].weight = '30'
|
||
jobs[1].dimensions = []
|
||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs)
|
||
const supervisor = { ...(await db.personnelSalaryBase.findMany())[0], id: 'manager-base', positionId: 'job0' }
|
||
db.personnelSalaryBase.findMany.mockResolvedValue([supervisor, ...['p2', 'p3', 'other'].map(id => ({ ...supervisor, id: `base-${id}`, employeeProfileId: id, name: id, flowerName: id, positionId: 'job1', jobGrade: '' }))])
|
||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([
|
||
{ id: 'p1', realName: '档案名字', flowerName: '档案花名', displayName: 'p1', employmentState: 'ACTIVE', departmentPath: '公司/配置部门' },
|
||
...['p2', 'p3', 'video'].map(id => ({ id, displayName: id, realName: id, employmentState: 'ACTIVE', departmentPath: '公司/配置部门' })),
|
||
{ id: 'other', displayName: 'other', employmentState: 'ACTIVE', departmentPath: '公司/其他部门' },
|
||
])
|
||
db.organizationUnit.findMany.mockResolvedValue([{ sourceDeptId: 1, name: '配置部门', path: '公司/配置部门' }, { sourceDeptId: 2, name: '其他部门', path: '公司/其他部门' }])
|
||
workflow.mockResolvedValue({ sourceMonth: '2026-10', points: new Map([['p1', 71]]), onTimeRates: new Map([['p1', 100]]), deliveryCounts: new Map([['p1', { onTime: 1, total: 1 }], ['p2', { onTime: 5, total: 10 }], ['other', { onTime: 0, total: 10 }]]) })
|
||
const candidate = (key: string, change: number): MarketIntentCandidate => ({ key, workflowId: key, approvalNumber: key, productId: '123456', brand: '测试', completedAt: '2026-09-01T00:00:00Z', invalidReason: null, intentRateChange: change, sevenDayIntentRate: .1, fifteenDayIntentRate: .1 * (1 + change) })
|
||
;(readSalaryMarketIntent as jest.Mock).mockResolvedValue(new Map([['p2', summarizeMarketIntent('2026-09', [candidate('shared', .12), candidate('a', .10)])], ['p3', summarizeMarketIntent('2026-09', [candidate('shared', .12), candidate('b', .11)])]]))
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10'), row = data.roles.management[0]
|
||
const marketId = jobs[0].dimensions[1].metrics[0].id, deliveryId = jobs[0].dimensions[1].metrics[1].id
|
||
expect(readSalaryMarketIntent).toHaveBeenCalledTimes(2)
|
||
expect(new Set((readSalaryMarketIntent as jest.Mock).mock.calls[0][2])).toEqual(new Set(['p2', 'p3']))
|
||
expect(row.values[`${marketId}RawValue`]).toBe(111)
|
||
expect(row.values[`${marketId}Score`]).toBe(17.76)
|
||
expect(row.values[`${deliveryId}RawValue`]).toBe(75)
|
||
expect(row.values[`${deliveryId}Score`]).toBe(9)
|
||
expect(row.metricEvidence?.[marketId]).toMatchObject({ month: '2026-09', candidateCount: 3, departmentScope: { members: expect.any(Array) } })
|
||
expect(row.metricEvidence?.[deliveryId]).toMatchObject({ month: '2026-10', includedCount: 2, members: expect.arrayContaining([expect.objectContaining({ employeeProfileId: 'video', included: false })]) })
|
||
expect(data.roles['ai-planning'].every(p => p.performanceMatch === 'unmatched')).toBe(true)
|
||
expect(data.departmentMatchIssues).toEqual([])
|
||
})
|
||
|
||
test('主管组织归属不明时部门指标留空并提示,不能使用薪资部门文本或个人交付率代替', async () => {
|
||
const jobs = positions(), base = { ...(await db.personnelSalaryBase.findMany())[0], positionId: 'job0' }
|
||
db.salaryPositionConfig.findMany.mockResolvedValue(jobs); db.personnelSalaryBase.findMany.mockResolvedValue([base])
|
||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([{ id: 'p1', realName: '档案名字', flowerName: '档案花名', displayName: 'p1', employmentState: 'ACTIVE' }])
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10')
|
||
expect(data.roles.management[0].values[`${jobs[0].dimensions[1].metrics[1].id}RawValue`]).toBeNull()
|
||
expect(data.departmentMatchIssues).toEqual([expect.objectContaining({ employeeProfileId: 'p1', message: expect.stringContaining('主部门') })])
|
||
})
|
||
|
||
test('当前岗位基础阶段仅查询人员和岗位快照,不等待调研、流程、经营或组织读取', async () => {
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role: 'ai-planning', phase: 'base' })
|
||
expect(data.scope).toEqual({ role: 'ai-planning', phase: 'base', sources: [] })
|
||
expect(data.roles['ai-planning'][0].values.baseSalary).toBe('100.01')
|
||
expect(db.salaryPositionConfig.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { deletedAt: null, salaryRole: 'ai-planning' } }))
|
||
expect(db.performanceSurveyEmployeeProfile.findMany).not.toHaveBeenCalled()
|
||
expect(db.organizationUnit.findMany).not.toHaveBeenCalled()
|
||
expect(db.performanceSurveyResponse.findMany).not.toHaveBeenCalled()
|
||
expect(db.performanceSurveyResponse.count).not.toHaveBeenCalled()
|
||
expect(readSalaryWorkflowSnapshots).not.toHaveBeenCalled()
|
||
expect(dashboard).not.toHaveBeenCalled()
|
||
})
|
||
|
||
test.each(['ai-technical', 'photography', 'spatial-visual', 'management'] as const)('%s只启用正权重来源,不读其他岗位积分或经营数据', async role => {
|
||
const job = singleMetricPosition(role)
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role, phase: 'full' })
|
||
expect(data.roles[role][0].values).toMatchObject({ currentTotal: '147.01', previousTotal: '147.01', points: null })
|
||
expect(data.scope?.sources.map(item => item.source)).toEqual(['survey', 'survey'])
|
||
expect(db.performanceSurveyResponse.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||
where: expect.objectContaining({
|
||
target: { employeeProfileId: { in: ['p1'] } },
|
||
survey: expect.objectContaining({ templateCode: { in: ['visual_brand_tone'] } }),
|
||
}),
|
||
}))
|
||
expect(db.organizationUnit.findMany).not.toHaveBeenCalled()
|
||
expect(readSalaryWorkflowSnapshots).not.toHaveBeenCalled()
|
||
expect(workflow).not.toHaveBeenCalled()
|
||
expect(readSalaryMarketIntentBatch).not.toHaveBeenCalled()
|
||
expect(dashboard).not.toHaveBeenCalled()
|
||
expect(data.positionGroups[0].position.id).toBe(job.id)
|
||
})
|
||
|
||
test('策划岗从原看板读取当月积分,流程快照失败时积分可独立完成', async () => {
|
||
;(readSalaryWorkflowSnapshots as jest.Mock).mockRejectedValueOnce(new Error('snapshot unavailable'))
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role: 'ai-planning', phase: 'full' })
|
||
expect(data.roles['ai-planning'][0].values.points).toBe(71)
|
||
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'on-time', status: 'failed' }))
|
||
expect(data.scope?.sources).toContainEqual({ source: 'points', status: 'ready', salaryMonth: '2026-10', sourceMonth: '2026-10' })
|
||
expect(dashboard).toHaveBeenCalledTimes(1)
|
||
expect(readArtPointOvertimeExemptions).toHaveBeenCalledWith(dashboard.mock.results[0].value)
|
||
})
|
||
|
||
test('积分来源失败单独显示可重试,重试获取新积分,旧接口仍返回503', async () => {
|
||
dashboard.mockRejectedValueOnce(new Error('private dashboard URL'))
|
||
const scope = { role: 'ai-planning', phase: 'full' } as const
|
||
const result = await getPerformanceSalaryDetails('reader', '2026-10', scope)
|
||
expect(result.roles['ai-planning'][0].values).toMatchObject({ points: null, performanceCoefficient: .89, currentTotal: '146.71' })
|
||
expect(result.scope?.sources).toContainEqual(expect.objectContaining({ source: 'points', status: 'failed', code: 'SALARY_POINTS_UNAVAILABLE' }))
|
||
expect(JSON.stringify(result.scope)).not.toContain('private dashboard URL')
|
||
dashboard.mockResolvedValueOnce(pointPayload(-5))
|
||
const retry = await getPerformanceSalaryDetails('reader', '2026-10', scope)
|
||
expect(retry.roles['ai-planning'][0].values).toMatchObject({ points: -5, performanceCoefficient: .89, currentTotal: '146.71' })
|
||
dashboard.mockRejectedValueOnce(new Error('unavailable'))
|
||
await expect(getPerformanceSalaryDetails('reader', '2026-10')).rejects.toMatchObject({ status: 503, code: 'SALARY_POINTS_UNAVAILABLE' })
|
||
})
|
||
|
||
test('积分归属遇到姓名与花名碰撞时留空并单独列入核对清单', async () => {
|
||
db.performanceSurveyEmployeeProfile.findMany.mockResolvedValue([
|
||
{ id: 'p1', realName: '档案名字', flowerName: '档案花名' },
|
||
{ id: 'p2', flowerName: '档案名字' },
|
||
])
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role: 'ai-planning', phase: 'full' })
|
||
expect(data.roles['ai-planning'][0].values.points).toBeNull()
|
||
expect(data.pointsMatchIssues).toEqual([expect.objectContaining({ employeeProfileId: 'p1', employeeLabel: '档案花名' })])
|
||
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'points', status: 'ready' }))
|
||
})
|
||
|
||
test('基础数据和调研先到达,慢经营来源独立完成;最终金额与完整计算一致', async () => {
|
||
let finishMarket!: (value: Map<string, Map<string, unknown>>) => void
|
||
;(readSalaryMarketIntentBatch as jest.Mock).mockImplementationOnce(() => new Promise(resolve => { finishMarket = resolve }))
|
||
const progress: import('../performance-salary-details-contract').SalaryDetails[] = []
|
||
const pending = getPerformanceSalaryDetails('reader', '2026-10', {
|
||
role: 'ai-planning', phase: 'full', onProgress: data => progress.push(data),
|
||
})
|
||
for (let i = 0; i < 40 && !progress.some(data => data.scope?.sources.some(source => source.source === 'survey' && source.status === 'ready')); i++) await Promise.resolve()
|
||
expect(progress[0].scope?.phase).toBe('base')
|
||
expect(progress[0].roles['ai-planning'][0].values.baseSalary).toBe('100.01')
|
||
const partial = progress.find(data => data.scope?.sources.some(source => source.source === 'survey' && source.status === 'ready'))!
|
||
expect(partial.scope?.sources).toContainEqual(expect.objectContaining({ source: 'market-intent-top3', status: 'pending' }))
|
||
expect(partial.roles['ai-planning'][0].values.currentTotal).toBeNull()
|
||
finishMarket(new Map(['2026-08', '2026-09'].map(month => [month, new Map([['p1', { rawScore: 100 }]])])))
|
||
const data = await pending
|
||
expect(data.scope?.sources.every(source => source.status === 'ready')).toBe(true)
|
||
expect(data.roles['ai-planning'][0].values).toMatchObject({ currentTotal: '146.71', previousTotal: '146.71', salaryDifference: '0.00', points: 71 })
|
||
})
|
||
|
||
test('仅上月经营来源失败保留本月工资和成功指标,重试重新计算并恢复上月及差值', async () => {
|
||
const { SalaryError } = jest.requireActual('../personnel-salary')
|
||
;(readSalaryMarketIntentBatch as jest.Mock).mockImplementationOnce(async (_months, _people, _ids, _rows, onFailure) => {
|
||
onFailure('2026-08', new SalaryError('经营数据暂时无法读取。', 503, 'MARKET_INTENT_UNAVAILABLE'))
|
||
return new Map([['2026-09', new Map([['p1', { rawScore: 100 }]])]])
|
||
})
|
||
const scope = { role: 'ai-planning' as const, phase: 'full' as const }
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10', scope)
|
||
expect(data.roles['ai-planning'][0].values).toMatchObject({ currentTotal: '146.71', previousTotal: null, salaryDifference: null, points: 71 })
|
||
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'market-intent-top3', salaryMonth: '2026-09', status: 'failed' }))
|
||
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'market-intent-top3', salaryMonth: '2026-10', status: 'ready' }))
|
||
const retry = await getPerformanceSalaryDetails('reader', '2026-10', scope)
|
||
expect(retry.roles['ai-planning'][0].values).toMatchObject({ currentTotal: '146.71', previousTotal: '146.71', salaryDifference: '0.00' })
|
||
expect(readSalaryWorkflowSnapshots).toHaveBeenCalledTimes(2)
|
||
})
|
||
|
||
test('某月调研读取失败不隐藏基础工资、交付率或另一月结果,也不泄露内部错误', async () => {
|
||
db.performanceSurveyResponse.findMany.mockImplementation(async ({ where }: any) => {
|
||
if (where.survey.assessmentMonth === '2026-10') throw new Error('SELECT private salary')
|
||
return [response('p1', 'visual_brand_tone', 90), response('p1', 'work_cooperation', 60)]
|
||
})
|
||
const data = await getPerformanceSalaryDetails('reader', '2026-10', { role: 'ai-planning', phase: 'full' })
|
||
const row = data.roles['ai-planning'][0]
|
||
expect(row.values).toMatchObject({ baseSalary: '100.01', currentTotal: null, previousTotal: '146.71', salaryDifference: null, points: 71 })
|
||
expect(Object.values(row.metrics)).toContain(90)
|
||
expect(JSON.stringify(data.scope)).not.toContain('private salary')
|
||
expect(data.scope?.sources).toContainEqual(expect.objectContaining({ source: 'survey', salaryMonth: '2026-10', status: 'failed' }))
|
||
})
|