Files
SupplierSystem/server/tests/mainSystemFulfillmentEvents.test.ts
T
Ubuntu 3798082811
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(对接收尾): 9 处只读路径仍在用「分公司编码」当 supplierCode ⇒ 403 静默失效
真库日志抓到(每轮在刷):
  [main-system-actual-facts] BR003 … 刷新失败:换取对接 Token 失败(forbidden: 未授权访问该供应商:
    该(分公司 × 供应商)尚未绑定子系统接入编码…)

根因:接入编码落地时我改掉了全部**写**路径,**读**路径漏了 9 处,仍把 branchCode 传进
主系统接口的第一参数 `supplierCode`(按供货关系鉴权)⇒ 解耦后必然 403;而它们全是
"失败只记日志继续跑"的兜底/跟随路径 ⇒ **静默失效**:
  · 核货事实刷新 mainSystemActualFacts:135
  · 退货/改派跟随 lookup 与归档反查 mainSystemReturnFollow:357/:388
  · 缺货跟随剔除 mainSystemOrderImport:1764、报缺货前状态 mainSystemStockout:429
  · 履约事件对账兜底 mainSystemFulfillmentEvents:363
  · Q6 漏推自愈 mainSystemPriceQtyRequest:1416、mainSystemActualQtyInbox:917/:1117

修法:新增 server/src/services/mainSystemBranchApi.ts(与写路径的 resolveSupplierCodeForPrep 同口径)
  · listSupplierCodesForBranch:该分公司全部生效绑定的 supplier_code
  · groupItemsBySupplierCode:按**行级台账**分组;台账缺失时只有唯一绑定才回退,多绑定则**跳过并告警**(不猜)
  · lookup/归档/申请列表:逐供应商调用后**合并**;部分失败保留成功结果(兜底要能推进多少算多少),全失败才报错
并把这 9 处换成包装器(含两处测试 mock 转接)。

回归守卫(防复发):
  · mainSystemSupplierCodeCallSites.test.ts:全仓扫描,禁止再把 branch/branchCode/params.branchCode
    传进 9 个"首参是 supplierCode"的对接函数(连写路径一起钉),并断言 8 条兜底路径都在用新包装器
  · mainSystemBranchApi.test.ts 11 例:只认台账 / 唯一绑定才回退 / 多绑定跳过 / 合并与部分失败保留 / 未绑定返回

实测(真库 + 真主系统):
  · refreshOrderActualFacts(BR003, …_0001) ⇒ refreshed:true,6 行事实全取回(**403 消失**)
  · 调度真入口跑一轮 ⇒ 日志「BR003:在飞单 1 张,刷新到核货事实 1 张」(403 绝迹)
  · 顺带验证合并键:BR003 现有两张单(主系统 BR002 的 6 行 / 主系统 BR007 的 3 行)⇒ 不同主系统分公司各自成单 ✅
  · 服务端 2350 用例 / 失败文件 25 = 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice(非本次引入)

设计记录:docs/design/20261027-分公司接入编码与主系统供应商绑定.md §12.5.1
2026-10-10 18:56:31 +08:00

428 lines
18 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 { describe, expect, it, vi, beforeEach } from 'vitest';
import { readFileSync } from 'node:fs';
import path from 'path';
/**
* 主系统履约事件接收端(2026-10-10,设计文档
* `docs/design/20261010-第三方订单履约事件接收端与免入库回写时机.md`)的行为回归。
*
* 覆盖:幂等占坑、两条链路的收口入口与前置、乱序不越级、无台账忽略、
* 业务闸门(零价)不绕过、实收量事实落账、以及"零反向写回"的源码合同。
*/
const query = vi.hoisted(() => vi.fn());
const runWithTenantDbContext = vi.hoisted(() => vi.fn());
const completeOrderWithoutDriverDelivery = vi.hoisted(() => vi.fn());
const finalizeOrderFulfillment = vi.hoisted(() => vi.fn());
const lookupMainSystemPreparationStates = vi.hoisted(() => vi.fn());
const recordPrepActualQty = vi.hoisted(() => vi.fn());
/** 按分公司的包装器转接回本文件既有的 lookup mock(见 mainSystemBranchApi 的说明) */
vi.mock('../src/services/mainSystemBranchApi', () => ({
// 包装器与旧调用**同形**(第一参数=分公司/供应商,第二=items)⇒ 原样透传,既有断言不改
lookupPreparationStatesForBranch: (...a: unknown[]) => lookupMainSystemPreparationStates(...a),
fetchArchivedPreparationsForBranch: vi.fn(),
listRequestsForBranch: vi.fn(),
listSupplierCodesForBranch: vi.fn(async () => []),
groupItemsBySupplierCode: vi.fn(async () => new Map()),
}));
vi.mock('../src/db', () => ({
pool: { query: (...a: unknown[]) => query(...a), connect: vi.fn() },
getRawPoolQuery: () => query,
}));
vi.mock('../src/config', () => ({
config: {
mainSystemIntegration: {
fulfillmentEventsEnabled: true,
skipInboundAwaitPickup: true,
clientId: 'x',
clientSecret: 'y',
preparationsPath: '/api/supplier/preparations',
statusPath: '/api/supplier/preparations/status',
oauthPath: '/api/supplier/oauth/token',
},
mainSystem: { baseUrl: 'http://stub', timeoutMs: 1000 },
},
}));
vi.mock('../src/services/tenantDbContext', () => ({
runWithTenantDbContext: (...a: unknown[]) => runWithTenantDbContext(...a),
}));
vi.mock('../src/services/orderWorkflowFulfillmentService', () => ({
completeOrderWithoutDriverDelivery: (...a: unknown[]) => completeOrderWithoutDriverDelivery(...a),
finalizeOrderFulfillment: (...a: unknown[]) => finalizeOrderFulfillment(...a),
}));
vi.mock('../src/services/mainSystemPreparations', () => ({
lookupMainSystemPreparationStates: (...a: unknown[]) => lookupMainSystemPreparationStates(...a),
}));
vi.mock('../src/services/mainSystemPrepLedger', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystemPrepLedger')>();
return { ...actual, recordPrepActualQty: (...a: unknown[]) => recordPrepActualQty(...a) };
});
const {
handleFulfillmentEvent,
isFulfillmentEvent,
concludeByFulfillmentEvent,
PREP_PICKED_UP_EVENT,
PREP_INBOUND_COMPLETED_EVENT,
} = await import('../src/services/mainSystemFulfillmentEvents');
type QueryResult = { rows: unknown[]; rowCount: number };
/** 按 SQL 特征分派:台账订单号 / 我方订单状态 / 事件幂等占坑 / 事件更新 */
function mockDb(options: {
ourOrderCode?: string | null;
orderStatus?: number | null;
insertWins?: boolean;
}) {
const { ourOrderCode = 'ORD_API_1', orderStatus = 50, insertWins = true } = options;
query.mockImplementation(async (sql: string) => {
const text = String(sql);
if (text.includes('FROM public.main_system_order_imports')) {
return { rows: ourOrderCode ? [{ our_order_code: ourOrderCode }] : [], rowCount: ourOrderCode ? 1 : 0 } as QueryResult;
}
if (text.includes('SELECT order_status FROM orders')) {
return { rows: orderStatus === null ? [] : [{ order_status: orderStatus }], rowCount: orderStatus === null ? 0 : 1 } as QueryResult;
}
if (text.includes('INSERT INTO public.main_system_fulfillment_events')) {
return { rows: insertWins ? [{ id: 'evt-1' }] : [], rowCount: insertWins ? 1 : 0 } as QueryResult;
}
return { rows: [], rowCount: 1 } as QueryResult;
});
}
beforeEach(() => {
query.mockReset();
runWithTenantDbContext.mockReset().mockImplementation(async (_b: string, fn: () => unknown) => fn());
completeOrderWithoutDriverDelivery.mockReset().mockResolvedValue(true);
finalizeOrderFulfillment.mockReset().mockResolvedValue(true);
lookupMainSystemPreparationStates.mockReset();
recordPrepActualQty.mockReset().mockResolvedValue(undefined);
});
describe('事件名识别', () => {
it('只认两个履约事件', () => {
expect(isFulfillmentEvent('preparations.picked_up')).toBe(true);
expect(isFulfillmentEvent('preparations.inbound_completed')).toBe(true);
expect(isFulfillmentEvent('preparations.allocated')).toBe(false);
expect(isFulfillmentEvent('')).toBe(false);
});
});
describe('幂等:主系统侧不做持久去重,必须由我方兜住', () => {
it('重复投递 ⇒ duplicate=true,且不重复收口', async () => {
mockDb({ insertWins: false });
const result = await handleFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
mainOrderCode: 'ORD_WEB_1',
});
expect(result.duplicate).toBe(true);
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
});
it('首次投递 ⇒ 占坑成功并收口', async () => {
mockDb({ insertWins: true, orderStatus: 50 });
const result = await handleFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
mainOrderCode: 'ORD_WEB_1',
});
expect(result.duplicate).toBe(false);
expect(result.outcome.status).toBe('done');
expect(completeOrderWithoutDriverDelivery).toHaveBeenCalledTimes(1);
});
});
describe('C1 picked_up(免入库):停在 50 ⇒ 收口', () => {
it('订单在 50 ⇒ 走 completeOrderWithoutDriverDelivery(接受 30/50)', async () => {
mockDb({ orderStatus: 50 });
const outcome = await concludeByFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
ourOrderCode: 'ORD_API_1',
});
expect(outcome.status).toBe('done');
expect(completeOrderWithoutDriverDelivery).toHaveBeenCalledWith('ORD_API_1');
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
});
it('订单还在 45 ⇒ suspended,**不越级改状态**', async () => {
mockDb({ orderStatus: 45 });
const outcome = await concludeByFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
ourOrderCode: 'ORD_API_1',
});
expect(outcome.status).toBe('suspended');
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
});
});
describe('C2 inbound_completed(送仓):已发车到 60 ⇒ 收口', () => {
it('订单在 60 ⇒ 走 finalizeOrderFulfillment(接受 60)', async () => {
mockDb({ orderStatus: 60 });
const outcome = await concludeByFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_INBOUND_COMPLETED_EVENT,
ourOrderCode: 'ORD_API_1',
});
expect(outcome.status).toBe('done');
expect(finalizeOrderFulfillment).toHaveBeenCalledWith('ORD_API_1');
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
});
it('订单还在 50(我方尚未发车)⇒ suspended', async () => {
mockDb({ orderStatus: 50 });
const outcome = await concludeByFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_INBOUND_COMPLETED_EVENT,
ourOrderCode: 'ORD_API_1',
});
expect(outcome.status).toBe('suspended');
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
});
});
describe('边界', () => {
it('订单已 90 ⇒ done(幂等命中),不重复结案', async () => {
mockDb({ orderStatus: 90 });
const outcome = await concludeByFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
ourOrderCode: 'ORD_API_1',
});
expect(outcome.status).toBe('done');
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
});
it('我方订单不存在 ⇒ ignored', async () => {
mockDb({ orderStatus: null });
const outcome = await concludeByFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
ourOrderCode: 'ORD_API_MISSING',
});
expect(outcome.status).toBe('ignored');
});
it('台账无该主系统订单 ⇒ ignored(不是我们的单)', async () => {
mockDb({ ourOrderCode: null });
const result = await handleFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
mainOrderCode: 'ORD_WEB_OTHER',
});
expect(result.outcome.status).toBe('ignored');
expect(completeOrderWithoutDriverDelivery).not.toHaveBeenCalled();
});
it('零价闸门拦下 ⇒ suspended 且原因写明,**不绕过财务口径**', async () => {
mockDb({ orderStatus: 50 });
completeOrderWithoutDriverDelivery.mockRejectedValueOnce(
Object.assign(new Error('订单有 1 条明细售价为 0,请先补价后再签收'), { code: 'zero_price_blocked' })
);
const result = await handleFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
mainOrderCode: 'ORD_WEB_1',
});
expect(result.outcome.status).toBe('suspended');
expect(String(result.outcome.reason)).toContain('zero_price_blocked');
});
});
describe('实收量事实落账(铁律二:实收 ≠ 申报是常态)', () => {
it('带 actualQty 的行落台账;actualQty=null 的行不落(不得用申报量冒充)', async () => {
mockDb({ orderStatus: 50 });
await handleFulfillmentEvent({
branchCode: 'SUP1',
event: PREP_PICKED_UP_EVENT,
mainOrderCode: 'ORD_WEB_1',
rows: [
{
id: 'prep-1', orderCode: 'ORD_WEB_1', skuCode: 'S1', itemName: '西红柿', displayName: null,
prepareQty: 10, unit: '斤', orderQty: null, orderUnit: null, purchasePrice: 3.5,
suggestedPrice: null, prepareStatus: 30, deliveryDate: null, taskDay: null,
isStockout: false, processingMethod: null, returnCode: null, returnReason: null,
requiresQualityReport: false, orderItemRemark: null, skipInbound: true, isDirectDelivery: false,
actualQty: 9.5, actualQtyAt: '2026-10-10T05:10:00.000Z', qtyDiff: -0.5,
isInbounded: false, inboundAt: null, orderDepartedAt: null,
},
{
id: 'prep-2', orderCode: 'ORD_WEB_1', skuCode: 'S2', itemName: '土豆', displayName: null,
prepareQty: 5, unit: '斤', orderQty: null, orderUnit: null, purchasePrice: 2,
suggestedPrice: null, prepareStatus: 30, deliveryDate: null, taskDay: null,
isStockout: false, processingMethod: null, returnCode: null, returnReason: null,
requiresQualityReport: false, orderItemRemark: null, skipInbound: true, isDirectDelivery: false,
actualQty: null, actualQtyAt: null, qtyDiff: null,
isInbounded: false, inboundAt: null, orderDepartedAt: null,
},
],
});
expect(recordPrepActualQty).toHaveBeenCalledTimes(1);
expect(recordPrepActualQty.mock.calls[0][0]).toMatchObject({
branchCode: 'SUP1', prepId: 'prep-1', actualQty: 9.5, qtyDiff: -0.5,
});
});
});
describe('R3 履约字段:三处映射必须同改(防 2026-10-09「只改一处丢字段」重演)', () => {
// 2026-10-11:主系统备货接口按"模块化 + 接口封装"拆到 ./mainSystem/api/preparations.ts
// (mainSystemPreparations.ts 变成兼容门面),所以三处映射的锚点跟着实现文件走。
const prepSrc = readFileSync(path.join(__dirname, '../src/services/mainSystem/api/preparations.ts'), 'utf8');
const facadeSrc = readFileSync(path.join(__dirname, '../src/services/mainSystemPreparations.ts'), 'utf8');
const routeSrc = readFileSync(path.join(__dirname, '../src/routes/mainSystemIntegration.ts'), 'utf8');
const R3_KEYS = ['actual_qty', 'actual_qty_at', 'qty_diff', 'is_inbounded', 'inbound_at', 'order_departed_at'];
it('① 拉取(mapRow)与 ② lookup 两处都在 mainSystem/api/preparations.ts,且都映射 R3 字段', () => {
for (const key of R3_KEYS) {
const hits = [...prepSrc.matchAll(new RegExp(`raw\\?\\.${key}\\b`, 'g'))].length;
// 同一文件里两处映射(拉取 + lookup)⇒ 每个字段至少出现 2 次
expect(hits, `字段 ${key} 在 mainSystem/api/preparations.ts 只映射了 ${hits} 处(应为 ≥2)`).toBeGreaterThanOrEqual(2);
}
});
it('①′ 兼容门面仍从实现文件再导出(业务模块与测试都 import 门面路径,不得断)', () => {
expect(facadeSrc).toMatch(/from '\.\/mainSystem\/api\/preparations'/);
expect(facadeSrc).toMatch(/MainPreparationRow/);
});
it('③ webhook 载荷(mapWebhookRow)同样映射 R3 字段', () => {
for (const key of R3_KEYS) {
expect(routeSrc, `webhook 映射缺字段 ${key}`).toMatch(new RegExp(`raw\\?\\.${key}\\b`));
}
});
it('类型定义含 R3 字段(漏加字段会编译失败,这里再钉一道)', () => {
for (const field of ['actualQty', 'actualQtyAt', 'qtyDiff', 'isInbounded', 'inboundAt', 'orderDepartedAt']) {
expect(prepSrc).toMatch(new RegExp(`${field}:`));
}
});
});
describe('拉取兜底:性能纪律(不逐单打主系统)', () => {
it('N 张在途订单也只打 **1 次** lookup(内部按 500 分片),不是 N 次', async () => {
// 两张主系统订单 → 两张我方订单,都在 60(已发车送仓)
query.mockImplementation(async (sql: string) => {
const text = String(sql);
if (text.includes('FROM public.main_system_order_imports')) {
return {
rows: [
{ main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_A' },
{ main_order_code: 'ORD_WEB_B', our_order_code: 'ORD_API_B' },
],
rowCount: 2,
} as QueryResult;
}
if (text.includes('SELECT order_code, order_status FROM orders')) {
return {
rows: [
{ order_code: 'ORD_API_A', order_status: 60 },
{ order_code: 'ORD_API_B', order_status: 60 },
],
rowCount: 2,
} as QueryResult;
}
// 单张订单状态(concludeByFulfillmentEvent 用的那一条)
if (text.includes('SELECT order_status FROM orders')) {
return { rows: [{ order_status: 60 }], rowCount: 1 } as QueryResult;
}
if (text.includes('main_sku_code')) {
return {
rows: [
{ main_order_code: 'ORD_WEB_A', main_sku_code: 'S1' },
{ main_order_code: 'ORD_WEB_B', main_sku_code: 'S2' },
],
rowCount: 2,
} as QueryResult;
}
if (text.includes('INSERT INTO public.main_system_fulfillment_events')) {
return { rows: [{ id: 'e' }], rowCount: 1 } as QueryResult;
}
return { rows: [], rowCount: 1 } as QueryResult;
});
lookupMainSystemPreparationStates.mockResolvedValue({
kind: 'ok',
results: [
{ orderCode: 'ORD_WEB_A', skuCode: 'S1', isInbounded: true, orderItemPresent: true, orderDepartedAt: null },
{ orderCode: 'ORD_WEB_B', skuCode: 'S2', isInbounded: true, orderItemPresent: true, orderDepartedAt: null },
],
});
const { reconcileFulfillmentFromPull } = await import('../src/services/mainSystemFulfillmentEvents');
const result = await reconcileFulfillmentFromPull('SUP1');
// 关键断言:无论多少张单,lookup 只调一次
expect(lookupMainSystemPreparationStates).toHaveBeenCalledTimes(1);
const [, items] = lookupMainSystemPreparationStates.mock.calls[0] as [string, unknown[]];
expect(items).toHaveLength(2); // 两张单的行合并进同一次请求
expect(result.closed).toBe(2);
});
it('主系统问不到(lookup 失败)⇒ 一律不判定,不误收口', async () => {
query.mockImplementation(async (sql: string) => {
const text = String(sql);
if (text.includes('FROM public.main_system_order_imports')) {
return { rows: [{ main_order_code: 'ORD_WEB_A', our_order_code: 'ORD_API_A' }], rowCount: 1 } as QueryResult;
}
if (text.includes('SELECT order_code, order_status FROM orders')) {
return { rows: [{ order_code: 'ORD_API_A', order_status: 60 }], rowCount: 1 } as QueryResult;
}
if (text.includes('main_sku_code')) {
return { rows: [{ main_order_code: 'ORD_WEB_A', main_sku_code: 'S1' }], rowCount: 1 } as QueryResult;
}
return { rows: [], rowCount: 0 } as QueryResult;
});
lookupMainSystemPreparationStates.mockResolvedValue({ kind: 'unavailable', reason: '超时' });
const { reconcileFulfillmentFromPull } = await import('../src/services/mainSystemFulfillmentEvents');
const result = await reconcileFulfillmentFromPull('SUP1');
expect(result.closed).toBe(0);
expect(finalizeOrderFulfillment).not.toHaveBeenCalled();
});
});
describe('零反向写回(铁律一)的源码合同', () => {
const src = readFileSync(
path.join(__dirname, '../src/services/mainSystemFulfillmentEvents.ts'),
'utf8'
);
const configSrc = readFileSync(path.join(__dirname, '../src/config.ts'), 'utf8');
it('接收端不 import 任何"写主系统"的模块(回写状态 / 改价)', () => {
// 不得调用主系统的任何写接口
expect(src).not.toMatch(/writebackMainSystemPreparationStatus/);
expect(src).not.toMatch(/amend-price|amendPrice|prepAmendRequest/);
// 也不得触碰库存/成本(本批不做自动补库存,见设计文档 §6 D2)
expect(src).not.toMatch(/inventory_logs|inventoryAdjustService|cost_details/);
});
it('收口只走既有结案入口,不新造状态边', () => {
expect(src).toMatch(/completeOrderWithoutDriverDelivery/);
expect(src).toMatch(/finalizeOrderFulfillment/);
// 不得直接写 order_status(状态推进一律走既有函数)
expect(src).not.toMatch(/UPDATE\s+orders\s+SET\s+order_status/i);
});
it('两个开关 2026-10-11 定稿均改为默认开(`!== .0.` 才关)', () => {
// 成对:接收端负责收口 90,skipInbound 负责停在 50 等骑手取货;只翻一个就卡单
expect(configSrc).toMatch(
/fulfillmentEventsEnabled:\s*process\.env\.MAIN_SYSTEM_FULFILLMENT_EVENTS !== '0'/
);
// 默认开:`!== '0'` 才关(与 MAIN_SYSTEM_WRITEBACK 同风格);写成 0 即回退旧行为
expect(configSrc).toMatch(
/skipInboundAwaitPickup:\s*process\.env\.MAIN_SYSTEM_SKIP_INBOUND_AWAIT_PICKUP !== '0'/
);
// 两者是**一对**:配置注释必须写明"接收端关着则停在 50 收不了口",防止后人只翻一个开关
expect(configSrc).toMatch(/永远收不了口/);
});
});