Files
SupplierSystem/server/tests/branchBindingSync.test.ts
T
Ubuntu e1efe3b2e9
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(对接体检): 回读通道鉴权改为 Bearer(与主系统实现对齐)+ 编码不认识单列原因并 warn
背景:主系统第八批已交付(`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 既知红)。
2026-10-10 17:47:39 +08:00

272 lines
12 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';
/**
* 绑定关系**同步接收端**(2026-10-27 接入编码设计 §8 P0-2)。
*
* 为什么值得单独钉:绑定是我方路由与拉单的**唯一依据**("编码没被绑定就收不到"),
* 而这份绑定只有两个来源 —— 主系统回调 `binding.changed`(复用 webhook 通道)与
* 只读端点回读。两条通道写的是同一张表,因此判定必须一致、且**不认识就忽略**(绝不猜、不建数据)。
*/
const findBranch = vi.hoisted(() => vi.fn());
const upsert = vi.hoisted(() => vi.fn());
const unbind = vi.hoisted(() => vi.fn());
vi.mock('../src/services/branchAccessCode', () => ({
findBranchCodeByAccessCode: (...args: unknown[]) => findBranch(...args),
upsertBinding: (...args: unknown[]) => upsert(...args),
unbindBinding: (...args: unknown[]) => unbind(...args),
}));
const fetchMock = vi.hoisted(() => vi.fn());
vi.stubGlobal('fetch', fetchMock);
const poolQuery = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => poolQuery(...args), connect: vi.fn() },
getRawPoolQuery: () => poolQuery,
}));
const tokenMock = vi.hoisted(() => vi.fn());
vi.mock('../src/services/mainSystem/token', () => ({
getMainSystemToken: (...args: unknown[]) => tokenMock(...args),
}));
const {
isBindingChangedEvent,
parseBindingChange,
parseBindingChangePayload,
applyBindingChange,
applyBindingSnapshot,
syncMainSystemBindings,
} = await import('../src/services/branchBindingSync');
beforeEach(() => {
poolQuery.mockReset();
poolQuery.mockResolvedValue({ rows: [{ code: 'SUP_BOUND' }], rowCount: 1 } as never);
tokenMock.mockReset();
tokenMock.mockResolvedValue({ kind: 'ok', token: 'tok-1', branchCode: 'BR002', expiresAt: Date.now() + 60000 });
findBranch.mockReset();
upsert.mockReset();
unbind.mockReset();
fetchMock.mockReset();
});
describe('事件名与载荷解析(容错但不含糊)', () => {
it('认这三种写法,别的都不认', () => {
for (const name of ['binding.changed', 'preparations.binding_changed', 'supplier.binding_changed']) {
expect(isBindingChangedEvent(name), name).toBe(true);
}
expect(isBindingChangedEvent('preparations.allocated')).toBe(false);
expect(isBindingChangedEvent('')).toBe(false);
expect(isBindingChangedEvent(undefined)).toBe(false);
});
it('字段名兼容:subsystem_code/access_code、branch_code/main_branch_code、supplier_code', () => {
expect(
parseBindingChange({
subsystem_code: 'sc7k3q9m2xtp',
branch_code: 'br002',
supplier_code: 'sup1',
action: 'bind',
})
).toEqual({ accessCode: 'sc7k3q9m2xtp', mainBranchCode: 'br002', mainSupplierCode: 'sup1', action: 'bind' });
expect(
parseBindingChange({ access_code: 'SC1', main_branch_code: 'BR2', main_supplier_code: 'SUP3' })
).toEqual({ accessCode: 'SC1', mainBranchCode: 'BR2', mainSupplierCode: 'SUP3', action: 'bind' });
});
it('缺编码或缺供应商标记为不可解析(整条丢掉,不猜)', () => {
expect(parseBindingChange({ supplier_code: 'SUP1' })).toBeNull();
expect(parseBindingChange({ subsystem_code: 'SC1' })).toBeNull();
expect(parseBindingChange(null)).toBeNull();
});
it('解绑动作的多种写法都归一为 unbind;缺省 = bind', () => {
for (const action of ['unbind', 'UNBOUND', 'remove', 'detach']) {
expect(parseBindingChange({ subsystem_code: 'SC1', supplier_code: 'S1', action })?.action).toBe('unbind');
}
expect(parseBindingChange({ subsystem_code: 'SC1', supplier_code: 'S1' })?.action).toBe('bind');
});
it('批量形式:`bindings: [...]` 与 `data: [...]` 都支持,坏的条目被跳过', () => {
const batch = parseBindingChangePayload({
event: 'binding.changed',
bindings: [
{ subsystem_code: 'SC1', supplier_code: 'SUP1', branch_code: 'BR1' },
{ subsystem_code: '', supplier_code: 'SUP2' },
{ subsystem_code: 'SC2', supplier_code: 'SUP3', branch_code: 'BR2', action: 'unbind' },
],
});
expect(batch).toHaveLength(2);
expect(batch[1].action).toBe('unbind');
const single = parseBindingChangePayload({ subsystem_code: 'SC9', supplier_code: 'SUP9' });
expect(single).toHaveLength(1);
});
});
describe('落到绑定表(唯一写入口)', () => {
it('绑定:按接入编码定位分公司 ⇒ upsert,并带回"改绑前是哪家"', async () => {
findBranch.mockResolvedValue('BR007');
upsert.mockResolvedValue({ branchCode: 'BR007', previousBranchCode: 'BR008' });
const r = await applyBindingChange(
{ accessCode: 'sc7k3q9m2xtp', mainBranchCode: 'br002', mainSupplierCode: 'sup1', action: 'bind' },
'main_push'
);
expect(r.status).toBe('applied');
expect(r.branchCode).toBe('BR007');
expect(r.previousBranchCode).toBe('BR008');
expect(upsert).toHaveBeenCalledWith(
expect.objectContaining({
branchCode: 'BR007',
accessCode: 'SC7K3Q9M2XTP',
mainBranchCode: 'BR002',
mainSupplierCode: 'SUP1',
source: 'main_push',
})
);
});
it('分公司未知(主系统分公司没给)⇒ 记通配 `*`,不是丢弃', async () => {
findBranch.mockResolvedValue('BR007');
upsert.mockResolvedValue({ branchCode: 'BR007', previousBranchCode: null });
await applyBindingChange({ accessCode: 'SC1', mainBranchCode: null, mainSupplierCode: 'SUP1', action: 'bind' }, 'main_push');
expect(upsert.mock.calls[0][0].mainBranchCode).toBe('*');
});
it('编码不认识 ⇒ ignored/unknown_access_code,**零写入**', async () => {
findBranch.mockResolvedValue(null);
const r = await applyBindingChange(
{ accessCode: 'SCZZZZZZZZZZ', mainBranchCode: 'BR002', mainSupplierCode: 'SUP1', action: 'bind' },
'main_push'
);
expect(r.status).toBe('ignored');
expect(r.reason).toBe('unknown_access_code');
expect(upsert).not.toHaveBeenCalled();
expect(unbind).not.toHaveBeenCalled();
});
it('解绑:对方没绑过(无 active 行)也算成功语义但记 ignored(幂等,不报错)', async () => {
findBranch.mockResolvedValue('BR007');
unbind.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
const first = await applyBindingChange(
{ accessCode: 'SC1', mainBranchCode: 'BR002', mainSupplierCode: 'SUP1', action: 'unbind' },
'main_push'
);
const second = await applyBindingChange(
{ accessCode: 'SC1', mainBranchCode: 'BR002', mainSupplierCode: 'SUP1', action: 'unbind' },
'main_push'
);
expect(first.status).toBe('unbound');
expect(second.status).toBe('ignored');
expect(second.reason).toBe('no_active_binding');
});
});
describe('回读(退路通道)', () => {
it('未配置 URL ⇒ 直接跳过(不猜路径、不发请求)', async () => {
const { config } = await import('../src/config');
const original = config.mainSystemIntegration.bindingSyncUrl;
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = '';
const r = await syncMainSystemBindings();
expect(r.checked).toBe(0);
expect(r.reason).toContain('MAIN_SYSTEM_BINDING_SYNC_URL');
expect(fetchMock).not.toHaveBeenCalled();
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original;
});
it('配了 URL ⇒ 用**对接 token**(Bearer)请求,并带 include_disabled=1(否则解绑同步不到)', async () => {
const { config } = await import('../src/config');
const original = config.mainSystemIntegration.bindingSyncUrl;
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl =
'http://127.0.0.1:3001/api/supplier/integration-bindings';
fetchMock.mockResolvedValue({
ok: true,
status: 200,
json: async () => ({
data: [{ branch_code: 'BR002', supplier_code: 'SUP1', subsystem_code: 'SC1', status: 1 }],
}),
});
findBranch.mockResolvedValue('BR007');
upsert.mockResolvedValue({ branchCode: 'BR007', previousBranchCode: null });
const r = await syncMainSystemBindings();
expect(tokenMock).toHaveBeenCalledWith('SUP_BOUND');
const [url, init] = fetchMock.mock.calls[0] as [string, { headers: Record<string, string> }];
expect(url).toContain('include_disabled=1');
expect(init.headers.Authorization).toBe('Bearer tok-1');
// ⚠️ 初版发的是 X-Client-Id/_Secret,与他们的实现不匹配 —— 这条钉住不许回退
expect(init.headers['X-Client-Secret']).toBeUndefined();
expect(r.applied).toBe(1);
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original;
});
it('没有任何已知供应商 ⇒ 跳过(换不到 token),不发请求', async () => {
const { config } = await import('../src/config');
const original = config.mainSystemIntegration.bindingSyncUrl;
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = 'http://x/y';
for (const table of ['bindings', 'branches', 'items']) {
void table;
}
poolQuery.mockResolvedValue({ rows: [{ code: null }], rowCount: 1 } as never);
const r = await syncMainSystemBindings();
expect(r.checked).toBe(0);
expect(r.reason).toContain('换不到对接 token');
expect(fetchMock).not.toHaveBeenCalled();
(config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original;
});
it('快照:active 行绑定、status=0 行解绑、缺 supplier_code 行跳过、空快照只记原因', async () => {
findBranch.mockResolvedValue('BR007');
upsert.mockResolvedValue({ branchCode: 'BR007', previousBranchCode: null });
unbind.mockResolvedValue(true);
const r = await applyBindingSnapshot({
data: [
{ subsystem_code: 'SC1', main_branch_code: 'BR002', supplier_code: 'SUP1', status: 1 },
{ subsystem_code: 'SC1', main_branch_code: 'BR003', supplier_code: 'SUP1', status: 0 },
{ subsystem_code: 'SC1', main_branch_code: 'BR004', supplier_code: '' },
],
});
expect(r.checked).toBe(3);
expect(r.applied).toBe(1);
expect(r.unbound).toBe(1);
expect(r.skipped).toBe(1);
const empty = await applyBindingSnapshot({ data: [] });
expect(empty.checked).toBe(0);
expect(empty.reason).toContain('快照为空');
});
});
describe('接线:webhook 分支必须在"绑定路由闸门"之前', () => {
const src = readFileSync(new URL('../src/routes/mainSystemIntegration.ts', import.meta.url), 'utf8');
it('binding.changed 分支存在,且早于 resolveOurBranchByBinding 的闸门', () => {
const branchAt = src.indexOf('isBindingChangedEvent(event)');
const gateAt = src.indexOf('await resolveOurBranchByBinding({');
expect(branchAt).toBeGreaterThan(0);
expect(gateAt).toBeGreaterThan(0);
expect(branchAt, '这条事件本身在建绑定,拿它查绑定表必然查不到 ⇒ 必须放在闸门前').toBeLessThan(gateAt);
});
it('逐条独立:一条失败不能拖累其余(全量重推场景)', () => {
const block = src.slice(src.indexOf('isBindingChangedEvent(event)'), src.indexOf('await resolveOurBranchByBinding({'));
expect(block).toContain('for (const change of changes)');
expect(block).toContain('.catch(');
expect(block).toContain("reason: `应用失败:");
});
});
describe('调度接线:回读在导入之前跑(本轮新绑的当轮就能拉单)', () => {
const jobs = readFileSync(new URL('../src/services/scheduledJobs.ts', import.meta.url), 'utf8');
it('syncMainSystemBindings 早于 importMainSystemOrdersForAllSupplierBranches', () => {
const syncAt = jobs.indexOf('syncMainSystemBindings()');
const importAt = jobs.indexOf('importMainSystemOrdersForAllSupplierBranches()');
expect(syncAt).toBeGreaterThan(0);
expect(importAt).toBeGreaterThan(0);
expect(syncAt).toBeLessThan(importAt);
});
});