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', mainBranchName: null, action: 'bind' }); expect( parseBindingChange({ access_code: 'SC1', main_branch_code: 'BR2', main_supplier_code: 'SUP3' }) ).toEqual({ accessCode: 'SC1', mainBranchCode: 'BR2', mainSupplierCode: 'SUP3', mainBranchName: null, 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('显式配置 off ⇒ 直接跳过(不猜路径、不发请求)', async () => { const { config } = await import('../src/config'); const original = config.mainSystemIntegration.bindingSyncUrl; (config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = 'off'; const r = await syncMainSystemBindings(); expect(r.checked).toBe(0); expect(r.reason).toContain('未启用'); expect(fetchMock).not.toHaveBeenCalled(); (config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = original; }); it('未配置 + 非生产环境 ⇒ 默认走标准端点 /api/supplier/integration-bindings', async () => { const { config } = await import('../src/config'); const originalUrl = config.mainSystemIntegration.bindingSyncUrl; const originalBase = config.mainSystem.baseUrl; const originalNodeEnv = process.env.NODE_ENV; (config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = ''; (config.mainSystem as { baseUrl: string }).baseUrl = 'http://127.0.0.1:3001'; process.env.NODE_ENV = 'development'; fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({ data: [] }) } as never); const r = await syncMainSystemBindings(); expect(fetchMock).toHaveBeenCalledTimes(1); const [url] = fetchMock.mock.calls[0] as [string]; expect(url).toContain('/api/supplier/integration-bindings'); expect(url).toContain('include_disabled=1'); expect(r.checked).toBe(0); process.env.NODE_ENV = originalNodeEnv; (config.mainSystemIntegration as { bindingSyncUrl: string }).bindingSyncUrl = originalUrl; (config.mainSystem as { baseUrl: string }).baseUrl = originalBase; }); it('镜像里残留的已解绑供应商 token 失败时,继续用下一个候选换 token(不整轮卡死)', 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'; poolQuery.mockImplementation(async (sql: unknown) => { if (String(sql).includes('SELECT main_supplier_code AS code') && String(sql).includes('FROM public.main_supplier_bindings')) { return { rows: [{ code: 'SUP_STALE' }, { code: 'SUP_GOOD' }], rowCount: 2 } as never; } if (String(sql).includes('FROM public.branches') || String(sql).includes('FROM public.main_system_order_import_items')) { return { rows: [], rowCount: 0 } as never; } return { rows: [], rowCount: 0 } as never; }); tokenMock.mockImplementation(async (code: string) => code === 'SUP_STALE' ? { kind: 'unavailable', reason: 'forbidden: 残留绑定已解绑' } : { kind: 'ok', token: 'tok-ok', branchCode: 'BR002', expiresAt: Date.now() + 60000 } ); fetchMock.mockResolvedValue({ ok: true, status: 200, json: async () => ({ data: [{ branch_code: 'BR002', supplier_code: 'SUP_GOOD', subsystem_code: 'SC1', status: 1 }], }), } as never); findBranch.mockResolvedValue('BR002'); upsert.mockResolvedValue({ branchCode: 'BR002', previousBranchCode: null }); const r = await syncMainSystemBindings(); expect(tokenMock).toHaveBeenCalledWith('SUP_STALE'); expect(tokenMock).toHaveBeenCalledWith('SUP_GOOD'); expect(r.applied).toBe(1); (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 }]; 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('快照为空'); }); it('全量快照对账:快照里不存在的 active 绑定 ⇒ 自动解绑(权威优先,防残留绑定继续拉货)', async () => { findBranch.mockResolvedValue('BR002'); upsert.mockResolvedValue({ branchCode: 'BR002', previousBranchCode: null }); unbind.mockResolvedValue(true); poolQuery.mockImplementation(async (sql: unknown) => { if (String(sql).includes('FROM public.main_supplier_bindings')) { return { rows: [ { branch_code: 'BR002', main_branch_code: 'BR002', main_supplier_code: 'SUP37831443' }, { branch_code: 'BR002', main_branch_code: 'BR002', main_supplier_code: 'SUP35143228' }, ], rowCount: 2, } as never; } return { rows: [], rowCount: 0 } as never; }); const r = await applyBindingSnapshot({ data: [{ subsystem_code: 'SC1', main_branch_code: 'BR002', supplier_code: 'SUP37831443', status: 1 }], }); expect(r.applied).toBe(1); expect(r.unboundMissing, '快照里没有的 SUP35143228 必须被解绑').toBe(1); expect(unbind).toHaveBeenCalledTimes(1); expect(unbind).toHaveBeenCalledWith( expect.objectContaining({ mainBranchCode: 'BR002', mainSupplierCode: 'SUP35143228' }) ); }); }); 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); }); });