Files
SupplierSystem/server/tests/selfPurchaseStockInboundTxnSafety.test.ts
T
Ubuntu e64b1a001b
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(独立入库): 返回成功却一行不落库(事务内吞异常致 COMMIT 变 ROLLBACK)
事故(真跑 P0):自采界面「新增自采」(= 独立入库)返回 200 与 batch_no,但
self_purchase_stock_inbounds 与 inspections 各 0 行 —— 货与待验单静默消失。

根因三层(缺一层都不会丢数):
① createSelfPurchaseStockInbound 引用**不存在的列** inspections.order_item_id(该表实测 30 列,无此列);
② 该语句在事务内报错被 catch 吞掉(只 console.warn,不抛、不回滚到 SAVEPOINT);
③ PG 语义:事务 aborted 后末尾 COMMIT 等价 ROLLBACK,而返回值已由 RETURNING 取到 ⇒ 照常返回成功。

开发者裁决(2026-10-15):「独立入库本来就不与订单关联」,它是给需要加工的产品采购原材料的入口
(createIndependentInboundInspection 恒写 order_code=NULL,输入接口也没有订单号字段)
⇒ 整块删掉订单实收回写,而不是去补一个"合法关联"。

改前 → 改后(同一脚本、同一 SKU SKU97144738818):
· self_purchase_stock_inbounds 0 行 → 1 行;inspections 0 行 → 1 行;
· stderr 报 column "order_item_id" does not exist → 无该告警;
· 链路端到端:创建 1 行 + 真实验收(actual_qty=3 合格)后 inventory / inventory_logs / cost_details 各 1 行。

测试:
· 删除 selfPurchaseActualQtyWriteback.test.ts —— 它把缺陷当契约钉住(断言了那条不存在的列 SQL 与吞异常日志文案);
· 新增 selfPurchaseStockInboundTxnSafety.test.ts(9 例):不得引用该列 + BEGIN…COMMIT 之间不得出现
  「只记日志」的 catch + 注入旧码必须 FAIL 的反向验证(已实测:注回旧码 5 例转红)。
验证:server tsc 0 error;vitest 32 failed / 2993 passed —— 失败数与本轮基线 32 例相同、失败文件集是基线子集(无新增);
设计门禁 8 通过 / 1 红(check-ai-cost,已知不许调绿) / 1 未执行(verify-facts,本地库连接探测),与改动前同基线。

设计:docs/design/20261015-独立入库不与订单关联(删掉订单实收回写与吞异常).md
同族风险:另有 6 处「事务内吞异常」站点(下单 / 明细保存等,属 finance/order 冻结面)已在设计文 §8 逐条列出,
本次**只报告未修**,等开发者裁决。
2026-10-15 07:07:31 +08:00

199 lines
7.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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');
});
});