diff --git a/components/department-dashboard/PerformanceSalaryDetails.test.tsx b/components/department-dashboard/PerformanceSalaryDetails.test.tsx index 4319e099..10a99d09 100644 --- a/components/department-dashboard/PerformanceSalaryDetails.test.tsx +++ b/components/department-dashboard/PerformanceSalaryDetails.test.tsx @@ -229,7 +229,7 @@ test('经营指标双列显示、计算明细可操作,包含不足3条与缺 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: { 'immature-window': 1, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 }, + 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)) @@ -255,12 +255,12 @@ 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: [], records: [], 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: { '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() const trigger = await screen.findByRole('button', { name: '测试花名市场验证计算明细' }) expect(trigger).toHaveTextContent('——'); fireEvent.click(trigger) - expect(screen.getByText(/暂无有效意向率环比/)).toBeInTheDocument() + expect(screen.getByText(/暂无可参与排名的有效意向率环比/)).toBeInTheDocument() expect(screen.getByText(/2026年8月参与的有效已完结美术流程没有可关联的商品ID/)).toBeInTheDocument() }) test('零分显示0.00,缺失原始值及贡献均显示占位符', async () => { diff --git a/components/department-dashboard/PerformanceSalaryDetails.tsx b/components/department-dashboard/PerformanceSalaryDetails.tsx index 007c4cff..7c9c5e92 100644 --- a/components/department-dashboard/PerformanceSalaryDetails.tsx +++ b/components/department-dashboard/PerformanceSalaryDetails.tsx @@ -174,7 +174,8 @@ function SalaryDetailsView({ role, month }: { role: SalaryRole; month: string })
薪资计算说明

调研得分取同月绩效考核的两位小数正式得分。考核得分=原始指标分×综合占比,逐项保留两位小数后相加为绩效得分。绩效系数=绩效得分÷100,四舍五入保留两位小数;当月总薪资=基本工资+职级工资+绩效工资×绩效系数。本月和上月分别使用各自生效的方案,人员按最新档案归属。环比上月薪资差值=本月总薪资−上月总薪资;任一月份薪资缺失时差值显示“——”。正占比指标缺失时系数及总薪资显示“——”。

- {role === 'management' &&

主管市场验证取本部门策划成员上月完结流程的最高3条有效环比均值;按时交付率取本部门当月有有效流程成员的个人比例均值。均仅统计组织架构主部门直属在职成员,点击原始值查看计算明细。

} + {groups.some(({ position }) => position.dimensions.some(dimension => dimension.metrics.some(metric => metric.source.kind === 'market-intent-top3'))) &&

市场验证取上月完结流程。需求类型为“新品”的流程保留明细,排除排名、平均及计分。{role === 'management' ? '部门合并主部门直属在职策划成员的关联记录并去重。' : ''}从其余有效记录中取最高3条,不足3条按实际数量平均。点击原始值查看计算明细。

} + {role === 'management' &&

部门按时交付率取主部门直属在职成员中,当月有有效流程成员的个人比例均值。点击原始值查看计算明细。

} {groups.some(({ position }) => [CREATIVE_MANAGER_POSITION_ID, CREATIVE_PLANNING_POSITION_ID].includes(position.personnelPositionId || position.id)) &&

品牌创意策划的个人按时交付率、品牌创意经理部门各成员的按时交付率均仅统计美术设计流程。“内容视频和图片拍摄”流程整类排除;排除后无有效流程的成员不参与部门平均。

}

左右滚动查看完整字段。

diff --git a/components/department-dashboard/SalaryMarketIntentDetails.test.tsx b/components/department-dashboard/SalaryMarketIntentDetails.test.tsx index d949e6d7..c09cf0b3 100644 --- a/components/department-dashboard/SalaryMarketIntentDetails.test.tsx +++ b/components/department-dashboard/SalaryMarketIntentDetails.test.tsx @@ -13,7 +13,7 @@ test('4条关联含2条无经营数据时全部显示,平均值及映射结果 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(/共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) @@ -31,12 +31,34 @@ test('默认完整显示长列表、未入选有效记录、0%和负环比,不 }) 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 }))) + const invalidReasons = Object.keys(MARKET_INTENT_EXCLUSION_LABELS).filter(reason => reason !== 'new-product') as Array> + show(invalidReasons.map((reason, i) => ({ ...candidate(`invalid-${i}`, null, reason), 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(/暂无可参与排名的有效意向率环比/)).toBeInTheDocument() + for (const reason of invalidReasons) expect(screen.getByText(`无效原因:${MARKET_INTENT_EXCLUSION_LABELS[reason]}`)).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() }) +test('新品显示不入选、需求类型和排除原因,仍展示经营值及链接', () => { + show([{ ...candidate('new-product', .5, 'new-product'), demandType: '新品' }, candidate('regular', -.1)]) + const rows = screen.getAllByRole('listitem') + expect(rows).toHaveLength(2) + expect(within(rows[0]).getByText('已入选')).toBeInTheDocument() + expect(within(rows[1]).getByText('不入选')).toBeInTheDocument() + expect(within(rows[1]).getByText('需求类型 新品')).toBeInTheDocument() + expect(within(rows[1]).getByText('未入选原因 需求类型为新品,不参与市场验证计分')).toBeInTheDocument() + expect(within(rows[1]).getByText('7日均值 10.00%')).toBeInTheDocument() + expect(within(rows[1]).getByText('意向率环比 50.00%')).toBeInTheDocument() + expect(within(rows[1]).getByRole('link', { name: '查看经营明细' })).toHaveAttribute('href', expect.stringContaining('workflowId=new-product')) + expect(screen.getByText(/共2条关联记录,1条可参与排名的有效环比,选取最高1条/)).toBeInTheDocument() + expect(within(screen.getByText('映射后市场验证得分').parentElement!).getByText('90.00 分')).toBeInTheDocument() +}) +test('全部新品时仍完整展示,提示缺失并省略评分平均', () => { + show([{ ...candidate('new-product', 0, 'new-product'), demandType: '新品' }]) + expect(screen.getByText('不入选')).toBeInTheDocument() + expect(screen.getByText(/暂无可参与排名的有效意向率环比,市场验证得分显示“——”/)).toBeInTheDocument() + expect(screen.getByText('意向率环比 0.00%')).toBeInTheDocument() + expect(screen.queryByText('入选环比均值')).not.toBeInTheDocument() +}) diff --git a/components/department-dashboard/SalaryMarketIntentDetails.tsx b/components/department-dashboard/SalaryMarketIntentDetails.tsx index d01c657b..db6a4c21 100644 --- a/components/department-dashboard/SalaryMarketIntentDetails.tsx +++ b/components/department-dashboard/SalaryMarketIntentDetails.tsx @@ -7,7 +7,7 @@ import { salaryMonthLabel } from '@/lib/performance-salary-templates' import { SALARY_DEPARTMENT_UNRESOLVED } from '@/lib/salary-department-contract' const percent = (value: number | null) => value === null ? '——' : `${(value * 100).toFixed(2)}%` -const statusLabels = { selected: '已入选', 'valid-not-selected': '有效但未入选', invalid: '无效' } +const statusLabels = { selected: '已入选', 'valid-not-selected': '有效但未入选', excluded: '不入选', invalid: '无效' } export default function SalaryMarketIntentDetails({ id, employeeLabel, evidence, overallShare, contribution, close }: { id: string; employeeLabel: string; evidence: MarketIntentEvidence; overallShare: number; contribution: number | null; close: () => void }) { @@ -17,20 +17,21 @@ export default function SalaryMarketIntentDetails({ id, employeeLabel, evidence, return

{employeeLabel} · 市场验证计算明细

-

考核月份:{salaryMonthLabel(evidence.month)},按该月完结流程关联的商品ID计算。共{evidence.candidateCount}条关联记录,{evidence.validCount}条有效环比,选取最高{evidence.selected.length}条。

- {evidence.departmentScope &&

{evidence.departmentScope.department ? `${evidence.departmentScope.department.name}直属在职策划成员${evidence.departmentScope.members.length}人:${evidence.departmentScope.members.map(member => member.employeeLabel).join('、') || '暂无成员'}。合并全部记录并按流程×商品ID去重后统一取最高3条。` : SALARY_DEPARTMENT_UNRESOLVED}

} +

考核月份:{salaryMonthLabel(evidence.month)},按该月完结流程关联的商品ID计算。共{evidence.candidateCount}条关联记录,{evidence.validCount}条可参与排名的有效环比,选取最高{evidence.selected.length}条。

+ {evidence.departmentScope &&

{evidence.departmentScope.department ? `${evidence.departmentScope.department.name}直属在职策划成员${evidence.departmentScope.members.length}人:${evidence.departmentScope.members.map(member => member.employeeLabel).join('、') || '暂无成员'}。合并全部记录并按流程×商品ID去重后统一取最高3条。` : SALARY_DEPARTMENT_UNRESOLVED}

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

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

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

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

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

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

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

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

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

    {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.participants &&

    本部门参与成员:{item.participants.map(member => member.employeeLabel).join('、')}

    } - {item.invalidReason &&

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

    } +

    {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))}

    +

    需求类型 {item.demandType || '——'}

    +

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

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

    + {item.participants &&

    本部门参与成员:{item.participants.map(member => member.employeeLabel).join('、')}

    } + {item.invalidReason &&

    {item.status === 'excluded' ? '未入选原因 ' : '无效原因:'}{MARKET_INTENT_EXCLUSION_LABELS[item.invalidReason]}

    }

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

    查看经营明细 @@ -39,12 +40,12 @@ export default function SalaryMarketIntentDetails({ id, employeeLabel, evidence,
} {evidence.selected.length > 0 &&
-
入选环比均值
{percent(evidence.averageChange!)}
-
映射后市场验证得分
{evidence.rawScore!.toFixed(2)} 分
-
考核得分(综合占比{(overallShare * 100).toFixed(2)}%)
{contribution === null ? '——' : `${contribution.toFixed(2)} 分`}
+
入选环比均值
{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分。先平均再映射,保留完整精度计算后乘综合占比。

+ {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/lib/__tests__/performance-salary-details.test.ts b/lib/__tests__/performance-salary-details.test.ts index 0ce5ab9a..0df7b228 100644 --- a/lib/__tests__/performance-salary-details.test.ts +++ b/lib/__tests__/performance-salary-details.test.ts @@ -118,6 +118,30 @@ test('市场来源上月与上上月独立计分;先得到两位小数工资 expect(row.values).toMatchObject({ performanceCoefficient: 1.01, currentTotal: '0.81', previousTotal: '0.30', salaryDifference: '0.51' }) }) +test('新品保留明细但不计入工资,全部新品月份独立缺失且与直接查看上月一致', async () => { + const job = singleMetricPosition('ai-planning', { kind: 'market-intent-top3' }) + const metricId = job.dimensions[0].metrics[0].id + const newProduct: MarketIntentCandidate = { + key: 'new:123456', workflowId: 'new', approvalNumber: 'new', productId: '123456', brand: '亿家达', + completedAt: '2026-09-01T00:00:00Z', demandType: '新品', invalidReason: 'new-product', + sevenDayIntentRate: 1, fifteenDayIntentRate: 1.9, intentRateChange: .9, + } + const existingProduct: MarketIntentCandidate = { + ...newProduct, key: 'existing:123456', workflowId: 'existing', demandType: '优化', invalidReason: null, + fifteenDayIntentRate: 1.1, intentRateChange: .1, + } + ;(readSalaryMarketIntent as jest.Mock).mockImplementation(async month => new Map([ + ['p1', summarizeMarketIntent(month, month === '2026-09' ? [newProduct, existingProduct] : [newProduct])], + ])) + const row = (await getPerformanceSalaryDetails('reader', '2026-10')).roles['ai-planning'][0] + expect(row).toMatchObject({ totalScore: 110, values: { performanceCoefficient: 1.1, currentTotal: '153.01', previousTotal: null, salaryDifference: null } }) + expect(row.metricEvidence?.[metricId]).toMatchObject({ candidateCount: 2, validCount: 1, selected: [{ key: 'existing:123456' }], records: [{ status: 'selected' }, { status: 'excluded' }] }) + const previous = (await getPerformanceSalaryDetails('reader', '2026-09')).roles['ai-planning'][0] + expect(previous).toMatchObject({ totalScore: null, values: { performanceCoefficient: null, currentTotal: null } }) + expect(previous.metricEvidence?.[metricId]).toMatchObject({ candidateCount: 1, validCount: 0, records: [{ status: 'excluded' }] }) + expect(row.values.previousTotal).toBe(previous.values.currentTotal) +}) + test('上月来源失败必须整体失败,不返回仅本月结果;权限失败不读任何来源', async () => { workflow.mockImplementation(async month => { if (month === '2026-09') throw Object.assign(new Error('source unavailable'), { status: 503 }) diff --git a/lib/__tests__/salary-department-metrics.test.ts b/lib/__tests__/salary-department-metrics.test.ts index b86ad28a..0af0ccf8 100644 --- a/lib/__tests__/salary-department-metrics.test.ts +++ b/lib/__tests__/salary-department-metrics.test.ts @@ -63,3 +63,15 @@ test('不足3条、负环比、0%及全无效沿用原映射,8.74%在主管16% personal.set('p1', summarizeMarketIntent('2026-09', [{ ...record('invalid', 0), invalidReason: 'zero-baseline', intentRateChange: null }])) expect(summarizeDepartmentMarketIntent('2026-09', scopes(), personal)).toMatchObject({ rawScore: null, candidateCount: 1, validCount: 0 }) }) +test('部门共享新品只保留一次并合并参与人,从全部其余有效记录中统一取前三', () => { + const shared: MarketIntentCandidate = { ...record('new:product', .9), demandType: '新品', invalidReason: 'new-product' } + const personal = new Map([ + ['p1', summarizeMarketIntent('2026-10', [shared, record('a', .1), record('b', 0)])], + ['p2', summarizeMarketIntent('2026-10', [shared, record('c', .05), record('d', -.1)])], + ]) + const result = summarizeDepartmentMarketIntent('2026-10', scopes(), personal) + expect(result).toMatchObject({ candidateCount: 5, validCount: 4, rawScore: 105, excludedCounts: { 'new-product': 1 } }) + expect(result.selected.map(item => item.key)).toEqual(['a', 'c', 'b']) + expect(result.records[4]).toMatchObject({ key: 'new:product', demandType: '新品', status: 'excluded', intentRateChange: .9 }) + expect(result.records[4].participants?.map(item => item.employeeProfileId)).toEqual(['p1', 'p2']) +}) diff --git a/lib/__tests__/salary-market-intent.test.ts b/lib/__tests__/salary-market-intent.test.ts index de1f71ee..a95813fc 100644 --- a/lib/__tests__/salary-market-intent.test.ts +++ b/lib/__tests__/salary-market-intent.test.ts @@ -62,6 +62,29 @@ test('不足3条按实际条数平均,没有有效环比为缺失,0正常计 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('新品环比最高也不入选,保留数值并排在其余有效记录之后、无效记录之前', () => { + const newProduct = (key: string, completedAt: string): MarketIntentCandidate => ({ ...record(key, .9), completedAt, demandType: '新品', invalidReason: 'new-product' }) + const result = summarizeMarketIntent('2026-09', [ + newProduct('new-old', '2026-09-01T00:00:00Z'), record('a', .1), record('b', .05), record('c', 0), record('d', -.1), + { ...record('invalid', 0), invalidReason: 'zero-baseline', intentRateChange: null }, + newProduct('new-z', '2026-09-20T00:00:00Z'), newProduct('new-a', '2026-09-20T00:00:00Z'), + ]) + expect(result).toMatchObject({ candidateCount: 8, validCount: 4, excludedCounts: { 'new-product': 3, 'zero-baseline': 1 }, rawScore: 105 }) + expect(result.averageChange).toBeCloseTo(.05) + expect(result.records.map(item => [item.key, item.status])).toEqual([ + ['a', 'selected'], ['b', 'selected'], ['c', 'selected'], ['d', 'valid-not-selected'], + ['new-a', 'excluded'], ['new-z', 'excluded'], ['new-old', 'excluded'], ['invalid', 'invalid'], + ]) + expect(result.records[4]).toMatchObject({ demandType: '新品', intentRateChange: .9, sevenDayIntentRate: 1, fifteenDayIntentRate: 1.9 }) + expect(result.validCount + Object.values(result.excludedCounts).reduce((sum, count) => sum + count, 0)).toBe(result.records.length) +}) +test('全为新品时保留全部明细,得分和平均为缺失', () => { + const item: MarketIntentCandidate = { ...record('new', .8), demandType: '新品', invalidReason: 'new-product' } + expect(summarizeMarketIntent('2026-09', [item, item])).toMatchObject({ + candidateCount: 1, validCount: 0, selected: [], averageChange: null, rawScore: null, + excludedCounts: { 'new-product': 1 }, records: [{ status: 'excluded', intentRateChange: .8 }], + }) +}) 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' } @@ -105,6 +128,39 @@ test('10个当月完结流程中5个关联有效ID,取最高3条;同流程 windows.mockImplementation(async (items: any[]) => new Map(items.map(item => [item.key, windowValue(0)]))) expect((await readSalaryMarketIntent('2026-09', people, ['p'])).get('p')!.validCount).toBe(2) }) +test('按标准化需求类型精确排除新品,多商品及重复参与人共用一次经营窗口读取', async () => { + const form = { plannerOwner: 'ding-p', productId: '123456,123456,234567' } + db.mockResolvedValue([ + flow('new', { formFields: { ...form, demandType: ' 新品 ' }, activeTasks: [{ taskId: 'make', activityId: 'a9e1_5be0', assigneeUserId: 'ding-maker' }] }), + flow('json-new', { formFields: { ...form, demandType: '["新品"]' } }), + flow('optimized', { title: '新品优化', formFields: { ...form, demandType: '优化' } }), + flow('unknown', { formFields: form }), + flow('similar', { formFields: { ...form, demandType: '新品优化' } }), + ]) + windows.mockImplementation(async (items: any[]) => new Map(items.map(item => [item.key, windowValue(item.workflowId.includes('new') ? .9 : .1)]))) + const result = await readSalaryMarketIntent('2026-09', people, ['p', 'maker']) + expect(windows).toHaveBeenCalledTimes(1) + expect(windows.mock.calls[0][0]).toHaveLength(10) + expect(result.get('p')).toMatchObject({ candidateCount: 10, validCount: 6, rawScore: expect.closeTo(110), excludedCounts: { 'new-product': 4 } }) + expect(result.get('maker')).toMatchObject({ candidateCount: 2, validCount: 0, rawScore: null, excludedCounts: { 'new-product': 2 } }) + const excluded = result.get('p')!.records.filter(item => item.status === 'excluded') + expect(excluded).toHaveLength(4) + expect(excluded.every(item => item.demandType === '新品' && item.intentRateChange !== null)).toBe(true) + expect(result.get('p')!.selected.every(item => ['optimized', 'unknown', 'similar'].includes(item.workflowId))).toBe(true) +}) +test('新品排除应用于跨年两月,已有可计算均值保留,无数据时仍明确标为不入选', async () => { + db.mockResolvedValue([ + flow('november-new', { sourceFinishedAtRaw: '2026-11-30T15:59:59Z', formFields: { plannerOwner: 'ding-p', productId: '123456', demandType: '新品' } }), + flow('december-new', { sourceFinishedAtRaw: '2026-11-30T16:00:00Z', formFields: { plannerOwner: 'ding-p', productId: '123456', demandType: '新品' } }), + flow('december-existing', { sourceFinishedAtRaw: '2026-11-30T16:00:00Z' }), + ]) + windows.mockImplementation(async (items: any[]) => new Map(items.map(item => [item.key, windowValue(.1, item.workflowId === 'december-new' ? { supported: false, sourceDaily: [], daily: [] } : {})]))) + const result = await readSalaryMarketIntentBatch(['2026-11', '2026-12'], people, ['p']) + expect(result.get('2026-11')!.get('p')).toMatchObject({ candidateCount: 1, validCount: 0, rawScore: null, records: [{ status: 'excluded', intentRateChange: expect.closeTo(.1) }] }) + const december = result.get('2026-12')!.get('p')! + expect(december).toMatchObject({ candidateCount: 2, validCount: 1, rawScore: expect.closeTo(110) }) + expect(december.records[1]).toMatchObject({ status: 'excluded', invalidReason: 'new-product', sevenDayIntentRate: null, fifteenDayIntentRate: null, intentRateChange: null }) +}) test('上海完结月筛选,不取积分审核月份;共用15日窗口可跨月,无效与未就绪分别记录', async () => { db.mockResolvedValue([ flow('august', { sourceFinishedAtRaw: '2026-08-31T15:59:59Z' }), @@ -157,6 +213,15 @@ test('来源失败整体503,不能跳过失败候选或当作0分;恢复后 windows.mockResolvedValue(new Map([['one:123456', windowValue(0)]])) expect((await readSalaryMarketIntent('2026-09', people, ['p'])).get('p')?.rawScore).toBe(100) }) +test('新品经营源失败仍返回可重试503,恢复后保留新品数值和排除状态', async () => { + db.mockResolvedValue([flow('new', { formFields: { plannerOwner: 'ding-p', productId: '123456', demandType: '新品' } })]) + windows.mockRejectedValueOnce(new Error('source offline')) + await expect(readSalaryMarketIntent('2026-09', people, ['p'])).rejects.toMatchObject({ status: 503, code: 'MARKET_INTENT_UNAVAILABLE' }) + windows.mockResolvedValue(new Map([['new:123456', windowValue(.1)]])) + expect((await readSalaryMarketIntent('2026-09', people, ['p'])).get('p')).toMatchObject({ + validCount: 0, rawScore: null, records: [{ status: 'excluded', intentRateChange: expect.closeTo(.1) }], + }) +}) test('一个窗口失败使关联月份整体待重试,不能丢弃失败记录后用剩余记录计分;其他月份正常', async () => { db.mockResolvedValue([ diff --git a/lib/salary-market-intent-contract.ts b/lib/salary-market-intent-contract.ts index 2278f74e..4e9cba57 100644 --- a/lib/salary-market-intent-contract.ts +++ b/lib/salary-market-intent-contract.ts @@ -1,8 +1,9 @@ import type { SalaryDepartmentMember } from './salary-department-contract' import type { SalaryOrganizationUnit } from './salary-organization-department' -export type MarketIntentExclusion = 'immature-window' | 'zero-baseline' | 'unsupported-platform' | 'no-source-data' | 'invalid-intent' +export type MarketIntentExclusion = 'new-product' | 'immature-window' | 'zero-baseline' | 'unsupported-platform' | 'no-source-data' | 'invalid-intent' export const MARKET_INTENT_EXCLUSION_LABELS: Record = { + 'new-product': '需求类型为新品,不参与市场验证计分', 'immature-window': '完结后未满15个自然日', 'zero-baseline': '7日意向率均值为0', 'unsupported-platform': '平台未接入经营数据', @@ -13,6 +14,7 @@ export type MarketIntentRecord = { key: string; workflowId: string; approvalNumber: string | null; productId: string brand: string; completedAt: string; intentRateChange: number sevenDayIntentRate: number; fifteenDayIntentRate: number + demandType?: string | null participants?: SalaryDepartmentMember[] } export type MarketIntentCandidate = Omit & { @@ -20,7 +22,7 @@ export type MarketIntentCandidate = Omit [item.key, item])).values()) 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) + const rejected = unique.filter(item => item.invalidReason !== null) .sort((a, b) => Date.parse(b.completedAt) - Date.parse(a.completedAt) || a.key.localeCompare(b.key)) + const newProducts = rejected.filter(item => item.invalidReason === 'new-product') + const invalid = rejected.filter(item => item.invalidReason !== 'new-product') 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 excludedCounts: MarketIntentEvidence['excludedCounts'] = { 'new-product': 0, 'immature-window': 0, 'zero-baseline': 0, 'unsupported-platform': 0, 'no-source-data': 0, 'invalid-intent': 0 } + for (const item of rejected) 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: valid.length, candidateCount: unique.length, records: [...valid.map((item, index): MarketIntentEvidenceRecord => ({ ...item, status: index < 3 ? 'selected' : 'valid-not-selected' })), + ...newProducts.map((item): MarketIntentEvidenceRecord => ({ ...item, status: 'excluded' })), ...invalid.map((item): MarketIntentEvidenceRecord => ({ ...item, status: 'invalid' }))], excludedCounts, selected, averageChange, rawScore: averageChange === null ? null : marketIntentScore(averageChange) } } diff --git a/lib/salary-market-intent.ts b/lib/salary-market-intent.ts index 6da67336..2b88a73f 100644 --- a/lib/salary-market-intent.ts +++ b/lib/salary-market-intent.ts @@ -1,7 +1,7 @@ import { SalaryError } from './personnel-salary' import { prepareSalaryWorkflow, readSalaryWorkflowSnapshots, type SalaryWorkflowSnapshot } from './salary-workflow-source' import { artPointPersonResolver, parseArtPointRows, type ArtPointPerson } from './art-workflow-points' -import { normalizeDetailFormFields, normalizeWorkflowTasks } from './ding-workflow-sync' +import { DING_WORKFLOW_NEW_PRODUCT_DEMAND_TYPE, 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 MarketIntentCandidate, type MarketIntentExclusion } from './salary-market-intent-contract' @@ -66,7 +66,7 @@ async function readMarketIntentBatch( if (!items.length) return [] const { input } = prepareSalaryWorkflow(row) const participants = Array.from(resolveMarketParticipants(input.formFields, input.tasks, resolve)).filter(id => employeeSet.has(id)) - return participants.length ? items.map(workflow => ({ workflow, participants, month })) : [] + return participants.length ? items.map(workflow => ({ workflow, participants, month, demandType: input.formFields.demandType })) : [] }) const failedMonths = new Set() const monthByKey = new Map(candidates.map(item => [item.workflow.key, item.month])) @@ -84,11 +84,12 @@ async function readMarketIntentBatch( } : {}), }) const recordsByMonth = new Map(Array.from(monthSet, month => [month, new Map()])) - for (const { workflow, participants, month } of candidates) { + for (const { workflow, participants, month, demandType } of candidates) { if (failedMonths.has(month)) continue const records = recordsByMonth.get(month)! const window = windows.get(workflow.key)!, summary = buildIntentRateWindowSummary(window.daily) - const reason: MarketIntentExclusion | null = !window.supported ? 'unsupported-platform' : window.daily.length < 15 ? 'immature-window' + const reason: MarketIntentExclusion | null = demandType === DING_WORKFLOW_NEW_PRODUCT_DEMAND_TYPE ? 'new-product' + : !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. @@ -97,7 +98,7 @@ async function readMarketIntentBatch( for (const id of participants) { 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, - invalidReason: reason, intentRateChange: nullableValue(summary.intentRateChange), sevenDayIntentRate: nullableValue(summary.sevenDayIntentRate), fifteenDayIntentRate: nullableValue(summary.fifteenDayIntentRate) }) + demandType, invalidReason: reason, intentRateChange: nullableValue(summary.intentRateChange), sevenDayIntentRate: nullableValue(summary.sevenDayIntentRate), fifteenDayIntentRate: nullableValue(summary.fifteenDayIntentRate) }) records.set(id, list) } }