import { beforeEach, describe, expect, it, vi } from 'vitest'; import { loadEnv } from '../src/env'; /** * T2 Addendum 2 · rev10 独立复测(2026-10-19,tester)。 * * 覆盖第三轮修复: * a) 墓碑 reason 按优先级合并(真实 SQL,事务内 ROLLBACK): * reallocated → item_removed 必须**升级硬删**,E1 仍 blocked 且墓碑不被 clear; * removed → reallocated 必须**保持 removed**(硬删不可降级),E1 仍 blocked。 * b) `repairMissingPrepLedgerRows`:reallocated 旧对照 + 旧退货行 + 新行 ⇒ 只认新行; * 候选为空 ⇒ 不 imported;第二次 item_removed 只删新行、旧退货行保留。 */ const H = vi.hoisted(() => ({ poolQuery: vi.fn(), tenantCtx: vi.fn(), markPrep: vi.fn(), removeItem: vi.fn(), recalc: vi.fn(), notify: vi.fn(), tombstones: [] as Array<{ branch: string; kind: 'prep' | 'order'; key: string; reason: string | null }>, cleared: [] as string[], })); function normalize(kind: string, key: unknown): string { const text = String(key ?? '').trim(); return kind === 'prep' ? text.toLowerCase() : text; } 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.recalc(...args) }; }); vi.mock('../src/services/notificationService', () => ({ notifyRoleUsers: (...args: unknown[]) => H.notify(...args), })); vi.mock('../src/services/mainSystemReverseEvents', async (importOriginal) => { const actual = await importOriginal(); const byKind = (branch: string, kind: string, keys: string[]) => { const want = new Set(keys.map((key) => normalize(kind, key))); return H.tombstones.filter((row) => row.branch === branch && row.kind === kind && want.has(row.key)); }; return { ...actual, listReverseTombstoneKeys: async (input: { branchCode: string; kind: string; keys: string[] }) => new Set(byKind(input.branchCode, input.kind, input.keys || []).map((row) => row.key)), listReallocatedReverseTombstones: async (input: { branchCode: string; keys: string[] }) => new Set( byKind(input.branchCode, 'prep', input.keys || []) .filter((row) => row.reason === 'reallocated') .map((row) => row.key) ), clearReverseTombstone: async (input: { branchCode: string; kind: string; businessKey: string }) => { const key = normalize(input.kind, input.businessKey); H.cleared.push(key); const before = H.tombstones.length; H.tombstones = H.tombstones.filter( (row) => !(row.branch === input.branchCode && row.kind === input.kind && row.key === key) ); return before - H.tombstones.length; }, }; }); import type { MainOrderGroup as Grp } from '../src/services/mainSystemOrderImport'; const { filterTombstonedGroups } = await import('../src/services/mainSystemOrderImport'); const { repairMissingPrepLedgerRows } = await import('../src/services/mainSystemReturnFollow'); const { applyItemNoLongerOurs, recordReverseTombstone } = await import( '../src/services/mainSystemReverseEvents' ); function group(orderCode: string, prepIds: string[]): Grp { return { orderCode, deliveryDate: '2026-10-23', taskDay: '2026-10-23', rows: prepIds.map((id) => ({ id, itemName: '肉片', prepareQty: 2, isStockout: false })) as unknown as Grp['rows'], }; } beforeEach(() => { H.poolQuery.mockReset(); H.tenantCtx.mockReset(); H.markPrep.mockReset(); H.removeItem.mockReset(); H.recalc.mockReset(); H.notify.mockReset(); H.tombstones = []; H.cleared = []; H.tenantCtx.mockImplementation(async (fn: () => Promise) => fn()); H.markPrep.mockResolvedValue(undefined); H.removeItem.mockResolvedValue('deleted'); H.recalc.mockResolvedValue(undefined); H.notify.mockResolvedValue(undefined); }); type PgClient = { connect: () => Promise; end: () => Promise; query: (sql: string, params?: unknown[]) => Promise<{ rows: Array>; rowCount?: number }>; }; async function loadPgClient(): Promise { loadEnv(); if (!process.env.DATABASE_URL) return null; const pg = (await import('pg')).default as unknown as { Client: new (cfg: { connectionString: string }) => PgClient; }; const client = new pg.Client({ connectionString: process.env.DATABASE_URL }); try { await client.connect(); } catch { return null; } return client; } /* ── a) 墓碑 reason 优先级(真实 SQL) ─────────────────────────────────── */ describe('T2 rev10-a:墓碑 reason 合并(真实 SQL,事务内 ROLLBACK)', () => { it('reallocated→item_removed 升级硬删;removed→reallocated 保持 removed;E1 仍 blocked 不 clear', async (ctx) => { // 捕获 recordReverseTombstone 的真实 SQL(db 为 fake,只取 SQL 文本) H.poolQuery.mockResolvedValue({ rows: [], rowCount: 1 }); await recordReverseTombstone({ branchCode: 'T2TEST', kind: 'prep', businessKey: 'k0', reason: 'reallocated' }); const insertSql = String(H.poolQuery.mock.calls[0][0]); expect(insertSql).toContain('ON CONFLICT (branch_code, kind, business_key) DO UPDATE'); // A1 终局复攻后 reason 先 trim:SQL 为 LOWER(TRIM(COALESCE(...))) expect(insertSql).toMatch(/LOWER\(TRIM\(COALESCE\(EXCLUDED\.reason/); expect(insertSql).toMatch(/LOWER\(TRIM\(COALESCE\(public\.main_system_reverse_tombstones\.reason/); const client = await loadPgClient(); if (!client) { ctx.skip(); return; } const branch = `T2TEST-${Date.now()}`; try { await client.query('BEGIN'); // 1) reallocated → item_removed:必须升级 await client.query(insertSql, [branch, 'prep', 'k1', 'reallocated', '{}']); await client.query(insertSql, [branch, 'prep', 'k1', 'item_removed', '{}']); const upgraded = await client.query( `SELECT reason FROM public.main_system_reverse_tombstones WHERE branch_code = $1 AND kind = 'prep' AND business_key = 'k1'`, [branch] ); expect(upgraded.rows[0]?.reason).toBe('item_removed'); expect(upgraded.rows).toHaveLength(1); // 2) removed → reallocated:硬删不可降级 await client.query(insertSql, [branch, 'prep', 'k2', 'removed', '{}']); await client.query(insertSql, [branch, 'prep', 'k2', 'reallocated', '{}']); const kept = await client.query( `SELECT reason FROM public.main_system_reverse_tombstones WHERE branch_code = $1 AND kind = 'prep' AND business_key = 'k2'`, [branch] ); expect(kept.rows[0]?.reason).toBe('removed'); await client.query('ROLLBACK'); // 回滚后无残留 const left = await client.query( `SELECT count(*)::int AS n FROM public.main_system_reverse_tombstones WHERE branch_code = $1`, [branch] ); expect(Number(left.rows[0]?.n)).toBe(0); } finally { await client.end(); } // E1 侧:item_removed 墓碑 ⇒ 仍 skipped,且**不会**被 clear H.tombstones = [{ branch: 'BR002', kind: 'prep', key: 'k1', reason: 'item_removed' }]; const blocked = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['k1'])]); expect(blocked.groups).toHaveLength(0); expect(blocked.skipped[0]).toMatchObject({ status: 'skipped_tombstoned' }); expect(H.cleared).toEqual([]); expect(H.tombstones).toHaveLength(1); // removed → reallocated 之后的墓碑(真实 SQL 结果仍是 removed)⇒ 仍 blocked、不 clear H.tombstones = [{ branch: 'BR002', kind: 'prep', key: 'k2', reason: 'removed' }]; H.cleared = []; const stillBlocked = await filterTombstonedGroups('BR002', [group('ORD_WEB_OK', ['k2'])]); expect(stillBlocked.groups).toHaveLength(0); expect(stillBlocked.skipped[0]).toMatchObject({ status: 'skipped_tombstoned' }); expect(H.cleared).toEqual([]); }); }); /* ── b) repairMissingPrepLedgerRows ───────────────────────────────────── */ const OLD_RETURNED_ID = '11111111-1111-4111-8111-111111111111'; const NEW_ITEM_ID = '22222222-2222-4222-8222-222222222222'; const PREP_ID = '33333333-3333-4333-8333-333333333333'; type RepairCaptured = { itemSql: string; upsertParams: unknown[] | null }; function installRepairDb(candidateRows: Array<{ id: string; item_name: string }>): RepairCaptured { const captured: RepairCaptured = { itemSql: '', upsertParams: null }; H.poolQuery.mockImplementation(async (sql: string, params: unknown[] = []) => { const text = String(sql); if (/FROM public\.main_system_order_imports i/i.test(text)) { return { rows: [ { main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_1', main_supplier_code: 'SUP1', payload: [{ id: PREP_ID, itemName: '肉片', prepareQty: 2, isStockout: false }], }, ], rowCount: 1, }; } if (/FROM order_items/i.test(text)) { captured.itemSql = text; return { rows: candidateRows, rowCount: candidateRows.length }; } if (/INSERT INTO public\.main_system_order_import_items/i.test(text)) { captured.upsertParams = params; return { rows: [], rowCount: 1 }; } return { rows: [], rowCount: 0 }; }); return captured; } describe('T2 rev10-b:repairMissingPrepLedgerRows 只认未退货新行', () => { it('候选 SQL(真实 PG 排序)过滤旧退货行;repair 对照 = 新行且 imported', async () => { // 1) 捕获候选 SQL const first = installRepairDb([]); await repairMissingPrepLedgerRows('BR002'); expect(first.itemSql).toMatch(/COALESCE\(is_returned, false\) = false/); expect(first.itemSql).toMatch(/COALESCE\(is_extra_dish, false\) = false/); // B1 终局复攻:候选还要排除已被同分公司其它备货行占用的订单行 expect(first.itemSql).toContain('NOT EXISTS ('); expect(first.itemSql).toContain('public.main_system_order_import_items claimed'); // 2) 真实 PG:旧退货行 sort_order 更靠前也不被选中 const client = await loadPgClient(); let candidates: Array<{ id: string; item_name: string }> = []; if (!client) { // 无库时退化为纯 SQL 契约断言,不静默通过 expect(first.itemSql).toContain('ORDER BY sort_order NULLS LAST, created_at, id'); } else { try { await client.query('SET default_transaction_read_only = on'); const fixture = `(VALUES ('${OLD_RETURNED_ID}'::uuid, 'ORD_API_1'::text, '肉片'::text, 0, '2026-01-01 00:00:00+08'::timestamptz, true, false), ('${NEW_ITEM_ID}'::uuid, 'ORD_API_1'::text, '肉片'::text, 1, '2026-10-19 00:00:00+08'::timestamptz, false, false) ) AS order_items(id, order_code, item_name, sort_order, created_at, is_returned, is_extra_dish)`; const sql = first.itemSql.replace('FROM order_items', `FROM ${fixture}`); // B1 后候选 SQL 参数为 [order_code, branch_code, exclude_prep_ids] const rows = (await client.query(sql, ['ORD_API_1', 'BR002', [PREP_ID]])).rows; candidates = rows.map((row) => ({ id: String(row.id), item_name: String(row.item_name || '') })); expect(candidates.map((row) => row.id)).toEqual([NEW_ITEM_ID]); } finally { await client.end(); } } // 3) 第二次 repair:候选 = 真实查询结果(新行)⇒ 对照指向新行、disposition=imported const second = installRepairDb(candidates); await repairMissingPrepLedgerRows('BR002'); expect(second.upsertParams).toBeTruthy(); expect(second.upsertParams![4]).toBe(NEW_ITEM_ID); expect(second.upsertParams![11]).toBe('imported'); }); it('候选为空(只有退货行)⇒ 不 imported:link=NULL、disposition 非 imported', async () => { const captured = installRepairDb([]); await repairMissingPrepLedgerRows('BR002'); expect(captured.upsertParams).toBeTruthy(); expect(captured.upsertParams![4]).toBeNull(); expect(captured.upsertParams![11]).not.toBe('imported'); }); it('repair 后第二次 item_removed:只删新行,旧退货行保留', async () => { const dbRows = [{ id: OLD_RETURNED_ID }, { id: NEW_ITEM_ID }]; 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: 'ORD_API_1', our_order_item_id: NEW_ITEM_ID }], rowCount: 1, }; } if (/FROM public\.main_system_order_imports i/i.test(text)) { return { rows: [], rowCount: 0 }; } void text; return { rows: [], rowCount: 0 }; }); H.removeItem.mockImplementation(async (args: { itemId: string }) => { const idx = dbRows.findIndex((row) => row.id === args.itemId); if (idx >= 0) dbRows.splice(idx, 1); return 'deleted'; }); const outcome = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: PREP_ID, mainOrderCode: 'ORD_WEB_A', reason: 'item_removed', }); expect(outcome.status).toBe('removed'); expect(H.removeItem).toHaveBeenCalledTimes(1); expect(H.removeItem.mock.calls[0][0]).toMatchObject({ itemId: NEW_ITEM_ID }); expect(dbRows.map((row) => row.id)).toEqual([OLD_RETURNED_ID]); expect(H.markPrep.mock.calls[0][0]).toMatchObject({ prepId: PREP_ID, disposition: 'removed' }); }); });