import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * T2 独立边界复测 · orphan 策略 A + 改派往返(2026-10-19,tester)。 * * 与 dev 的 `mainSystemReverseEvents.test.ts` / `mainSystemPrepLedgerRevive.test.ts` 独立: * c) orphan 策略 A:全删只剩 2 orphan ⇒ 停用订单、orphan 行保留、operation_logs 1 条、 * orphan 通知 1 次、clearDayPointer 1 次;合并单只删 A(B 有来源)⇒ 不停用;已完成 90 ⇒ 零改动。 * d) 改派往返:A→B 写 reallocated;同 prep 再回 A ⇒ imported 且不重复行;removed 后再出现 ⇒ 仍阻断; * 重复投递幂等。 */ const H = vi.hoisted(() => ({ poolQuery: vi.fn(), tenantCtx: vi.fn(), markPrep: vi.fn(), removeItem: vi.fn(), recalcHeader: vi.fn(), clearDayPointer: vi.fn(), notify: vi.fn(), audit: vi.fn(), })); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => H.poolQuery(...args), connect: vi.fn() }, query: (...args: unknown[]) => H.poolQuery(...args), getRawPoolQuery: () => H.poolQuery, })); vi.mock('../src/services/tenantDbContext', () => ({ runWithTenantDbContext: (_code: unknown, fn: () => Promise) => H.tenantCtx(fn), })); vi.mock('../src/services/mainSystemPrepLedger', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, markPrepDisposition: (...args: unknown[]) => H.markPrep(...args), }; }); vi.mock('../src/services/orderManageItemsService', () => ({ removeOrderItemForMainSystemReturn: (...args: unknown[]) => H.removeItem(...args), })); vi.mock('../src/services/mainSystemStockout', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, recalcOrderHeaderTotals: (...args: unknown[]) => H.recalcHeader(...args) }; }); vi.mock('../src/services/mirrorOrderClosureService', () => ({ clearDayPointerIfPointsTo: (...args: unknown[]) => H.clearDayPointer(...args), })); vi.mock('../src/services/notificationService', () => ({ notifyRoleUsers: (...args: unknown[]) => H.notify(...args), })); vi.mock('../src/services/auditService', () => ({ writeAuditLog: (...args: unknown[]) => H.audit(...args), })); const { applyOrderCancelledByMainSystem, applyItemNoLongerOurs } = await import( '../src/services/mainSystemReverseEvents' ); const { needsAppendToOrder } = await import('../src/services/mainSystemOrderImport'); const { recordImportedPrepItems } = await import('../src/services/mainSystemPrepLedger'); type Call = [string, unknown[]?]; /** c) orphan 场景的可控 DB:按 SQL 形状返回,order_items 行集合保持可观测 */ function installOrphanDb(input: { ourOrderCode: string; status: number; rows: Array<{ id: string }>; leftovers: Array<{ order_code: string; n: number; sourced_n: number }>; }): void { H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => { const text = String(sql); if (/SELECT DISTINCT msi\.main_order_code/i.test(text)) { return { rows: [{ main_order_code: 'ORD_WEB_T2', our_order_code: input.ourOrderCode }], rowCount: 1 }; } if (/SELECT order_code, order_status FROM orders/i.test(text)) { return { rows: [{ order_code: input.ourOrderCode, order_status: input.status }], rowCount: 1 }; } if (/sourced_n/i.test(text)) { return { rows: input.leftovers, rowCount: input.leftovers.length }; } if (/FROM order_items oi/i.test(text)) { return { rows: [], rowCount: 0 }; // 被取消主系统单已无"有来源"行需要移除 } if (/UPDATE orders/i.test(text)) return { rows: [], rowCount: 1 }; void params; return { rows: [], rowCount: 0 }; }); } beforeEach(() => { H.poolQuery.mockReset(); H.tenantCtx.mockReset(); H.markPrep.mockReset(); H.removeItem.mockReset(); H.recalcHeader.mockReset(); H.clearDayPointer.mockReset(); H.notify.mockReset(); H.audit.mockReset(); H.tenantCtx.mockImplementation(async (fn: () => Promise) => fn()); H.markPrep.mockResolvedValue(undefined); H.removeItem.mockResolvedValue('deleted'); H.recalcHeader.mockResolvedValue(undefined); H.clearDayPointer.mockResolvedValue(0); H.notify.mockResolvedValue(undefined); H.audit.mockResolvedValue(undefined); }); /* ── c) orphan 策略 A ───────────────────────────────────────────────────── */ describe('T2c:orphan 策略 A', () => { it('全删只剩 2 orphan ⇒ 停用订单、2 行保留、operation_logs 1、orphan 通知 1、清占坑 1', async () => { const orphanRows = [{ id: 'orphan-1' }, { id: 'orphan-2' }]; installOrphanDb({ ourOrderCode: 'ORD_API_T2C1', status: 40, rows: orphanRows, leftovers: [{ order_code: 'ORD_API_T2C1', n: 2, sourced_n: 0 }], }); const outcome = await applyOrderCancelledByMainSystem({ branchCode: 'BR002', orderCode: 'ORD_WEB_T2', reason: '主系统删整单(只剩 orphan)', }); expect(outcome.status).toBe('cancelled'); expect(orphanRows, 'orphan 行必须原样保留(不物理删/不红冲)').toHaveLength(2); const calls = H.poolQuery.mock.calls as Call[]; const updateOrder = calls.find(([sql]) => /UPDATE orders/i.test(String(sql))); expect(updateOrder, '必须停用订单(写 deleted_at)').toBeTruthy(); expect(String(updateOrder![0])).toMatch(/deleted_at\s*=\s*COALESCE\(deleted_at,\s*NOW\(\)\)/); expect(updateOrder![1]?.[0]).toEqual(['ORD_API_T2C1']); expect(String(updateOrder![1]?.[1] || '')).toContain('主系统作废'); // 不得对 order_items 做物理删/更新(orphan 保留) expect(calls.some(([sql]) => /DELETE\s+FROM\s+order_items/i.test(String(sql)))).toBe(false); expect(calls.some(([sql]) => /UPDATE\s+order_items/i.test(String(sql)))).toBe(false); // operation_logs 1 条(orphan 留痕) const orphanAudit = H.audit.mock.calls .map(([arg]) => arg as Record) .filter((arg) => arg.operationType === 'main_system_order_deleted_orphans_kept'); expect(orphanAudit).toHaveLength(1); expect(orphanAudit[0]).toMatchObject({ targetTable: 'orders', targetId: 'ORD_API_T2C1', branchCode: 'BR002', newValue: expect.objectContaining({ orphan_row_count: 2, action: 'deleted_orphans_kept' }), }); // orphan 通知 1 次(另有一条"订单已停用"通知,故总次数为 2;orphan 专项计数必须为 1) const orphanNotify = H.notify.mock.calls.filter( ([arg]) => (arg as Record).notifyType === 'main_system_order_deleted_orphans_kept' ); expect(orphanNotify).toHaveLength(1); expect(orphanNotify[0][0]).toMatchObject({ roles: ['admin', 'operator'], notifyType: 'main_system_order_deleted_orphans_kept', content: expect.stringContaining('2 行无来源'), }); // 清当日占坑指针 1 次 expect(H.clearDayPointer).toHaveBeenCalledTimes(1); expect(H.clearDayPointer).toHaveBeenCalledWith('BR002', 'ORD_API_T2C1'); }); it('合并单只删 A(B 有来源)⇒ 不停用、不清占坑、不写 orphan 审计', async () => { installOrphanDb({ ourOrderCode: 'ORD_API_T2C2', status: 40, rows: [{ id: 'B-row-still-there' }], leftovers: [{ order_code: 'ORD_API_T2C2', n: 2, sourced_n: 1 }], }); const outcome = await applyOrderCancelledByMainSystem({ branchCode: 'BR002', orderCode: 'ORD_WEB_T2', reason: '合并单只删 A(B 有来源)', }); expect(outcome.status).toBe('already'); const calls = H.poolQuery.mock.calls as Call[]; expect(calls.some(([sql]) => /UPDATE orders/i.test(String(sql)))).toBe(false); expect(H.clearDayPointer).not.toHaveBeenCalled(); expect(H.removeItem).not.toHaveBeenCalled(); expect( H.audit.mock.calls.some( ([arg]) => (arg as Record).operationType === 'main_system_order_deleted_orphans_kept' ) ).toBe(false); // A 自己的台账仍要置 cancelled(防止 A 被重新导入) expect(calls.some(([sql]) => /UPDATE public\.main_system_order_import_items/i.test(String(sql)))).toBe(true); }); it('已完成 90 ⇒ 零改动(订单/明细/台账都不动,只留痕)', async () => { installOrphanDb({ ourOrderCode: 'ORD_API_T2C3', status: 90, rows: [{ id: 'done-row' }], leftovers: [], }); const outcome = await applyOrderCancelledByMainSystem({ branchCode: 'BR002', orderCode: 'ORD_WEB_T2', reason: '主系统删单(我方已完成)', }); expect(outcome.status).toBe('skipped_completed'); const calls = H.poolQuery.mock.calls as Call[]; expect(calls.some(([sql]) => /UPDATE orders/i.test(String(sql)))).toBe(false); expect(calls.some(([sql]) => /UPDATE public\.main_system_order_import_items/i.test(String(sql)))).toBe(false); expect(H.removeItem).not.toHaveBeenCalled(); expect(H.clearDayPointer).not.toHaveBeenCalled(); expect(H.notify).not.toHaveBeenCalled(); // 只留痕(no_change_completed) expect(H.audit).toHaveBeenCalledTimes(1); expect(H.audit.mock.calls[0][0]).toMatchObject({ operationType: 'main_system_order_deleted_follow', targetId: 'ORD_API_T2C3', newValue: expect.objectContaining({ action: 'no_change_completed' }), }); }); }); /* ── d) 改派往返 / removed 阻断 / 幂等 ─────────────────────────────────── */ function installPrepLink(prepId: string, ourOrderCode: string, itemId: string): void { H.poolQuery.mockImplementation(async (sql: string) => { const text = String(sql); if (/FROM public\.main_system_order_import_items/i.test(text)) { return { rows: [{ our_order_code: ourOrderCode, our_order_item_id: itemId }], rowCount: 1 }; } if (/INSERT INTO public\.main_system_reverse_tombstones/i.test(text)) { throw new Error('不应写墓碑:该 prep 有台账对照'); } void prepId; return { rows: [], rowCount: 0 }; }); } describe('T2d:改派往返 A→他人→A 与 removed 硬删', () => { it('A→B:台账置 reallocated(含通知),不落墓碑', async () => { installPrepLink('PREP-R', 'ORD_API_T2D', 'item-R'); const outcome = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'PREP-R', mainOrderCode: 'ORD_WEB_T2', itemName: '肉片', skuCode: 'SKU1', reason: 'reallocated', }); expect(outcome.status).toBe('removed'); expect(H.markPrep).toHaveBeenCalledTimes(1); expect(H.markPrep.mock.calls[0][0]).toMatchObject({ branchCode: 'BR002', prepId: 'PREP-R', disposition: 'reallocated', }); expect(H.removeItem).toHaveBeenCalledWith( expect.objectContaining({ orderCode: 'ORD_API_T2D', itemId: 'item-R' }) ); expect(H.notify).toHaveBeenCalledTimes(1); expect(H.notify.mock.calls[0][0]).toMatchObject({ notifyType: 'main_system_items_removed', title: expect.stringContaining('改派'), }); }); it('同一 prep 再回 A ⇒ needsAppend=true(可复活)且 upsert 会把 reallocated 复位 imported、不重复行', async () => { expect( needsAppendToOrder( { id: 'PREP-R', isStockout: false }, [{ prep_id: 'PREP-R', our_order_item_id: 'item-old', disposition: 'reallocated' }] ) ).toBe(true); H.poolQuery.mockResolvedValue({ rows: [], rowCount: 0 }); await recordImportedPrepItems({ branchCode: 'BR002', mainOrderCode: 'ORD_WEB_T2', supplierCode: 'INTERNAL', ourOrderCode: 'ORD_API_T2D', prepRows: [{ id: 'PREP-R', itemName: '肉片', prepareQty: 2 }], ourItems: [{ id: 'item-new', item_name: '肉片' }], mapping: new Map([['PREP-R', 'item-new']]), }); const insert = H.poolQuery.mock.calls.find(([sql]: [string]) => /INSERT INTO public\.main_system_order_import_items/i.test(String(sql)) ); expect(insert, '必须走台账 upsert').toBeTruthy(); const sql = String(insert![0]); // 同一 (branch_code, prep_id) 唯一键 ⇒ 不会出现第二行 expect(sql).toContain('ON CONFLICT (branch_code, prep_id) DO UPDATE'); // reallocated 例外:旧对照允许被本次映射覆盖 + 复位 imported const reallocatedResets = sql.split("= 'reallocated'").length - 1; expect(reallocatedResets).toBe(2); expect(sql).toMatch(/disposition = 'reallocated'[\s\S]{0,120}THEN EXCLUDED\.our_order_item_id/); expect(sql).toMatch(/disposition = 'reallocated'[\s\S]{0,160}THEN EXCLUDED\.disposition/); }); it('removed 后再出现 ⇒ 仍阻断(needsAppend=false,且 upsert 不重置 removed)', async () => { const row = { id: 'PREP-R', isStockout: false }; expect( needsAppendToOrder(row, [{ prep_id: 'PREP-R', our_order_item_id: null, disposition: 'removed' }]) ).toBe(false); expect( needsAppendToOrder(row, [{ prep_id: 'PREP-R', our_order_item_id: 'item-old', disposition: 'removed' }]) ).toBe(false); H.poolQuery.mockResolvedValue({ rows: [], rowCount: 0 }); await recordImportedPrepItems({ branchCode: 'BR002', mainOrderCode: 'ORD_WEB_T2', supplierCode: 'INTERNAL', ourOrderCode: 'ORD_API_T2D', prepRows: [{ id: 'PREP-R', itemName: '肉片', prepareQty: 2 }], ourItems: [{ id: 'item-new', item_name: '肉片' }], mapping: new Map([['PREP-R', 'item-new']]), }); const sql = String( H.poolQuery.mock.calls.find(([s]: [string]) => /INSERT INTO public\.main_system_order_import_items/i.test(String(s)) )![0] ); expect(sql).not.toContain("= 'removed'"); // removed 不参与任何复位 CASE }); it('重复投递同一改派事件幂等:两次都只更新同一台账行、不重复建行', async () => { installPrepLink('PREP-R', 'ORD_API_T2D', 'item-R'); H.removeItem.mockResolvedValueOnce('deleted').mockResolvedValueOnce('not_found'); const first = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'PREP-R', mainOrderCode: 'ORD_WEB_T2', reason: 'reallocated', }); const second = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: 'PREP-R', mainOrderCode: 'ORD_WEB_T2', reason: 'reallocated', }); expect(first.status).toBe('removed'); expect(second.status).toBe('already_gone'); // 两次都是对同一 (branch_code, prep_id) 的 UPDATE(markPrepDisposition),没有插入第二行台账 expect(H.markPrep).toHaveBeenCalledTimes(2); for (const [arg] of H.markPrep.mock.calls) { expect(arg).toMatchObject({ branchCode: 'BR002', prepId: 'PREP-R', disposition: 'reallocated' }); } expect( H.poolQuery.mock.calls.some(([sql]: [string]) => /INSERT INTO public\.main_system_order_import_items/i.test(String(sql)) ) ).toBe(false); }); });