import { beforeEach, describe, expect, it, vi } from 'vitest'; import { loadEnv } from '../src/env'; /** * T2 rev16 合并最终复测 · tester 独立边界(2026-10-19)。 * * a) R-A:台账 P3A `imported` 但指向**已退货行 OLD**;同单有活行 NEW/NEXT,payload 缺行 P3B。 * repair 必须**先清坏指针**再一对一映射 ⇒ P3A→NEW、P3B→NEXT;后续 item_removed 只删活行。 * b) 重复 item_removed 指向**已删行** ⇒ 返回 already_gone(no-op),路由按 200 + results 返回,不 500。 * c) 真实 PG 事务内跑 repair 的两条真实 SQL(清坏指针 UPDATE / 候选 SELECT),验证后 ROLLBACK(无残留)。 */ const H = vi.hoisted(() => ({ poolQuery: vi.fn(), tenantCtx: vi.fn(), markPrep: vi.fn(), removeItem: vi.fn(), recalc: vi.fn(), notify: 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.recalc(...args) }; }); vi.mock('../src/services/notificationService', () => ({ notifyRoleUsers: (...args: unknown[]) => H.notify(...args), })); const { repairMissingPrepLedgerRows } = await import('../src/services/mainSystemReturnFollow'); const { applyItemNoLongerOurs } = await import('../src/services/mainSystemReverseEvents'); const PREP_A = '33333333-3333-4333-8333-3333333333a1'; const PREP_B = '33333333-3333-4333-8333-3333333333b2'; const OLD_RETURNED = '11111111-1111-4111-8111-111111111111'; const NEW_ACTIVE = '22222222-2222-4222-8222-222222222222'; const NEXT_ACTIVE = '44444444-4444-4444-8444-444444444444'; const ORDER = 'ORD_API_R16'; type LedgerEntry = { disposition: string; link: string | null }; const state = { ledger: new Map(), /** 同单订单行:[{id, returned}] */ items: [] as Array<{ id: string; returned: boolean }>, clearSql: '', candidateSql: '', fixedSql: '', upserts: [] as Array<{ prepId: string; link: string | null; disposition: string }>, }; /** 按 repairMissingPrepLedgerRows 的真实查询形状返回(含 R-A 清坏指针 UPDATE) */ function installRepairDb(): void { 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_R16', our_order_code: ORDER, main_supplier_code: 'SUP1', payload: [ { id: PREP_A, itemName: '肉片', prepareQty: 2, isStockout: false }, { id: PREP_B, itemName: '肉片', prepareQty: 2, isStockout: false }, ], }, ], rowCount: 1, }; } if (/SET our_order_item_id = NULL/i.test(text)) { state.clearSql = text; const [, , ourOrderCode] = params as [string, string, string]; let changed = 0; for (const [prepId, entry] of state.ledger) { const item = state.items.find((row) => row.id === entry.link); if ( entry.link && ourOrderCode === ORDER && [PREP_A, PREP_B].includes(prepId) && (!item || item.returned) ) { state.ledger.set(prepId, { ...entry, link: null }); changed += 1; } } return { rows: [], rowCount: changed }; } if (/JOIN order_items oi ON oi\.id = li\.our_order_item_id/i.test(text)) { state.fixedSql = text; const rows = [...state.ledger.entries()] .filter(([prepId, entry]) => entry.link && [PREP_A, PREP_B].includes(prepId)) .map(([prepId, entry]) => ({ prep_id: prepId, our_order_item_id: entry.link })); return { rows, rowCount: rows.length }; } // findLocalItemByPrep(item_removed 定位我方行) if (/FROM public\.main_system_order_import_items/i.test(text) && /prep_id = \$2::uuid/i.test(text)) { const entry = state.ledger.get(String(params[1])); return entry?.link ? { rows: [{ our_order_code: ORDER, our_order_item_id: entry.link }], rowCount: 1 } : { rows: [], rowCount: 0 }; } if (/FROM order_items/i.test(text)) { state.candidateSql = text; // 候选:只有活行(OLD 已退货被过滤) const rows = state.items.filter((row) => !row.returned).map((row) => ({ id: row.id, item_name: '肉片' })); return { rows, rowCount: rows.length }; } if (/INSERT INTO public\.main_system_order_import_items/i.test(text)) { const prepId = String(params[2]); const link = (params[4] as string | null) ?? null; const disposition = String(params[11]); state.upserts.push({ prepId, link, disposition }); const existing = state.ledger.get(prepId); if (!existing) state.ledger.set(prepId, { disposition, link }); else state.ledger.set(prepId, { disposition: existing.disposition, link: existing.link ?? link }); return { rows: [], rowCount: 1 }; } return { rows: [], rowCount: 0 }; }); } beforeEach(() => { H.poolQuery.mockReset(); H.tenantCtx.mockReset(); H.markPrep.mockReset(); H.removeItem.mockReset(); H.recalc.mockReset(); H.notify.mockReset(); H.tenantCtx.mockImplementation(async (fn: () => Promise) => fn()); H.markPrep.mockResolvedValue(undefined); H.removeItem.mockResolvedValue('deleted'); H.recalc.mockResolvedValue(undefined); H.notify.mockResolvedValue(undefined); state.ledger = new Map([[PREP_A, { disposition: 'imported', link: OLD_RETURNED }]]); state.items = [ { id: OLD_RETURNED, returned: true }, { id: NEW_ACTIVE, returned: false }, { id: NEXT_ACTIVE, returned: false }, ]; state.clearSql = ''; state.candidateSql = ''; state.fixedSql = ''; state.upserts = []; installRepairDb(); }); describe('T2 R-A:坏对照(已退货行)清 NULL 后一对一映射', () => { it('P3A imported→OLD(退货) + 活行 NEW/NEXT + 缺行 P3B ⇒ P3A→NEW、P3B→NEXT;item_removed 只删活行', async () => { const written = await repairMissingPrepLedgerRows('BR002'); expect(written).toBeGreaterThan(0); // 先清坏指针(真实 UPDATE 带退货/加菜 EXISTS 排除) expect(state.clearSql).toMatch(/SET our_order_item_id = NULL/i); expect(state.clearSql).toMatch(/COALESCE\(oi\.is_returned, false\) = false/i); expect(state.clearSql).toMatch(/COALESCE\(oi\.is_extra_dish, false\) = false/i); // 一对一映射:活行 NEW 给 P3A、NEXT 给 P3B(NEW 不被浪费) expect(state.ledger.get(PREP_A)).toEqual({ disposition: 'imported', link: NEW_ACTIVE }); expect(state.ledger.get(PREP_B)).toEqual({ disposition: 'imported', link: NEXT_ACTIVE }); const upsertA = state.upserts.find((row) => row.prepId === PREP_A); const upsertB = state.upserts.find((row) => row.prepId === PREP_B); expect(upsertA).toMatchObject({ link: NEW_ACTIVE, disposition: 'imported' }); expect(upsertB).toMatchObject({ link: NEXT_ACTIVE, disposition: 'imported' }); // 后续 item_removed:台账现在指向活行 NEW ⇒ 只删 NEW;OLD(退货)/NEXT(P3B) 不动 H.removeItem.mockImplementation(async (args: { itemId: string }) => { const idx = state.items.findIndex((row) => row.id === args.itemId); if (idx >= 0) state.items.splice(idx, 1); return 'deleted'; }); const outcome = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: PREP_A, mainOrderCode: 'ORD_WEB_R16', reason: 'item_removed', }); expect(outcome.status).toBe('removed'); expect(H.removeItem).toHaveBeenCalledTimes(1); expect(H.removeItem.mock.calls[0][0]).toMatchObject({ itemId: NEW_ACTIVE }); expect(state.items.map((row) => row.id)).toEqual([OLD_RETURNED, NEXT_ACTIVE]); expect(H.markPrep.mock.calls[0][0]).toMatchObject({ prepId: PREP_A, disposition: 'removed' }); }); it('重复 item_removed 指向已删行 ⇒ already_gone(no-op),不抛错;路由按 200+results 返回', async () => { H.removeItem.mockResolvedValue('not_found'); 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: ORDER, our_order_item_id: NEW_ACTIVE }], rowCount: 1 }; } void text; return { rows: [], rowCount: 0 }; }); const first = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: PREP_A, mainOrderCode: 'ORD_WEB_R16', reason: 'item_removed', }); const second = await applyItemNoLongerOurs({ branchCode: 'BR002', prepId: PREP_A, mainOrderCode: 'ORD_WEB_R16', reason: 'item_removed', }); expect(first.status).toBe('already_gone'); expect(second.status).toBe('already_gone'); expect(H.removeItem).toHaveBeenCalledTimes(2); // 路由契约:反向事件一律 res.json({ ok:true, results }),业务结果 already_gone 不会走到 500 const routeSource = (await import('node:fs')).readFileSync( new URL('../src/routes/mainSystemIntegration.ts', import.meta.url), 'utf8' ); const reverseBlock = routeSource.slice( routeSource.indexOf('if (isReverseOrderEvent(event))'), routeSource.indexOf('if (isFulfillmentEvent(event))') ); expect(reverseBlock).toContain('res.json({ ok: true, results })'); expect(reverseBlock).not.toMatch(/status\(500\)/); }); }); /* ── 真实 PG 事务验证(ROLLBACK) ─────────────────────────────────────── */ type PgClient = { connect: () => Promise; end: () => Promise; query: (sql: string, params?: unknown[]) => Promise<{ rows: Array>; rowCount?: number }>; }; describe('T2 R-A:真实 PG 事务内验证 repair SQL(ROLLBACK)', () => { it('清坏指针 UPDATE + 候选 SELECT 在真实库可执行且结果正确,回滚无残留', async (ctx) => { // 先跑一次 repair 以捕获真实 SQL(fake db) await repairMissingPrepLedgerRows('BR002'); const clearSql = state.clearSql; const fixedSql = state.fixedSql; const candidateSql = state.candidateSql; expect(clearSql).toContain('UPDATE public.main_system_order_import_items li'); expect(fixedSql).toContain('JOIN order_items oi ON oi.id = li.our_order_item_id'); expect(candidateSql).toContain('FROM order_items'); loadEnv(); if (!process.env.DATABASE_URL) { ctx.skip(); return; } 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 { ctx.skip(); return; } const orderCode = `T2R16_${Date.now()}`; const ledgerId = '99999999-9999-4999-8999-999999999999'; try { await client.query('BEGIN'); await client.query(`SELECT set_config('app.branch_code','BR002',true)`); await client.query(`SELECT set_config('search_path','tenant_br002, public',true)`); // 订单骨架(满足 order_items FK) await client.query( `INSERT INTO orders (order_code, cycle_code, bid_code, branch_code) VALUES ($1,'202610',$1,'BR002')`, [orderCode] ); // 三行:OLD 已退货、NEW/NEXT 活行 await client.query( `INSERT INTO order_items (id, order_code, item_name, quantity, price, amount, sort_order, is_returned, branch_code) VALUES ($1::uuid,$2,'肉片',2,0,0,0,true,'BR002'), ($3::uuid,$2,'肉片',2,0,0,1,false,'BR002'), ($4::uuid,$2,'肉片',2,0,0,2,false,'BR002')`, [OLD_RETURNED, orderCode, NEW_ACTIVE, NEXT_ACTIVE] ); // 台账:P3A imported → OLD(退货) await client.query( `INSERT INTO public.main_system_order_import_items (id, branch_code, main_order_code, prep_id, our_order_code, our_order_item_id, disposition, writeback_status, payload, created_at, updated_at, qty_decision) VALUES ($1::uuid,'BR002',$2,$3::uuid,$2,$4::uuid,'imported','pending','{}'::jsonb,NOW(),NOW(),'none')`, [ledgerId, orderCode, PREP_A, OLD_RETURNED] ); // 执行真实「清坏指针」UPDATE → OLD 已退货 ⇒ 指针置 NULL const cleared = await client.query(clearSql, ['BR002', [PREP_A, PREP_B], orderCode]); expect(cleared.rowCount).toBe(1); const linkAfter = await client.query( `SELECT our_order_item_id::text AS link FROM public.main_system_order_import_items WHERE id = $1::uuid`, [ledgerId] ); expect(linkAfter.rows[0]?.link).toBeNull(); // 第二档:fixed mapping SELECT(已清坏指针 ⇒ 不该再有固定对照) const fixed = await client.query(fixedSql, ['BR002', orderCode, [PREP_A, PREP_B]]); expect(fixed.rows).toEqual([]); // 第三档:候选 SELECT(已排除退货行 + 已占用行)⇒ 只剩 NEW/NEXT const candidates = await client.query(candidateSql, [orderCode, 'BR002', []]); expect(candidates.rows.map((row) => String(row.id)).sort()).toEqual([NEW_ACTIVE, NEXT_ACTIVE].sort()); await client.query('ROLLBACK'); // ROLLBACK 会撤销事务内 LOCAL set_config ⇒ 重新设置会话上下文再查残留 await client.query(`SELECT set_config('search_path','tenant_br002, public',false)`); await client.query(`SELECT set_config('app.branch_code','BR002',false)`); const left = await client.query(`SELECT count(*)::int AS n FROM orders WHERE order_code = $1`, [orderCode]); expect(Number(left.rows[0]?.n)).toBe(0); } finally { await client.end(); } }, 30000); });