import { readFileSync } from 'node:fs'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * U20:事件延迟导致已完成订单漏导 —— 归档补拉(A)/ 延迟告警(B)/ 回填单号(C)。 * * 真实案例:ORD_WEB_20261103_BR002_0012 已完成(status=90、prepare_status=30), * 主系统事件延迟 15.5h 才被消费;active 定向拉取为空 → 归档补拉(3 行)→ 建单 → 回填 our_order_code。 */ const runtime = vi.hoisted(() => ({ query: vi.fn() })); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => runtime.query(...args) }, })); vi.mock('../src/services/mainSystemBranchApi', () => ({ listSupplierCodesForBranch: vi.fn() })); vi.mock('../src/services/mainSystem/token', () => ({ getMainSystemToken: vi.fn() })); vi.mock('../src/services/mainSystem/api/events', () => ({ fetchSupplierEvents: vi.fn() })); vi.mock('../src/services/tenantDbContext', () => ({ runWithTenantDbContext: async (_branchCode: string, fn: () => Promise) => fn(), })); vi.mock('../src/services/mainSystemReturnFollow', () => ({ followMainSystemPrepChanges: vi.fn() })); vi.mock('../src/services/mainSystemPreparations', () => ({ lookupPreparationStatesBatch: vi.fn(), fetchActivePreparationsForOrder: vi.fn(), })); import { computeEventDelayMinutes, isArchivedBackfillEnabled, resolveArchivedBackfillRange, resolveLateEventWarnMinutes, shouldAttemptArchivedBackfill, tryArchivedBackfillForOrder, } from '../src/services/mainSystemEventConsumer'; import { backfillActualQtyRequestOrderCode } from '../src/services/mainSystemActualQtyBackfill'; const consumerSource = readFileSync( new URL('../src/services/mainSystemEventConsumer.ts', import.meta.url), 'utf8' ); const branchPullSource = readFileSync( new URL('../src/services/mainSystemBranchPull.ts', import.meta.url), 'utf8' ); const prepSource = readFileSync( new URL('../src/services/mainSystem/api/preparations.ts', import.meta.url), 'utf8' ); const importSource = readFileSync( new URL('../src/services/mainSystemOrderImport.ts', import.meta.url), 'utf8' ); type ImportedOutcome = Awaited> extends never ? never : { kind: 'ok'; branchCode: string; created: number; appended: number; skipped: number; failed: number; results: Array<{ mainOrderCode: string; ourOrderCode: string | null; itemCount: number; status: 'created' | 'appended' | 'skipped' | 'skipped_tombstoned' | 'failed'; }>; }; function okOutcome(created: number, appended: number): ImportedOutcome { return { kind: 'ok', branchCode: 'BR002', created, appended, skipped: 0, failed: 0, results: [] }; } const archivedPull = { kind: 'ok' as const, branchCode: 'BR002', failures: [], pulls: [ { supplierCode: 'SUP-BR002', mainBranchCode: 'BR002', outcome: { kind: 'ok' as const, supplierCode: 'SUP-BR002', branchCode: 'BR002', orders: [ { orderCode: 'ORD_WEB_20261103_BR002_0012', deliveryDate: '2026-11-03', taskDay: '2026-11-03', rows: [ { id: 'prep-1' }, { id: 'prep-2' }, { id: 'prep-3' }, ] as never, }, ], rowCount: 3, }, }, ], }; beforeEach(() => { vi.clearAllMocks(); runtime.query.mockResolvedValue({ rowCount: 0, rows: [] }); }); describe('U20-A:归档补拉(active 为空才触发、开关、幂等)', () => { it('sql/函数契约:archived fetch 支持 order_code、新增 pullArchivedPreparationsForOrders、targeted_pull 有归档回退', () => { expect(prepSource).toContain('fetchMainSystemArchivedPreparations'); expect(prepSource).toContain('order_code='); expect(branchPullSource).toContain('pullArchivedPreparationsForOrders'); expect(branchPullSource).toContain('fetchMainSystemArchivedPreparations(supplierCode, range, orderCode)'); expect(consumerSource).toContain('shouldAttemptArchivedBackfill'); expect(consumerSource).toContain('tryArchivedBackfillForOrder'); expect(consumerSource).toContain('MAIN_SYSTEM_ARCHIVED_BACKFILL'); }); it('仅 active 0 建单/0 补行才尝试归档(active 有数据绝不调归档)', () => { expect(shouldAttemptArchivedBackfill(okOutcome(0, 0))).toBe(true); expect(shouldAttemptArchivedBackfill(okOutcome(1, 0))).toBe(false); expect(shouldAttemptArchivedBackfill(okOutcome(0, 2))).toBe(false); expect(shouldAttemptArchivedBackfill(okOutcome(0, 0), false)).toBe(false); }); it('开关:默认开;MAIN_SYSTEM_ARCHIVED_BACKFILL=0/false 关闭(回到原行为)', () => { expect(isArchivedBackfillEnabled(undefined)).toBe(true); expect(isArchivedBackfillEnabled('1')).toBe(true); expect(isArchivedBackfillEnabled('0')).toBe(false); expect(isArchivedBackfillEnabled('false')).toBe(false); expect(isArchivedBackfillEnabled('FALSE')).toBe(false); const pullArchived = vi.fn(async () => archivedPull); const importOrders = vi.fn(async () => okOutcome(0, 0)); return tryArchivedBackfillForOrder({ branchCode: 'BR002', orderCode: 'ORD_WEB_20261103_BR002_0012', enabled: false, pullArchived, importOrders, }).then((result) => { expect(result.status).toBe('disabled'); expect(pullArchived).not.toHaveBeenCalled(); expect(importOrders).not.toHaveBeenCalled(); }); }); it('事件日期 → 归档区间 date−2d ~ date+1d(归档日按 prepare_time/created_at)', () => { const range = resolveArchivedBackfillRange('2026-11-03T13:47:00+08:00', new Date('2026-11-04T05:16:50+08:00')); expect(range).toEqual({ dateFrom: '2026-11-01', dateTo: '2026-11-04' }); // 缺失 createdAt → 用 now 兜底 expect(resolveArchivedBackfillRange(null, new Date('2026-11-04T05:16:50+08:00'))).toEqual({ dateFrom: '2026-11-02', dateTo: '2026-11-05', }); }); it('归档为空 → 维持原行为(不二次导入);归档异常 → ignored', async () => { const pullEmpty = vi.fn(async () => ({ ...archivedPull, pulls: [{ ...archivedPull.pulls[0], outcome: { ...archivedPull.pulls[0].outcome, orders: [], rowCount: 0 } }], })); const importOrders = vi.fn(async () => okOutcome(0, 0)); const outcome = await tryArchivedBackfillForOrder({ branchCode: 'BR002', orderCode: 'ORD_WEB_20261103_BR002_0012', eventCreatedAt: '2026-11-03T13:47:00+08:00', pullArchived: pullEmpty as never, importOrders, }); expect(outcome.status).toBe('ignored'); expect(outcome.reason).toBe('archived_empty'); expect(importOrders).not.toHaveBeenCalled(); const throwingPull = vi.fn(async () => { throw new Error('network down'); }); const thrown = await tryArchivedBackfillForOrder({ branchCode: 'BR002', orderCode: 'ORD_WEB_20261103_BR002_0012', pullArchived: throwingPull as never, importOrders, }); expect(thrown.status).toBe('ignored'); expect(thrown.reason).toBe('archived_pull_error'); expect(importOrders).not.toHaveBeenCalled(); }); it('幂等:重复跑归档补拉,第二次 import 无新建/补行 → 不再建单(ignored)', async () => { const pullArchived = vi.fn(async () => archivedPull); const importOrders = vi .fn() .mockResolvedValueOnce(okOutcome(1, 0)) .mockResolvedValueOnce(okOutcome(0, 0)); const first = await tryArchivedBackfillForOrder({ branchCode: 'BR002', orderCode: 'ORD_WEB_20261103_BR002_0012', pullArchived: pullArchived as never, importOrders, }); const second = await tryArchivedBackfillForOrder({ branchCode: 'BR002', orderCode: 'ORD_WEB_20261103_BR002_0012', pullArchived: pullArchived as never, importOrders, }); expect(first.status).toBe('applied'); expect(second.status).toBe('ignored'); expect(importOrders).toHaveBeenCalledTimes(2); // 两次都走 import 幂等;第二次 created=0/appended=0 ⇒ 不重复建单 expect(second.archivedCreated ?? 0).toBe(0); }); }); describe('U20-B:事件延迟告警', () => { it('默认阈值 10 分钟、env 可调;延迟计算正确', () => { expect(resolveLateEventWarnMinutes(undefined)).toBe(10); expect(resolveLateEventWarnMinutes('5')).toBe(5); expect(resolveLateEventWarnMinutes('abc')).toBe(10); const late15h = computeEventDelayMinutes( '2026-11-03T13:47:00+08:00', new Date('2026-11-04T05:16:50+08:00').getTime() ); // 13:47 → 次日 05:16:50 = 15h29m50s ≈ 929.83 分钟 expect(late15h).toBeCloseTo(15 * 60 + 29 + 50 / 60, 2); expect(computeEventDelayMinutes(null)).toBeNull(); expect(computeEventDelayMinutes('not-a-date')).toBeNull(); }); }); describe('U20-C:回填 our_order_code(只填空值、不覆盖)', () => { it('SQL 只更新空/空串行,参数含 branch/order/our_order_code', async () => { runtime.query.mockResolvedValue({ rowCount: 3, rows: [] }); const updated = await backfillActualQtyRequestOrderCode({ branchCode: 'BR002', mainOrderCode: 'ORD_WEB_20261103_BR002_0012', ourOrderCode: 'ORD_LOCAL_PREVIEW_001', }); expect(updated).toBe(3); const [sql, params] = runtime.query.mock.calls[0] as [string, unknown[]]; expect(sql).toContain('UPDATE public.main_system_actual_qty_requests'); expect(sql).toContain('SET our_order_code = $3'); expect(sql).toContain("(our_order_code IS NULL OR TRIM(our_order_code) = '')"); expect(sql).not.toContain('SET order_code'); expect(params).toEqual(['BR002', 'ORD_WEB_20261103_BR002_0012', 'ORD_LOCAL_PREVIEW_001']); }); it('缺参数不执行 UPDATE;导入成功后调用点存在', async () => { expect( await backfillActualQtyRequestOrderCode({ branchCode: '', mainOrderCode: 'A', ourOrderCode: 'B' }) ).toBe(0); expect(runtime.query).not.toHaveBeenCalled(); expect(importSource).toContain('backfillActualQtyRequestOrderCode'); expect(importSource).toContain("result.status === 'created' || result.status === 'appended'"); }); }); describe('U20 真实案例离线复现(active 空 + archived 3 行 ⇒ 建单 + 回填单号)', () => { it('ORD_WEB_20261103_BR002_0012:延迟 15.5h 消费 → active 0 → 归档补拉 3 行 → 建单 → 回填 our_order_code', async () => { const branchCode = 'BR002'; const mainOrderCode = 'ORD_WEB_20261103_BR002_0012'; const ourOrderCode = 'ORD_LOCAL_20261104_0001'; const eventCreatedAt = '2026-11-03T13:47:00+08:00'; // 1) active 定向导入:0 建单/0 补行(订单已完成、active 拉不到) const activeImport = okOutcome(0, 0); expect(shouldAttemptArchivedBackfill(activeImport)).toBe(true); // 2) 归档补拉 + 导入(真实 import 由 mock 模拟:建单成功后调用 C 回填) const pullArchived = vi.fn(async () => archivedPull); const importOrders = vi.fn(async (params: { preloadedPull?: unknown }) => { // 模拟真实 import 的 C 调用点(创建成功后回填) const updated = await backfillActualQtyRequestOrderCode({ branchCode, mainOrderCode, ourOrderCode, }); return { ...okOutcome(1, 0), results: [ { mainOrderCode, ourOrderCode, itemCount: 3, status: 'created' as const, }, ], backfilled: updated, } as unknown as ImportedOutcome; }); const backfill = await tryArchivedBackfillForOrder({ branchCode, orderCode: mainOrderCode, eventCreatedAt, pullArchived: pullArchived as never, importOrders: importOrders as never, }); // 3) 断言:归档被调用(带 order 与 date 区间)、建单成功、回填 SQL 落到本系统单号 expect(backfill.status).toBe('applied'); expect(backfill.archivedCreated).toBe(1); expect(pullArchived).toHaveBeenCalledWith(branchCode, [mainOrderCode], { dateFrom: '2026-11-01', dateTo: '2026-11-04', }); expect(importOrders).toHaveBeenCalledTimes(1); const updateCall = runtime.query.mock.calls.find(([sql]) => String(sql).includes('UPDATE public.main_system_actual_qty_requests') ); expect(updateCall).toBeTruthy(); expect(updateCall?.[1]).toEqual([branchCode, mainOrderCode, ourOrderCode]); }); });