Files
SupplierSystem/server/tests/mainSystemBranchApi.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

207 lines
8.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 { describe, expect, it, vi, beforeEach } from 'vitest';
/**
* 「按分公司」调用主系统只读接口的包装器(2026-10-10 接入编码收尾)。
*
* 钉住三件在生产上会**静默出错**的事:
* ① 行 → supplier_code 的归属**只认行级台账**;多绑定且台账缺失时**跳过**(不猜、不硬塞);
* ② 唯一绑定时才允许回退(老环境/首轮导入);
* ③ 逐供应商调用后**合并**结果;部分失败保留已成功的(兜底路径要能推进多少算多少),全失败才报错。
*/
const poolQuery = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...a: unknown[]) => poolQuery(...a), connect: vi.fn() },
getRawPoolQuery: () => poolQuery,
}));
const listBindings = vi.hoisted(() => vi.fn());
vi.mock('../src/services/branchAccessCode', () => ({
listActiveBindingsForBranch: (...a: unknown[]) => listBindings(...a),
}));
const lookupMock = vi.hoisted(() => vi.fn());
const archivedMock = vi.hoisted(() => vi.fn());
const listRequestsMock = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystemPreparations', () => ({
lookupMainSystemPreparationStates: (...a: unknown[]) => lookupMock(...a),
fetchMainSystemArchivedPreparations: (...a: unknown[]) => archivedMock(...a),
}));
vi.mock('../src/services/mainSystem/api/preparations', () => ({
listMainSystemRequests: (...a: unknown[]) => listRequestsMock(...a),
}));
const {
listSupplierCodesForBranch,
groupItemsBySupplierCode,
lookupPreparationStatesForBranch,
fetchArchivedPreparationsForBranch,
listRequestsForBranch,
} = await import('../src/services/mainSystemBranchApi');
function binding(mainSupplierCode: string, mainBranchCode = 'BR002') {
return {
branchCode: 'BR003',
accessCode: 'SCSTSHD6XVX4',
mainBranchCode,
mainSupplierCode,
status: 'active',
source: 'main_push',
boundAt: '2026-10-10T10:00:00.000Z',
unboundAt: null,
};
}
beforeEach(() => {
poolQuery.mockReset();
poolQuery.mockResolvedValue({ rows: [], rowCount: 0 });
listBindings.mockReset();
lookupMock.mockReset();
archivedMock.mockReset();
listRequestsMock.mockReset();
});
describe('分公司 → 供应商编码', () => {
it('多个绑定全部返回(去重、稳定顺序)', async () => {
listBindings.mockResolvedValue([binding('SUP_A'), binding('SUP_B'), binding('SUP_A', 'BR009')]);
expect(await listSupplierCodesForBranch('BR003')).toEqual(['SUP_A', 'SUP_B']);
});
it('未绑定时为空数组(调用方据此走 not_bound/跳过)', async () => {
listBindings.mockResolvedValue([]);
expect(await listSupplierCodesForBranch('BR003')).toEqual([]);
});
});
describe('行 → supplier_code 分组(只认台账)', () => {
it('按台账把行分到各自的供应商', async () => {
listBindings.mockResolvedValue([binding('SUP_A'), binding('SUP_B')]);
poolQuery.mockResolvedValue({
rows: [
{ prep_id: 'p1', main_supplier_code: 'SUP_A' },
{ prep_id: 'p2', main_supplier_code: 'SUP_B' },
],
rowCount: 2,
});
const groups = await groupItemsBySupplierCode({
branchCode: 'BR003',
items: [{ id: 'p1' }, { id: 'p2' }],
});
expect([...groups.keys()].sort()).toEqual(['SUP_A', 'SUP_B']);
expect(groups.get('SUP_A')?.[0]).toEqual({ id: 'p1' });
});
it('台账缺失但**只有一家**绑定 ⇒ 回退到它(老环境/首轮导入)', async () => {
listBindings.mockResolvedValue([binding('SUP_ONLY')]);
const groups = await groupItemsBySupplierCode({ branchCode: 'BR003', items: [{ id: 'p9' }] });
expect([...groups.keys()]).toEqual(['SUP_ONLY']);
});
it('台账缺失且**多家**绑定 ⇒ 跳过(不猜、不硬塞)', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
listBindings.mockResolvedValue([binding('SUP_A'), binding('SUP_B')]);
const groups = await groupItemsBySupplierCode({ branchCode: 'BR003', items: [{ id: 'p9' }] });
expect(groups.size).toBe(0);
expect(warn).toHaveBeenCalled();
warn.mockRestore();
});
});
describe('lookup:逐供应商调用并合并', () => {
it('两家的结果合并返回;调用参数是**供应商编码**而不是分公司编码', async () => {
listBindings.mockResolvedValue([binding('SUP_A'), binding('SUP_B')]);
poolQuery.mockResolvedValue({
rows: [
{ prep_id: 'p1', main_supplier_code: 'SUP_A' },
{ prep_id: 'p2', main_supplier_code: 'SUP_B' },
],
rowCount: 2,
});
lookupMock.mockImplementation(async (supplierCode: string, items: Array<{ id: string }>) => ({
kind: 'ok',
results: items.map((item) => ({ id: item.id, orderCode: 'O', skuCode: 'S', found: supplierCode === 'SUP_A' })),
}));
const outcome = await lookupPreparationStatesForBranch('BR003', [
{ orderCode: 'O', skuCode: 'S', id: 'p1' },
{ orderCode: 'O', skuCode: 'S', id: 'p2' },
]);
expect(outcome.kind).toBe('ok');
if (outcome.kind === 'ok') expect(outcome.results).toHaveLength(2);
expect(lookupMock.mock.calls.map((c) => c[0]).sort()).toEqual(['SUP_A', 'SUP_B']);
});
it('一家失败、一家成功 ⇒ **保留**成功结果(兜底路径能推进多少算多少)', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
listBindings.mockResolvedValue([binding('SUP_A'), binding('SUP_B')]);
poolQuery.mockResolvedValue({
rows: [
{ prep_id: 'p1', main_supplier_code: 'SUP_A' },
{ prep_id: 'p2', main_supplier_code: 'SUP_B' },
],
rowCount: 2,
});
lookupMock.mockImplementation(async (supplierCode: string, items: Array<{ id: string }>) =>
supplierCode === 'SUP_A'
? { kind: 'unavailable', reason: '超时' }
: { kind: 'ok', results: items.map((item) => ({ id: item.id, orderCode: 'O', skuCode: 'S', found: true })) }
);
const outcome = await lookupPreparationStatesForBranch('BR003', [
{ orderCode: 'O', skuCode: 'S', id: 'p1' },
{ orderCode: 'O', skuCode: 'S', id: 'p2' },
]);
expect(outcome.kind).toBe('ok');
if (outcome.kind === 'ok') expect(outcome.results.map((r) => r.id)).toEqual(['p2']);
warn.mockRestore();
});
it('全部失败 ⇒ 返回失败(调用方据此报"拉取失败")', async () => {
listBindings.mockResolvedValue([binding('SUP_A')]);
lookupMock.mockResolvedValue({ kind: 'unavailable', reason: 'forbidden: 未授权' });
const outcome = await lookupPreparationStatesForBranch('BR003', [
{ orderCode: 'O', skuCode: 'S', id: 'p1' },
]);
expect(outcome.kind).toBe('unavailable');
if (outcome.kind === 'unavailable') expect(outcome.reason).toContain('forbidden');
});
it('没有绑定 ⇒ 直接返回 unavailable(不发请求)', async () => {
listBindings.mockResolvedValue([]);
const outcome = await lookupPreparationStatesForBranch('BR003', [
{ orderCode: 'O', skuCode: 'S', id: 'p1' },
]);
expect(outcome.kind).toBe('unavailable');
expect(lookupMock).not.toHaveBeenCalled();
});
});
describe('归档视图 / 申请列表:遍历绑定并合并', () => {
it('归档:两家合并 orders/rowCount,任一 truncated 即为 truncated', async () => {
listBindings.mockResolvedValue([binding('SUP_A'), binding('SUP_B')]);
archivedMock
.mockResolvedValueOnce({ kind: 'ok', supplierCode: 'SUP_A', branchCode: 'BR002', orders: [{ orderCode: 'A' }], rowCount: 2, truncated: false })
.mockResolvedValueOnce({ kind: 'ok', supplierCode: 'SUP_B', branchCode: 'BR002', orders: [{ orderCode: 'B' }], rowCount: 3, truncated: true });
const outcome = await fetchArchivedPreparationsForBranch('BR003', { date: '2026-10-09' });
expect(outcome.kind).toBe('ok');
if (outcome.kind === 'ok') {
expect(outcome.orders.map((o) => o.orderCode)).toEqual(['A', 'B']);
expect(outcome.rowCount).toBe(5);
expect(outcome.truncated).toBe(true);
}
expect(archivedMock.mock.calls.map((c) => c[0])).toEqual(['SUP_A', 'SUP_B']);
});
it('申请列表:两家合并 rows;未绑定 ⇒ unavailable', async () => {
listBindings.mockResolvedValue([binding('SUP_A'), binding('SUP_B')]);
listRequestsMock
.mockResolvedValueOnce({ kind: 'ok', rows: [{ request_id: 'r1' }], truncated: false })
.mockResolvedValueOnce({ kind: 'ok', rows: [{ request_id: 'r2' }], truncated: false });
const merged = await listRequestsForBranch('BR003', { kind: 'actual_qty' });
expect(merged.kind).toBe('ok');
if (merged.kind === 'ok') expect(merged.rows.map((r) => r.request_id)).toEqual(['r1', 'r2']);
listBindings.mockResolvedValue([]);
const none = await listRequestsForBranch('BR003', { kind: 'actual_qty' });
expect(none.kind).toBe('unavailable');
});
});