243 lines
20 KiB
TypeScript
243 lines
20 KiB
TypeScript
/** @jest-environment node */
|
||
import { prisma } from '../prisma'
|
||
import { readSalaryMarketIntent, readSalaryMarketIntentBatch, marketIntentParticipants } from '../salary-market-intent'
|
||
import { readPerformanceConversionWindows } from '../performance-conversion'
|
||
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() } } }))
|
||
jest.mock('../performance-conversion', () => {
|
||
const actual = jest.requireActual('../performance-conversion')
|
||
return { ...actual, readPerformanceConversionWindows: jest.fn() }
|
||
})
|
||
const db = prisma.dingWorkflowSnapshot.findMany as jest.Mock
|
||
const windows = readPerformanceConversionWindows as jest.Mock
|
||
const people = [
|
||
{ id: 'p', dingtalkUserId: 'ding-p', realName: '策划', flowerName: '洛神', displayName: '策划' },
|
||
{ id: 'maker', dingtalkUserId: 'ding-maker', realName: '制作', flowerName: '制作', displayName: '制作' },
|
||
{ id: 'manager', dingtalkUserId: 'ding-manager', realName: '管理', flowerName: '管理', displayName: '管理' },
|
||
]
|
||
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 }
|
||
}
|
||
function windowValue(change: number, overrides = {}) {
|
||
// A first-seven-day mean of 1; choose the next eight days to produce the desired 15/7 change.
|
||
return { supported: true, sourceDaily: [{}], daily: Array.from({ length: 15 }, (_, index) => ({ date: '2026-09-01', favorites: 0, cartUsers: 0, visitors: 100, paymentConversionRate: index < 7 ? 1 : 1 + change * 15 / 8 })), ...overrides }
|
||
}
|
||
beforeEach(() => { jest.resetAllMocks() })
|
||
|
||
test('跨年双月共用一次窗口读取,多人同流程不重复读;各月最高3条独立', async () => {
|
||
const participants = [{ taskId: 'make', activityId: 'a9e1_5be0', assigneeUserId: 'ding-maker' }]
|
||
db.mockResolvedValue([
|
||
flow('november', { sourceFinishedAtRaw: '2026-11-30T15:59:59Z', activeTasks: participants }),
|
||
flow('december', { sourceFinishedAtRaw: '2026-11-30T16:00:00Z', activeTasks: participants }),
|
||
flow('january', { sourceFinishedAtRaw: '2026-12-31T16:00:00Z' }),
|
||
])
|
||
windows.mockImplementation(async (items: any[]) => new Map(items.map(item => [item.key, windowValue(item.workflowId === 'november' ? -.1 : .1)])))
|
||
const batch = await readSalaryMarketIntentBatch(['2026-11', '2026-12'], people, ['p', 'maker'])
|
||
expect(db).toHaveBeenCalledTimes(1)
|
||
expect(windows).toHaveBeenCalledTimes(1)
|
||
expect(windows.mock.calls[0][0].map((item: any) => item.workflowId)).toEqual(['november', 'december'])
|
||
expect(batch.get('2026-11')!.get('p')).toMatchObject({ month: '2026-11', rawScore: expect.closeTo(90), candidateCount: 1 })
|
||
expect(batch.get('2026-12')!.get('p')).toMatchObject({ month: '2026-12', rawScore: expect.closeTo(110), candidateCount: 1 })
|
||
expect(batch.get('2026-11')!.get('p')).toEqual(batch.get('2026-11')!.get('maker'))
|
||
expect(batch.get('2026-12')!.get('p')).toEqual(batch.get('2026-12')!.get('maker'))
|
||
})
|
||
|
||
test.each([[-.20001, 0], [-.2, 80], [-.105, 89.5], [0, 100], [.0874, 108.74], [.19999, 119.999], [.2, 120], [.5, 120]])('映射边界 %s → %s', (change, score) => {
|
||
expect(marketIntentScore(change)).toBeCloseTo(score, 10)
|
||
})
|
||
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]])
|
||
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)]).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('新品环比最高也不入选,保留数值并排在其余有效记录之后、无效记录之前', () => {
|
||
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' }
|
||
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' }] }])
|
||
const tasks = [{ taskId: 'make', activityId: 'a9e1_5be0', assigneeUserId: 'ding-maker' }, { taskId: 'assign', activityId: '38da_544a', assigneeUserId: 'ding-manager' }, { taskId: 'review', activityId: 'c255_84b3', assigneeUserId: 'ding-manager' }]
|
||
expect(Array.from(marketIntentParticipants({ plannerOwner: 'ding-p', graphicTaskStats: stats }, tasks, people)).sort()).toEqual(['maker', 'p'])
|
||
const multipleContacts = JSON.stringify([{ rowValue: [{ label: '全案策划', value: JSON.stringify([{ emplId: 'ding-p' }, { emplId: 'ding-maker' }, { emplId: 'ding-p' }]) }] }])
|
||
expect(Array.from(marketIntentParticipants({ graphicTaskStats: multipleContacts }, [], people)).sort()).toEqual(['maker', 'p'])
|
||
const ambiguous = [...people, { ...people[0], id: 'other', dingtalkUserId: 'other-ding' }]
|
||
expect(Array.from(marketIntentParticipants({ plannerOwner: '洛神' }, [], ambiguous))).toEqual([])
|
||
})
|
||
test('10个当月完结流程中5个关联有效ID,取最高3条;同流程重复ID去重,多ID分开', async () => {
|
||
db.mockResolvedValue(Array.from({ length: 10 }, (_, i) => flow(`f${i}`, i < 5 ? {} : { formFields: {} })))
|
||
windows.mockImplementation(async (items: any[]) => new Map(items.map((item, i) => [item.key, windowValue([.1, .4, -.1, .2, 0][i])])))
|
||
const result = (await readSalaryMarketIntent('2026-09', people, ['p'])).get('p')!
|
||
expect(result.validCount).toBe(5)
|
||
expect(result.selected.map(item => item.workflowId)).toEqual(['f1', 'f3', 'f0'])
|
||
expect(result.averageChange).toBeCloseTo(.7 / 3)
|
||
expect(result.rawScore).toBe(120)
|
||
db.mockResolvedValue([flow('multi', { formFields: { plannerOwner: 'ding-p', productId: '123456,123456,234567' } })])
|
||
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' }),
|
||
flow('september', { sourceFinishedAtRaw: '2026-08-31T16:00:00Z' }),
|
||
flow('last-day', { sourceFinishedAtRaw: '2026-09-30T15:59:59Z' }),
|
||
flow('october', { sourceFinishedAtRaw: '2026-09-30T16:00:00Z' }),
|
||
flow('zero'), flow('unsupported'), flow('empty'), flow('rejected', { result: 'refuse' }),
|
||
])
|
||
windows.mockImplementation(async (items: any[]) => new Map(items.map(item => [item.key,
|
||
item.workflowId === 'last-day' ? windowValue(.1, { daily: [] }) : item.workflowId === 'zero' ? windowValue(-1, { daily: Array.from({ length: 15 }, () => ({ favorites: 0, cartUsers: 0, visitors: 100, paymentConversionRate: 0 })) })
|
||
: item.workflowId === 'unsupported' ? windowValue(.1, { supported: false }) : item.workflowId === 'empty' ? windowValue(.1, { sourceDaily: [] }) : windowValue(.0874)])))
|
||
const result = (await readSalaryMarketIntent('2026-09', people, ['p'])).get('p')!
|
||
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'))
|
||
await expect(readSalaryMarketIntent('2026-09', people, ['p'])).rejects.toMatchObject({ status: 503, code: 'MARKET_INTENT_UNAVAILABLE' })
|
||
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([
|
||
flow('august-failed', { sourceFinishedAtRaw: '2026-08-10T00:00:00Z' }),
|
||
flow('august-valid', { sourceFinishedAtRaw: '2026-08-12T00:00:00Z' }),
|
||
flow('september-valid'),
|
||
])
|
||
windows.mockImplementation(async (items: any[], options) => {
|
||
options.onWindowFailure([items.find(item => item.workflowId === 'august-failed').key])
|
||
return new Map(items.map(item => [item.key, windowValue(.1)]))
|
||
})
|
||
const onFailure = jest.fn()
|
||
const result = await readSalaryMarketIntentBatch(['2026-08', '2026-09'], people, ['p'], undefined, onFailure)
|
||
expect(onFailure).toHaveBeenCalledTimes(1)
|
||
expect(onFailure).toHaveBeenCalledWith('2026-08', expect.objectContaining({ status: 503, code: 'MARKET_INTENT_UNAVAILABLE' }))
|
||
expect(result.get('2026-08')?.get('p')?.rawScore).toBeNull()
|
||
expect(result.get('2026-09')?.get('p')?.rawScore).toBeCloseTo(110)
|
||
})
|