Files
SupplierSystem/server/tests/bindingAutoPullGuard.test.ts
T
Ubuntu 2fcf6f495a fix(绑定收紧): 未绑接入编码不再拉货 —— 回填/空码/编码不一致的绑定一律不自动拉
开发者:「供应商系统的编码明明没有给主系统绑定,但是就是分配过来了,存在问题」
(对应远端已记录的 §2.13「P0-空码放行」+ 设计文档 §6 G1 待裁决项)

根因(两侧各一半,真库核实):
- 主系统侧:supplier_integration_client_suppliers 的「凭据→供应商」授权不要求 subsystem_code;
  实测本地主系统 5 条授权里 2 条 subsystem_code IS NULL(SUP35143228 已停用 / SUP92185841 有效)
  ⇒ 空码也能换 Token 拉到备货(已请对方给口径,见对接清单 §2.13)
- 我方侧:migrations/20261031 的迁移回填会给"只有 branches.main_supplier_code、无主系统证据"的
  分公司建一条 main_branch_code='*' 的 active 通配绑定 ⇒ 本地据此主动去拉,于是"没绑也收到了货"

本次收紧(我方侧,G1 裁决为"收紧"):
1) 新增 branchAccessCode.listAutoPullableBindingsForBranch():自动拉单只认
   「主系统明确把我方接入编码绑到该供应商」的绑定 —— backfill(迁移回填/无证据通配)、
   空接入编码、分公司当前无编码、编码已换的残留行一律不拉
2) mainSystemBranchPull 改用它;只存在不可拉绑定时给区分性 not_bound 文案且不发任何 HTTP
3) 展示路径不变:listBindingsForBranch 仍把回填行显示给运营(含来源列),只是不再据它拉货
4) 环境隔离自检:MAIN_SYSTEM_BASE_URL 指向非本机 + 开着自动拉单/回写 ⇒ 启动醒目告警
   (warnIfRemoteMainSystemWithWriteback;只告警、不改配置)——事故里"本地 dev 连线上拉货"那一层

真库验证(本地库):
- 现有 3 条 main_push 绑定(接入编码与分公司当前编码一致)⇒ 照常可拉,无回归
- 复现事故:临时插入 source='backfill'、main_branch_code='*' 的通配绑定(SUP92185841)
  ⇒ 该供应商不进可拉列表,实际拉取只发 SUP41472132/SUP04604778 两次 = 未绑不再拉;夹具残留 0

测试:新增 server/tests/bindingAutoPullGuard.test.ts 6 例;绑定相关 4 文件 32 例全绿。
文档:20261013-主系统订单被本地拉取机制与绑定缺陷.md 追加 §8(改动/真库验证/仍未闭合的那一半)
并把 §6 G1 标为已裁决收紧、G2 标为已加启动告警;对接清单 §2.13 四、① 标为已落地。
2026-10-13 11:16:25 +08:00

150 lines
5.9 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest';
import { readFileSync } from 'node:fs';
import path from 'node:path';
/**
* 「未绑接入编码却拉到货」的**我方侧收紧**(2026-10-13)。
*
* 事故:开发者「接入编码明明没给主系统绑定,订单却被分配过来了」(真机样本
* `ORD_API_20261013_SUP35143228_0001`)。两层根因:
* ① 主系统侧:`supplier_integration_client_suppliers` 的"凭据→供应商"授权**不要求**填
* `subsystem_code`(实测本地主系统 5 条授权里 2 条为 NULL)⇒ 空码也能换 Token 拉货
* (已记入 `docs/给主系统AI的对接改造清单.md` §2.13「P0-空码放行」待对方裁决);
* ② 我方侧:`migrations/20261031` 的**迁移回填**会建 `main_branch_code='*'` 的 active 通配绑定,
* 本地据此**主动去拉**。
*
* 本文件钉住 ② 的封堵:自动拉单只认「主系统明确把我们的接入编码绑到了该供应商」的绑定。
*/
const query = vi.hoisted(() => vi.fn());
const fetchPreps = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => query(...args) },
}));
vi.mock('../src/services/mainSystemPreparations', () => ({
fetchMainSystemPreparations: (...args: unknown[]) => fetchPreps(...args),
}));
import { listAutoPullableBindingsForBranch } from '../src/services/branchAccessCode';
import { pullPreparationsForBranch } from '../src/services/mainSystemBranchPull';
const pullSrc = readFileSync(
path.join(__dirname, '../src/services/mainSystemBranchPull.ts'),
'utf8'
);
const accessSrc = readFileSync(
path.join(__dirname, '../src/services/branchAccessCode.ts'),
'utf8'
);
const mainConfigSrc = readFileSync(
path.join(__dirname, '../src/services/mainSystem/config.ts'),
'utf8'
);
const indexSrc = readFileSync(path.join(__dirname, '../src/index.ts'), 'utf8');
type Row = {
branch_code: string;
access_code: string;
main_branch_code: string;
main_supplier_code: string;
status: string;
source: string;
bound_at: string;
unbound_at: string | null;
};
const row = (over: Partial<Row> = {}): Row => ({
branch_code: 'BR003',
access_code: 'SCSTSHD6XVX4',
main_branch_code: 'BR002',
main_supplier_code: 'SUP41472132',
status: 'active',
source: 'main_push',
bound_at: '2026-10-10T09:50:31.130Z',
unbound_at: null,
...over,
});
function wire(bindings: Row[], currentAccessCode: string | null) {
query.mockImplementation((sql: string) => {
const text = String(sql);
if (text.includes('FROM public.main_supplier_bindings')) {
return Promise.resolve({ rows: bindings, rowCount: bindings.length });
}
if (text.includes('access_code FROM public.branches')) {
return Promise.resolve({
rows: currentAccessCode === null ? [] : [{ access_code: currentAccessCode }],
rowCount: currentAccessCode === null ? 0 : 1,
});
}
throw new Error(`未预期的 SQL: ${text.slice(0, 60)}`);
});
}
describe('自动拉单只认「接入编码已绑给主系统」的绑定', () => {
beforeEach(() => {
query.mockReset();
fetchPreps.mockReset();
});
it('① 过滤:回填行 / 空接入编码 / 编码已换的残留行 一律不参与自动拉单', async () => {
wire(
[
row({ main_supplier_code: 'SUP_OK', source: 'main_push' }),
row({ main_supplier_code: 'SUP_BACKFILL', source: 'backfill' }),
row({ main_supplier_code: 'SUP_EMPTY', access_code: '' }),
row({ main_supplier_code: 'SUP_STALE', access_code: 'SC-OLD-CODE' }),
row({ main_supplier_code: 'SUP_MANUAL', source: 'manual' }),
],
'SCSTSHD6XVX4'
);
const pullable = await listAutoPullableBindingsForBranch('BR003');
expect(pullable.map((b) => b.mainSupplierCode)).toEqual(['SUP_OK', 'SUP_MANUAL']);
});
it('② 分公司没有接入编码时,任何绑定都不自动拉(无法自证归属)', async () => {
wire([row()], null);
expect(await listAutoPullableBindingsForBranch('BR003')).toEqual([]);
});
it('③ 回填行 ⇒ 拉取返回 not_bound,且**不发任何 HTTP**', async () => {
wire([row({ source: 'backfill', main_branch_code: '*' })], 'SCSTSHD6XVX4');
const out = await pullPreparationsForBranch('BR003', 'active');
expect(out.kind).toBe('not_bound');
if (out.kind === 'not_bound') {
expect(out.reason).toContain('接入编码已绑给主系统');
}
expect(fetchPreps).not.toHaveBeenCalled();
});
it('④ 正常绑定(主系统推送过接入编码)⇒ 照常拉取', async () => {
wire([row()], 'SCSTSHD6XVX4');
fetchPreps.mockResolvedValue({
kind: 'ok',
rows: [{ orderCode: 'ORD_WEB_X', skuCode: 'SKU1', supplierCode: 'SUP41472132' }],
});
const out = await pullPreparationsForBranch('BR003', 'active');
expect(out.kind).toBe('ok');
expect(fetchPreps).toHaveBeenCalledTimes(1);
expect(fetchPreps.mock.calls[0][0]).toBe('SUP41472132');
});
it('⑤ 源码守卫:拉取路径必须走收紧后的绑定查询;展示路径保留原样', () => {
expect(pullSrc).toContain('listAutoPullableBindingsForBranch');
expect(accessSrc).toContain('export async function listAutoPullableBindingsForBranch');
expect(accessSrc).toContain("=== 'backfill'");
// 展示/排查仍要看得到回填行(含来源列),不得把原函数删掉
expect(accessSrc).toContain('export async function listBindingsForBranch');
});
});
describe('环境隔离自检(事故后补:本地 dev 指向线上 + 自动拉单 ⇒ 可读可写线上)', () => {
it('⑥ 非本机地址 + 自动拉单/回写开启时告警一次;本机地址不告警', () => {
expect(mainConfigSrc).toContain('export function warnIfRemoteMainSystemWithWriteback');
expect(mainConfigSrc).toContain("host === 'localhost'");
expect(mainConfigSrc).toContain('环境隔离告警');
// 进程启动时自检
expect(indexSrc).toContain('warnIfRemoteMainSystemWithWriteback');
});
});