474 lines
33 KiB
TypeScript
474 lines
33 KiB
TypeScript
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||
import PerformanceSalaryDetails from './PerformanceSalaryDetails'
|
||
import { SALARY_XLSX_MIME, type SalaryDetails } from '@/lib/performance-salary-details-contract'
|
||
import { INITIAL_SALARY_POSITIONS } from '@/lib/salary-position-seeds'
|
||
import { getPositionSalaryTemplate, previousSalaryMonth, SALARY_TEMPLATE_BLANK_ROWS } from '@/lib/performance-salary-templates'
|
||
|
||
const push = jest.fn()
|
||
jest.mock('next/navigation', () => ({ useRouter: () => ({ push }) }))
|
||
const position = { ...INITIAL_SALARY_POSITIONS[1].value, id: 'position', revision: 1, personnelCount: 1, updatedAt: '2026-10-28' }
|
||
const payload = (month = '2026-10'): SalaryDetails => {
|
||
const roles: SalaryDetails['roles'] = {
|
||
'ai-planning': [{ employeeProfileId: 'employee', employeeLabel: '测试花名', hasSalaryBase: true, positionGroupCode: 'ai_planning_creative', metrics: { cooperation: null }, totalScore: null, values: { name: '测试姓名', nickname: '测试花名', baseSalary: '1000.01', points: 42.5, onTimeRate: 80, brandReviewScore: 90 } }],
|
||
photography: [], 'spatial-visual': [], management: [], 'ai-technical': [],
|
||
}
|
||
return { displayMonth: month, sourceMonth: month, marketSourceMonth: previousSalaryMonth(month), isFallback: false, roles, positionGroups: [{ position, template: getPositionSalaryTemplate(position, month), rows: roles['ai-planning'] }] }
|
||
}
|
||
const json = (data: unknown, ok = true) => ({ ok, json: async () => data })
|
||
beforeEach(() => { jest.clearAllMocks(); global.fetch = jest.fn().mockResolvedValue(json(payload())) })
|
||
|
||
const managementPosition = {
|
||
...INITIAL_SALARY_POSITIONS[0].value, id: 'supervisor', revision: 2, personnelCount: 0, updatedAt: '2026-11-07',
|
||
dimensions: INITIAL_SALARY_POSITIONS[0].value.dimensions.map((dimension, index) => ({
|
||
...dimension, weight: ['50', '40', '10'][index],
|
||
metrics: dimension.metrics.map((metric, metricIndex) => ({ ...metric, weight: [['80', '20'], ['40', '30', '30'], ['100']][index][metricIndex] })),
|
||
})),
|
||
}
|
||
const managementPayload = (month = '2026-10'): SalaryDetails => ({
|
||
...payload(month), roles: { 'ai-planning': [], photography: [], 'spatial-visual': [], management: [], 'ai-technical': [] },
|
||
positionGroups: [{ position: managementPosition, template: getPositionSalaryTemplate(managementPosition, month), rows: [] }],
|
||
})
|
||
|
||
const technicalPosition = {
|
||
...INITIAL_SALARY_POSITIONS[2].value, id: 'technical', revision: 2, personnelCount: 0, updatedAt: '',
|
||
dimensions: INITIAL_SALARY_POSITIONS[2].value.dimensions.map((dimension, index) => ({
|
||
...dimension, weight: ['30', '60', '10'][index],
|
||
metrics: dimension.metrics.map((metric, metricIndex) => ({ ...metric,
|
||
name: index === 1 && metricIndex === 0 ? 'AI功能降本成效' : metric.name,
|
||
weight: [['50', '50'], ['30', '30', '40'], ['100']][index][metricIndex],
|
||
})),
|
||
})),
|
||
}
|
||
const technicalPayload = (): SalaryDetails => ({
|
||
...managementPayload(),
|
||
positionGroups: [{ position: technicalPosition, template: getPositionSalaryTemplate(technicalPosition, '2026-10'), rows: [] }],
|
||
})
|
||
|
||
test('技术岗无人时展示已保存六项指标和5行真空白,公共列与策划岗一致且无积分', async () => {
|
||
const data = technicalPayload()
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-technical" month="2026-10" />)
|
||
expect(await screen.findByText('暂无AI技术设计师岗人员,请在人员薪资配置中新增')).toBeInTheDocument()
|
||
const region = screen.getByRole('region', { name: 'AI技术设计师薪资明细表格' })
|
||
expect(region).toHaveAttribute('tabindex', '0')
|
||
expect(region).toHaveClass('overflow-auto', 'max-w-full')
|
||
const table = within(region).getByRole('table'), rows = within(table).getAllByRole('row')
|
||
expect(rows).toHaveLength(7)
|
||
const headers = within(rows[1]).getAllByRole('columnheader')
|
||
expect(headers.slice(0, 7).map(cell => cell.textContent)).toEqual(['花名', '姓名', '职级', '部门', '基本工资', '职级工资', '绩效工资'])
|
||
expect(headers.slice(-5).map(cell => cell.textContent)).toEqual(['绩效系数', '2026年10月合计总薪资', '2026年9月合计总薪资', '环比上月薪资差值', '备注'])
|
||
expect(headers.filter(cell => /考核得分/.test(cell.textContent || '')).map(cell => cell.textContent?.match(/综合占比(\d+)%/)?.[1])).toEqual(['15', '15', '18', '18', '24', '10'])
|
||
expect(headers.some(cell => cell.textContent?.includes('积分'))).toBe(false)
|
||
expect(headers[0]).toHaveClass('sticky', 'left-0')
|
||
for (const row of rows.slice(2)) {
|
||
const cells = within(row).getAllByRole('cell')
|
||
expect(cells).toHaveLength(24)
|
||
expect(cells.every(cell => cell.textContent === '')).toBe(true)
|
||
expect(cells[0]).toHaveClass('sticky', 'left-0')
|
||
}
|
||
})
|
||
|
||
test('技术岗有人员时仅展示真实行,缺失分数和工资保持空值,零占比两列不展示', async () => {
|
||
const data = technicalPayload()
|
||
const hidden = technicalPosition.dimensions[0].metrics[0]
|
||
const configured = { ...technicalPosition, dimensions: technicalPosition.dimensions.map((dimension, index) => index === 0 ? {
|
||
...dimension, metrics: dimension.metrics.map((metric, metricIndex) => ({ ...metric, weight: metricIndex === 0 ? '0' : '100' })),
|
||
} : dimension) }
|
||
const row = { ...payload().roles['ai-planning'][0], values: { name: '技术姓名', nickname: '技术花名', baseSalary: '2500.00', points: 99, performanceCoefficient: null, currentTotal: null, [`${hidden.id}RawValue`]: 100, [`${hidden.id}Score`]: 0 } }
|
||
data.roles['ai-technical'] = [row]
|
||
data.positionGroups = [{ position: configured, template: getPositionSalaryTemplate(configured, '2026-10'), rows: [row] }]
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-technical" month="2026-10" />)
|
||
expect(await screen.findByText('技术花名')).toHaveClass('sticky', 'left-0')
|
||
expect(screen.queryByText('暂无AI技术设计师岗人员,请在人员薪资配置中新增')).not.toBeInTheDocument()
|
||
const table = screen.getByRole('table'), rows = within(table).getAllByRole('row')
|
||
expect(rows).toHaveLength(3)
|
||
const headers = within(rows[1]).getAllByRole('columnheader'), cells = within(rows[2]).getAllByRole('cell')
|
||
expect(headers.some(header => header.textContent?.includes(hidden.name) || header.textContent?.includes('积分'))).toBe(false)
|
||
expect(cells).toHaveLength(22)
|
||
for (const label of ['绩效系数', '2026年10月合计总薪资']) expect(cells[headers.findIndex(header => header.textContent === label)]).toHaveTextContent('——')
|
||
})
|
||
|
||
test('管理岗无人时展示保存方案完整表头与5行真空白,不伪造人员、分数或积分列', async () => {
|
||
const data = managementPayload()
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="management" month="2026-10" />)
|
||
expect(await screen.findByText('暂无管理岗人员,请在人员薪资配置中新增')).toBeInTheDocument()
|
||
expect(screen.queryByText('暂无薪资明细')).not.toBeInTheDocument()
|
||
expect(screen.getByText('0人')).toBeInTheDocument()
|
||
const region = screen.getByRole('region', { name: '主管薪资明细表格' })
|
||
expect(region).toHaveAttribute('tabindex', '0')
|
||
expect(region).toHaveClass('overflow-auto')
|
||
const table = within(region).getByRole('table')
|
||
const headings = within(within(table).getAllByRole('row')[1]).getAllByRole('columnheader')
|
||
expect(headings.map(cell => cell.textContent)).toEqual(data.positionGroups[0].template.columns.map(column => column.label))
|
||
expect(headings[0]).toHaveTextContent('花名')
|
||
expect(headings[0]).toHaveClass('sticky', 'left-0')
|
||
expect(headings[1]).toHaveTextContent('姓名')
|
||
expect(headings.slice(0, 7).map(cell => cell.textContent)).toEqual(['花名', '姓名', '职级', '部门', '基本工资', '职级工资', '绩效工资'])
|
||
expect(headings.slice(-5).map(cell => cell.textContent)).toEqual(['绩效系数', '2026年10月合计总薪资', '2026年9月合计总薪资', '环比上月薪资差值', '备注'])
|
||
expect(headings.some(cell => cell.textContent === '基础薪资' || cell.textContent === '品牌')).toBe(false)
|
||
expect(headings.some(cell => cell.textContent?.includes('积分'))).toBe(false)
|
||
expect(headings.filter(cell => cell.textContent === '绩效系数')).toHaveLength(1)
|
||
expect(headings.filter(cell => /考核得分/.test(cell.textContent || '')).map(cell => cell.textContent?.match(/综合占比(\d+)%/)?.[1])).toEqual(['40', '10', '16', '12', '12', '10'])
|
||
const blankRows = within(table).getAllByRole('row').slice(2)
|
||
expect(blankRows).toHaveLength(SALARY_TEMPLATE_BLANK_ROWS)
|
||
for (const row of blankRows) {
|
||
const cells = within(row).getAllByRole('cell')
|
||
expect(cells).toHaveLength(headings.length)
|
||
expect(cells.every(cell => cell.textContent === '')).toBe(true)
|
||
expect(cells[0]).toHaveClass('sticky', 'left-0')
|
||
}
|
||
expect(data.roles.management).toHaveLength(0)
|
||
})
|
||
|
||
test('管理岗出现真实人员后只展示真实行,保留缺分和薪资空值', async () => {
|
||
const data = managementPayload(), row = { ...payload().roles['ai-planning'][0], values: { name: '测试主管', baseSalary: '2500.00', gradeSalary: '1000.00', performanceSalary: '1500.00', performanceCoefficient: null, currentTotal: null } }
|
||
data.roles.management.push(row)
|
||
data.positionGroups[0].rows.push(row)
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="management" month="2026-10" />)
|
||
expect(await screen.findByText('测试主管')).toBeInTheDocument()
|
||
expect(screen.queryByText('暂无管理岗人员,请在人员薪资配置中新增')).not.toBeInTheDocument()
|
||
const table = screen.getByRole('table')
|
||
expect(within(table).getAllByRole('row')).toHaveLength(3)
|
||
expect(screen.getByText('2500.00')).toBeInTheDocument()
|
||
const headers = within(within(table).getAllByRole('row')[1]).getAllByRole('columnheader')
|
||
const cells = within(within(table).getAllByRole('row')[2]).getAllByRole('cell')
|
||
expect(cells[0]).toHaveTextContent('——')
|
||
expect(cells[1]).toHaveTextContent('测试主管')
|
||
for (const label of ['绩效系数', '2026年10月合计总薪资', '2026年9月合计总薪资', '环比上月薪资差值']) expect(cells[headers.findIndex(header => header.textContent === label)]).toHaveTextContent('——')
|
||
})
|
||
|
||
test('多个管理岗方案分别展示,其他入口无人时保持原空状态', async () => {
|
||
const data = managementPayload()
|
||
const other = { ...managementPosition, id: 'other-supervisor', name: '其他主管方案' }
|
||
data.positionGroups.push({ position: other, template: getPositionSalaryTemplate(other, '2026-10'), rows: [] })
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
const { rerender } = render(<PerformanceSalaryDetails role="management" month="2026-10" />)
|
||
expect(await screen.findAllByText('暂无管理岗人员,请在人员薪资配置中新增')).toHaveLength(2)
|
||
expect(screen.getAllByRole('table')).toHaveLength(2)
|
||
rerender(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
expect(await screen.findByText('暂无薪资明细')).toBeInTheDocument()
|
||
expect(screen.queryByRole('table')).not.toBeInTheDocument()
|
||
})
|
||
|
||
test('展示真实人员、精确金额、缺失值、来源提示及内部横向滚动', async () => {
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
expect(screen.getByRole('status')).toHaveTextContent('正在读取薪资明细')
|
||
expect(await screen.findByText('测试姓名')).toBeInTheDocument()
|
||
expect(within(screen.getAllByRole('row')[1]).getAllByRole('columnheader')).toHaveLength(21)
|
||
expect(screen.getAllByRole('row')).toHaveLength(3)
|
||
const cells = screen.getAllByRole('cell')
|
||
expect(cells[0]).toHaveTextContent('测试花名')
|
||
expect(cells[0]).toHaveClass('sticky', 'left-0')
|
||
expect(cells[1]).toHaveTextContent('测试姓名')
|
||
expect(cells[1]).not.toHaveClass('sticky')
|
||
expect(screen.getByText('1000.01')).toBeInTheDocument()
|
||
expect(screen.getAllByRole('cell').filter(cell => cell.textContent === '——').length).toBeGreaterThan(0)
|
||
expect(screen.getByText('数据月份:2026年10月;市场验证考核月份:2026年9月')).toBeInTheDocument()
|
||
expect(screen.getByRole('region', { name: 'AI策划师-创意部薪资明细表格' })).toHaveAttribute('tabindex', '0')
|
||
expect(fetch).toHaveBeenCalledWith(expect.stringContaining('month=2026-10'), expect.objectContaining({ cache: 'no-store' }))
|
||
expect(screen.queryByText(/加权得分/)).not.toBeInTheDocument()
|
||
expect(screen.getByRole('columnheader', { name: '项目按时交付率 · 考核得分(综合占比63%)' })).toBeInTheDocument()
|
||
})
|
||
|
||
test('原始值在考核得分前,交付率保留百分号,系数两位小数且总分不单独列出', async () => {
|
||
const data = payload('2026-09')
|
||
const metric = position.dimensions[1].metrics[1]
|
||
data.roles['ai-planning'][0].values[`${metric.id}RawValue`] = 100
|
||
data.roles['ai-planning'][0].values[`${metric.id}Score`] = 63
|
||
const survey = position.dimensions[0].metrics[0]
|
||
data.roles['ai-planning'][0].values[`${survey.id}RawValue`] = 90
|
||
data.roles['ai-planning'][0].values[`${survey.id}Score`] = 22.5
|
||
data.roles['ai-planning'][0].values.performanceScore = 89.2
|
||
data.roles['ai-planning'][0].values.performanceCoefficient = .89
|
||
data.roles['ai-planning'][0].values.currentTotal = '146.71'
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-09" />)
|
||
expect(await screen.findByText('63.00 分')).toBeInTheDocument()
|
||
expect(screen.getByText('100.00%')).toBeInTheDocument()
|
||
expect(screen.getByText('100.00%').nextElementSibling).toHaveTextContent('63.00 分')
|
||
expect(screen.getByText('90.00 分').nextElementSibling).toHaveTextContent('22.50 分')
|
||
expect(screen.getByText('0.89')).toBeInTheDocument()
|
||
expect(screen.getByText('146.71')).toBeInTheDocument()
|
||
expect(screen.queryByText('89.20 分')).not.toBeInTheDocument()
|
||
expect(screen.getAllByRole('columnheader', { name: /^绩效系数$/ })).toHaveLength(1)
|
||
expect(screen.queryByRole('columnheader', { name: /^绩效得分$/ })).not.toBeInTheDocument()
|
||
expect(screen.getByText(/逐项保留两位小数后相加为绩效得分/)).toBeInTheDocument()
|
||
})
|
||
|
||
test.each([0, 1, 1.03])('系数%s固定展示两位小数,无百分号或分单位', async coefficient => {
|
||
const data = payload('2026-09')
|
||
data.roles['ai-planning'][0].values.performanceCoefficient = coefficient
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-09" />)
|
||
const cell = await screen.findByText(coefficient.toFixed(2))
|
||
expect(cell.textContent).toBe(coefficient.toFixed(2))
|
||
})
|
||
test.each([
|
||
['5000.01', '4999.99', '0.02'],
|
||
['4999.99', '5000.01', '-0.02'],
|
||
['0.00', '0.00', '0.00'],
|
||
[null, '5000.01', null],
|
||
['5000.01', null, null],
|
||
])('本月%s、上月%s、金额差%s按两位小数字符串展示,缺失不补零', async (currentTotal, previousTotal, salaryDifference) => {
|
||
const data = payload(), row = data.roles['ai-planning'][0]
|
||
Object.assign(row.values, { currentTotal, previousTotal, salaryDifference })
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
await screen.findByText('测试姓名')
|
||
const cells = within(screen.getAllByRole('row')[2]).getAllByRole('cell')
|
||
for (const [key, value] of Object.entries({ currentTotal, previousTotal, salaryDifference })) {
|
||
const index = data.positionGroups[0].template.columns.findIndex(column => column.key === key)
|
||
expect(cells[index].textContent).toBe(value ?? '——')
|
||
}
|
||
expect(screen.getByText(/环比上月薪资差值=本月总薪资−上月总薪资/)).toBeInTheDocument()
|
||
})
|
||
test('经营指标双列显示、计算明细可操作,包含不足3条与缺失原因;收起后恢复焦点', async () => {
|
||
const data = payload('2026-09'), row = data.roles['ai-planning'][0], metric = position.dimensions[1].metrics[0]
|
||
row.values[`${metric.id}RawValue`] = 108.74; row.values[`${metric.id}Score`] = 7.61
|
||
row.metricEvidence = { [metric.id]: { kind: 'market-intent-top3', month: '2026-08', candidateCount: 2, validCount: 1, averageChange: .0874, rawScore: 108.74,
|
||
excludedCounts: { 'new-product': 0, 'immature-window': 1, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 },
|
||
records: [{ key: 'flow:123456', workflowId: 'flow', approvalNumber: 'APPROVAL', productId: '123456', brand: '亿家达', completedAt: '2026-08-31T10:00:00Z', intentRateChange: .0874, sevenDayIntentRate: .1, fifteenDayIntentRate: .10874, invalidReason: null, status: 'selected' }, { key: 'immature:234567', workflowId: 'immature', approvalNumber: 'IMMATURE', productId: '234567', brand: '亿家达', completedAt: '2026-08-31T10:00:00Z', intentRateChange: null, sevenDayIntentRate: .1, fifteenDayIntentRate: null, invalidReason: 'immature-window', status: 'invalid' }],
|
||
selected: [{ key: 'flow:123456', workflowId: 'flow', approvalNumber: 'APPROVAL', productId: '123456', brand: '亿家达', completedAt: '2026-08-31T10:00:00Z', intentRateChange: .0874, sevenDayIntentRate: .1, fifteenDayIntentRate: .10874 }] } }
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-09" />)
|
||
const trigger = await screen.findByRole('button', { name: '测试花名市场验证计算明细' })
|
||
expect(screen.getByRole('columnheader', { name: '创意成果市场验证 · 市场验证得分(上月)' })).toBeInTheDocument()
|
||
expect(trigger).toHaveTextContent('108.74 分'); expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||
fireEvent.click(trigger)
|
||
expect(trigger).toHaveAttribute('aria-expanded', 'true')
|
||
expect(screen.getByText(/考核月份:2026年8月,按该月完结流程关联的商品ID计算/)).toBeInTheDocument()
|
||
expect(screen.getByText(/完结后7日、15日观察窗口可跨月/)).toBeInTheDocument()
|
||
expect(screen.getByText('有效记录不足3条,按实际1条取平均。')).toBeInTheDocument()
|
||
expect(screen.getAllByRole('link', { name: '查看经营明细' })[0]).toHaveAttribute('href', expect.stringContaining('workflowId=flow&productId=123456'))
|
||
expect(screen.getByText('已入选')).toBeInTheDocument()
|
||
expect(screen.getByText('无效原因:完结后未满15个自然日')).toBeInTheDocument()
|
||
expect(screen.getByText('15日均值 ——')).toBeInTheDocument()
|
||
expect(screen.getAllByRole('link', { name: '查看经营明细' })).toHaveLength(2)
|
||
expect(screen.getByText(/未参与排名:完结后未满15个自然日 1条/)).toBeInTheDocument()
|
||
fireEvent.click(screen.getByRole('button', { name: '收起明细' }))
|
||
expect(trigger).toHaveFocus()
|
||
expect(screen.queryByRole('heading', { name: '测试花名 · 市场验证计算明细' })).not.toBeInTheDocument()
|
||
})
|
||
|
||
test('经营指标无有效记录也可查看缺失说明,不显示0分', async () => {
|
||
const data = payload('2026-09'), row = data.roles['ai-planning'][0], metric = position.dimensions[1].metrics[0]
|
||
row.metricEvidence = { [metric.id]: { kind: 'market-intent-top3', month: '2026-08', candidateCount: 0, validCount: 0, averageChange: null, rawScore: null, selected: [], records: [], excludedCounts: { 'new-product': 0, 'immature-window': 0, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 } } }
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-09" />)
|
||
const trigger = await screen.findByRole('button', { name: '测试花名市场验证计算明细' })
|
||
expect(trigger).toHaveTextContent('——'); fireEvent.click(trigger)
|
||
expect(screen.getByText(/暂无可参与排名的有效意向率环比/)).toBeInTheDocument()
|
||
expect(screen.getByText(/2026年8月参与的有效已完结美术流程没有可关联的商品ID/)).toBeInTheDocument()
|
||
})
|
||
test('零分显示0.00,缺失原始值及贡献均显示占位符', async () => {
|
||
const data = payload('2026-09')
|
||
const metric = position.dimensions[0].metrics[0]
|
||
data.roles['ai-planning'][0].values[`${metric.id}RawValue`] = 0
|
||
data.roles['ai-planning'][0].values[`${metric.id}Score`] = 0
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-09" />)
|
||
expect(await screen.findAllByText('0.00 分')).toHaveLength(2)
|
||
const headers = within(screen.getAllByRole('row')[1]).getAllByRole('columnheader')
|
||
expect(headers.some(header => header.textContent?.includes('跨部门协同'))).toBe(false)
|
||
const missingIndex = headers.findIndex(header => header.textContent === '工作配合满意度 · 调研得分')
|
||
const cells = within(screen.getAllByRole('row')[2]).getAllByRole('cell')
|
||
expect(cells[missingIndex]).toHaveTextContent('——')
|
||
expect(cells[missingIndex + 1]).toHaveTextContent('——')
|
||
})
|
||
test('月份切换推入URL,前进后退props同步,岗位空状态保留来源提示', async () => {
|
||
const { rerender } = render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
await screen.findByText('测试姓名')
|
||
fireEvent.change(screen.getByLabelText('薪资月份'), { target: { value: '2027-01' } })
|
||
fireEvent.click(screen.getByRole('button', { name: '查询' }))
|
||
expect(push).toHaveBeenCalledWith('/workspaces/organization/performance-review?role=ai-planning&month=2027-01', { scroll: false })
|
||
;(fetch as jest.Mock).mockResolvedValue(json(payload('2027-01')))
|
||
rerender(<PerformanceSalaryDetails role="management" month="2027-01" />)
|
||
expect(screen.queryByText('测试姓名')).not.toBeInTheDocument()
|
||
expect(await screen.findByText('暂无薪资明细')).toBeInTheDocument()
|
||
expect(screen.getByText('所选入口暂无已配置岗位的人员薪资档案。')).toBeInTheDocument()
|
||
expect(screen.getByText('数据月份:2027年1月;市场验证考核月份:2026年12月')).toBeInTheDocument()
|
||
expect(screen.getByLabelText('薪资月份')).toHaveValue('2027-01')
|
||
})
|
||
test('接口失败有就地重试,过期响应不覆盖新月份', async () => {
|
||
;(fetch as jest.Mock).mockResolvedValueOnce(json({ error: '明细暂时不可用' }, false)).mockResolvedValueOnce(json(payload()))
|
||
const { rerender } = render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
expect(await screen.findByRole('alert')).toHaveTextContent('明细暂时不可用')
|
||
fireEvent.click(screen.getByRole('button', { name: '重新加载' }))
|
||
await screen.findByText('测试姓名')
|
||
let stale!: (value: unknown) => void
|
||
;(fetch as jest.Mock).mockImplementationOnce(() => new Promise(resolve => { stale = resolve })).mockResolvedValueOnce(json(payload('2026-12')))
|
||
rerender(<PerformanceSalaryDetails role="ai-planning" month="2026-11" />)
|
||
rerender(<PerformanceSalaryDetails role="management" month="2026-12" />)
|
||
await screen.findByText('数据月份:2026年12月;市场验证考核月份:2026年11月')
|
||
stale(json(payload('2026-11')))
|
||
await waitFor(() => expect(screen.queryByText('数据月份:2026年11月;市场验证考核月份:2026年10月')).not.toBeInTheDocument())
|
||
})
|
||
const exportUrl = '/api/organization/performance-salary/details/export?month=2026-10'
|
||
const xlsx = () => ({ ok: true, headers: { get: () => SALARY_XLSX_MIME }, blob: async () => new Blob() })
|
||
|
||
test('从空岗位也可导出已查询月份的全部岗位,失败可重试且生成期间防重复', async () => {
|
||
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: jest.fn(() => 'blob:salary-details') })
|
||
Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: jest.fn() })
|
||
const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function(this: HTMLAnchorElement) {
|
||
expect(this.download).toBe('绩效薪资明细_2026-10.xlsx')
|
||
})
|
||
try {
|
||
render(<PerformanceSalaryDetails role="photography" month="2026-10" />)
|
||
await screen.findByText('暂无薪资明细')
|
||
fireEvent.change(screen.getByLabelText('薪资月份'), { target: { value: '2026-11' } })
|
||
const request = fetch as jest.Mock
|
||
let finish!: (response: ReturnType<typeof xlsx>) => void
|
||
request.mockResolvedValueOnce(json({ error: '2026年9月市场验证暂时无法读取,请稍后重新导出。' }, false))
|
||
.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
|
||
fireEvent.click(screen.getByRole('button', { name: '导出薪资明细' }))
|
||
expect(await screen.findByRole('alert')).toHaveTextContent('2026年9月市场验证')
|
||
expect(click).not.toHaveBeenCalled()
|
||
fireEvent.click(screen.getByRole('button', { name: '导出薪资明细' }))
|
||
const busy = screen.getByRole('button', { name: '正在生成…' })
|
||
expect(busy).toBeDisabled()
|
||
fireEvent.click(busy)
|
||
expect(request.mock.calls.filter(([url]) => url === exportUrl)).toHaveLength(2)
|
||
expect(request).toHaveBeenLastCalledWith(exportUrl, expect.objectContaining({ cache: 'no-store', signal: expect.any(AbortSignal) }))
|
||
finish(xlsx())
|
||
expect(await screen.findByRole('status')).toHaveTextContent('当月全部岗位薪资明细已生成')
|
||
expect(click).toHaveBeenCalledTimes(1)
|
||
} finally { click.mockRestore() }
|
||
})
|
||
|
||
test('切换岗位取消旧导出,旧请求完成也不触发下载', async () => {
|
||
const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||
try {
|
||
const { rerender } = render(<PerformanceSalaryDetails role="photography" month="2026-10" />)
|
||
await screen.findByText('暂无薪资明细')
|
||
const request = fetch as jest.Mock
|
||
let finish!: (response: ReturnType<typeof xlsx>) => void
|
||
request.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
|
||
fireEvent.click(screen.getByRole('button', { name: '导出薪资明细' }))
|
||
const [url, { signal }] = request.mock.lastCall!
|
||
expect(url).toBe(exportUrl)
|
||
request.mockResolvedValueOnce(json(payload('2026-11')))
|
||
rerender(<PerformanceSalaryDetails role="ai-planning" month="2026-11" />)
|
||
expect(signal.aborted).toBe(true)
|
||
finish(xlsx())
|
||
expect(await screen.findByText('测试姓名')).toBeInTheDocument()
|
||
expect(screen.getByRole('button', { name: '导出薪资明细' })).toBeEnabled()
|
||
expect(click).not.toHaveBeenCalled()
|
||
expect(screen.queryByText(/薪资明细已生成/)).not.toBeInTheDocument()
|
||
} finally { click.mockRestore() }
|
||
})
|
||
|
||
|
||
test('核对清单只显示当前入口且不回填冲突人员的缺失调研分', async () => {
|
||
const data = payload()
|
||
data.surveyMatchIssues = [
|
||
{ employeeProfileId: 'employee', employeeLabel: '测试花名', salaryRole: 'ai-planning', reason: 'ambiguous', message: '姓名或花名对应多名人员' },
|
||
{ employeeProfileId: 'manager', employeeLabel: '其他主管', salaryRole: 'management', reason: 'id-conflict', message: '姓名匹配人员与档案已有人员ID不一致' },
|
||
]
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
const checklist = await screen.findByRole('region', { name: '调研关联待核对' })
|
||
expect(checklist).toHaveTextContent('调研关联待核对(1人)')
|
||
expect(checklist).toHaveTextContent('测试花名:姓名或花名对应多名人员')
|
||
expect(checklist).not.toHaveTextContent('其他主管')
|
||
expect(screen.getByText(/调研得分取同月绩效考核的两位小数正式得分/)).toBeInTheDocument()
|
||
})
|
||
|
||
test('积分归属冲突提示核对人名,积分保留缺失展示', async () => {
|
||
const data = payload()
|
||
data.roles['ai-planning'][0].values.points = null
|
||
data.pointsMatchIssues = [{ employeeProfileId: 'employee', employeeLabel: '测试花名', message: '请核对姓名与花名' }]
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
expect(await screen.findByRole('region', { name: '积分归属待核对' })).toHaveTextContent('测试花名:请核对姓名与花名')
|
||
const index = screen.getAllByRole('columnheader').findIndex(header => header.textContent === '2026年10月积分')
|
||
expect(screen.getAllByRole('cell')[index]).toHaveTextContent('——')
|
||
})
|
||
|
||
test('主管部门交付率复用原始值明细按钮,展开聚焦标题,收起恢复触发器焦点', async () => {
|
||
const data = managementPayload(), metric = managementPosition.dimensions[1].metrics[1]
|
||
const row = { ...payload().roles['ai-planning'][0], values: { nickname: '主管花名', [`${metric.id}RawValue`]: 75, [`${metric.id}Score`]: 9 }, metricEvidence: {
|
||
[metric.id]: { kind: 'department-on-time-average' as const, month: '2026-10', department: { sourceDeptId: 1, name: 'A部', path: '公司/A部' }, members: [
|
||
{ employeeProfileId: 'a', employeeLabel: '甲', onTimeCount: 1, totalCount: 1, rate: 100, included: true },
|
||
{ employeeProfileId: 'b', employeeLabel: '乙', onTimeCount: 5, totalCount: 10, rate: 50, included: true },
|
||
], includedCount: 2, rawScore: 75 },
|
||
} }
|
||
data.roles.management.push(row); data.positionGroups[0].rows.push(row)
|
||
;(fetch as jest.Mock).mockResolvedValue(json(data))
|
||
render(<PerformanceSalaryDetails role="management" month="2026-10" />)
|
||
const trigger = await screen.findByRole('button', { name: '测试花名部门按时交付率计算明细' })
|
||
expect(trigger).toHaveTextContent('75.00%')
|
||
fireEvent.click(trigger)
|
||
expect(screen.getByRole('heading', { name: '测试花名 · 部门按时交付率计算明细' })).toHaveFocus()
|
||
expect(screen.getByText('按时完成5条 / 有效交付流程10条')).toBeInTheDocument()
|
||
fireEvent.click(screen.getByRole('button', { name: '收起明细' }))
|
||
expect(trigger).toHaveFocus(); expect(trigger).toHaveAttribute('aria-expanded', 'false')
|
||
})
|
||
|
||
test('分项加载时人员工资先出现,来源失败可在保留已读数据的情况下重试', async () => {
|
||
const market = position.dimensions[1].metrics[0]
|
||
const survey = position.dimensions[0].metrics[0]
|
||
const scoped = (phase: 'base' | 'partial' | 'full', marketStatus: 'pending' | 'failed' | 'ready') => {
|
||
const data = payload()
|
||
const row = data.roles['ai-planning'][0]
|
||
const context = { salaryMonth: '2026-10', sourceMonth: '2026-09', source: 'market-intent-top3' as const }
|
||
data.scope = { role: 'ai-planning', phase, sources: phase === 'base' ? [] : [
|
||
{ ...context, source: 'survey', sourceMonth: '2026-10', status: 'ready' },
|
||
marketStatus === 'failed'
|
||
? { ...context, status: marketStatus, code: 'MARKET_INTENT_UNAVAILABLE', message: '经营数据暂时无法读取。' }
|
||
: { ...context, status: marketStatus },
|
||
] }
|
||
if (phase !== 'base') row.values[`${survey.id}RawValue`] = 92.5
|
||
if (marketStatus === 'ready') {
|
||
row.values[`${market.id}RawValue`] = 108.74
|
||
row.values.currentTotal = '2000.00'
|
||
}
|
||
return data
|
||
}
|
||
|
||
const { TextEncoder, TextDecoder } = await import('node:util')
|
||
const originalDecoder = globalThis.TextDecoder
|
||
Object.assign(globalThis, { TextDecoder })
|
||
const encoder = new TextEncoder()
|
||
let receive!: (result: { done: boolean; value?: Uint8Array }) => void
|
||
const read = jest.fn(() => new Promise(resolve => { receive = resolve }))
|
||
const stream = { ok: true, headers: { get: () => 'application/x-ndjson' }, body: { getReader: () => ({ read, cancel: async () => {}, releaseLock: () => {} }) } }
|
||
const emit = (data: SalaryDetails) => receive({ done: false, value: encoder.encode(JSON.stringify({ data }) + '\n') })
|
||
const fetchMock = fetch as jest.Mock
|
||
fetchMock.mockResolvedValueOnce(stream).mockResolvedValueOnce(stream)
|
||
try {
|
||
render(<PerformanceSalaryDetails role="ai-planning" month="2026-10" />)
|
||
await waitFor(() => expect(read).toHaveBeenCalledTimes(1))
|
||
emit(scoped('base', 'pending'))
|
||
expect(await screen.findByText('1000.01')).toBeInTheDocument()
|
||
expect(screen.getAllByText('加载中').length).toBeGreaterThan(1)
|
||
emit(scoped('partial', 'pending'))
|
||
expect(await screen.findByText('92.50 分')).toBeInTheDocument()
|
||
emit(scoped('full', 'failed'))
|
||
expect(await screen.findByRole('alert')).toHaveTextContent('市场验证')
|
||
expect(screen.getAllByText('读取失败')).toHaveLength(2)
|
||
expect(screen.getByText('92.50 分')).toBeInTheDocument()
|
||
receive({ done: true })
|
||
|
||
const retry = screen.getByRole('button', { name: '重试计算' })
|
||
retry.focus()
|
||
fireEvent.click(retry)
|
||
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
|
||
expect(screen.getByText('1000.01')).toBeInTheDocument()
|
||
expect(screen.getByText('92.50 分')).toBeInTheDocument()
|
||
emit(scoped('base', 'pending'))
|
||
await waitFor(() => expect(read).toHaveBeenCalledTimes(6))
|
||
expect(screen.getByText('92.50 分')).toBeInTheDocument()
|
||
emit(scoped('full', 'ready'))
|
||
expect(await screen.findByText('2000.00')).toBeInTheDocument()
|
||
expect(screen.getByText('108.74 分')).toBeInTheDocument()
|
||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||
expect(screen.getByText('薪资明细已更新。')).toHaveFocus()
|
||
receive({ done: true })
|
||
} finally {
|
||
Object.assign(globalThis, { TextDecoder: originalDecoder })
|
||
}
|
||
})
|