gongxiangp2/lib/__tests__/salary-market-intent.test.ts

142 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** @jest-environment node */
import { prisma } from '../prisma'
import { readSalaryMarketIntent, 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.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('完整列表依次为最高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('上海完结月筛选,不取积分审核月份;共用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)
})