- 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 超长修复
408 lines
17 KiB
TypeScript
408 lines
17 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
|
||
/**
|
||
* 主系统「同一订单后来追加分配」的行级增量导入(2026-10-10 用户报障)。
|
||
*
|
||
* 缺陷现场:主系统把某个商品**重新指派**给同一个供应商(同一张主系统订单多出一行),
|
||
* 子系统里看不到 —— 因为导入是**整单幂等**(`imported.has(orderCode)` 就整单跳过),
|
||
* 后来追加的行被静默丢掉。
|
||
*
|
||
* 这里钉住五件事:
|
||
* ① 已导入订单 + 台账里没有的新行 ⇒ 走**改明细**追加(不是再建一张单);
|
||
* ② 追加时既有行必须原样回传(尤其 `cost_price`=unit_cost,漏传会把既有行成本清成 0),
|
||
* 且 `allowUnpriced: true`(主系统没定价 ⇒ 售价 0 是正常口径,不能被既有零价行挡住);
|
||
* ③ 订单已到「配送中/已完成」(≥ 60,**2026-10-12 口径**)⇒ 不再往那张单追加:
|
||
* 当日单 ≥60 时**同日另开补单**(见 `mainSystemImportClaim.test.ts`);
|
||
* `< 60`(含 50 待配送/待取货)仍走本文件的**行级追加**;
|
||
* ④ 没有新行 ⇒ 不调任何写路径(重复对账幂等,绝不重复追加);
|
||
* (2026-10-10 起合并键是**(分公司, 配送日)**:日级占坑抢不到、且该日已有单号 ⇒ 走本文件的追加路径)
|
||
* ⑤ 行级台账 INSERT 的占位符编号必须与参数个数一致
|
||
* (修复前是 `$13` 却只传 12 个参数 → 线上**每一次**台账写入都抛
|
||
* `bind message supplies 12 parameters, but prepared statement "" requires 13`,
|
||
* 而调用点 catch 成"不影响建单",于是行级台账从来没写进去过)。
|
||
*/
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
const syncItems = vi.hoisted(() => vi.fn());
|
||
const enrich = vi.hoisted(() => vi.fn());
|
||
const withTenant = vi.hoisted(() => vi.fn());
|
||
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
acquireTenantSessionClient: async () => ({ query, release: () => undefined }),
|
||
releaseTenantSessionClient: async () => undefined,
|
||
}));
|
||
vi.mock('../src/services/orderManageItemsService', () => ({
|
||
syncOrderManageItems: (...args: unknown[]) => syncItems(...args),
|
||
}));
|
||
vi.mock('../src/services/customerOrderSubmitService', () => ({
|
||
submitMobileCustomerOrder: vi.fn(),
|
||
}));
|
||
vi.mock('../src/services/customerOrderEnrichService', () => ({
|
||
enrichCustomerOrderItems: (...args: unknown[]) => enrich(...args),
|
||
}));
|
||
vi.mock('../src/services/tenantSchemaService', async (importOriginal) => {
|
||
const actual = await importOriginal<typeof import('../src/services/tenantSchemaService')>();
|
||
return {
|
||
...actual,
|
||
runWithTenantDataAccess: (...args: unknown[]) => withTenant(...args),
|
||
resolveActiveTenantSchema: async () => 'tenant_br001',
|
||
};
|
||
});
|
||
|
||
import { importMainSystemGroups } from '../src/services/mainSystemOrderImport';
|
||
import { recordImportedPrepItems } from '../src/services/mainSystemPrepLedger';
|
||
import type { MainOrderGroup } from '../src/services/mainSystemPreparations';
|
||
|
||
const OUR_ORDER = 'ORD_API_20261010_SUP001_0001';
|
||
const MAIN_ORDER = 'ORD_WEB_20261010_BR002_0007';
|
||
const EXISTING_PREP_ID = '11111111-1111-4111-8111-111111111111';
|
||
const NEW_PREP_ID = '22222222-2222-4222-8222-222222222222';
|
||
const NEW_ITEM_ID = '33333333-3333-4333-8333-333333333333';
|
||
|
||
function prepRow(over: Record<string, unknown>) {
|
||
return {
|
||
orderCode: MAIN_ORDER,
|
||
skuCode: null,
|
||
displayName: null,
|
||
prepareQty: 1,
|
||
unit: '斤',
|
||
orderQty: null,
|
||
orderUnit: null,
|
||
purchasePrice: 0,
|
||
suggestedPrice: null,
|
||
prepareStatus: 10,
|
||
deliveryDate: '2026-10-10',
|
||
taskDay: '2026-10-10',
|
||
isStockout: false,
|
||
processingMethod: null,
|
||
returnCode: null,
|
||
returnReason: null,
|
||
requiresQualityReport: false,
|
||
orderItemRemark: null,
|
||
skipInbound: false,
|
||
isDirectDelivery: false,
|
||
...over,
|
||
} as never;
|
||
}
|
||
|
||
/** 既有行(桔皮,售价 0 —— 正是"零价行不能挡住追加"的现场)+主系统新分配的行(花生) */
|
||
const GROUP: MainOrderGroup = {
|
||
orderCode: MAIN_ORDER,
|
||
deliveryDate: '2026-10-10',
|
||
taskDay: '2026-10-10',
|
||
rows: [
|
||
prepRow({ id: EXISTING_PREP_ID, itemName: '桔皮', prepareQty: 0.5, unit: '斤', purchasePrice: 0 }),
|
||
prepRow({ id: NEW_PREP_ID, itemName: '花生', prepareQty: 2, unit: '包', purchasePrice: 6 }),
|
||
],
|
||
};
|
||
|
||
const LEDGER_ROW = {
|
||
id: 'led-1',
|
||
branch_code: 'SUP001',
|
||
main_order_code: MAIN_ORDER,
|
||
prep_id: EXISTING_PREP_ID,
|
||
our_order_code: OUR_ORDER,
|
||
our_order_item_id: 'existing-item-1',
|
||
main_supplier_code: 'SUP001',
|
||
main_sku_code: null,
|
||
item_name: '桔皮',
|
||
last_prepare_qty: '0.5',
|
||
last_prepare_status: 10,
|
||
last_return_code: null,
|
||
disposition: 'imported',
|
||
disposition_reason: null,
|
||
writeback_status: null,
|
||
last_seen_active_at: null,
|
||
payload: null,
|
||
};
|
||
|
||
/** 追加前读到的订单头/明细,与追加后台账重读的明细 */
|
||
const EXISTING_ITEM_ROW = {
|
||
id: 'existing-item-1',
|
||
item_name: '桔皮',
|
||
sku_code: 'SKU_EXISTING',
|
||
quantity: '10.00',
|
||
unit: '斤',
|
||
price: '0.00',
|
||
amount: '0.00',
|
||
cost_price: '3.5000',
|
||
supplier_code: 'INTERNAL',
|
||
processing_method: '原材料',
|
||
processing_owner: null,
|
||
category_code: 'CAT_1',
|
||
category_name: '蔬菜',
|
||
sort_order: 1,
|
||
remark: null,
|
||
is_extra_dish: false,
|
||
quality_report_id: null,
|
||
};
|
||
|
||
function sqlOf(call: unknown[]): string {
|
||
return String(call[0] || '');
|
||
}
|
||
|
||
/** 租户连接:按 SQL 内容分派(追加路径只读这几处) */
|
||
function tenantClient(orderStatus: number) {
|
||
return {
|
||
query: async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
if (sql.includes('SELECT order_status FROM orders')) {
|
||
return { rowCount: 1, rows: [{ order_status: orderStatus }] };
|
||
}
|
||
if (sql.includes('SELECT id, item_name, sku_code, quantity, unit, price, amount,')) {
|
||
return { rowCount: 1, rows: [EXISTING_ITEM_ROW] };
|
||
}
|
||
if (sql.includes('SELECT id::text AS id, item_name')) {
|
||
return {
|
||
rowCount: 2,
|
||
rows: [
|
||
{ id: 'existing-item-1', item_name: '桔皮' },
|
||
{ id: NEW_ITEM_ID, item_name: '花生' },
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
},
|
||
};
|
||
}
|
||
|
||
describe('已导入订单的新分配行 → 行级增量追加', () => {
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
syncItems.mockReset();
|
||
enrich.mockReset();
|
||
withTenant.mockReset();
|
||
enrich.mockImplementation(async (_c: string, items: unknown[]) => items);
|
||
syncItems.mockResolvedValue({ total_amount: 12, total_weight: 10, items: [] });
|
||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||
fn(tenantClient(30))
|
||
);
|
||
query.mockImplementation(async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
// 日级占坑:抢不到(该配送日已建过单)⇒ 读回已有单号 → 走行级增量追加
|
||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
if (sql.includes('SELECT our_order_code FROM public.main_system_daily_order_imports')) {
|
||
return { rowCount: 1, rows: [{ our_order_code: OUR_ORDER }] };
|
||
}
|
||
if (sql.includes('FROM public.main_system_order_imports')) {
|
||
return { rowCount: 1, rows: [{ main_order_code: MAIN_ORDER, our_order_code: OUR_ORDER }] };
|
||
}
|
||
if (sql.includes('FROM public.main_system_order_import_items')) {
|
||
return { rowCount: 1, rows: [LEDGER_ROW] };
|
||
}
|
||
// 台账 INSERT:模拟 pg 对占位符个数的校验(多一个 $n 少一个参数会抛)
|
||
if (sql.includes('INSERT INTO public.main_system_order_import_items')) {
|
||
const params = (args[1] as unknown[]) || [];
|
||
const referenced = [...sql.matchAll(/\$(\d+)/g)].map((m) => Number(m[1]));
|
||
const max = referenced.length ? Math.max(...referenced) : 0;
|
||
if (max > params.length) {
|
||
throw new Error(
|
||
`bind message supplies ${params.length} parameters, but prepared statement "" requires ${max}`
|
||
);
|
||
}
|
||
return { rowCount: 1, rows: [] };
|
||
}
|
||
// 其余(含租户 schema 注册表探测):rowCount 0 ⇒ 不借会话连接,直接进租户上下文
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
});
|
||
|
||
it('新行走改明细追加:既有行原样回传 + 新行带 create_product + 放行零价', async () => {
|
||
const outcome = await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [GROUP],
|
||
});
|
||
|
||
expect(outcome.appended).toBe(1);
|
||
expect(outcome.created).toBe(0);
|
||
expect(syncItems).toHaveBeenCalledTimes(1);
|
||
|
||
const params = syncItems.mock.calls[0][0] as {
|
||
orderCode: string;
|
||
items: Array<Record<string, unknown>>;
|
||
allowUnpriced?: boolean;
|
||
provisionPurchaserOrderSkus?: boolean;
|
||
canForceEdit?: boolean;
|
||
};
|
||
expect(params.orderCode).toBe(OUR_ORDER);
|
||
expect(params.allowUnpriced).toBe(true);
|
||
expect(params.provisionPurchaserOrderSkus).toBe(true);
|
||
/**
|
||
* ⚠️ 系统追加**必须带 `canForceEdit`**(2026-10-12 真库实测的静默丢失)。
|
||
* 本文件此前 mock 掉了 `syncOrderManageItems`,所以这道权限闸没被覆盖到 ——
|
||
* 而真链路上 `order_status >= 40`(待验收/待分拣/待配送)时它要求 `order_force_edit`,
|
||
* 系统身份没有 ⇒「追加新分配行失败:当前状态不可修改商品明细(履约中须持「强制改单」权限)」
|
||
* ⇒ 主系统新分配的商品在子系统不落库(webhook 收到、台账没有)。
|
||
* 阀门口径:< 60(含 50 待取货)应追加;≥ 60 另开补单,到不了这里。
|
||
*/
|
||
expect(params.canForceEdit).toBe(true);
|
||
|
||
const existing = params.items.find((it) => it.id === 'existing-item-1')!;
|
||
// 既有行必须原样回传:unit_cost 由 cost_price 推导,漏传会把它清成 0
|
||
expect(existing.cost_price).toBe('3.5000');
|
||
expect(existing.quantity).toBe('10.00');
|
||
expect(existing.supplier_code).toBe('INTERNAL');
|
||
|
||
const appended = params.items.find((it) => it.item_name === '花生')!;
|
||
expect(appended).toBeTruthy();
|
||
expect(Number(appended.price)).toBe(6);
|
||
expect(appended.create_product).toBe(true);
|
||
// 归不上类也要有分类(否则录单链路会以"商品未选择分类"400)
|
||
expect(String(appended.category_code || '')).not.toBe('');
|
||
});
|
||
|
||
it('待分拣(45)追加:系统身份必须带 canForceEdit(真库事故的现场复刻)', async () => {
|
||
/**
|
||
* 2026-10-12 真库事故:我方单 `order_status = 45`(待分拣)+ 主系统新增一行 ⇒
|
||
* 追加走的改明细链路在 `>= 40` 时要求 `order_force_edit`;导入侧先前没传 `canForceEdit`
|
||
* ⇒「当前状态不可修改商品明细(履约中须持「强制改单」权限)」⇒ 新分配商品静默丢失。
|
||
* 本用例把**订单状态锁在 45**,断言系统路径确实带上了这个强制位
|
||
* (配合 `orderManageItemsLock.test.ts` 的闸门口径:45 无强制位 = 拒绝、有 = 放行)。
|
||
*/
|
||
// 复刻真库现场:该单处于 45(待分拣)——租户连接读回的订单状态就是它
|
||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||
fn(tenantClient(45))
|
||
);
|
||
const outcome = await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [GROUP],
|
||
});
|
||
expect(outcome.appended).toBe(1);
|
||
const params = syncItems.mock.calls[0][0] as { canForceEdit?: boolean; operatorRoles?: string };
|
||
expect(params.canForceEdit).toBe(true);
|
||
expect(params.operatorRoles).toBe('main_system_import');
|
||
});
|
||
|
||
it('追加成功后把新行的行级对照写进台账(含 our_order_item_id)', async () => {
|
||
await importMainSystemGroups({ supplierCode: 'SUP001', branchCode: 'SUP001', userId: null, groups: [GROUP] });
|
||
|
||
const inserts = query.mock.calls.filter(
|
||
(c) =>
|
||
sqlOf(c).includes('INSERT INTO public.main_system_order_import_items') &&
|
||
String(sqlOf(c)).includes('disposition')
|
||
);
|
||
expect(inserts.length).toBeGreaterThan(0);
|
||
// 花生那行的对照必须指向新追加的订单行(整单行全量写入,逐行找它)
|
||
const peanut = inserts.map((c) => c[1] as unknown[]).find((params) => params[2] === NEW_PREP_ID);
|
||
expect(peanut).toBeTruthy();
|
||
expect(peanut![4]).toBe(NEW_ITEM_ID);
|
||
expect(peanut![11]).toBe('imported');
|
||
// 桔皮那行顺带把此前为空的对照补上
|
||
const orange = inserts.map((c) => c[1] as unknown[]).find((params) => params[2] === EXISTING_PREP_ID);
|
||
expect(orange![4]).toBe('existing-item-1');
|
||
});
|
||
|
||
it('订单 45 待分拣(< 60)⇒ 仍按行追加,不再挂起(2026-10-12 阀门由 40 收到 60)', async () => {
|
||
withTenant.mockImplementation(async (_b: string, fn: (c: unknown) => Promise<unknown>) =>
|
||
fn(tenantClient(45))
|
||
);
|
||
|
||
const outcome = await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [GROUP],
|
||
});
|
||
|
||
expect(syncItems).toHaveBeenCalledTimes(1);
|
||
expect(outcome.appended).toBe(1);
|
||
expect(outcome.skipped).toBe(0);
|
||
// 不再挂待处理
|
||
const suspend = query.mock.calls.find((c) => sqlOf(c).includes('SET disposition = $3'));
|
||
expect(suspend).toBeFalsy();
|
||
});
|
||
|
||
it('台账里已有这两行 → 没有新行,不调用任何写路径(重复对账幂等)', async () => {
|
||
query.mockImplementation(async (...args: unknown[]) => {
|
||
const sql = sqlOf(args);
|
||
if (sql.includes('INSERT INTO public.main_system_daily_order_imports')) {
|
||
return { rowCount: 0, rows: [] };
|
||
}
|
||
if (sql.includes('SELECT our_order_code FROM public.main_system_daily_order_imports')) {
|
||
return { rowCount: 1, rows: [{ our_order_code: OUR_ORDER }] };
|
||
}
|
||
if (sql.includes('FROM public.main_system_order_imports')) {
|
||
return { rowCount: 1, rows: [{ main_order_code: MAIN_ORDER, our_order_code: OUR_ORDER }] };
|
||
}
|
||
if (sql.includes('FROM public.main_system_order_import_items')) {
|
||
return {
|
||
rowCount: 2,
|
||
rows: [
|
||
LEDGER_ROW,
|
||
{ ...LEDGER_ROW, id: 'led-2', prep_id: NEW_PREP_ID, item_name: '花生', our_order_item_id: 'item-2' },
|
||
],
|
||
};
|
||
}
|
||
return { rowCount: 0, rows: [] };
|
||
});
|
||
|
||
const outcome = await importMainSystemGroups({
|
||
supplierCode: 'SUP001',
|
||
branchCode: 'SUP001',
|
||
userId: null,
|
||
groups: [GROUP],
|
||
});
|
||
|
||
expect(syncItems).not.toHaveBeenCalled();
|
||
expect(outcome.appended).toBe(0);
|
||
expect(outcome.skipped).toBe(1);
|
||
expect(String(outcome.results[0].message)).toContain('没有新分配的行');
|
||
});
|
||
|
||
it('行级台账写入:列清单与占位符必须逐位对应(修复前 disposition→$13 与 payload→$12 是错位的)', async () => {
|
||
// 缺货行不建明细,但同样要落台账(处置 skipped_stockout),且不得占用名字匹配位
|
||
await recordImportedPrepItems({
|
||
branchCode: 'SUP001',
|
||
mainOrderCode: MAIN_ORDER,
|
||
supplierCode: 'SUP001',
|
||
ourOrderCode: OUR_ORDER,
|
||
prepRows: [
|
||
{ id: NEW_PREP_ID, itemName: '花生', prepareQty: 2, prepareStatus: 10, isStockout: true },
|
||
],
|
||
ourItems: [{ id: NEW_ITEM_ID, item_name: '花生' }],
|
||
});
|
||
|
||
const insert = query.mock.calls.find((c) =>
|
||
sqlOf(c).includes('INSERT INTO public.main_system_order_import_items')
|
||
)!;
|
||
const sql = sqlOf(insert);
|
||
const params = (insert[1] as unknown[]) || [];
|
||
|
||
// ① 占位符编号不得超出参数个数($13 配 12 个参数 ⇒ Postgres 直接报
|
||
// `bind message supplies 12 parameters … requires 13`,而调用点只当"不影响建单"吞掉)
|
||
const referenced = [...sql.matchAll(/\$(\d+)/g)].map((m) => Number(m[1]));
|
||
expect(Math.max(...referenced)).toBeLessThanOrEqual(params.length);
|
||
|
||
// ② 更强的判据:列清单里 `disposition` 同位的占位符,取到的参数必须真是一个处置值。
|
||
// 修复前 SQL 是 `… last_return_code, disposition, payload … VALUES (…,$11,$13,$12::jsonb)`
|
||
// ⇒ 同位的 $13 取到的是 JSON 快照对象(写进 varchar(20) 必然失败/错位)。
|
||
const colStart = sql.indexOf('(');
|
||
const cols = sql.slice(colStart + 1, sql.indexOf(')', colStart)).split(',').map((c) => c.trim());
|
||
const valStart = sql.indexOf('VALUES (') + 'VALUES ('.length;
|
||
const values = sql
|
||
.slice(valStart, sql.indexOf(')', valStart))
|
||
.split(',')
|
||
.map((v) => v.trim());
|
||
const dispositionAt = cols.indexOf('disposition');
|
||
expect(dispositionAt).toBeGreaterThan(-1);
|
||
const payloadAt = cols.indexOf('payload');
|
||
const paramOf = (position: number) => params[Number(values[position].replace(/[^0-9]/g, '')) - 1];
|
||
|
||
expect(['imported', 'skipped_stockout']).toContain(paramOf(dispositionAt));
|
||
expect(typeof paramOf(payloadAt)).toBe('string');
|
||
expect(() => JSON.parse(String(paramOf(payloadAt)))).not.toThrow();
|
||
|
||
// ③ 缺货行:处置写 skipped_stockout,且**不给订单行对照**(本系统没建这行)
|
||
expect(paramOf(dispositionAt)).toBe('skipped_stockout');
|
||
expect(paramOf(cols.indexOf('our_order_item_id'))).toBeNull();
|
||
});
|
||
});
|