Files
SupplierSystem/server/tests/mainSystemBranchApi.test.ts
T
Ubuntu 44a660e18a
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
perf(跨系统): 出站闸门唯一化 + 无未决不拉(未绑编码 = 零沟通)
开发者要求:未绑接入编码的分公司全程不该与主系统沟通;后面可能几千家,
有的连主系统有的不连。核查发现 8-13 的收紧只闸住了"拉货"一条路:

- 申请列表 Q5/Q6(实收对账 / 我方价量对账 / 归档反查 / 按行分组)仍读"任何 active 绑定"
  ⇒ 迁移回填行、空接入编码行也解析出 supplier_code ⇒ 抱着注定 403 的编码换 Token + 发 GET
  (对方已收紧为「必须有接入编码才放行」,回执 §4.5.22)
- 定时对账 fan-out 名单用"有任何 active 绑定行"⇒ 这些分公司每轮白跑一遍
- 两条对账**先拉后判**:本地一条待审都没有也每 10 分钟发一次 GET

P1(判定点唯一):
- branchAccessCode:新增 listConnectableBindingsForBranch(四条规则压进一条 JOIN)+
  listConnectableBranchCodes(同谓词的分公司名单);listAutoPullableBindingsForBranch 保留旧名转发
- mainSystemBranchApi.listSupplierCodesForBranch → 同一判定点(出站正门)
- mainSystemOrderImport.listMainSupplierBranchCodes → listConnectableBranchCodes(fan-out 名单)

P2(无未决 ⇒ 不拉):
- reconcilePendingActualQtyRequests / reconcileOurPriceQtyRequestsWithMainSystem
  先查本地待审计数(轻查询),为 0 直接返回 —— 两者本来就只处理本地 pending 行,语义无变化

验证(真库冒烟,本地栈):
- 已绑编码的 BR002/BR003:仍进名单、仍解析出 1/2 条编码、拉取 ok(真 HTTP);
  真跑 fan-out branches=2 / failed=0
- 反证:临时清空 BR003 编码 ⇒ 名单 ["BR002"]、编码 []、拉取 not_bound(零 HTTP),BR002 不受影响;
  夹具已还原(残留 0)
- P2:0 条待审 ⇒ 跳过拉取;BR002 现库 1 条真实待审 ⇒ 不短路照旧拉;探针待审 ⇒ 立刻恢复真拉取
- 用例:mainSystemReconcileShortCircuit.test.ts(4 例,新)+ bindingAutoPullGuard P1/P2 段(14 例)
  + mainSystemBranchApi(11 例);服务端 tsc 0 错;全量 26 failed/377 passed 与基线持平
- 设计文 docs/design/20261013-主系统订单被本地拉取机制与绑定缺陷.md §9(收益估算:1000 家 43万→14万 GET/天)
2026-10-13 14:28:30 +08:00

209 lines
8.9 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', () => ({
// 2026-10-13:出站判定点统一为 `listConnectableBindingsForBranch`(与拉货侧同一实现)
listConnectableBindingsForBranch: (...a: unknown[]) => listBindings(...a),
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');
});
});