import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; /** * 独立入库(自采界面「新增自采」)**不与订单关联** —— 契约与事务安全(2026-10-15) * * 事故(真跑,评审员 C):`createSelfPurchaseStockInbound` 返回 `{pending:true, batch_no:…}`(HTTP 200 成功), * 但 `self_purchase_stock_inbounds` 与 `inspections` **各 0 行** —— 货与单据静默消失。 * * 根因三层叠加(缺一层都不会丢数): * ① 引用**不存在的列**:`SELECT order_item_id FROM inspections`(`inspections` 无此列,实测 30 列); * ② 事务内 `catch` **只记日志**、不抛、不回滚到 SAVEPOINT; * ③ PG 语义:事务一旦报错即 aborted,末尾 `COMMIT` **等价 ROLLBACK**;而返回值已由 `RETURNING` 取到 * ⇒ 照常返回成功。 * * 开发者裁决(2026-10-15):「独立入库本来就不与订单关联」,故**整块删除**订单实收回写, * 而不是去补一个"合法关联"。见 docs/design/20261015-独立入库不与订单关联(删掉订单实收回写与吞异常).md * * 本测试对每条断言都给出**注入旧码必须 FAIL** 的反向验证(本项目既定纪律)。 */ const src = readFileSync( new URL('../src/services/selfPurchaseStockInboundService.ts', import.meta.url), 'utf8' ); /** 按「下一个 export 声明」切出函数体(不依赖固定字符窗口,函数一长就失准) */ function functionBody(source: string, name: string): string { const start = source.indexOf(`export async function ${name}`); expect(start, `${name} 应存在`).toBeGreaterThanOrEqual(0); const rest = source.slice(start + 1); const candidates = [ rest.indexOf('export async function'), rest.indexOf('export function'), ].filter((n) => n >= 0); const next = candidates.length ? Math.min(...candidates) : -1; return next >= 0 ? source.slice(start, start + 1 + next) : source.slice(start); } /** 去注释(保留字符串内容),使断言只针对**代码**、不被注释里的同名字样误伤 */ function stripComments(text: string): string { let out = ''; let i = 0; let quote: string | null = null; while (i < text.length) { const ch = text[i]; const next = text[i + 1]; if (quote) { out += ch; if (ch === '\\') { out += next ?? ''; i += 2; continue; } if (ch === quote) quote = null; i += 1; continue; } if (ch === "'" || ch === '"' || ch === '`') { quote = ch; out += ch; i += 1; continue; } if (ch === '/' && next === '/') { while (i < text.length && text[i] !== '\n') i += 1; continue; } if (ch === '/' && next === '*') { i += 2; while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i += 1; i += 2; continue; } out += ch; i += 1; } return out; } /** 「只记日志、不抛、不回滚到 SAVEPOINT」的 catch 块正文 —— 就是本次丢数的机制 */ function swallowedCatchBodies(code: string): string[] { const found: string[] = []; const re = /\bcatch\s*(?:\([^)]*\))?\s*\{/g; let m: RegExpExecArray | null; while ((m = re.exec(code))) { const start = m.index + m[0].length; let depth = 1; let i = start; while (i < code.length && depth > 0) { if (code[i] === '{') depth += 1; else if (code[i] === '}') depth -= 1; i += 1; } const body = code.slice(start, i - 1); if (/\bthrow\b/.test(body)) continue; if (/ROLLBACK\s+TO\s+SAVEPOINT/i.test(body)) continue; found.push(body); } return found; } /** * 取函数内 BEGIN 与**最后一次** COMMIT 之间的代码(事务体)。 * ⚠️ 必须取最后一次:函数开头还有一处「幂等重放命中即提前 COMMIT + return」, * 那不是主事务的终点,用它会把事务体截成 6 行、断言变成空转。 */ function transactionSegment(body: string): string { const begin = body.indexOf("query('BEGIN')"); const commit = body.lastIndexOf("query('COMMIT')"); expect(begin, '应有 BEGIN').toBeGreaterThanOrEqual(0); expect(commit, '应有 COMMIT').toBeGreaterThan(begin); return body.slice(begin, commit); } /** 主事务终点的 COMMIT 行(把旧码注回它之前,才是缺陷原来的位置) */ function commitLineIndex(body: string): number { const idx = body.lastIndexOf(COMMIT_LINE); expect(idx, '应能找到主事务 COMMIT').toBeGreaterThanOrEqual(0); return idx; } const body = functionBody(src, 'createSelfPurchaseStockInbound'); const code = stripComments(body); const tx = transactionSegment(code); /** 旧码(缺陷本体)——用于反向验证:注回去必须让本文件的断言失败 */ const OLD_BLOCK = " if (inspectionId) {\n" + ' try {\n' + ' const linked = await client.query(`SELECT order_item_id FROM inspections WHERE id = $1::uuid LIMIT 1`, [inspectionId]);\n' + ' await client.query(`UPDATE inspections SET actual_qty = $2 WHERE id = $1::uuid`, [inspectionId, qty]);\n' + ' } catch (error: unknown) {\n' + " console.warn('订单实收回写失败(不影响入库)');\n" + ' }\n' + ' }\n'; const COMMIT_LINE = " if (owns) await client.query('COMMIT');"; /** 把旧码注回主事务终点之前(反向验证的统一入口) */ function injectOldBlock(bodyText: string): string { const idx = commitLineIndex(bodyText); return bodyText.slice(0, idx) + OLD_BLOCK + bodyText.slice(idx); } describe('① 独立入库不得引用 inspections.order_item_id(该列不存在)', () => { it('函数内不出现 order_item_id', () => { expect(code).not.toContain('order_item_id'); }); it('全仓不存在 "order_item_id FROM inspections" 这一形状', () => { expect(src).not.toMatch(/order_item_id\s+FROM\s+inspections/i); }); it('反向验证:注入旧码 ⇒ 命中该形状(断言必须失败)', () => { const injected = injectOldBlock(body); expect(injected).toMatch(/order_item_id\s+FROM\s+inspections/i); expect(stripComments(injected)).toContain('order_item_id'); }); }); describe('② BEGIN…COMMIT 之间不得吞异常(否则 COMMIT 等价 ROLLBACK)', () => { it('事务体里没有"只记日志"的 catch', () => { expect(swallowedCatchBodies(tx)).toEqual([]); }); it('事务体里连 catch 都不该有(本函数无需要的失败兜底)', () => { expect(stripComments(tx)).not.toContain('catch'); }); it('反向验证:注入旧码 ⇒ 事务体内出现吞异常 catch(断言必须失败)', () => { const injected = injectOldBlock(body); const injectedTx = transactionSegment(stripComments(injected)); const swallowed = swallowedCatchBodies(injectedTx); expect(swallowed.length).toBe(1); expect(swallowed[0]).toContain('不影响入库'); }); }); describe('③ 独立入库的既有口径不被绕过', () => { it('待验单仍由 createIndependentInboundInspection 产出(order_code 恒 NULL)', () => { expect(body).toContain('createIndependentInboundInspection'); }); it('入库行仍写 self_purchase_stock_inbounds,且同事务落库(在 BEGIN…COMMIT 之内)', () => { expect(body).toContain('INSERT INTO self_purchase_stock_inbounds'); expect(body.indexOf('INSERT INTO self_purchase_stock_inbounds')).toBeLessThan( commitLineIndex(body) ); expect(body.indexOf("query('BEGIN')")).toBeLessThan( body.indexOf('INSERT INTO self_purchase_stock_inbounds') ); }); it('直接入库分支(开关关闭)与幂等重放都还在', () => { expect(body).toContain('inboundFromWeigh'); expect(body).toContain('loadSelfPurchaseInboundByRequestId'); }); });