Files
SupplierSystem/server/tests/branchBindingSync.test.ts
T
Ubuntu cb1cbecfc5
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(对接): 绑定成功即刻拉一次 —— 消掉"刚绑完要等 15 分钟才看到货"的窗口
开发者报障:「为什么 18381421533 这个水产供应商分公司收不到主系统分配过来的订单?」

排查结论(真库 + 他们的投递日志 + 我方日志):
  · 我方绑定是有的:BR003 水产供应商 ← (BR002, SUP41472132) ← 接入编码 SCSTSHD6XVX4(main_push 已到);
  · 他们那边授权行也绑好了(subsystem_code=SCSTSHD6XVX4),且**确实分了 6 行货**给 SUP41472132
    (ORD_WEB_20261010_BR002_0001/0002,17:53:38/48,prepare_status=10);
  · 但**他们没有推 `preparations.allocated`** —— 他们的 `supplier_integration_webhook_deliveries`
    里只有两条 `binding.changed`(17:49/17:50),没有任何 assigned 投递记录;
  · 我方兜底对账挂在**调度 tick** 上:`setInterval(..., 15*60*1000)` + 内部限流 10 分钟
    ⇒ **实际周期是 15 分钟**(设计文档此前写的"≤10 分钟"不准,已更正)。用户 17:58 来问时还没轮到。

本提交的修复:`binding.changed` 应用成功后,**立即**对该分公司 fire-and-forget 拉取一次
(不阻塞 webhook 响应、失败只记日志,兜底仍是定时对账)⇒ 窗口从"最多 15 分钟"变成"秒级"。
实测有效:手动触发导入后 BR003 落单 `ORD_API_20261010_BR003_0003`(两张主系统单按配送日合并成一张,
¥534.80,配送日 2026-10-11),拉取→建单→落库全链路正常。

顺带记录(未改,供裁决):
  1. 租户表是 FORCE RLS:直连 psql 查数据必须 `set_config('app.branch_code', …)` 且 search_path
     含租户 schema —— 我第一轮就是漏了这一步,把"有数据"误判成"没落库"(已复核纠正);
  2. `cleanup_orphan_fulfillments()` 用**非限定表名** `order_item_fulfillments`:
     在 search_path 不含租户 schema 的连接上删单会报 `relation … does not exist`(既有缺陷)。

验证:服务端 2334 用例 / 失败 30、失败文件 24 = 与基线逐字相同;branchBindingSync 17 例全绿
(新增"绑定后必须立即拉取且 fire-and-forget"一条);tsc 通过;门禁同基线。
2026-10-10 18:04:58 +08:00

280 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('绑定成功即刻拉一次(否则用户刚绑完要等 15 分钟才看到货)', () => {
const block = src.slice(src.indexOf('isBindingChangedEvent(event)'), src.indexOf('await resolveOurBranchByBinding({'));
expect(block).toContain('importMainSystemOrders({ branchCode: branch, userId: null })');
// 必须 fire-and-forget:不阻塞 webhook 响应,失败只记日志(兜底仍是定时对账)
expect(block).toContain('.catch(');
expect(block).toContain('交给定时对账兜底');
});
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);
});
});