import express from 'express'; import request from 'supertest'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * **超管解绑路由**的主系统接入(2026-11-06 双向解绑联调)。 * * 钉住的是路由层的**编排语义**(不是主系统客户端本身,那个在 `mainSystemUnbindBinding.test.ts`): * ① 先调主系统解绑,`subsystem_code` 取**本分公司接入编码**、`supplier_code` 取 body; * ② 不论主系统结果如何,**本地解绑一定执行**(兜底:不先停我方接收,主系统解不掉就还在收货); * 并且带 `allowAlreadyUnbound: true`(主系统解绑的 `binding.changed` 会抢先把它刷成 unbound); * ③ 响应把主系统结果放进 `main_system`(`unbound`/`noop`/`failed`/`unavailable`/`not_configured`); * ④ **只有本地**解绑 404 才 404(主系统 404 只体现为 `main_system.status='failed'`); * ⑤ 主系统结果单独补一条审计(本地解绑那条由 `manualUnbindBinding` 自己写)。 */ const H = vi.hoisted(() => ({ currentUserId: '11111111-1111-4111-8111-111111111111', isSuperAdmin: true, poolQuery: vi.fn(), getBranchAccessCode: vi.fn(), manualUnbindBinding: vi.fn(), unbindMainSystemBinding: vi.fn(), writeAuditLog: vi.fn(), })); vi.mock('../src/middleware/auth', () => ({ authMiddleware: (req: { userId?: string }, _res: unknown, next: () => void) => { req.userId = H.currentUserId; next(); }, invalidateAuthVersionCache: () => undefined, })); vi.mock('../src/db', () => { const pool = { query: (...args: unknown[]) => H.poolQuery(...args), connect: vi.fn(), }; return { pool, getRawPoolQuery: () => H.poolQuery }; }); vi.mock('../src/services/branchAccessCode', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, getBranchAccessCode: (...args: unknown[]) => H.getBranchAccessCode(...args), manualUnbindBinding: (...args: unknown[]) => H.manualUnbindBinding(...args), }; }); vi.mock('../src/services/mainSystem', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, unbindMainSystemBinding: (...args: unknown[]) => H.unbindMainSystemBinding(...args), }; }); vi.mock('../src/services/auditService', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, writeAuditLog: (...args: unknown[]) => H.writeAuditLog(...args) }; }); const { default: authRouter } = await import('../src/routes/auth'); const app = express(); app.use(express.json()); app.use('/api/auth', authRouter); const BRANCH = 'BR002'; const SUPPLIER = 'SUP37831443'; const ACCESS_CODE = 'SCQEM2X7B6P5'; const URL_PATH = `/api/auth/admin/branches/${BRANCH}/bindings/unbind`; const LOCAL_BINDING = { branchCode: BRANCH, accessCode: ACCESS_CODE, mainBranchCode: BRANCH, mainSupplierCode: SUPPLIER, status: 'unbound', source: 'main_pull', boundAt: '2026-11-06T03:36:04.653Z', unboundAt: '2026-11-06T05:00:00.000Z', localOverrideState: 'manual_unbound', localOverrideReason: null, localOverrideAt: null, localOverrideByName: null, }; function remoteResult(kind: string, overrides: Record = {}) { return { kind, httpStatus: kind === 'ok' || kind === 'noop' ? 200 : kind === 'rejected' ? 403 : 0, action: kind === 'ok' ? 'unbound' : kind === 'noop' ? 'noop' : null, affected: kind === 'ok' ? 1 : 0, bindings: kind === 'ok' ? [{ branch_code: BRANCH, supplier_code: SUPPLIER, subsystem_code: ACCESS_CODE }] : [], reason: kind === 'rejected' ? 'token 无权解绑该供应商授权' : kind === 'unavailable' ? '主系统主动解绑超时' : '', attempts: 2, raw: null, ...overrides, }; } beforeEach(() => { H.isSuperAdmin = true; H.poolQuery.mockReset(); H.poolQuery.mockImplementation(async (sql: unknown) => { const text = String(sql); if (text.includes('super_admin')) return { rows: [{ '?column?': 1 }], rowCount: 1 }; return { rows: [], rowCount: 0 }; }); H.getBranchAccessCode.mockReset(); H.getBranchAccessCode.mockResolvedValue(ACCESS_CODE); H.manualUnbindBinding.mockReset(); H.manualUnbindBinding.mockResolvedValue(LOCAL_BINDING); H.unbindMainSystemBinding.mockReset(); H.unbindMainSystemBinding.mockResolvedValue(remoteResult('ok')); H.writeAuditLog.mockReset(); H.writeAuditLog.mockResolvedValue(undefined); }); describe('① 主系统解绑成功(unbound / noop)', () => { it('ok ⇒ 先远端后本地,响应 main_system.status=unbound', async () => { const response = await request(app).post(URL_PATH).send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER, reason: '联调', }); expect(response.status).toBe(200); expect(H.unbindMainSystemBinding).toHaveBeenCalledWith({ supplierCode: SUPPLIER, subsystemCode: ACCESS_CODE, mainBranchCode: 'BR002', reason: '联调', }); expect(H.manualUnbindBinding).toHaveBeenCalledWith( expect.objectContaining({ mainBranchCode: 'BR002', mainSupplierCode: SUPPLIER, branchCode: BRANCH, reason: '联调', allowAlreadyUnbound: true, }) ); // 远端一定在本地之前(本地先解的话,远端失败时用户会以为双方都解了) expect(H.unbindMainSystemBinding.mock.invocationCallOrder[0]).toBeLessThan( H.manualUnbindBinding.mock.invocationCallOrder[0] ); expect(response.body).toMatchObject({ ok: true, binding: { status: 'unbound' }, main_system: { status: 'unbound', affected: 1, attempts: 2, httpStatus: 200 }, }); }); it('noop ⇒ 仍是成功路径,main_system.status=noop', async () => { H.unbindMainSystemBinding.mockResolvedValue(remoteResult('noop')); const response = await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER }); expect(response.status).toBe(200); expect(H.manualUnbindBinding).toHaveBeenCalledTimes(1); expect(response.body.main_system).toMatchObject({ status: 'noop', affected: 0, attempts: 2 }); }); }); describe('② 主系统失败也必须本地兜底', () => { it('rejected ⇒ 本地仍解绑,响应 ok:true + main_system.status=failed + 明确文案', async () => { H.unbindMainSystemBinding.mockResolvedValue(remoteResult('rejected')); const response = await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER }); expect(response.status).toBe(200); expect(H.manualUnbindBinding).toHaveBeenCalledTimes(1); expect(response.body).toMatchObject({ ok: true, main_system: { status: 'failed', httpStatus: 403, error: 'token 无权解绑该供应商授权', message: '主系统侧解绑失败,已本地停用', }, }); }); it('unavailable ⇒ 本地仍解绑,main_system.status=unavailable(含重试次数)', async () => { H.unbindMainSystemBinding.mockResolvedValue(remoteResult('unavailable')); const response = await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER }); expect(response.status).toBe(200); expect(H.manualUnbindBinding).toHaveBeenCalledTimes(1); expect(response.body.main_system).toMatchObject({ status: 'unavailable', attempts: 2, message: '主系统暂不可用,已本地停用', }); }); it('not_configured(主系统未配置)⇒ 本地仍解绑', async () => { H.unbindMainSystemBinding.mockResolvedValue(remoteResult('not_configured', { attempts: 0 })); const response = await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER }); expect(response.status).toBe(200); expect(H.manualUnbindBinding).toHaveBeenCalledTimes(1); expect(response.body.main_system).toMatchObject({ status: 'not_configured', message: '未配置主系统对接,已本地停用', }); }); it('本分公司没有接入编码 ⇒ **不调**主系统(白打一次 400),按 not_configured 记 + 本地兜底', async () => { H.getBranchAccessCode.mockResolvedValue(null); const response = await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER }); expect(response.status).toBe(200); expect(H.unbindMainSystemBinding).not.toHaveBeenCalled(); expect(H.manualUnbindBinding).toHaveBeenCalledTimes(1); expect(response.body.main_system).toMatchObject({ status: 'not_configured', attempts: 0, error: '该分公司未配置接入编码,无法调用主系统解绑', }); }); }); describe('③ 404 / 400 / 权限边界', () => { it('本地解绑 404 ⇒ 才返回 404(主系统结果一并带回)', async () => { H.manualUnbindBinding.mockRejectedValue( Object.assign(new Error('绑定不存在或已解绑'), { status: 404, code: 'not_found' }) ); const response = await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER }); expect(response.status).toBe(404); expect(response.body).toMatchObject({ error: 'not_found', error_description: '绑定不存在或已解绑', main_system: { status: 'unbound' }, }); // 主系统已经解掉了:必须在日志里能看出这个**不对称**状态 expect(H.writeAuditLog).not.toHaveBeenCalled(); }); it('缺 main_supplier_code ⇒ 400,且**不调**主系统/本地', async () => { const response = await request(app).post(URL_PATH).send({ main_branch_code: 'BR002' }); expect(response.status).toBe(400); expect(H.unbindMainSystemBinding).not.toHaveBeenCalled(); expect(H.manualUnbindBinding).not.toHaveBeenCalled(); }); it('非超管 ⇒ 403,且不调主系统/本地', async () => { H.isSuperAdmin = false; H.poolQuery.mockResolvedValue({ rows: [], rowCount: 0 }); const response = await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER }); expect(response.status).toBe(403); expect(H.unbindMainSystemBinding).not.toHaveBeenCalled(); expect(H.manualUnbindBinding).not.toHaveBeenCalled(); }); }); describe('④ 审计:主系统结果单独一条', () => { it('把 main_system 与主系统回执里的授权行写进 newValue', async () => { await request(app) .post(URL_PATH) .send({ main_branch_code: 'BR002', main_supplier_code: SUPPLIER, reason: '联调' }); expect(H.writeAuditLog).toHaveBeenCalledTimes(1); expect(H.writeAuditLog).toHaveBeenCalledWith( expect.objectContaining({ operationType: 'main_supplier_binding_unbind_main_system', targetTable: 'main_supplier_bindings', branchCode: BRANCH, actionCategory: 'system', newValue: expect.objectContaining({ branch_code: BRANCH, access_code: ACCESS_CODE, main_supplier_code: SUPPLIER, main_system: expect.objectContaining({ status: 'unbound' }), bindings: [{ branch_code: BRANCH, supplier_code: SUPPLIER, subsystem_code: ACCESS_CODE }], }), }) ); }); });