背景:主系统第八批已交付(`22ef34a8` 绑定入口 + `0dad08f3` binding.changed 推送),本轮做对接体检。
体检发现的**我方**缺口(已修):
1. 回读通道鉴权不匹配:他们交付的 `GET /api/supplier/integration-bindings` 走
`Authorization: Bearer <对接 token>`(按 token 所属 client 圈作用域),
而我方初版按草稿发 `X-Client-Id`/`X-Client-Secret` ⇒ 会 401。已改为用
`getMainSystemToken()` 换 token 后 Bearer 调用;并补 `?include_disabled=1`
(默认只返回 status=1 ⇒ 不加就永远同步不到"解绑")。
supplier_code 取法:镜像 active 绑定 → 分公司手工登记 → 台账最近值;都没有则跳过(冷启动无绑定可对账)。
2. 「编码不认识」与「这家没绑我们」原先都回 `not_bound`,真机上分不清。现在单列
`unknown_access_code`(并 `console.warn` 打出编码原值)—— 抄错一位是这条路上最可能的人为错,
必须能从对方的投递日志/我方日志一眼看出。
体检发现(记录进清单 §2.11.4b,给我方待办):
· 他们的 `bindIntegrationSupplier()` **不校验编码格式**,错码会静默变成"没绑"⇒ 建议加正则
`^SC[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{10}$`(P1 加固,我们已用 warn + 独立 reason 兜住可观测性)。
体检结论(他们的实现与契约逐条对齐):
· 信封带 `subsystem_code`(`supplierPrepWebhookService.ts:149`,空码行为 null);
· `binding.changed` 推送:事件名/字段(同时给 subsystem_code 与 access_code)/改绑=unbind+bind/
目标解析不看 status(解绑也要推)✅;
· 迁移 `20261014_supplier_integration_subsystem_code.sql` 加列 + 部分索引,且**空码 = 存量行为不变**;
· P0-4:自动授权**只对已绑编码的行补**(`supplierIntegrationClientService.ts:420-440`)✅;
· 回读端点按 token 的 client 圈作用域(无跨客户端视图)✅。
验证:服务端 2333 用例 / 失败 30、失败文件 24 = 与基线逐字相同(无新增失败);
branchAccessCode 14 例 + branchBindingSync 16 例全绿;tsc 通过;门禁同基线(check-ai-cost 既知红)。
250 lines
11 KiB
TypeScript
250 lines
11 KiB
TypeScript
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||
|
||
/**
|
||
* 分公司「接入编码」与绑定路由(2026-10-27 设计,验收项 V1–V8 的可机检部分)。
|
||
*
|
||
* 钉住四件事(这几条错了就是**串单/漏单**,比报错更难查):
|
||
* ① 编码形态固定(`SC` + 10 位、无易混字符);
|
||
* ② 入站路由的**判定顺序**:我方编码 → 精确 (主系统分公司+供应商) → 唯一绑定 → 通配 → 拒收;
|
||
* ③ 「该主系统分公司有行但已解绑」必须 `not_bound`(尊重显式解绑,不得回落成"唯一绑定");
|
||
* ④ 多绑定且不知分公司 ⇒ **ambiguous 拒收**(宁可漏一单,也不张冠李戴)。
|
||
*
|
||
* 设计:docs/design/20261027-分公司接入编码与主系统供应商绑定.md §3.3 / §9
|
||
*/
|
||
|
||
const query = vi.hoisted(() => vi.fn());
|
||
vi.mock('../src/db', () => ({
|
||
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
|
||
getRawPoolQuery: () => query,
|
||
}));
|
||
|
||
const {
|
||
generateUniqueBranchAccessCode,
|
||
isBranchAccessCode,
|
||
resolveOurBranchByBinding,
|
||
upsertBinding,
|
||
resolveSupplierCodeForPrep,
|
||
} = await import('../src/services/branchAccessCode');
|
||
|
||
/** 让 pool.query 按 SQL 关键字返回预设结果(顺序敏感:先查分支编码,再查绑定行,再查台账) */
|
||
function mockQueries(handlers: Array<(sql: string, params: unknown[]) => unknown>) {
|
||
query.mockImplementation(async (sql: string, params: unknown[]) => {
|
||
for (const handler of handlers) {
|
||
const result = handler(String(sql), params ?? []);
|
||
if (result !== undefined) return result;
|
||
}
|
||
throw new Error(`未预期的 SQL:${String(sql).slice(0, 80)}`);
|
||
});
|
||
}
|
||
|
||
beforeEach(() => {
|
||
query.mockReset();
|
||
});
|
||
|
||
describe('接入编码形态(V1)', () => {
|
||
it('合法形态:SC + 10 位、字符集不含 0/O/1/I/L', () => {
|
||
expect(isBranchAccessCode('SC7K3Q9M2XTP')).toBe(true);
|
||
expect(isBranchAccessCode('sc7k3q9m2xtp')).toBe(true);
|
||
});
|
||
|
||
it('非法:长度不对、前缀不对、含易混字符、空值', () => {
|
||
expect(isBranchAccessCode('SC7K3Q9M2X')).toBe(false);
|
||
expect(isBranchAccessCode('SC7K3Q9M2XTPZ')).toBe(false);
|
||
expect(isBranchAccessCode('XX7K3Q9M2XT')).toBe(false);
|
||
expect(isBranchAccessCode('SC7K3Q9M2X0')).toBe(false);
|
||
expect(isBranchAccessCode('SC7K3Q9M2XO')).toBe(false);
|
||
expect(isBranchAccessCode('')).toBe(false);
|
||
expect(isBranchAccessCode(null)).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('编码生成:撞码只会重试,退役码不复用', () => {
|
||
it('查重同时覆盖 branches 与绑定历史(分公司删了码也不回收)', async () => {
|
||
const sqls: string[] = [];
|
||
let calls = 0;
|
||
query.mockImplementation(async (sql: string) => {
|
||
sqls.push(String(sql));
|
||
if (String(sql).includes('access_code = $1')) {
|
||
calls += 1;
|
||
// 第一次"撞码" ⇒ 必须重试;第二次放行
|
||
return calls === 1 ? { rowCount: 1, rows: [{ '?column?': 1 }] } : { rowCount: 0, rows: [] };
|
||
}
|
||
throw new Error(`未预期的 SQL:${String(sql).slice(0, 60)}`);
|
||
});
|
||
const code = await generateUniqueBranchAccessCode();
|
||
expect(isBranchAccessCode(code), `生成的编码应合法:${code}`).toBe(true);
|
||
expect(calls, '第一次撞码后必须重试一次').toBe(2);
|
||
expect(sqls[0]).toContain('public.branches');
|
||
expect(sqls[0], '必须同时查绑定历史,否则删掉分公司后编码会被回收').toContain('public.main_supplier_bindings');
|
||
});
|
||
|
||
it('连续撞码 20 次 ⇒ 抛错(不返回可疑编码)', async () => {
|
||
query.mockImplementation(async () => ({ rowCount: 1, rows: [{ '?column?': 1 }] }));
|
||
await expect(generateUniqueBranchAccessCode()).rejects.toThrow('连续 20 次撞唯一键');
|
||
});
|
||
});
|
||
|
||
describe('入站路由(V2–V6)', () => {
|
||
it('① 带了我们的 subsystem_code ⇒ 直接按我方编码定位(最稳)', async () => {
|
||
mockQueries([
|
||
(sql) => (sql.includes('FROM public.branches WHERE access_code') ? { rows: [{ branch_code: 'BR007' }] } : undefined),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ subsystemCode: 'SC7K3Q9M2XTP', supplierCode: 'SUP1' });
|
||
expect(r).toEqual({ ok: true, branchCode: 'BR007', binding: null, via: 'access_code' });
|
||
});
|
||
|
||
it('编码不认识 ⇒ unknown_access_code(单列一个原因:真机上 99% 是抄错一位)', async () => {
|
||
mockQueries([(sql) => (sql.includes('FROM public.branches WHERE access_code') ? { rows: [] } : undefined)]);
|
||
const r = await resolveOurBranchByBinding({ subsystemCode: 'SCZZZZZZZZZZ', supplierCode: 'SUP1' });
|
||
expect(r.ok).toBe(false);
|
||
if (!r.ok) expect(r.reason).toBe('unknown_access_code');
|
||
});
|
||
|
||
it('② 精确命中 (主系统分公司 + 供应商)', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [
|
||
{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'active' },
|
||
{ branch_code: 'BR008', main_branch_code: 'BR003', main_supplier_code: 'SUP1', status: 'active' },
|
||
],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR003' });
|
||
expect(r.ok).toBe(true);
|
||
if (r.ok) {
|
||
expect(r.branchCode).toBe('BR008');
|
||
expect(r.via).toBe('exact');
|
||
}
|
||
});
|
||
|
||
it('③ 该主系统分公司有行、但已解绑 ⇒ not_bound(不得回落成"唯一绑定")', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [
|
||
{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'unbound' },
|
||
{ branch_code: 'BR008', main_branch_code: 'BR003', main_supplier_code: 'SUP1', status: 'active' },
|
||
],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR002' });
|
||
expect(r.ok).toBe(false);
|
||
if (!r.ok) expect(r.reason).toBe('not_bound');
|
||
});
|
||
|
||
it('④ 分公司未知、该供应商只有一家我方分公司在绑 ⇒ 唯一命中', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'active' }],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1' });
|
||
expect(r.ok).toBe(true);
|
||
if (r.ok) {
|
||
expect(r.branchCode).toBe('BR007');
|
||
expect(r.via).toBe('unique_supplier');
|
||
}
|
||
});
|
||
|
||
it('⑤ 分公司未知 + 多家在绑 ⇒ ambiguous **拒收**(不猜)', async () => {
|
||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||
mockQueries([
|
||
() => ({
|
||
rows: [
|
||
{ branch_code: 'BR007', main_branch_code: 'BR002', main_supplier_code: 'SUP1', status: 'active' },
|
||
{ branch_code: 'BR008', main_branch_code: 'BR003', main_supplier_code: 'SUP1', status: 'active' },
|
||
],
|
||
}),
|
||
]);
|
||
const r = await resolveOurBranchByBinding({ supplierCode: 'SUP1' });
|
||
expect(r.ok).toBe(false);
|
||
if (!r.ok) expect(r.reason).toBe('ambiguous');
|
||
warn.mockRestore();
|
||
});
|
||
|
||
it('通配行(`*`)在精确行缺失时兜底;完全没绑 ⇒ not_bound;无供应商编码 ⇒ missing_supplier_code', async () => {
|
||
mockQueries([
|
||
() => ({
|
||
rows: [{ branch_code: 'BR007', main_branch_code: '*', main_supplier_code: 'SUP1', status: 'active' }],
|
||
}),
|
||
]);
|
||
const wild = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR009' });
|
||
expect(wild.ok).toBe(true);
|
||
if (wild.ok) expect(wild.via).toBe('wildcard');
|
||
|
||
query.mockReset();
|
||
mockQueries([() => ({ rows: [] })]);
|
||
const none = await resolveOurBranchByBinding({ supplierCode: 'SUP1', mainBranchCode: 'BR009' });
|
||
expect(none.ok).toBe(false);
|
||
if (!none.ok) expect(none.reason).toBe('not_bound');
|
||
|
||
query.mockReset();
|
||
mockQueries([]);
|
||
const missing = await resolveOurBranchByBinding({ supplierCode: '' });
|
||
expect(missing.ok).toBe(false);
|
||
if (!missing.ok) expect(missing.reason).toBe('missing_supplier_code');
|
||
});
|
||
});
|
||
|
||
describe('绑定登记:改绑要留痕(V7)', () => {
|
||
it('同一 (主系统分公司+供应商) 改绑到另一家 ⇒ 旧行转 unbound 并记 note', async () => {
|
||
const calls: Array<{ sql: string; params: unknown[] }> = [];
|
||
mockQueries([
|
||
(sql, params) => {
|
||
calls.push({ sql, params });
|
||
if (sql.includes('SELECT branch_code FROM public.main_supplier_bindings')) {
|
||
return { rows: [{ branch_code: 'BR007' }] };
|
||
}
|
||
if (sql.includes('UPDATE public.main_supplier_bindings')) return { rowCount: 1 };
|
||
if (sql.includes('INSERT INTO public.main_supplier_bindings')) return { rowCount: 1 };
|
||
return undefined;
|
||
},
|
||
]);
|
||
const result = await upsertBinding({
|
||
branchCode: 'BR008',
|
||
accessCode: 'sc7k3q9m2xtp',
|
||
mainBranchCode: 'br002',
|
||
mainSupplierCode: 'sup1',
|
||
source: 'main_push',
|
||
});
|
||
expect(result.previousBranchCode).toBe('BR007');
|
||
const unbind = calls.find((c) => c.sql.includes('UPDATE public.main_supplier_bindings') && c.sql.includes("status = 'unbound'"));
|
||
expect(unbind, '必须先把旧行转 unbound(留痕)').toBeTruthy();
|
||
const insert = calls.find((c) => c.sql.includes('INSERT INTO public.main_supplier_bindings'));
|
||
expect(insert?.params[1]).toBe('SC7K3Q9M2XTP');
|
||
expect(insert?.params[2]).toBe('BR002');
|
||
expect(insert?.params[3]).toBe('SUP1');
|
||
// 改绑后原行应保留(不删数据):只 UPDATE 状态,不 DELETE
|
||
expect(calls.some((c) => c.sql.includes('DELETE FROM public.main_supplier_bindings'))).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe('出站 supplier_code 解析(接入编码 ≠ 对方 supplier_code)', () => {
|
||
it('优先取行级台账的 main_supplier_code', async () => {
|
||
mockQueries([
|
||
(sql) =>
|
||
sql.includes('FROM public.main_system_order_import_items')
|
||
? { rows: [{ main_supplier_code: 'SUP_F' }] }
|
||
: undefined,
|
||
]);
|
||
expect(await resolveSupplierCodeForPrep({ branchCode: 'BR007', prepId: 'p1' })).toBe('SUP_F');
|
||
});
|
||
|
||
it('台账没有 ⇒ 退该分公司唯一生效绑定;多于一条或没有 ⇒ null(不猜)', async () => {
|
||
mockQueries([
|
||
(sql) => (sql.includes('FROM public.main_system_order_import_items') ? { rows: [] } : undefined),
|
||
(sql) =>
|
||
sql.includes('FROM public.main_supplier_bindings')
|
||
? { rows: [{ branch_code: 'BR007', access_code: 'SC7K3Q9M2XTP', main_branch_code: '*', main_supplier_code: 'SUP_ONLY', status: 'active', source: 'manual', bound_at: new Date(), unbound_at: null }] }
|
||
: undefined,
|
||
]);
|
||
expect(await resolveSupplierCodeForPrep({ branchCode: 'BR007', prepId: 'p1' })).toBe('SUP_ONLY');
|
||
|
||
query.mockReset();
|
||
mockQueries([
|
||
(sql) => (sql.includes('FROM public.main_system_order_import_items') ? { rows: [] } : undefined),
|
||
(sql) => (sql.includes('FROM public.main_supplier_bindings') ? { rows: [] } : undefined),
|
||
]);
|
||
expect(await resolveSupplierCodeForPrep({ branchCode: 'BR007', prepId: 'p1' })).toBeNull();
|
||
});
|
||
});
|