import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * **BIZ-12:SKU 映射推/拉必须按 (main_branch_code, main_supplier_code) 成对出站**(2026-10-19 T10a)。 * * 缺陷(审计 BIZ-12):`skuMappingService` 的 D4/D5 只取"最新一条绑定的 supplier_code" * (`resolveMainSupplierCode` = `ORDER BY bound_at DESC LIMIT 1`),再套到所有 `main_branch_code` 上。 * 一个我方分公司绑多个主系统分公司、且各自供应商码不同时: * · 推字典 ⇒ 用错码 ⇒ 对方 `requireActiveBinding` 403(或推到错的分公司); * · 拉映射 ⇒ 用错码拉到空集 ⇒ "证明拉全了"成立 ⇒ **把本地映射删空**。 * * 本机只有 1 条 binding(无法真库复现)⇒ 按任务要求用单测模拟**两对绑定**, * 断言出站两次且参数成对,并断言合并结果(推送汇总相加 / 拉取行去重合并)。 */ const H = vi.hoisted(() => ({ poolQuery: vi.fn(), tenantCtx: vi.fn(), resolveMainSupplierCode: vi.fn(), push: vi.fn(), pull: vi.fn(), })); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => H.poolQuery(...args) }, getRawPoolQuery: () => H.poolQuery, })); vi.mock('../src/services/tenantDbContext', () => ({ runWithTenantDbContext: (...args: unknown[]) => H.tenantCtx(...args), })); vi.mock('../src/services/mainSystemQuoteCostSync', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, resolveMainSupplierCode: (...args: unknown[]) => H.resolveMainSupplierCode(...args), }; }); vi.mock('../src/services/mainSystem/api/skuMappings', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, pushSkuDictionary: (...args: unknown[]) => H.push(...args), pullSkuMappings: (...args: unknown[]) => H.pull(...args), }; }); const { pushSkuDictionaryForBranch, pullMappingsFromMainSystem, isSkuMappingEnabled } = await import( '../src/services/skuMappingService' ); const BRANCH = 'SUP35143228'; const SKU_ROWS = [{ sku_code: 'SKU1', sku_name: '草鱼', unit: '斤' }]; type Pair = { main_branch_code: string; main_supplier_code: string }; /** 假库:绑定对查询与"主系统分公司码"查询分开路由(旧回退路径也要能跑) */ function installDb(options: { pairs: Pair[]; fallbackBranchCodes?: string[] }) { const calls: Array<{ sql: string; params: unknown[] }> = []; const handler = async (sql: string, params: unknown[] = []) => { const text = String(sql); calls.push({ sql: text, params }); if (text.includes('FROM public.main_supplier_bindings') && text.includes('main_supplier_code')) { return { rowCount: options.pairs.length, rows: options.pairs }; } if (text.includes('UPPER(TRIM(main_branch_code))') && text.includes('FROM public.main_supplier_bindings')) { const codes = options.fallbackBranchCodes ?? []; return { rowCount: codes.length, rows: codes.map((code) => ({ code })) }; } if (text.includes('FROM skus')) return { rowCount: SKU_ROWS.length, rows: SKU_ROWS }; if (text.includes('INSERT INTO main_system_sku_mappings')) return { rowCount: 1, rows: [] }; if (text.includes('DELETE FROM main_system_sku_mappings')) return { rowCount: 0, rows: [] }; if (text.includes('FROM main_system_sku_mappings') && text.includes('<> ALL')) return { rowCount: 0, rows: [] }; return { rowCount: 0, rows: [] }; }; H.poolQuery.mockImplementation((sql: string, params?: unknown[]) => handler(sql, params || [])); return { calls }; } beforeEach(() => { H.poolQuery.mockReset(); H.tenantCtx.mockReset(); H.resolveMainSupplierCode.mockReset(); H.push.mockReset(); H.pull.mockReset(); H.tenantCtx.mockImplementation(async (_branch: string, fn: () => Promise) => fn()); H.resolveMainSupplierCode.mockResolvedValue('SUP-LEGACY'); process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL = '1'; }); describe('BIZ-12 多绑定:推/拉按 (main_branch_code, main_supplier_code) 成对出站', () => { it('D4 推送:两个绑定对 ⇒ 出站两次且参数成对(不再只用一个 supplier_code)', async () => { installDb({ pairs: [ { main_branch_code: 'BR002', main_supplier_code: 'SUP-A' }, { main_branch_code: 'BR003', main_supplier_code: 'SUP-B' }, ], }); H.push.mockImplementation(async (input: { mainBranchCode: string; supplierCode: string }) => ({ kind: 'ok', data: { matched: 1, pending: 0, kept: 0, total: 1 }, })); const summary = await pushSkuDictionaryForBranch({ branchCode: BRANCH }); expect(H.push, '两个绑定对必须各推一次').toHaveBeenCalledTimes(2); expect(H.push.mock.calls.map((call) => call[0])).toEqual([ expect.objectContaining({ mainBranchCode: 'BR002', supplierCode: 'SUP-A' }), expect.objectContaining({ mainBranchCode: 'BR003', supplierCode: 'SUP-B' }), ]); // 汇总 = 两次调用相加(不是只算第一次) expect(summary).toMatchObject({ skus: 1, batches: 2, matched: 2, total: 2 }); // 旧口径的"取最新一条供应商码当唯一身份"不得再参与成对出站 expect(H.resolveMainSupplierCode).not.toHaveBeenCalled(); }); it('D5 拉取:两个绑定对 ⇒ 出站两次、参数成对,行按 supplier_sku_code 合并', async () => { installDb({ pairs: [ { main_branch_code: 'BR002', main_supplier_code: 'SUP-A' }, { main_branch_code: 'BR003', main_supplier_code: 'SUP-B' }, ], }); H.pull.mockImplementation(async (input: { mainBranchCode: string; supplierCode: string }) => { const rows = input.supplierCode === 'SUP-A' ? [ { supplier_sku_code: 'SKU-A1', supplier_sku_name: 'A1', supplier_unit: '斤', delivery_sku_code: 'D-A1', delivery_sku_name: 'A1(配送)', status: 'active', }, ] : [ { supplier_sku_code: 'SKU-B1', supplier_sku_name: 'B1', supplier_unit: '袋', delivery_sku_code: 'D-B1', delivery_sku_name: 'B1(配送)', status: 'active', }, ]; return { kind: 'ok', rows, nextCursor: null, total: rows.length }; }); const summary = await pullMappingsFromMainSystem({ branchCode: BRANCH }); expect(H.pull, '两个绑定对必须各拉一次').toHaveBeenCalledTimes(2); expect(H.pull.mock.calls.map((call) => call[0])).toEqual([ expect.objectContaining({ mainBranchCode: 'BR002', supplierCode: 'SUP-A' }), expect.objectContaining({ mainBranchCode: 'BR003', supplierCode: 'SUP-B' }), ]); // 合并结果:两对各自的映射都落库(total/upserted = 2,不是只看第一个绑定的 1) expect(summary).toMatchObject({ total: 2, upserted: 2, pages: 2, truncated: false, deleted: 0 }); }); it('D5 拉取:任一对失败 ⇒ truncated=true 且不删本地行(不误删)', async () => { const db = installDb({ pairs: [ { main_branch_code: 'BR002', main_supplier_code: 'SUP-A' }, { main_branch_code: 'BR003', main_supplier_code: 'SUP-B' }, ], }); H.pull.mockImplementation(async (input: { supplierCode: string }) => { if (input.supplierCode === 'SUP-B') return { kind: 'unavailable', reason: 'main system 503' }; return { kind: 'ok', rows: [ { supplier_sku_code: 'SKU-A1', supplier_sku_name: 'A1', supplier_unit: '斤', delivery_sku_code: 'D-A1', delivery_sku_name: 'A1(配送)', status: 'active', }, ], nextCursor: null, total: 1, }; }); const summary = await pullMappingsFromMainSystem({ branchCode: BRANCH }); expect(summary.truncated).toBe(true); expect(summary.total, '已拉到的部分保留(不整单丢弃)').toBe(1); expect( db.calls.some((call) => call.sql.includes('DELETE FROM main_system_sku_mappings')), '未证明拉全 ⇒ 不得删除本地映射(BIZ-12 最危险的后果)' ).toBe(false); }); it('回退:没有成对绑定 ⇒ 沿用旧口径(单供应商码 + 主系统分公司码),且只出站一次', async () => { const db = installDb({ pairs: [], fallbackBranchCodes: [BRANCH] }); H.push.mockImplementation(async () => ({ kind: 'ok', data: { matched: 0, pending: 1, kept: 0, total: 1 } })); const summary = await pushSkuDictionaryForBranch({ branchCode: BRANCH }); expect(H.resolveMainSupplierCode).toHaveBeenCalledWith(BRANCH); expect(H.push).toHaveBeenCalledTimes(1); expect(H.push.mock.calls[0][0]).toMatchObject({ mainBranchCode: BRANCH, supplierCode: 'SUP-LEGACY' }); expect(summary.batches).toBe(1); expect(db.calls.some((call) => call.sql.includes('FROM public.main_supplier_bindings'))).toBe(true); }); it('回退也拿不到供应商码 ⇒ 409 main_supplier_code_missing(不静默零出站)', async () => { installDb({ pairs: [], fallbackBranchCodes: [BRANCH] }); H.resolveMainSupplierCode.mockResolvedValue(null); await expect(pushSkuDictionaryForBranch({ branchCode: BRANCH })).rejects.toMatchObject({ status: 409, code: 'main_supplier_code_missing', }); expect(H.push).not.toHaveBeenCalled(); }); it('开关关闭 ⇒ 仍然零出站(本修复不改变开关语义)', async () => { delete process.env.MAIN_SYSTEM_QUOTE_PRICE_PROPOSAL; expect(isSkuMappingEnabled()).toBe(false); installDb({ pairs: [{ main_branch_code: 'BR002', main_supplier_code: 'SUP-A' }] }); await expect(pushSkuDictionaryForBranch({ branchCode: BRANCH })).rejects.toMatchObject({ status: 503, code: 'feature_disabled', }); expect(H.push).not.toHaveBeenCalled(); }); });