- 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 超长修复
449 lines
18 KiB
TypeScript
449 lines
18 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* BIZ-14 对抗回归(2026-10-19):**同订单同 SKU 多行改派自采不得串量**。
|
||
*
|
||
* 缺陷形态(adversary 真库 + E2E 已复现):`writeReattributedSelfPurchaseActual` 调
|
||
* `computeAccumulatedInboundQty` 时没传采购单号 ⇒ 累计口径变成「订单+SKU+自采」全量。
|
||
* 同一订单同 SKU 有两行(A 入库 3、B 入库 2)各自改派自采时:
|
||
* · A 先改 ⇒ 3;
|
||
* · B 后改 ⇒ 把 A 已改自采的批次也算进来 = 3+2 = 5(应为 2)。
|
||
* ⇒ 两张自采单 actual_qty=[3,5]、合计 8(真实入库总量 5),采购实收/金额被放大。
|
||
*
|
||
* 修复:改派前把该行挂过的旧采购单号(`sourcePurchaseCodes`)传入验收写入函数,
|
||
* 只累计这些单号命中的入库批次(`processing_details.purchase_code/purchase_codes`)。
|
||
*
|
||
* 本文件用真实 `reattributeInboundFulfillment` + 真实 `ensureCompletedSelfPurchase` +
|
||
* 真实 `writeReattributedSelfPurchaseActual`(仅 db 为内存 fake)钉住:
|
||
* ① 两行各自份额 [3,2]、合计 5(不串量);
|
||
* ② 单采购单多批次(分批入库)仍累计全部批次(5),不回归。
|
||
*/
|
||
|
||
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';
|
||
|
||
type Row = Record<string, any>;
|
||
type Call = { sql: string; params: unknown[] };
|
||
|
||
type Batch = {
|
||
id: string;
|
||
orderCode: string;
|
||
skuCode: string;
|
||
supplierCode: string | null;
|
||
purchaseCode: string;
|
||
actualQty: number;
|
||
completed: boolean;
|
||
};
|
||
|
||
type PurchaseOrder = {
|
||
purchaseCode: string;
|
||
orderCode: string;
|
||
sourceId: string;
|
||
purchaseStatus: number;
|
||
actualQty: number | null;
|
||
};
|
||
|
||
type DbState = {
|
||
batches: Batch[];
|
||
links: Map<string, string>;
|
||
purchaseOrders: PurchaseOrder[];
|
||
calls: Call[];
|
||
/** 同订单同 SKU 的**全部** order_items 行数(R-A1:含退货/加菜行,无采购单号时用于判断能否安全回退) */
|
||
orderSkuRows?: number;
|
||
};
|
||
|
||
/** 极简内存 DB:只实现本链路用到的查询形状 */
|
||
function makeDb(state: DbState) {
|
||
return {
|
||
query: async (sql: string, params: unknown[] = []) => {
|
||
const text = String(sql);
|
||
state.calls.push({ sql: text, params });
|
||
// 0) R-A1:同订单同 SKU 全部行数(不过滤退货/加菜)
|
||
if (text.includes('FROM order_items') && text.includes('COUNT(*)::int')) {
|
||
const cnt = state.orderSkuRows ?? 1;
|
||
return { rowCount: 1, rows: [{ cnt }] };
|
||
}
|
||
// 1) 是否存在该供应商口径的已入库批次
|
||
if (text.includes('FROM inspections') && text.includes('inbound_batch_no') && text.includes('LIMIT 1')) {
|
||
const [orderCode, skuCode, owner] = params as [string, string, string | null];
|
||
const hit = state.batches.some(
|
||
(b) =>
|
||
b.completed &&
|
||
b.orderCode === orderCode &&
|
||
b.skuCode === skuCode &&
|
||
(owner === null ? b.supplierCode === null : b.supplierCode === owner)
|
||
);
|
||
return { rowCount: hit ? 1 : 0, rows: hit ? [{ 1: 1 }] : [] };
|
||
}
|
||
// 2) listInboundBatchesForSupplier
|
||
if (text.includes('SELECT DISTINCT NULLIF(TRIM(inbound_batch_no)')) {
|
||
const [orderCode, skuCode, owner] = params as [string, string, string | null];
|
||
const rows = state.batches
|
||
.filter(
|
||
(b) =>
|
||
b.completed &&
|
||
b.orderCode === orderCode &&
|
||
b.skuCode === skuCode &&
|
||
(owner === null ? b.supplierCode === null : b.supplierCode === owner)
|
||
)
|
||
.map((b) => ({ batch_no: b.id }));
|
||
return { rowCount: rows.length, rows };
|
||
}
|
||
// 3) relabelInboundOwner:把旧供应商批次改挂到新口径
|
||
if (text.includes('UPDATE inspections') && text.includes('SET supplier_code = $4')) {
|
||
const [orderCode, skuCode, previousOwner, nextOwner] = params as [
|
||
string,
|
||
string,
|
||
string | null,
|
||
string | null,
|
||
];
|
||
for (const b of state.batches) {
|
||
if (
|
||
b.completed &&
|
||
b.orderCode === orderCode &&
|
||
b.skuCode === skuCode &&
|
||
(previousOwner === null ? b.supplierCode === null : b.supplierCode === previousOwner)
|
||
) {
|
||
b.supplierCode = nextOwner;
|
||
}
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
// 4) dropItemFulfillmentLinks:返回该行改派前挂的采购单号
|
||
if (text.includes('FROM order_item_fulfillments f')) {
|
||
const itemId = String(params[0]);
|
||
const code = state.links.get(itemId);
|
||
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')) return { rowCount: 0, rows: [] };
|
||
if (text.includes('DELETE FROM order_item_fulfillments')) {
|
||
state.links.delete(String(params[0]));
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
if (text.includes('SELECT COUNT(*)::int AS cnt FROM order_item_fulfillments')) return { rowCount: 1, rows: [{ cnt: 0 }] };
|
||
// 5) 既有自采单
|
||
if (text.includes('FROM purchase_orders') && text.includes('SELECT purchase_code')) {
|
||
const [orderCode, sourceId] = params as [string, string];
|
||
const po = state.purchaseOrders.find((p) => p.orderCode === orderCode && p.sourceId === sourceId);
|
||
return po ? { rowCount: 1, rows: [{ purchase_code: po.purchaseCode }] } : { rowCount: 0, rows: [] };
|
||
}
|
||
// 6) 新建自采单(必须 20 + actual NULL,实收由验收模块写)
|
||
if (text.includes('INSERT INTO purchase_orders')) {
|
||
const [purchaseCode, orderCode, , , , sourceId] = params as string[];
|
||
state.purchaseOrders.push({
|
||
purchaseCode,
|
||
orderCode,
|
||
sourceId: String(sourceId),
|
||
purchaseStatus: 20,
|
||
actualQty: null,
|
||
});
|
||
return { rowCount: 1, rows: [] };
|
||
}
|
||
// 7) fetchInboundBatchRows(验收累计口径)
|
||
if (text.includes('FROM inspections') && text.includes('actual_qty') && text.includes('parent_id')) {
|
||
const [orderCode, skuCode, supplierCode] = params as [string, string, string | null];
|
||
const codes = Array.isArray(params[3]) ? (params[3] as string[]) : [];
|
||
const rows = state.batches
|
||
.filter(
|
||
(b) =>
|
||
b.completed &&
|
||
b.orderCode === orderCode &&
|
||
b.skuCode === skuCode &&
|
||
(supplierCode === null ? b.supplierCode === null : b.supplierCode === supplierCode) &&
|
||
(codes.length === 0 || codes.includes(b.purchaseCode))
|
||
)
|
||
.map((b) => ({ id: b.id, actual_qty: b.actualQty, created_at: new Date(), parent_id: null }));
|
||
return { rowCount: rows.length, rows };
|
||
}
|
||
// 8) 验收模块写 30 + 实收
|
||
if (text.includes('UPDATE purchase_orders') && text.includes('purchase_status = 30')) {
|
||
const [purchaseCode, accumulated] = params as [string, number];
|
||
const po = state.purchaseOrders.find((p) => p.purchaseCode === purchaseCode);
|
||
if (po) {
|
||
po.purchaseStatus = 30;
|
||
po.actualQty = accumulated;
|
||
}
|
||
return { rowCount: 1, rows: [] };
|
||
}
|
||
// 9) 既有自采单基础字段更新 / 其它
|
||
return { rowCount: 0, rows: [] };
|
||
},
|
||
};
|
||
}
|
||
|
||
function seedTwoRows() {
|
||
return {
|
||
batches: [
|
||
{ id: 'B1', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP1', purchaseCode: 'PURC_A', actualQty: 3, completed: true },
|
||
{ id: 'B2', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP2', purchaseCode: 'PURC_B', actualQty: 2, completed: true },
|
||
],
|
||
links: new Map([
|
||
['item-1', 'PURC_A'],
|
||
['item-2', 'PURC_B'],
|
||
]),
|
||
purchaseOrders: [] as PurchaseOrder[],
|
||
calls: [] as Call[],
|
||
};
|
||
}
|
||
|
||
beforeEach(() => {
|
||
H.upsertCost.mockReset();
|
||
H.recalcStatements.mockReset();
|
||
H.upsertCost.mockResolvedValue(undefined);
|
||
H.recalcStatements.mockResolvedValue(undefined);
|
||
});
|
||
|
||
describe('BIZ-14 对抗:同单同 SKU 两行改派自采不串量', () => {
|
||
it('两张自采单 actual_qty=[3,2]、合计=5(真实入库总量),不把对方批次算进来', async () => {
|
||
const state = seedTwoRows();
|
||
const db = makeDb(state) as never;
|
||
|
||
// 第一行改派:SUP1 → 自采
|
||
await reattributeInboundFulfillment(db, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-1',
|
||
skuCode: 'SKU1',
|
||
itemName: '草鱼',
|
||
unit: '斤',
|
||
previousSupplierCode: 'SUP1',
|
||
nextSupplierCode: null,
|
||
quantity: 3,
|
||
unitCost: 10,
|
||
branchCode: 'BR002',
|
||
});
|
||
// 第二行改派:SUP2 → 自采(此时 B1 已挂自采,若不过滤采购单号会串到 3+2)
|
||
await reattributeInboundFulfillment(db, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-2',
|
||
skuCode: 'SKU1',
|
||
itemName: '草鱼',
|
||
unit: '斤',
|
||
previousSupplierCode: 'SUP2',
|
||
nextSupplierCode: null,
|
||
quantity: 2,
|
||
unitCost: 10,
|
||
branchCode: 'BR002',
|
||
});
|
||
|
||
expect(state.purchaseOrders).toHaveLength(2);
|
||
const bySource = new Map(state.purchaseOrders.map((p) => [p.sourceId, p]));
|
||
expect(bySource.get('item-1')!.actualQty).toBe(3);
|
||
expect(bySource.get('item-2')!.actualQty).toBe(2);
|
||
const total = state.purchaseOrders.reduce((sum, p) => sum + (p.actualQty || 0), 0);
|
||
expect(total, '两张自采单合计必须等于真实入库总量 5,而不是 8').toBe(5);
|
||
expect(state.purchaseOrders.every((p) => p.purchaseStatus === 30)).toBe(true);
|
||
|
||
// 验收写入 SQL 必须按采购单号过滤(数组),不是裸 order+sku
|
||
const writeQueries = state.calls.filter(
|
||
(c) => c.sql.includes('FROM inspections') && c.sql.includes('actual_qty') && c.sql.includes('parent_id')
|
||
);
|
||
expect(writeQueries.length).toBe(2);
|
||
expect(writeQueries[0].sql).toContain('= ANY($4::text[])');
|
||
expect(writeQueries[0].params[3]).toEqual(['PURC_A']);
|
||
expect(writeQueries[1].params[3]).toEqual(['PURC_B']);
|
||
});
|
||
|
||
it('单采购单多批次(分批入库)仍累计该单全部批次:2+3=5', async () => {
|
||
const state = {
|
||
batches: [
|
||
{ id: 'C1', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP3', purchaseCode: 'PURC_C', actualQty: 2, completed: true },
|
||
{ id: 'C2', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP3', purchaseCode: 'PURC_C', actualQty: 3, completed: true },
|
||
] as Batch[],
|
||
links: new Map([['item-3', 'PURC_C']]),
|
||
purchaseOrders: [] as PurchaseOrder[],
|
||
calls: [] as Call[],
|
||
};
|
||
const db = makeDb(state) as never;
|
||
|
||
await reattributeInboundFulfillment(db, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-3',
|
||
skuCode: 'SKU1',
|
||
itemName: '草鱼',
|
||
unit: '斤',
|
||
previousSupplierCode: 'SUP3',
|
||
nextSupplierCode: null,
|
||
quantity: 5,
|
||
unitCost: 10,
|
||
branchCode: 'BR002',
|
||
});
|
||
|
||
expect(state.purchaseOrders).toHaveLength(1);
|
||
expect(state.purchaseOrders[0].actualQty, '同一采购单的补收批次必须累加').toBe(5);
|
||
expect(state.purchaseOrders[0].purchaseStatus).toBe(30);
|
||
});
|
||
});
|
||
|
||
/**
|
||
* R-A/R-A1(2026-10-19 verifier 增量复核):**无 order_item_fulfillments 链接**的备货/历史行,
|
||
* `sourcePurchaseCodes` 为空时不得无条件回退 order+sku 全量累计(仍会串量)。
|
||
* 口径:同订单同 SKU 只有**1 行 order_items**(含退货/加菜行一起数)才回退;
|
||
* 多行 ⇒ 宁可不写(保持 20)也不放大金额。
|
||
*/
|
||
describe('BIZ-14 残余 R-A:无采购单号链接时,多行跳过 / 单行回退', () => {
|
||
it('无 links + 同单同 SKU 两行 ⇒ 0 次 30/实收 UPDATE,两张自采单保持 20、actual_qty 为空', async () => {
|
||
const state: DbState = {
|
||
batches: [
|
||
{ id: 'D1', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP1', purchaseCode: 'PURC_X', actualQty: 3, completed: true },
|
||
{ id: 'D2', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP2', purchaseCode: 'PURC_Y', actualQty: 2, completed: true },
|
||
],
|
||
links: new Map(), // 无 order_item_fulfillments 链接(备货/历史行)
|
||
purchaseOrders: [],
|
||
calls: [],
|
||
orderSkuRows: 2, // 同订单同 SKU 两行 order_items
|
||
};
|
||
const db = makeDb(state) as never;
|
||
|
||
await reattributeInboundFulfillment(db, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-1',
|
||
skuCode: 'SKU1',
|
||
itemName: '草鱼',
|
||
unit: '斤',
|
||
previousSupplierCode: 'SUP1',
|
||
nextSupplierCode: null,
|
||
quantity: 3,
|
||
unitCost: 10,
|
||
branchCode: 'BR002',
|
||
});
|
||
await reattributeInboundFulfillment(db, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-2',
|
||
skuCode: 'SKU1',
|
||
itemName: '草鱼',
|
||
unit: '斤',
|
||
previousSupplierCode: 'SUP2',
|
||
nextSupplierCode: null,
|
||
quantity: 2,
|
||
unitCost: 10,
|
||
branchCode: 'BR002',
|
||
});
|
||
|
||
const writeQueries = state.calls.filter(
|
||
(c) => c.sql.includes('UPDATE purchase_orders') && c.sql.includes('purchase_status = 30')
|
||
);
|
||
expect(writeQueries, '无单号可归集且同 SKU 多行 ⇒ 不得写 30/实收').toHaveLength(0);
|
||
expect(state.purchaseOrders).toHaveLength(2);
|
||
expect(state.purchaseOrders.every((p) => p.purchaseStatus === 20)).toBe(true);
|
||
expect(state.purchaseOrders.every((p) => p.actualQty === null)).toBe(true);
|
||
// 已调用同订单同 SKU 行数闸门(而不是直接回退累计)
|
||
expect(
|
||
state.calls.some(
|
||
(c) => c.sql.includes('FROM order_items') && c.sql.includes('COUNT(*)::int')
|
||
)
|
||
).toBe(true);
|
||
});
|
||
|
||
it('无 links + 同单同 SKU 仅 1 行 ⇒ 仍安全回退 order+sku,写 30 + 累计实收 3', async () => {
|
||
const state: DbState = {
|
||
batches: [
|
||
{ id: 'E1', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP1', purchaseCode: 'PURC_Z', actualQty: 3, completed: true },
|
||
],
|
||
links: new Map(),
|
||
purchaseOrders: [],
|
||
calls: [],
|
||
orderSkuRows: 1,
|
||
};
|
||
const db = makeDb(state) as never;
|
||
|
||
await reattributeInboundFulfillment(db, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-1',
|
||
skuCode: 'SKU1',
|
||
itemName: '草鱼',
|
||
unit: '斤',
|
||
previousSupplierCode: 'SUP1',
|
||
nextSupplierCode: null,
|
||
quantity: 3,
|
||
unitCost: 10,
|
||
branchCode: 'BR002',
|
||
});
|
||
|
||
expect(state.purchaseOrders).toHaveLength(1);
|
||
expect(state.purchaseOrders[0].purchaseStatus).toBe(30);
|
||
expect(state.purchaseOrders[0].actualQty).toBe(3);
|
||
const writeQueries = state.calls.filter(
|
||
(c) => c.sql.includes('UPDATE purchase_orders') && c.sql.includes('purchase_status = 30')
|
||
);
|
||
expect(writeQueries).toHaveLength(1);
|
||
});
|
||
|
||
/**
|
||
* R-A1(2026-10-19 verifier 增量复核):1 个有效行 + 1 个退货/加菜行**都有入库批次**时,
|
||
* 若闸门只数"有效行"⇒ 回退累计仍会把退货行的批次算进来、金额被放大。
|
||
* 修复:闸门统计同 order+sku **全部** order_items 行(退货/加菜是硬删语义,其批次仍挂在
|
||
* inspection 上)⇒ 两行即跳过,保持 20。
|
||
*/
|
||
it('无 links + 1 有效行 + 1 退货行(都有入库批次)⇒ 0 次 30/实收 UPDATE、保持 20', async () => {
|
||
const state: DbState = {
|
||
batches: [
|
||
{ id: 'F1', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP1', purchaseCode: 'PURC_OK', actualQty: 3, completed: true },
|
||
// 退货行的批次:改派前与有效行同供应商口径,回退累计会把 3+2 算成 5
|
||
{ id: 'F2', orderCode: 'ORD1', skuCode: 'SKU1', supplierCode: 'SUP1', purchaseCode: 'PURC_RET', actualQty: 2, completed: true },
|
||
],
|
||
links: new Map(), // 无履约关联 ⇒ sourcePurchaseCodes 为空
|
||
purchaseOrders: [],
|
||
calls: [],
|
||
// 同 order+sku 共 2 行:1 有效 + 1 已退货(is_returned=true)——闸门必须仍数到 2
|
||
orderSkuRows: 2,
|
||
};
|
||
const db = makeDb(state) as never;
|
||
|
||
await reattributeInboundFulfillment(db, {
|
||
orderCode: 'ORD1',
|
||
itemId: 'item-1',
|
||
skuCode: 'SKU1',
|
||
itemName: '草鱼',
|
||
unit: '斤',
|
||
previousSupplierCode: 'SUP1',
|
||
nextSupplierCode: null,
|
||
quantity: 3,
|
||
unitCost: 10,
|
||
branchCode: 'BR002',
|
||
});
|
||
|
||
const writeQueries = state.calls.filter(
|
||
(c) => c.sql.includes('UPDATE purchase_orders') && c.sql.includes('purchase_status = 30')
|
||
);
|
||
expect(writeQueries, '1 有效 + 1 退货行都有批次 ⇒ 不得写 30/实收(否则金额放大)').toHaveLength(0);
|
||
expect(state.purchaseOrders).toHaveLength(1);
|
||
expect(state.purchaseOrders[0].purchaseStatus).toBe(20);
|
||
expect(state.purchaseOrders[0].actualQty).toBeNull();
|
||
// 闸门 SQL 不得再按退货/加菜过滤(否则计数会漏掉退货行)
|
||
const gate = state.calls.find((c) => c.sql.includes('COUNT(*)::int') && c.sql.includes('FROM order_items'));
|
||
expect(gate).toBeTruthy();
|
||
expect(gate!.sql).not.toMatch(/is_returned/);
|
||
expect(gate!.sql).not.toMatch(/is_extra_dish/);
|
||
});
|
||
});
|