Files
SupplierSystem/server/tests/t1AddendumBiz14CrossQty.test.ts
T
Ubuntu 5fa2bbfd55
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(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

246 lines
10 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 { beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T1 Addendum · BIZ-14 串量复测(2026-10-19,tester;adversary 攻破项 + R-A 复测)。
*
* 攻破形态:同订单同 SKU 两行各自有入库批次(3 / 2),先后改派自采时,
* 验收写入若按「订单+SKU+自采」全量累计 ⇒ 第二张自采单 actual_qty=5(应为 2),合计 8(应为 5)。
*
* 修复演进:
* · 第一版:改派前把该行挂过的旧采购单号(`sourcePurchaseCodes`)传给验收写入,按单号归集;
* · R-A(2026-10-19 对抗残余):**没有**采购单号可归集时,先数「同订单同 SKU 有效订单行」,
* 多行 ⇒ 不写实收(新单保持 20 / actual_qty 为空,宁可不写也不放大),单行才回退全量累计。
*
* 本文件独立于 dev 的 `selfPurchaseReattributeMultiRowNoCrossQty.test.ts`(自写内存 DB、自写断言):
* ① 有 links(purchaseCodes 非空)多行 ⇒ actual_qty=[3,2]、合计 5,按单归集;
* ② 无 links + 多行 ⇒ 0 次 30/actual 写入、两张单保持 20/actual NULL、writer 返回 null;
* ③ 无 links + 单行 ⇒ 正常写 30 + actual_qty。
*/
const H = vi.hoisted(() => ({
upsertCost: vi.fn(),
recalcStatements: vi.fn(),
}));
vi.mock('../src/db', () => ({
pool: { query: vi.fn(), connect: vi.fn() },
query: vi.fn(),
getRawPoolQuery: () => vi.fn(),
}));
vi.mock('../src/services/orderCostPostingService', () => ({
upsertOrderSkuPurchaseCostFromUnitCost: (...args: unknown[]) => H.upsertCost(...args),
}));
vi.mock('../src/services/financeReconciliationService', () => ({
recalculateStatementsAffectedByOrder: (...args: unknown[]) => H.recalcStatements(...args),
}));
import { reattributeInboundFulfillment } from '../src/services/inboundFulfillmentReattributeService';
import { writeReattributedSelfPurchaseActual } from '../src/services/inspectionComplianceService';
type Call = { sql: string; params: unknown[] };
type Batch = { id: string; supplierCode: string | null; purchaseCodes: string[]; qty: number };
type PurchaseOrder = { code: string; sourceId: string; status: number; actualQty: number | null };
type State = {
batches: Batch[];
/** itemId → 改派前挂的采购单号(没有该行 ⇒ 没有可归集的单号) */
links: Map<string, string>;
orders: PurchaseOrder[];
calls: Call[];
/** 「同订单同 SKU 有效订单行数」查询返回(R-A) */
siblingRows: number;
siblingQueries: number;
};
function makeState(overrides: Partial<State> = {}): State {
return {
batches: [
{ id: 'B1', supplierCode: 'SUP1', purchaseCodes: ['PURC_A'], qty: 3 },
{ id: 'B2', supplierCode: 'SUP2', purchaseCodes: ['PURC_B'], qty: 2 },
],
links: new Map([
['item-1', 'PURC_A'],
['item-2', 'PURC_B'],
]),
orders: [],
calls: [],
siblingRows: 2,
siblingQueries: 0,
...overrides,
};
}
function makeDb(state: State) {
return {
query: async (sql: string, params: unknown[] = []) => {
const text = String(sql);
state.calls.push({ sql: text, params });
// R-A:无 sourcePurchaseCodes 时先查同订单同 SKU 有效订单行数
if (text.includes('COUNT(*)::int AS cnt') && text.includes('FROM order_items')) {
state.siblingQueries += 1;
return { rowCount: 1, rows: [{ cnt: state.siblingRows }] };
}
// 是否存在该旧供应商口径的已入库批次
if (text.includes('FROM inspections') && text.includes('inbound_batch_no') && text.includes('LIMIT 1')) {
const owner = params[2] as string | null;
const hit = state.batches.some((b) => b.supplierCode === owner);
return { rowCount: hit ? 1 : 0, rows: hit ? [{ 1: 1 }] : [] };
}
// 批次号列表(不参与断言,返回空即可)
if (text.includes('SELECT DISTINCT NULLIF(TRIM(inbound_batch_no)')) return { rowCount: 0, rows: [] };
// 改挂归属
if (text.includes('UPDATE inspections') && text.includes('SET supplier_code = $4')) {
const previous = params[2] as string | null;
const next = params[3] as string | null;
for (const b of state.batches) if (b.supplierCode === previous) b.supplierCode = next;
return { rowCount: 0, rows: [] };
}
if (text.includes('UPDATE inventory')) return { rowCount: 0, rows: [] };
// 改派前的履约关联(返回该行挂过的采购单号)
if (text.includes('FROM order_item_fulfillments f')) {
const code = state.links.get(String(params[0]));
return code
? {
rowCount: 1,
rows: [{ supplier_preparation_id: null, purchase_code: code, prep_sku: null, prep_supplier: null }],
}
: { rowCount: 0, rows: [] };
}
if (text.includes('SELECT set_config') || text.includes('DELETE FROM order_item_fulfillments')) {
state.links.delete(String(params[0]));
return { rowCount: 0, rows: [] };
}
if (text.includes('COUNT(*)::int AS cnt FROM order_item_fulfillments')) return { rowCount: 1, rows: [{ cnt: 0 }] };
// 既有自采单
if (text.includes('FROM purchase_orders') && text.includes('SELECT purchase_code')) {
const po = state.orders.find((p) => p.sourceId === String(params[1]));
return po ? { rowCount: 1, rows: [{ purchase_code: po.code }] } : { rowCount: 0, rows: [] };
}
if (text.includes('INSERT INTO purchase_orders')) {
state.orders.push({ code: String(params[0]), sourceId: String(params[5]), status: 20, actualQty: null });
return { rowCount: 1, rows: [] };
}
// 验收累计:有 purchaseCodes 时按数组过滤(按单归集)
if (text.includes('FROM inspections') && text.includes('actual_qty') && text.includes('parent_id')) {
const codes = Array.isArray(params[3]) ? (params[3] as string[]) : [];
const rows = state.batches
.filter((b) => b.supplierCode === null) // 自采口径
.filter((b) => codes.length === 0 || b.purchaseCodes.some((code) => codes.includes(code)))
.map((b) => ({ id: b.id, actual_qty: b.qty, created_at: new Date(), parent_id: null }));
return { rowCount: rows.length, rows };
}
// 验收唯一写入方:30 + actual_qty
if (text.includes('UPDATE purchase_orders') && text.includes('purchase_status = 30')) {
const po = state.orders.find((p) => p.code === String(params[0]));
if (po) {
po.status = 30;
po.actualQty = Number(params[1]);
}
return { rowCount: 1, rows: [] };
}
// 既有自采单基础字段更新 / 其它
return { rowCount: 0, rows: [] };
},
};
}
async function reattribute(db: unknown, itemId: string, previousSupplier: string, qty: number): Promise<void> {
await reattributeInboundFulfillment(db as never, {
orderCode: 'ORD1',
itemId,
skuCode: 'SKU1',
itemName: '草鱼',
unit: '斤',
previousSupplierCode: previousSupplier,
nextSupplierCode: null,
quantity: qty,
unitCost: 10,
branchCode: 'BR002',
});
}
/** 命中「写 30 + actual_qty」的 UPDATE(唯一写入方语句) */
function status30Writes(state: State): Call[] {
return state.calls.filter(
(c) => /UPDATE\s+purchase_orders/i.test(c.sql) && /purchase_status\s*=\s*30/.test(c.sql)
);
}
beforeEach(() => {
H.upsertCost.mockReset();
H.recalcStatements.mockReset();
H.upsertCost.mockResolvedValue(undefined);
H.recalcStatements.mockResolvedValue(undefined);
});
describe('BIZ-14 串量:同单同 SKU 两行', () => {
it('主路径(有 links):actual_qty=[3,2]、合计 5,按采购单号归集', async () => {
const state = makeState();
const db = makeDb(state);
await reattribute(db, 'item-1', 'SUP1', 3);
await reattribute(db, 'item-2', 'SUP2', 2);
expect(state.orders).toHaveLength(2);
const actual = state.orders.map((p) => p.actualQty);
expect(actual).toEqual([3, 2]);
expect(actual.reduce((sum, qty) => sum + (qty || 0), 0)).toBe(5);
expect(state.orders.every((p) => p.status === 30)).toBe(true);
expect(state.siblingQueries, '有 sourcePurchaseCodes 时不该数行').toBe(0);
const accumulations = state.calls.filter(
(c) => c.sql.includes('FROM inspections') && c.sql.includes('actual_qty') && c.sql.includes('parent_id')
);
expect(accumulations).toHaveLength(2);
expect(accumulations[0].sql).toContain('= ANY($4::text[])');
expect(accumulations[0].sql).toContain('?| $4::text[]');
expect(accumulations[0].params[3]).toEqual(['PURC_A']);
expect(accumulations[1].params[3]).toEqual(['PURC_B']);
});
it('无 links + 多行(R-A):0 次 30/actual 写入、两张单保持 20/actual NULL、返回 null', async () => {
const state = makeState({ links: new Map(), siblingRows: 2 });
const db = makeDb(state);
await reattribute(db, 'item-1', 'SUP1', 3);
await reattribute(db, 'item-2', 'SUP2', 2);
expect(state.orders).toHaveLength(2);
expect(state.orders.every((p) => p.status === 20)).toBe(true);
expect(state.orders.every((p) => p.actualQty === null)).toBe(true);
expect(status30Writes(state), '多行无单号可归集 ⇒ 不得写 30/actual_qty').toHaveLength(0);
expect(state.siblingQueries).toBe(2); // 两次改派各查一次行数
// 唯一写入方直接调用也必须返回 null(且不产生第 3 次 30 写入)
const direct = await writeReattributedSelfPurchaseActual(db as never, {
purchaseCode: 'PURC_DIRECT',
orderCode: 'ORD1',
skuCode: 'SKU1',
actualPrice: 10,
});
expect(direct, '多行无单号可归集 ⇒ 返回 null(跳过写入)').toBeNull();
expect(status30Writes(state)).toHaveLength(0);
});
it('无 links + 单行:正常写 30 + actual_qty(回退全量累计安全)', async () => {
const state = makeState({
batches: [{ id: 'C1', supplierCode: 'SUP3', purchaseCodes: ['PURC_C'], qty: 3 }],
links: new Map(),
siblingRows: 1,
});
const db = makeDb(state);
await reattribute(db, 'item-3', 'SUP3', 3);
expect(state.orders).toHaveLength(1);
expect(state.orders[0].status).toBe(30);
expect(state.orders[0].actualQty).toBe(3);
const writes = status30Writes(state);
expect(writes).toHaveLength(1);
expect(writes[0].params[1]).toBe(3);
expect(state.siblingQueries).toBe(1);
});
});