import { describe, expect, it, vi } from 'vitest'; import { readFileSync } from 'node:fs'; import path from 'node:path'; import { resolveProcessingPickReservationSplit } from '../src/services/processingPickReservationService'; import { fifoDeductInventory } from '../src/services/inventoryOutboundService'; /** 缺口通知会走 DB;本文件只验扣库校验,桩掉避免连库 */ vi.mock('../src/services/inventoryShortageNotificationService', () => ({ notifyInventoryShortage: vi.fn(async () => undefined), })); /** * **加工需求单领料:他单预留必须一次排除本单全部订单号**(2026-10-15 对抗式复核)。 * * 事故形态(`29fbf49` 引入):`pickDemandSheetMaterial` / 改领料补扣 用 * 「对每个本单订单号各调一次 `sumOtherOrderReservations` 再相加」估算他单预留。 * 但 `sumOtherOrderReservations(…, orderCode)` 每次只排除**一个** order_code: * · 同一需求单含 A、B 两张订单(汇单键:分公司+配送日+成品 SKU+加工方式,常态); * · 他单预留 O、A 预留 3、B 预留 2; * · 旧写法 otherReserved = sumOther(A) + sumOther(B) = (O+2) + (O+3) = 2O+5; * · 正确 otherReserved = O ⇒ 他单预留被算 2 倍。O=0 时(本单自己预留 5、无他单) * 退化成 otherReserved=5 ⇒ claimable = 毛可用 − 5,把「本单预留挡自己」的死锁又带回来。 * * 修复:`他单 = 全部在用预留 − 本单自己的在用预留`(一次成型), * 并复用 `ownReserved` 当领料前 `planned`,不多查一次。 */ const SRC = path.join(__dirname, '..', 'src'); const read = (rel: string) => readFileSync(path.join(SRC, rel), 'utf8'); type Call = { sql: string; params?: unknown[] }; /** T=全部在用预留,own=本单自己的在用预留;其余按查询形状分流 */ function makeDb(total: number, own: number, calls: Call[]) { return { query: async (sql: string, params?: unknown[]) => { const text = String(sql); calls.push({ sql: text, params }); if (text.includes('order_code = ANY($2::text[])')) { return { rowCount: 1, rows: [{ total: own }] }; } if (text.includes('FROM inventory_reservations')) { return { rowCount: 1, rows: [{ total }] }; } return { rowCount: 0, rows: [] }; }, }; } describe('① 预留切分:一次排除本单全部订单号', () => { it('A/B 两张本单订单、无他单预留 ⇒ 他单预留为 0(旧写法会算成 5 挡住自己)', async () => { const calls: Call[] = []; const split = await resolveProcessingPickReservationSplit(makeDb(5, 5, calls) as never, { orderCodes: ['ORD_A', 'ORD_B'], skuCode: 'SKU1', branchCode: 'BR002', }); expect(split.ownReserved).toBe(5); expect(split.totalReserved).toBe(5); expect(split.otherReserved, '本单自己的预留不是他单预留').toBe(0); }); it('有他单预留 4 ⇒ 他单预留恰为他单那部分(不是 n 倍)', async () => { const calls: Call[] = []; const split = await resolveProcessingPickReservationSplit(makeDb(9, 5, calls) as never, { orderCodes: ['ORD_A', 'ORD_B'], skuCode: 'SKU1', branchCode: 'BR002', }); expect(split.otherReserved).toBe(4); }); it('自采/独立加工(无本单订单号)⇒ 他单 = 全部在用预留', async () => { const calls: Call[] = []; const split = await resolveProcessingPickReservationSplit(makeDb(7, 0, calls) as never, { orderCodes: [], skuCode: 'SKU1', branchCode: 'BR002', }); expect(split.otherReserved).toBe(7); // 无本单订单号 ⇒ 不查 own(省一次查询;own 查询的特征是 `order_code = ANY($2::text[])`) expect(calls.some((c) => c.sql.includes('order_code = ANY($2::text[])'))).toBe(false); }); it('只读:不产生任何写语句', async () => { const calls: Call[] = []; await resolveProcessingPickReservationSplit(makeDb(5, 5, calls) as never, { orderCodes: ['ORD_A', 'ORD_B'], skuCode: 'SKU1', branchCode: 'BR002', }); expect(calls.some((c) => /INSERT|UPDATE|DELETE/i.test(c.sql))).toBe(false); }); }); describe('② 两个领料入口都改走统一切分(不再逐单号循环)', () => { for (const rel of [ 'services/processingDemandSheetService.ts', 'services/processingDemandPickAmendService.ts', ]) { it(`${rel}:无逐单号循环,改用 resolveProcessingPickReservationSplit`, () => { const src = read(rel); expect(src).toContain('resolveProcessingPickReservationSplit('); // 旧写法特征:`for (const code of ownOrderCodes` + `otherReserved +=` expect(src).not.toMatch(/for\s*\(\s*const\s+code\s+of\s+ownOrderCodes/); expect(src).not.toMatch(/otherReserved\s*\+=/); }); } }); /** * 光修预校验还不够:真正扣库的 `fifoDeductInventory` 内部还会再算一次「毛可用 − 他单预留」。 * 若只豁免 `ownOrderCodes[0]`,同一需求单里**其它本单订单**的预留会被当成"他单"挡住自己: * G=5、A 预留 3、B 预留 2、无他单、要领 5 ⇒ 内部只免 A ⇒ 可领 3 < 5 ⇒ 抛"库存不足"。 * 修复:`reservationExemptOrderCodes` 一次豁免全部本单订单号。 */ describe('③ FIFO 内部预留守卫一次豁免全部本单订单', () => { type Call = { sql: string; params?: unknown[] }; function makeFifoClient(gross: number, reservations: Array<{ order: string; qty: number }>, calls: Call[]) { return { query: async (sql: string, params?: unknown[]) => { const text = String(sql); calls.push({ sql: text, params }); if (text.includes('SUM(available_qty)')) { return { rowCount: 1, rows: [{ total: gross }] }; } if (text.includes('FROM inventory_reservations')) { const exclude = Array.isArray(params?.[2]) ? (params![2] as string[]) : []; const other = reservations .filter((r) => !exclude.includes(r.order)) .reduce((sum, r) => sum + r.qty, 0); return { rowCount: 1, rows: [{ total: other }] }; } if (text.includes('FOR UPDATE')) { return { rowCount: 1, rows: [ { id: 'inv1', batch_no: 'B1', available_qty: gross, cost_price: 3, supplier_code: null, created_at: new Date(), }, ], }; } if (text.startsWith('UPDATE inventory')) return { rowCount: 1, rows: [] }; if (text.includes('INSERT INTO inventory_logs')) return { rowCount: 1, rows: [] }; return { rowCount: 0, rows: [] }; }, }; } it('G=5、本单 A=3/B=2、无他单 ⇒ 领 5 必须放行(旧写法只免 A 会误报不足)', async () => { const calls: Call[] = []; const deducted: number[] = []; await expect( fifoDeductInventory( makeFifoClient(5, [{ order: 'ORD_A', qty: 3 }, { order: 'ORD_B', qty: 2 }], calls) as never, { skuCode: 'SKU1', qty: 5, branchCode: 'BR002', orderCode: 'ORD_A', reservationExemptOrderCodes: ['ORD_A', 'ORD_B'], pickCode: 'T1', operationType: 'processing_out', }, (_b, q) => deducted.push(q) ) ).resolves.toBeUndefined(); expect(deducted).toEqual([5]); }); });