import { beforeEach, describe, expect, it, vi } from 'vitest'; import { readFileSync } from 'node:fs'; import path from 'node:path'; /** * 「未绑接入编码却拉到货」的**我方侧收紧**(2026-10-13)。 * * 事故:开发者「接入编码明明没给主系统绑定,订单却被分配过来了」(真机样本 * `ORD_API_20261013_SUP35143228_0001`)。两层根因: * ① 主系统侧:`supplier_integration_client_suppliers` 的"凭据→供应商"授权**不要求**填 * `subsystem_code`(实测本地主系统 5 条授权里 2 条为 NULL)⇒ 空码也能换 Token 拉货 * (已记入 `docs/给主系统AI的对接改造清单.md` §2.13「P0-空码放行」待对方裁决); * ② 我方侧:`migrations/20261031` 的**迁移回填**会建 `main_branch_code='*'` 的 active 通配绑定, * 本地据此**主动去拉**。 * * 本文件钉住 ② 的封堵:自动拉单只认「主系统明确把我们的接入编码绑到了该供应商」的绑定。 */ const query = vi.hoisted(() => vi.fn()); const fetchPreps = vi.hoisted(() => vi.fn()); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => query(...args) }, getRawPoolQuery: () => query, })); vi.mock('../src/services/mainSystemPreparations', () => ({ fetchMainSystemPreparations: (...args: unknown[]) => fetchPreps(...args), })); import { listAutoPullableBindingsForBranch } from '../src/services/branchAccessCode'; import { pullPreparationsForBranch } from '../src/services/mainSystemBranchPull'; const pullSrc = readFileSync( path.join(__dirname, '../src/services/mainSystemBranchPull.ts'), 'utf8' ); const accessSrc = readFileSync( path.join(__dirname, '../src/services/branchAccessCode.ts'), 'utf8' ); const mainConfigSrc = readFileSync( path.join(__dirname, '../src/services/mainSystem/config.ts'), 'utf8' ); const indexSrc = readFileSync(path.join(__dirname, '../src/index.ts'), 'utf8'); type Row = { branch_code: string; access_code: string; main_branch_code: string; main_supplier_code: string; status: string; source: string; bound_at: string; unbound_at: string | null; }; const row = (over: Partial = {}): Row => ({ branch_code: 'BR003', access_code: 'SCSTSHD6XVX4', main_branch_code: 'BR002', main_supplier_code: 'SUP41472132', status: 'active', source: 'main_push', bound_at: '2026-10-10T09:50:31.130Z', unbound_at: null, ...over, }); function wire(connectable: Row[], all: Row[] = connectable) { /** * 2026-10-13 重构:过滤从 JS 挪进 **一条 JOIN 查询**(绑定 ⋈ 分公司当前编码)⇒ * 桩把"可沟通绑定"(JOIN)与"全部生效绑定"(不拉时给原因用)分别喂进去; * **谓词本身**由 ①/⑤c 的 SQL 源码钉 + 真库冒烟钉住(避免桩里再实现一遍过滤逻辑 ⇒ 那样测的是桩)。 */ query.mockImplementation((sql: string) => { const text = String(sql); if (text.includes('JOIN public.branches')) { return Promise.resolve({ rows: connectable, rowCount: connectable.length }); } if (text.includes('FROM public.main_supplier_bindings')) { return Promise.resolve({ rows: all, rowCount: all.length }); } if (text.includes('access_code FROM public.branches')) { return Promise.resolve({ rows: [], rowCount: 0 }); } throw new Error(`未预期的 SQL: ${text.slice(0, 60)}`); }); } describe('自动拉单只认「接入编码已绑给主系统」的绑定', () => { beforeEach(() => { query.mockReset(); fetchPreps.mockReset(); }); it('① 可沟通绑定:DB 按谓词筛完的行原样映射(含 source / accessCode 字段)', async () => { wire([row({ main_supplier_code: 'SUP_OK', source: 'main_push' }), row({ main_supplier_code: 'SUP_MANUAL', source: 'manual' })]); const pullable = await listAutoPullableBindingsForBranch('BR003'); expect(pullable.map((b) => b.mainSupplierCode)).toEqual(['SUP_OK', 'SUP_MANUAL']); expect(pullable[0].accessCode).toBe('SCSTSHD6XVX4'); expect(pullable[0].source).toBe('main_push'); }); it('② 分公司没有可沟通绑定 ⇒ 空数组(调用方走 not_bound,不发 HTTP)', async () => { wire([]); expect(await listAutoPullableBindingsForBranch('BR003')).toEqual([]); }); it('③ 无可沟通绑定(但有回填/空码行)⇒ not_bound,且**不发任何 HTTP**', async () => { wire([], [row({ source: 'backfill', main_branch_code: '*' })]); const out = await pullPreparationsForBranch('BR003', 'active'); expect(out.kind).toBe('not_bound'); if (out.kind === 'not_bound') { expect(out.reason).toContain('接入编码已绑给主系统'); } expect(fetchPreps).not.toHaveBeenCalled(); }); it('③b 完全没有绑定行 ⇒ not_bound(原因区分"尚未被绑定")', async () => { wire([], []); const out = await pullPreparationsForBranch('BR003', 'active'); expect(out.kind).toBe('not_bound'); if (out.kind === 'not_bound') { expect(out.reason).toContain('尚未被主系统任何供应商绑定'); } expect(fetchPreps).not.toHaveBeenCalled(); }); it('④ 正常绑定(主系统推送过接入编码)⇒ 照常拉取', async () => { wire([row()]); fetchPreps.mockResolvedValue({ kind: 'ok', rows: [{ orderCode: 'ORD_WEB_X', skuCode: 'SKU1', supplierCode: 'SUP41472132' }], }); const out = await pullPreparationsForBranch('BR003', 'active'); expect(out.kind).toBe('ok'); expect(fetchPreps).toHaveBeenCalledTimes(1); expect(fetchPreps.mock.calls[0][0]).toBe('SUP41472132'); }); it('⑤ 源码守卫:拉取与展示**都**排除回填行(没绑定就不拉、也不展示)', () => { expect(pullSrc).toContain('listAutoPullableBindingsForBranch'); expect(accessSrc).toContain('export async function listAutoPullableBindingsForBranch'); expect(accessSrc).toContain("<> 'backfill'"); // 展示路径:回填行(迁移造的过渡绑定,用户没绑过)不展示 expect(accessSrc).toContain('export async function listBindingsForBranch'); expect(accessSrc).toMatch(/listBindingsForBranch[\s\S]{0,400}source <> 'backfill'/); }); it('⑤b 展示查询在 SQL 里就排除 source=backfill(本地那两条通配回填行不再显示)', async () => { const seen: string[] = []; query.mockImplementation((sql: string) => { seen.push(String(sql)); return Promise.resolve({ rows: [], rowCount: 0 }); }); const { listBindingsForBranch } = await import('../src/services/branchAccessCode'); await listBindingsForBranch('BR003'); expect(seen.join('\n')).toContain("source <> 'backfill'"); }); }); /** * **P1(2026-10-13):把"能不能跟主系统说话"收成一个判定点**。 * * 改前有两套口径:拉货用"编码已绑"(`listAutoPullableBindingsForBranch`), * 但所有其它出站(申请列表 Q5/Q6、归档反查、按行分组)用"任何 active 绑定" ⇒ * **迁移回填行 / 空接入编码行**照样解析出 supplier_code ⇒ 对账抱着注定 403 的编码 * 去换 Token + 发 GET(对方已收紧为「必须有接入编码才放行」,回执 §4.5.22)。 * 定时任务的 fan-out 名单也用的是"有任何 active 绑定"⇒ 这些分公司每轮都要白跑一遍。 */ describe('P1:出站判定点唯一(未绑编码 = 零出站)', () => { const branchApiSrc = readFileSync( path.join(__dirname, '../src/services/mainSystemBranchApi.ts'), 'utf8' ); const importSrc = readFileSync( path.join(__dirname, '../src/services/mainSystemOrderImport.ts'), 'utf8' ); it('① 可沟通绑定查询把四条规则写在同一条 SQL 里(回填/空码/无码/换码)', () => { const fn = accessSrc.slice(accessSrc.indexOf('export async function listConnectableBindingsForBranch')); const sql = fn.slice(0, fn.indexOf('return result.rows.map')); expect(sql, 'join 分公司当前编码').toContain('JOIN public.branches br'); expect(sql, '排除迁移回填行').toContain("COALESCE(b.source, '') <> 'backfill'"); expect(sql, '绑定侧编码非空').toMatch(/NULLIF\(UPPER\(TRIM\(COALESCE\(b\.access_code/); expect(sql, '分公司侧编码非空').toMatch(/NULLIF\(UPPER\(TRIM\(COALESCE\(br\.access_code/); expect(sql, '两侧编码(大小写不敏感)相等').toContain( 'UPPER(TRIM(b.access_code)) = UPPER(TRIM(br.access_code))' ); }); it('② fan-out 名单与拉货同口径(listConnectableBranchCodes 同一谓词)', () => { const fn = accessSrc.slice(accessSrc.indexOf('export async function listConnectableBranchCodes')); const sql = fn.slice(0, fn.indexOf('return result.rows.map')); expect(sql).toContain("COALESCE(b.source, '') <> 'backfill'"); expect(sql).toContain('UPPER(TRIM(b.access_code)) = UPPER(TRIM(br.access_code))'); // 定时对账的名单必须走它(否则回填/空码分公司又进轮询) expect(importSrc).toMatch(/listMainSupplierBranchCodes[\s\S]{0,300}listConnectableBranchCodes/); }); it('③ 其它出站路径(申请列表/归档反查/按行分组)也走同一判定点', () => { expect(branchApiSrc).toContain('listConnectableBindingsForBranch'); // 不再直接读"任何 active 绑定"当出站依据 expect(branchApiSrc).not.toContain('listActiveBindingsForBranch('); }); it('④ 拉货侧保留旧名但实现同源(deprecated 转发)', () => { expect(accessSrc).toMatch( /listAutoPullableBindingsForBranch[\s\S]{0,200}return listConnectableBindingsForBranch\(branchCode\)/ ); }); }); /** * **P2(2026-10-13):无未决 ⇒ 不拉**。 * * 两条对账原来**先拉后判**:只要该分公司能解析出 supplier_code,就算本地一条待审行都没有, * 也每 10 分钟发一次 GET(几千家分公司规模下这是最大的一笔纯浪费)。 * 现在先查本地待审(轻查询),为 0 直接返回;语义无损失 —— 没有本地方案要核,拉回来也没东西可对。 */ describe('P2:本地无待审 ⇒ 不发任何请求', () => { const actualSrc = readFileSync( path.join(__dirname, '../src/services/mainSystemActualQtyInbox.ts'), 'utf8' ); const priceQtySrc = readFileSync( path.join(__dirname, '../src/services/mainSystemPriceQtyRequest.ts'), 'utf8' ); it('① 实收申请对账:本地 pending 计数在 listRequestsForBranch 之前', () => { const fn = actualSrc.slice(actualSrc.indexOf('export async function reconcilePendingActualQtyRequests')); const countAt = fn.indexOf('FROM public.main_system_actual_qty_requests'); const httpAt = fn.indexOf('listRequestsForBranch('); expect(countAt, '存在本地待审计数查询').toBeGreaterThan(-1); expect(httpAt, '存在拉取').toBeGreaterThan(-1); expect(countAt, '计数必须在拉取之前').toBeLessThan(httpAt); expect(fn.slice(countAt, httpAt), '计数后未命中就返回').toContain('跳过拉取'); }); it('② 我方价/量申请对账:同样的前置判定', () => { const fn = priceQtySrc.slice( priceQtySrc.indexOf('export async function reconcileOurPriceQtyRequestsWithMainSystem') ); const countAt = fn.indexOf('FROM public.main_system_price_qty_requests'); const httpAt = fn.indexOf('listRequestsForBranch('); expect(countAt).toBeGreaterThan(-1); expect(httpAt).toBeGreaterThan(-1); expect(countAt).toBeLessThan(httpAt); expect(fn.slice(countAt, httpAt)).toContain('跳过拉取'); }); }); describe('环境隔离自检(事故后补:本地 dev 指向线上 + 自动拉单 ⇒ 可读可写线上)', () => { it('⑥ 非本机地址 + 自动拉单/回写开启时告警一次;本机地址不告警', () => { expect(mainConfigSrc).toContain('export function warnIfRemoteMainSystemWithWriteback'); expect(mainConfigSrc).toContain("host === 'localhost'"); expect(mainConfigSrc).toContain('环境隔离告警'); // 进程启动时自检 expect(indexSrc).toContain('warnIfRemoteMainSystemWithWriteback'); }); });