diff --git a/components/department-dashboard/PerformanceSalaryDetails.test.tsx b/components/department-dashboard/PerformanceSalaryDetails.test.tsx index c772caff..984f6c6d 100644 --- a/components/department-dashboard/PerformanceSalaryDetails.test.tsx +++ b/components/department-dashboard/PerformanceSalaryDetails.test.tsx @@ -74,6 +74,7 @@ test('经营指标双列显示、计算明细可操作,包含不足3条与缺 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: { '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() @@ -85,7 +86,11 @@ test('经营指标双列显示、计算明细可操作,包含不足3条与缺 expect(screen.getByText(/考核月份:2026年8月,按该月完结流程关联的商品ID计算/)).toBeInTheDocument() expect(screen.getByText(/完结后7日、15日观察窗口可跨月/)).toBeInTheDocument() expect(screen.getByText('有效记录不足3条,按实际1条取平均。')).toBeInTheDocument() - expect(screen.getByRole('link', { name: '查看经营明细' })).toHaveAttribute('href', expect.stringContaining('workflowId=flow&productId=123456')) + 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() @@ -94,7 +99,7 @@ test('经营指标双列显示、计算明细可操作,包含不足3条与缺 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: [], excludedCounts: { 'immature-window': 0, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 } } } + row.metricEvidence = { [metric.id]: { kind: 'market-intent-top3', month: '2026-08', candidateCount: 0, validCount: 0, averageChange: null, rawScore: null, selected: [], records: [], excludedCounts: { 'immature-window': 0, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 } } } ;(fetch as jest.Mock).mockResolvedValue(json(data)) render() const trigger = await screen.findByRole('button', { name: '测试花名市场验证计算明细' }) diff --git a/components/department-dashboard/SalaryMarketIntentDetails.test.tsx b/components/department-dashboard/SalaryMarketIntentDetails.test.tsx new file mode 100644 index 00000000..d949e6d7 --- /dev/null +++ b/components/department-dashboard/SalaryMarketIntentDetails.test.tsx @@ -0,0 +1,42 @@ +import { render, screen, within } from '@testing-library/react' +import SalaryMarketIntentDetails from './SalaryMarketIntentDetails' +import { summarizeMarketIntent, type MarketIntentCandidate, MARKET_INTENT_EXCLUSION_LABELS } from '@/lib/salary-market-intent-contract' + +const candidate = (key: string, change: number | null, invalidReason: MarketIntentCandidate['invalidReason'] = null): MarketIntentCandidate => ({ + key, workflowId: key, approvalNumber: key, productId: key, brand: '测试品牌', completedAt: '2026-07-01T00:00:00Z', + intentRateChange: change, sevenDayIntentRate: change === null ? null : .1, fifteenDayIntentRate: change === null ? null : .1 * (1 + change), invalidReason, +}) +const show = (items: MarketIntentCandidate[]) => render() + +test('4条关联含2条无经营数据时全部显示,平均值及映射结果保持不变', () => { + show([candidate('valid-a', -.07104), candidate('valid-b', -.5333), candidate('invalid-a', null, 'no-source-data'), candidate('invalid-b', null, 'no-source-data')]) + expect(screen.getAllByRole('listitem')).toHaveLength(4) + expect(screen.getAllByText('已入选')).toHaveLength(2) + expect(screen.getAllByText('无效原因:没有关联的经营数据')).toHaveLength(2) + expect(screen.getByText(/共4条关联记录,2条有效环比,选取最高2条/)).toBeInTheDocument() + expect(screen.getByText('-30.22%')).toBeInTheDocument() + expect(within(screen.getByText('映射后市场验证得分').parentElement!).getByText('0.00 分')).toBeInTheDocument() + expect(screen.getAllByRole('link', { name: '查看经营明细' })).toHaveLength(4) +}) + +test('默认完整显示长列表、未入选有效记录、0%和负环比,不截断记录', () => { + show(Array.from({ length: 75 }, (_, i) => candidate(`long-workflow-${i}-` + '1234567890'.repeat(10), (3 - i) / 100))) + const rows = screen.getAllByRole('listitem') + expect(rows).toHaveLength(75) + expect(screen.getAllByText('已入选')).toHaveLength(3) + expect(screen.getAllByText('有效但未入选')).toHaveLength(72) + expect(within(rows[3]).getByText('意向率环比 0.00%')).toBeInTheDocument() + expect(within(rows[74]).getByText('意向率环比 -71.00%')).toBeInTheDocument() + expect(within(rows[74]).getByRole('link')).toHaveAttribute('href', expect.stringContaining('workflowId=long-workflow-74-')) +}) + +test('全部无效仍显示每一条及全部原因,保留可算均值和合法0值', () => { + show(Object.keys(MARKET_INTENT_EXCLUSION_LABELS).map((reason, i) => ({ ...candidate(`invalid-${i}`, null, reason as MarketIntentCandidate['invalidReason']), sevenDayIntentRate: i === 0 ? .1 : i === 1 ? 0 : null }))) + expect(screen.getAllByRole('listitem')).toHaveLength(5) + expect(screen.getByText(/暂无有效意向率环比/)).toBeInTheDocument() + for (const label of Object.values(MARKET_INTENT_EXCLUSION_LABELS)) expect(screen.getByText(`无效原因:${label}`)).toBeInTheDocument() + expect(screen.getByText('7日均值 10.00%')).toBeInTheDocument() + expect(screen.getByText('7日均值 0.00%')).toBeInTheDocument() + expect(screen.getAllByText('意向率环比 ——')).toHaveLength(5) + expect(screen.queryByText('入选环比均值')).not.toBeInTheDocument() +}) diff --git a/components/department-dashboard/SalaryMarketIntentDetails.tsx b/components/department-dashboard/SalaryMarketIntentDetails.tsx index 83382afb..bc3f92a8 100644 --- a/components/department-dashboard/SalaryMarketIntentDetails.tsx +++ b/components/department-dashboard/SalaryMarketIntentDetails.tsx @@ -5,7 +5,8 @@ import { MARKET_INTENT_EXCLUSION_LABELS, type MarketIntentEvidence } from '@/lib import { salarySecondary } from './SalaryConfigurationUI' import { salaryMonthLabel } from '@/lib/performance-salary-templates' -const percent = (value: number) => `${(value * 100).toFixed(2)}%` +const percent = (value: number | null) => value === null ? '——' : `${(value * 100).toFixed(2)}%` +const statusLabels = { selected: '已入选', 'valid-not-selected': '有效但未入选', invalid: '无效' } export default function SalaryMarketIntentDetails({ id, employeeLabel, evidence, overallShare, contribution, close }: { id: string; employeeLabel: string; evidence: MarketIntentEvidence; overallShare: number; contribution: number | null; close: () => void }) { @@ -19,25 +20,27 @@ export default function SalaryMarketIntentDetails({ id, employeeLabel, evidence, - {evidence.selected.length === 0 ?

暂无有效意向率环比,市场验证得分显示“——”。{evidence.candidateCount === 0 && `${salaryMonthLabel(evidence.month)}参与的有效已完结美术流程没有可关联的商品ID。`}

- : <> - {evidence.selected.length < 3 &&

有效记录不足3条,按实际{evidence.selected.length}条取平均。

} + {evidence.selected.length === 0 &&

暂无有效意向率环比,市场验证得分显示“——”。{evidence.candidateCount === 0 && `${salaryMonthLabel(evidence.month)}参与的有效已完结美术流程没有可关联的商品ID。`}

} + {evidence.selected.length > 0 && evidence.selected.length < 3 &&

有效记录不足3条,按实际{evidence.selected.length}条取平均。

} + {evidence.records.length > 0 &&
    - {evidence.selected.map((item, index) =>
  1. -

    {index + 1}. {item.approvalNumber || item.workflowId}

    {item.brand} · 商品ID {item.productId}

    完结日期:{new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.completedAt))}

    -

    7日均值 {percent(item.sevenDayIntentRate)} · 15日均值 {percent(item.fifteenDayIntentRate)}

    + {evidence.records.map((item, index) =>
  2. +

    {index + 1}. {item.approvalNumber || item.workflowId}

    {statusLabels[item.status]}

    {item.brand} · 商品ID {item.productId}

    完结日期:{new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(item.completedAt))}

    +

    7日均值 {percent(item.sevenDayIntentRate)}

    15日均值 {percent(item.fifteenDayIntentRate)}

    + {item.invalidReason &&

    无效原因:{MARKET_INTENT_EXCLUSION_LABELS[item.invalidReason]}

    }

    意向率环比 {percent(item.intentRateChange)}

    查看经营明细
  3. )} -
+ } + {evidence.selected.length > 0 &&
入选环比均值
{percent(evidence.averageChange!)}
映射后市场验证得分
{evidence.rawScore!.toFixed(2)} 分
考核得分(综合占比{(overallShare * 100).toFixed(2)}%)
{contribution === null ? '——' : `${contribution.toFixed(2)} 分`}
- } + } {exclusions.length > 0 &&

未参与排名:{exclusions.map(([reason, count]) => `${MARKET_INTENT_EXCLUSION_LABELS[reason as keyof typeof MARKET_INTENT_EXCLUSION_LABELS]} ${count}条`).join(';')}。

}

按薪资月上月的完结流程取数,完结后7日、15日观察窗口可跨月,不截断到月末。环比=(15日意向率均值-7日意向率均值)÷7日意向率均值。平均环比低于−20%为0分;−20%至20%为100加环比百分点;20%及以上为120分。先平均再映射,保留完整精度计算后乘综合占比。

diff --git a/docs/salary-market-intent.md b/docs/salary-market-intent.md index 9333ff93..044db0ce 100644 --- a/docs/salary-market-intent.md +++ b/docs/salary-market-intent.md @@ -14,6 +14,10 @@ 既有 `GET /api/organization/performance-salary/details?month=YYYY-MM` 的原始 `metrics`、`RawValue` 及 `Score` 规则保持一致;响应同时返回 `displayMonth`、`sourceMonth` 和市场验证专用的 `marketSourceMonth`。行级 `metricEvidence`,按指标ID保存候选/有效数量、未入选原因数量、最高3条记录、平均环比和映射分。响应仍使用当前数据库权限及 `private, no-store`。 +`metricEvidence.records` 保留该员工考核月的全部流程×商品ID关联,按稳定记录键去重。每条含流程及商品身份、可空的7日/15日均值和环比、`status`(`selected`、`valid-not-selected`、`invalid`)及可空的 `invalidReason`。数量、有效数、排除原因汇总和 `selected` 均从同一去重结果产生;原计分不变,不增加逐条查询。排序为环比降序的已入选/其余有效记录,再按完结时间倒序的无效记录,同值按稳定键排序。 + +展开明细默认完整列出全部记录及经营链接,不截断条数。无效记录逐条显示现有判定原因;没有数据来源时均值与环比为null,未满15日但已有7日均值时保留7日结果,真实0值正常展示。数据源读取失败仍为可重试503,不作为无效记录继续算分。 + 原始列名称为“市场验证得分(上月)”,考核得分表头同时标注上月和综合占比。来源提示分别显示当前数据月份和市场验证考核月份,计算明细显示实际考核月份、完结日期及跨月观察窗口说明。按钮展开表格下方计算明细,支持键盘、收起焦点恢复及经营明细链接。空白模板使用相同表头,仍只有5行空白,不导出真实人员、工资或经营记录。 ## 显式配置维护 diff --git a/lib/__tests__/salary-market-intent.test.ts b/lib/__tests__/salary-market-intent.test.ts index 10899763..3ecf03af 100644 --- a/lib/__tests__/salary-market-intent.test.ts +++ b/lib/__tests__/salary-market-intent.test.ts @@ -2,7 +2,7 @@ import { prisma } from '../prisma' import { readSalaryMarketIntent, marketIntentParticipants } from '../salary-market-intent' import { readPerformanceConversionWindows } from '../performance-conversion' -import { marketIntentScore, summarizeMarketIntent, type MarketIntentRecord } from '../salary-market-intent-contract' +import { marketIntentScore, summarizeMarketIntent, type MarketIntentCandidate } from '../salary-market-intent-contract' import { DING_WORKFLOW_ALLOWED_PROCESS_CODES } from '../ding-workflow-sync' jest.mock('../prisma', () => ({ prisma: { dingWorkflowSnapshot: { findMany: jest.fn() } } })) @@ -17,8 +17,7 @@ const people = [ { id: 'maker', dingtalkUserId: 'ding-maker', realName: '制作', flowerName: '制作', displayName: '制作' }, { id: 'manager', dingtalkUserId: 'ding-manager', realName: '管理', flowerName: '管理', displayName: '管理' }, ] -const record = (key: string, change: number): MarketIntentRecord => ({ key, workflowId: key, approvalNumber: key, productId: '123456', brand: '亿家达', completedAt: '2026-09-01T00:00:00Z', intentRateChange: change, sevenDayIntentRate: 1, fifteenDayIntentRate: 1 + change }) -const excluded = () => ({ 'immature-window': 0, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 }) +const record = (key: string, change: number): MarketIntentCandidate => ({ invalidReason: null, key, workflowId: key, approvalNumber: key, productId: '123456', brand: '亿家达', completedAt: '2026-09-01T00:00:00Z', intentRateChange: change, sevenDayIntentRate: 1, fifteenDayIntentRate: 1 + change }) function flow(id: string, overrides = {}) { return { processInstanceId: id, businessId: id, title: id, brand: '亿家达', status: 'COMPLETED', result: 'agree', bizAction: 'finish', processCode: DING_WORKFLOW_ALLOWED_PROCESS_CODES[0], sourceFinishedAtRaw: '2026-09-01T00:00:00Z', formFields: { productId: '123456', plannerOwner: 'ding-p' }, activeTasks: [], ...overrides } @@ -34,16 +33,38 @@ test.each([[-.20001, 0], [-.2, 80], [-.105, 89.5], [0, 100], [.0874, 108.74], [. }) test('取最高3条环比后平均再映射,同一商品跨流程及负数保留,不提前舍入', () => { const items = [.5, .1, -.1, -.2, -.5].map((change, i) => record(`flow${i}:123456`, change)) - const result = summarizeMarketIntent('2026-09', [...items, items[0]], excluded()) + const result = summarizeMarketIntent('2026-09', [...items, items[0]]) expect(result.validCount).toBe(5) expect(result.selected.map(item => item.intentRateChange)).toEqual([.5, .1, -.1]) expect(result.averageChange).toBeCloseTo(1 / 6) expect(result.rawScore).toBeCloseTo(116.6666666667) }) test('不足3条按实际条数平均,没有有效环比为缺失,0正常计分', () => { - expect(summarizeMarketIntent('2026-09', [record('a', 0)], excluded()).rawScore).toBe(100) - expect(summarizeMarketIntent('2026-09', [record('a', -.1), record('b', -.2)], excluded()).rawScore).toBeCloseTo(85) - expect(summarizeMarketIntent('2026-09', [], excluded())).toMatchObject({ averageChange: null, rawScore: null, validCount: 0 }) + expect(summarizeMarketIntent('2026-09', [record('a', 0)]).rawScore).toBe(100) + expect(summarizeMarketIntent('2026-09', [record('a', -.1), record('b', -.2)]).rawScore).toBeCloseTo(85) + expect(summarizeMarketIntent('2026-09', [])).toMatchObject({ averageChange: null, rawScore: null, validCount: 0 }) +}) +test('完整列表依次为最高3条、其余有效、无效;同值稳定排序且无效记录去重后计数', () => { + const invalid = (key: string, completedAt: string): MarketIntentCandidate => ({ ...record(key, 0), completedAt, invalidReason: 'no-source-data', intentRateChange: null, sevenDayIntentRate: null, fifteenDayIntentRate: null }) + const old = invalid('old', '2026-09-01T00:00:00Z'), recentB = invalid('recent-b', '2026-09-20T00:00:00Z'), recentA = { ...recentB, key: 'recent-a' } + const result = summarizeMarketIntent('2026-09', [old, record('negative', -.2), recentB, record('b', .1), record('zero', 0), record('a', .1), recentA, old]) + expect(result.records.map(item => [item.key, item.status])).toEqual([ + ['a', 'selected'], ['b', 'selected'], ['zero', 'selected'], ['negative', 'valid-not-selected'], + ['recent-a', 'invalid'], ['recent-b', 'invalid'], ['old', 'invalid'], + ]) + expect(result).toMatchObject({ candidateCount: 7, validCount: 4, excludedCounts: { 'no-source-data': 3 } }) + expect(result.records).toHaveLength(result.candidateCount) + expect(result.validCount + Object.values(result.excludedCounts).reduce((a, b) => a + b, 0)).toBe(result.candidateCount) + expect(result.averageChange).toBeCloseTo(.2 / 3) +}) +test('全部无效也保留身份、逐条原因、可用均值,零基数不伪装成零环比', () => { + const result = summarizeMarketIntent('2026-09', [ + { ...record('zero', 0), intentRateChange: null, sevenDayIntentRate: 0, fifteenDayIntentRate: .1, invalidReason: 'zero-baseline' }, + { ...record('bad', 0), intentRateChange: null, sevenDayIntentRate: .1, fifteenDayIntentRate: null, invalidReason: 'invalid-intent' }, + ]) + expect(result).toMatchObject({ candidateCount: 2, validCount: 0, selected: [], averageChange: null, rawScore: null }) + expect(result.records.every(item => item.status === 'invalid')).toBe(true) + expect(result.records[1]).toMatchObject({ key: 'zero', sevenDayIntentRate: 0, fifteenDayIntentRate: .1, intentRateChange: null }) }) test('策划负责人和制作节点及任务统计合并去重,只分配/审核不关联,不按重名猜人', () => { const stats = JSON.stringify([{ rowValue: [{ label: '全案策划', value: 'ding-maker' }] }]) @@ -81,6 +102,36 @@ test('上海完结月筛选,不取积分审核月份;共用15日窗口可跨 expect(windows.mock.calls[0][0].map((item: any) => item.workflowId)).toEqual(['september', 'last-day', 'zero', 'unsupported', 'empty']) expect(windows.mock.calls[0][1]).toEqual({ intentWindowOnly: true }) expect(result).toMatchObject({ validCount: 1, rawScore: expect.closeTo(108.74), excludedCounts: { 'immature-window': 1, 'zero-baseline': 1, 'unsupported-platform': 1, 'no-source-data': 1 } }) + expect(result.records).toHaveLength(5) + for (const id of ['unsupported', 'empty']) expect(result.records.find(item => item.workflowId === id)).toMatchObject({ status: 'invalid', intentRateChange: null, sevenDayIntentRate: null, fifteenDayIntentRate: null }) + expect(result.records.find(item => item.workflowId === 'zero')).toMatchObject({ invalidReason: 'zero-baseline', sevenDayIntentRate: 0, fifteenDayIntentRate: 0, intentRateChange: null }) + expect(windows).toHaveBeenCalledTimes(1) +}) +test('多人及同流程重复商品只批量读取一次,未满15日仍保留已算出的7日均值', async () => { + db.mockResolvedValue([flow('partial', { formFields: { plannerOwner: 'ding-p', productId: '123456,123456' }, activeTasks: [{ taskId: 'make', activityId: 'a9e1_5be0', assigneeUserId: 'ding-maker' }] })]) + windows.mockImplementation(async (items: any[]) => new Map(items.map(item => [item.key, windowValue(0, { daily: windowValue(0).daily.slice(0, 10) })]))) + const result = await readSalaryMarketIntent('2026-09', people, ['p', 'maker', 'manager']) + expect(result.get('p')).toEqual(result.get('maker')) + expect(result.get('p')).toMatchObject({ candidateCount: 1, validCount: 0, selected: [], records: [{ status: 'invalid', invalidReason: 'immature-window', sevenDayIntentRate: 1, fifteenDayIntentRate: null, intentRateChange: null }] }) + expect(result.get('manager')).toMatchObject({ candidateCount: 0, records: [] }) + expect(windows).toHaveBeenCalledTimes(1) + expect(windows.mock.calls[0][0]).toHaveLength(1) +}) +test('逐条无效原因保持原有优先级,无法计算的非有限均值不暴露为数值', async () => { + db.mockResolvedValue(['unsupported', 'immature', 'empty', 'invalid'].map(id => flow(id))) + const zero = windowValue(0).daily.map(day => ({ ...day, paymentConversionRate: 0 })) + windows.mockImplementation(async (items: any[]) => new Map(items.map(item => [item.key, + item.workflowId === 'unsupported' ? windowValue(0, { supported: false, daily: [], sourceDaily: [] }) + : item.workflowId === 'immature' ? windowValue(0, { daily: [], sourceDaily: [] }) + : item.workflowId === 'empty' ? windowValue(0, { daily: zero, sourceDaily: [] }) + : windowValue(0, { daily: zero.map(day => ({ ...day, paymentConversionRate: Number.MAX_VALUE })) }), + ]))) + const result = (await readSalaryMarketIntent('2026-09', people, ['p'])).get('p')! + expect(result.records.map(item => [item.workflowId, item.invalidReason])).toEqual([ + ['empty', 'no-source-data'], ['immature', 'immature-window'], ['invalid', 'invalid-intent'], ['unsupported', 'unsupported-platform'], + ]) + expect(result.records.every(item => item.intentRateChange === null && item.sevenDayIntentRate === null && item.fifteenDayIntentRate === null)).toBe(true) + expect(result).toMatchObject({ candidateCount: 4, validCount: 0, selected: [], rawScore: null }) }) test('来源失败整体503,不能跳过失败候选或当作0分;恢复后重新读取', async () => { db.mockResolvedValue([flow('one')]); windows.mockRejectedValueOnce(new Error('source offline')) diff --git a/lib/salary-market-intent-contract.ts b/lib/salary-market-intent-contract.ts index 8e3850a6..9cfdad39 100644 --- a/lib/salary-market-intent-contract.ts +++ b/lib/salary-market-intent-contract.ts @@ -11,9 +11,17 @@ export type MarketIntentRecord = { brand: string; completedAt: string; intentRateChange: number sevenDayIntentRate: number; fifteenDayIntentRate: number } +export type MarketIntentCandidate = Omit & { + intentRateChange: number | null; sevenDayIntentRate: number | null; fifteenDayIntentRate: number | null + invalidReason: MarketIntentExclusion | null +} +export type MarketIntentEvidenceRecord = MarketIntentCandidate & { + status: 'selected' | 'valid-not-selected' | 'invalid' +} export type MarketIntentEvidence = { kind: 'market-intent-top3'; month: string; candidateCount: number; validCount: number excludedCounts: Record + records: MarketIntentEvidenceRecord[] selected: MarketIntentRecord[]; averageChange: number | null; rawScore: number | null } /** Input is a ratio: 0.0874 means 8.74%. Never round before averaging or weighting. */ @@ -22,12 +30,19 @@ export function marketIntentScore(change: number): number { if (change >= 0.2) return 120 return 100 + change * 100 } -export function summarizeMarketIntent(month: string, records: MarketIntentRecord[], excludedCounts: MarketIntentEvidence['excludedCounts']): MarketIntentEvidence { +export function summarizeMarketIntent(month: string, records: MarketIntentCandidate[]): MarketIntentEvidence { const unique = Array.from(new Map(records.map(item => [item.key, item])).values()) - const selected = unique.sort((a, b) => b.intentRateChange - a.intentRateChange || a.key.localeCompare(b.key)).slice(0, 3) + const valid = unique.filter((item): item is MarketIntentCandidate & MarketIntentRecord => item.invalidReason === null) + .sort((a, b) => b.intentRateChange - a.intentRateChange || a.key.localeCompare(b.key)) + const invalid = unique.filter(item => item.invalidReason !== null) + .sort((a, b) => Date.parse(b.completedAt) - Date.parse(a.completedAt) || a.key.localeCompare(b.key)) + const selected = valid.slice(0, 3).map(({ invalidReason: _, ...item }) => item) + const excludedCounts: MarketIntentEvidence['excludedCounts'] = { 'immature-window': 0, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 } + for (const item of invalid) excludedCounts[item.invalidReason!]++ const averageChange = selected.length ? selected.reduce((sum, item) => sum + item.intentRateChange, 0) / selected.length : null - return { kind: 'market-intent-top3', month, validCount: unique.length, - candidateCount: unique.length + Object.values(excludedCounts).reduce((sum, count) => sum + count, 0), + return { kind: 'market-intent-top3', month, validCount: valid.length, candidateCount: unique.length, + records: [...valid.map((item, index): MarketIntentEvidenceRecord => ({ ...item, status: index < 3 ? 'selected' : 'valid-not-selected' })), + ...invalid.map((item): MarketIntentEvidenceRecord => ({ ...item, status: 'invalid' }))], excludedCounts, selected, averageChange, rawScore: averageChange === null ? null : marketIntentScore(averageChange) } } export const MARKET_INTENT_SOURCE_LABEL = '业绩转化 · 上月最高3条意向率环比' diff --git a/lib/salary-market-intent.ts b/lib/salary-market-intent.ts index 98aebc48..c9d981a9 100644 --- a/lib/salary-market-intent.ts +++ b/lib/salary-market-intent.ts @@ -4,7 +4,7 @@ import { artPointPersonResolver, parseArtPointRows, type ArtPointPerson } from ' import { DING_WORKFLOW_ALLOWED_PROCESS_CODES, DING_WORKFLOW_STARTED_AT_CUTOFF_ISO, normalizeDetailFormFields, normalizeWorkflowTasks } from './ding-workflow-sync' import { performanceConversionWorkflowItems, readPerformanceConversionWindows } from './performance-conversion' import { buildIntentRateWindowSummary, toShanghaiDateKey } from '@/components/department-dashboard/performance-conversion' -import { summarizeMarketIntent, type MarketIntentEvidence, type MarketIntentRecord, type MarketIntentExclusion } from './salary-market-intent-contract' +import { summarizeMarketIntent, type MarketIntentEvidence, type MarketIntentCandidate, type MarketIntentExclusion } from './salary-market-intent-contract' const PRODUCTION_ACTIVITIES = new Set(['31cf_5b23', 'a9e1_5be0', 'de46_708d', '2f9e_36f0', 'b306_c849', 'f073_738b', '6864_5429', '162b_23ea', 'c9fe_a6b8']) export function marketIntentParticipants(formFields: unknown, activeTasks: unknown, people: ArtPointPerson[]) { @@ -47,21 +47,21 @@ async function readMarketIntent(month: string, people: ArtPointPerson[], employe let windows: Awaited> try { windows = await readPerformanceConversionWindows(candidates.map(item => item.workflow), { intentWindowOnly: true }) } catch { throw new SalaryError('经营数据暂时无法读取,未计算市场验证得分,请稍后重新加载。', 503, 'MARKET_INTENT_UNAVAILABLE') } - const records = new Map() - const excluded = new Map() - for (const id of Array.from(employeeSet)) excluded.set(id, { 'immature-window': 0, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 }) + const records = new Map() for (const { workflow, participants } of candidates) { const window = windows.get(workflow.key)!, summary = buildIntentRateWindowSummary(window.daily) const reason: MarketIntentExclusion | null = !window.supported ? 'unsupported-platform' : window.daily.length < 15 ? 'immature-window' : !window.sourceDaily.length ? 'no-source-data' : summary.sevenDayIntentRate === 0 ? 'zero-baseline' : summary.intentRateChange === null || !Number.isFinite(summary.intentRateChange) ? 'invalid-intent' : null + // Calendar expansion creates synthetic zero days even when the source is empty. + // Only expose computable means backed by an available data source. + const nullableValue = (value: number | null) => window.supported && window.sourceDaily.length > 0 && value !== null && Number.isFinite(value) ? value : null for (const id of participants) { - if (reason) { excluded.get(id)![reason]++; continue } const list = records.get(id) ?? [] list.push({ key: workflow.key, workflowId: workflow.workflowId, approvalNumber: workflow.approvalNumber, productId: workflow.productId, brand: workflow.brand, completedAt: workflow.completedAt, - intentRateChange: summary.intentRateChange!, sevenDayIntentRate: summary.sevenDayIntentRate!, fifteenDayIntentRate: summary.fifteenDayIntentRate! }) + invalidReason: reason, intentRateChange: nullableValue(summary.intentRateChange), sevenDayIntentRate: nullableValue(summary.sevenDayIntentRate), fifteenDayIntentRate: nullableValue(summary.fifteenDayIntentRate) }) records.set(id, list) } } - return new Map(Array.from(employeeSet, id => [id, summarizeMarketIntent(month, records.get(id) ?? [], excluded.get(id)!)])) + return new Map(Array.from(employeeSet, id => [id, summarizeMarketIntent(month, records.get(id) ?? [])])) }