import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 批次报告推送(第九批)—— 契约守卫。 * * 权威:`docs/给主系统AI的对接改造清单.md` §2.12.9(最终调用契约)/ §4.5.17(逐条回执)。 * 这里钉住五类**做反就要返工**的行为: * ① 默认关 ⇒ 零出站;未绑定 / 非主系统下发的行 ⇒ 零出站(三重门禁); * ② 幂等:文件集指纹未变 + 已终态 ⇒ **不重推**;指纹变了(事后补充)⇒ **推完整文件集**; * ③ 请求体只含契约允许的字段(**绝不带** defer_coverage / sku_code / order_code / branch_code / supplier_code); * ④ 回执映射:200 stored / 404 ignored(终态) / 400 failed(终态) / 5xx transient(重试); * ⑤ 上传前置校验:仅 pdf+图片、单文件 ≤10MB。 */ const query = vi.hoisted(() => vi.fn()); const getObject = vi.hoisted(() => vi.fn()); const upload = vi.hoisted(() => vi.fn()); const register = vi.hoisted(() => vi.fn()); const voidReport = vi.hoisted(() => vi.fn()); const tenantCtx = vi.hoisted(() => vi.fn()); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => query(...args) }, getRawPoolQuery: () => query, })); vi.mock('../src/services/tenantDbContext', () => ({ runWithTenantDbContext: (...args: unknown[]) => tenantCtx(...args), })); vi.mock('../src/services/storageProvider', () => ({ getStorageProvider: () => ({ getObject: (...args: unknown[]) => getObject(...args) }), })); vi.mock('../src/services/mainSystem/api/qualityReports', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, uploadBatchReportFile: (...args: unknown[]) => upload(...args), registerBatchReportOnPreparation: (...args: unknown[]) => register(...args), voidSupplierBatchReport: (...args: unknown[]) => voidReport(...args), }; }); import { collectReportPushCandidates, filesFingerprint, isReportPushEnabled, pushBranchReports, pushReportCandidate, runReportPushReconcile, triggerReportPush, type ReportPushCandidate, } from '../src/services/mainSystemReportPushService'; function candidate(overrides: Partial = {}): ReportPushCandidate { return { branch_code: 'BR003', main_branch_code: 'BR002', main_supplier_code: 'SUP41472132', prep_id: '11111111-1111-1111-1111-111111111111', main_order_code: 'ORD_WEB_20261010_BR002_0001', our_order_code: 'ORD_API_20261010_BR003_0001', our_order_item_id: '22222222-2222-2222-2222-222222222222', report_type: 'batch', our_file_paths: ['batch/a.pdf'], report_ids: ['33333333-3333-3333-3333-333333333333'], batch_nos: ['STK202610107YRQEO'], batch_no: 'STK202610107YRQEO', produced_at: '2026-10-08', testing_org: 'XX检测中心', product_names: ['香菇', '平菇'], ...overrides, }; } /** 台账 INSERT ... RETURNING 的应答 */ function ledgerRow(patch: Partial<{ file_fingerprint: string; status: string; our_file_paths: string[]; their_file_paths: string[] }> = {}) { return { id: '99', file_fingerprint: patch.file_fingerprint ?? filesFingerprint(['batch/a.pdf'], ['STK202610107YRQEO']), status: patch.status ?? 'pending', our_file_paths: patch.our_file_paths ?? [], their_file_paths: patch.their_file_paths ?? [], }; } beforeEach(() => { query.mockReset(); getObject.mockReset(); upload.mockReset(); register.mockReset(); voidReport.mockReset(); tenantCtx.mockReset(); // 默认:直接执行回调(等价于"上下文可用"),并记录调用参数 tenantCtx.mockImplementation(async (_code: string, fn: () => Promise) => fn()); delete process.env.MAIN_SYSTEM_REPORT_ENABLED; query.mockResolvedValue({ rows: [ledgerRow()], rowCount: 1 }); getObject.mockResolvedValue({ buffer: Buffer.from('%PDF-1.4 test') }); }); describe('门禁:默认关 / 未绑定 ⇒ 零出站', () => { it('开关未打开时 pushBranchReports 直接返回且**不查库**', async () => { const stat = await pushBranchReports({ branchCode: 'BR003' }); expect(stat).toEqual({ candidates: 0, stored: 0, ignored: 0, failed: 0, skipped: 0, transient: 0, stale: 0 }); expect(query).not.toHaveBeenCalled(); expect(upload).not.toHaveBeenCalled(); expect(register).not.toHaveBeenCalled(); }); it('triggerReportPush(触发点入口)在关闭时同样零出站', () => { triggerReportPush('BR003'); expect(query).not.toHaveBeenCalled(); expect(isReportPushEnabled()).toBe(false); }); it('候选采集 SQL 把"绑定 + 主系统下发的行"写进 WHERE/JOIN(未绑定天然查不出来)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockResolvedValueOnce({ rows: [] }); await collectReportPushCandidates({ branchCode: 'BR003' }); const sql = String(query.mock.calls[0]?.[0] || ''); expect(sql).toContain("b.status = 'active'"); // ① 必须有 active 绑定 expect(sql).toContain('l.prep_id IS NOT NULL'); // ② 必须是主系统下发的行(有 prep_id 对照) expect(sql).toContain('r.status = 30'); // ③ 报告必须已人工确认 expect(sql).toContain('outbound_batches'); // 源① 分拣选定的批次 }); it('**双源**:除分拣计划外,还要覆盖「实际出库流水」(没开分拣的单也能推)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockResolvedValueOnce({ rows: [] }); await collectReportPushCandidates({ branchCode: 'BR003' }); const sql = String(query.mock.calls[0]?.[0] || ''); expect(sql).toContain('inventory_logs'); // 源② expect(sql).toContain("'picking_out'"); // 分拣出库 expect(sql).toContain("'delivery_loading_out'"); // 发车核货出库(无分拣单走这条) expect(sql).toContain('il.related_order_code = o.order_code'); // 挂到订单行的键 expect(sql).toContain('il.batch_no = inv.batch_no'); expect(sql).not.toContain('delivery_loading_restore'); // 冲正不算消耗 }); it('候选按 (prep_id, report_type) **聚合**,不按批次分组(E2E 踩过:分组会让后推覆盖前推)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockResolvedValueOnce({ rows: [] }); await collectReportPushCandidates({ branchCode: 'BR003' }); const sql = String(query.mock.calls[0]?.[0] || ''); // GROUP BY 里**不能**出现 h.batch_no(否则同一行多批次会被拆成多条候选、互相作废) const groupBy = sql.slice(sql.indexOf('GROUP BY'), sql.indexOf('ORDER BY')); expect(groupBy).not.toContain('h.batch_no'); expect(groupBy).toContain('l.prep_id'); // 多批次时 batch_no 留空(对方是单值列、≤50 字符,无法表达多个) expect(sql).toContain('count(DISTINCT h.batch_no) = 1'); expect(sql).toContain('array_agg(DISTINCT unnest_name)'); }); }); describe('幂等:指纹未变不重推,变了推完整集', () => { it('指纹稳定:与顺序无关、去重', () => { expect(filesFingerprint(['b.pdf', 'a.pdf', 'a.pdf'])).toBe(filesFingerprint(['a.pdf', 'b.pdf'])); }); it('③ 换绑(文件没变、批次变了)⇒ 指纹必须变(否则修正静默丢失)', () => { expect(filesFingerprint(['a.pdf'], ['STK-A'])).not.toBe(filesFingerprint(['a.pdf'], ['STK-B'])); expect(filesFingerprint(['a.pdf'], ['STK-A'])).toBe(filesFingerprint(['a.pdf'], ['STK-A'])); }); it('③ 同集换绑 ⇒ 触发重推(不是 skipped)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; // 台账里旧指纹对应批次 STK-OLD,本次候选批次 STK-NEW(文件相同) query.mockResolvedValueOnce({ rows: [ledgerRow({ file_fingerprint: filesFingerprint(['batch/a.pdf'], ['STK-OLD']), status: 'stored' })], rowCount: 1, }); upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' }); register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-2', status: 200, payload: {} }); const result = await pushReportCandidate(candidate({ batch_nos: ['STK-NEW'] })); expect(result.status).toBe('stored'); expect(register).toHaveBeenCalledTimes(1); }); it('已 stored 且指纹未变 ⇒ 不调用任何出站接口', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockResolvedValueOnce({ rows: [ledgerRow({ status: 'stored', our_file_paths: ['batch/a.pdf'], their_file_paths: ['rnd-1.pdf'] })], rowCount: 1, }); const result = await pushReportCandidate(candidate()); expect(result.status).toBe('skipped'); expect(upload).not.toHaveBeenCalled(); expect(register).not.toHaveBeenCalled(); }); it('文件集变化(事后补充)⇒ 重推**完整文件集**(旧文件一起传)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; const files = ['batch/a.pdf', 'batch/b.pdf']; // 台账旧指纹只有 a.pdf ⇒ 与本次指纹不同 ⇒ 必须重推 query.mockResolvedValueOnce({ rows: [ledgerRow({ file_fingerprint: filesFingerprint(['batch/a.pdf']), status: 'stored', our_file_paths: ['batch/a.pdf'], their_file_paths: ['rnd-a.pdf'] })], rowCount: 1, }); upload.mockResolvedValue({ kind: 'ok', path: 'rnd-new.pdf' }); register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-1', status: 200, payload: {} }); const result = await pushReportCandidate(candidate({ our_file_paths: files })); expect(result.status).toBe('stored'); // a.pdf 命中缓存不重复上传;b.pdf 新上传 ⇒ 登记时必须带**完整集** expect(upload).toHaveBeenCalledTimes(1); const registered = register.mock.calls[0][0] as { files: string[] }; expect(registered.files).toEqual(['rnd-a.pdf', 'rnd-new.pdf']); }); }); describe('契约字段:只传允许的,绝不带 defer_coverage 与派生字段', () => { it('传给登记 API 的参数只含契约允许项(派生字段一律不带)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' }); register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-1', status: 200, payload: {} }); await pushReportCandidate(candidate()); const input = register.mock.calls[0][0] as Record; expect(Object.keys(input).sort()).toEqual( ['batchNo', 'files', 'preparationId', 'producedAt', 'productNames', 'reportType', 'supplierCode', 'testingOrg'].sort() ); expect(input.reportType).toBe('batch'); expect(input.files).toEqual(['rnd-1.pdf']); // 契约 §2.12.9 ④-2/④-4:绝不出现这些键(含 defer_coverage) for (const forbidden of ['deferCoverage', 'defer_coverage', 'skuCode', 'orderCode', 'branchCode', 'categoryCode', 'deliveryDate']) { expect(input[forbidden]).toBeUndefined(); } }); }); describe('回执映射(§2.12.9 ③)', () => { beforeEach(() => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' }); }); it('404 ⇒ ignored(终态,不再重推)', async () => { register.mockResolvedValue({ kind: 'ignored', status: 404, reason: 'not_found' }); const result = await pushReportCandidate(candidate()); expect(result.status).toBe('ignored'); const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes')); expect(String(update?.[1]?.[1])).toBe('ignored'); }); it('400 invalid_report_type ⇒ failed(终态 + 告警)', async () => { register.mockResolvedValue({ kind: 'failed', status: 400, reason: '类型不支持', error: 'invalid_report_type' }); const result = await pushReportCandidate(candidate()); expect(result.status).toBe('failed'); }); it('5xx ⇒ transient(进重试:status 回到 pending + next_retry_at)', async () => { register.mockResolvedValue({ kind: 'transient', status: 503, reason: 'main system down' }); const result = await pushReportCandidate(candidate()); expect(result.status).toBe('transient'); const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes')); expect(String(update?.[1]?.[1])).toBe('pending'); expect(update?.[1]?.[4]).toBe(true); // retry=true }); it('401 ⇒ 也按重试处理(换 token 再试)', async () => { register.mockResolvedValue({ kind: 'token_expired', reason: 'invalid_token' }); const result = await pushReportCandidate(candidate()); expect(result.status).toBe('transient'); }); }); describe('上传前置校验(§2.12.9 ①)', () => { beforeEach(() => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; }); it('非 pdf/图片 ⇒ failed 且**不上传**', async () => { const result = await pushReportCandidate(candidate({ our_file_paths: ['batch/报告.docx'] })); expect(result.status).toBe('failed'); expect(upload).not.toHaveBeenCalled(); }); it('我方对象缺失 ⇒ failed(不静默丢)', async () => { getObject.mockResolvedValue(null); const result = await pushReportCandidate(candidate()); expect(result.status).toBe('failed'); expect(upload).not.toHaveBeenCalled(); }); }); describe('④ 失效侦测(修正后不再静默)', () => { it('候选消失且未被截断 ⇒ 标记 stale + 告警(stale 计数 = 仍未撤下数)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); query.mockReset(); query .mockResolvedValueOnce({ rows: [] }) // ① 采集:无候选 .mockResolvedValueOnce({ rows: [{ id: '99', prep_id: 'p1' }], rowCount: 1 }) // ② 标记 stale .mockResolvedValueOnce({ rows: [] }) // ③ 无带对方报告 id 的 stale ⇒ 不撤下 .mockResolvedValueOnce({ rows: [{ n: 1 }] }); // ④ 仍未撤下 = 1 const stat = await pushBranchReports({ branchCode: 'BR003' }); expect(stat.candidates).toBe(0); expect(stat.stale).toBe(1); const sql = String(query.mock.calls[1]?.[0] || ''); expect(sql).toContain("SET status = 'stale'"); expect(sql).toContain("status = 'stored'"); expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain('候选消失'); warn.mockRestore(); }); it('历史 stale 行即使本轮无新转,也要**继续尝试撤下**(E2E 第 ⑪ 步踩到的 bug)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockReset(); query .mockResolvedValueOnce({ rows: [] }) // ① 采集 .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // ② 本轮无新转 stale .mockResolvedValueOnce({ rows: [{ id: '7', main_supplier_code: 'SUP1', their_report_id: 'their-old' }] }) // ③ 历史 stale .mockResolvedValueOnce({ rows: [], rowCount: 1 }) // ④ 记"撤下未生效"原因 .mockResolvedValueOnce({ rows: [{ n: 1 }] }); // ⑤ 仍未撤下 voidReport.mockResolvedValue({ kind: 'not_found', status: 404, reason: 'HTTP 404' }); const stat = await pushBranchReports({ branchCode: 'BR003' }); expect(voidReport).toHaveBeenCalledWith({ supplierCode: 'SUP1', theirReportId: 'their-old' }); expect(stat.stale).toBe(1); }); it('候选数触到 limit(可能被截断)⇒ **不**做失效判定(避免误报)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockReset(); const many = Array.from({ length: 2 }, (_, i) => ({ ...candidate({ prep_id: `00000000-0000-0000-0000-00000000000${i}` }), our_file_paths: ['batch/a.pdf'] })); query.mockResolvedValueOnce({ rows: many.map(() => ({ branch_code: 'BR003', main_branch_code: 'BR002', main_supplier_code: 'SUP41472132', prep_id: '11111111-1111-1111-1111-111111111111', main_order_code: null, our_order_code: null, our_order_item_id: null, payload_report_type: 'batch', requires_report: 'false', batch_no: 'STK-A', batch_nos: ['STK-A'], report_ids: [], our_file_paths: ['batch/a.pdf'], produced_at: null, testing_org: null, product_names: [], })) }); query.mockResolvedValue({ rows: [ledgerRow({ status: 'stored' })], rowCount: 1 }); register.mockResolvedValue({ kind: 'stored', theirReportId: 'x', status: 200, payload: {} }); upload.mockResolvedValue({ kind: 'ok', path: 'rnd.pdf' }); await pushBranchReports({ branchCode: 'BR003', limit: 2 }); const usedStaleSql = query.mock.calls.some((c) => String(c[0]).includes("SET status = 'stale'")); expect(usedStaleSql).toBe(false); }); }); describe('定时兜底', () => { it('开关关闭 ⇒ 不查分公司、零出站', async () => { const summary = await runReportPushReconcile(); expect(summary).toEqual({ branches: 0, stored: 0, ignored: 0, failed: 0, stale: 0 }); expect(query).not.toHaveBeenCalled(); }); }); describe('护栏 A(主系统 §4.5.19):人工报告不可被机器覆盖', () => { it('409 staff_report_exists ⇒ 终态 failed + 告警,不重试', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' }); register.mockResolvedValue({ kind: 'blocked_by_staff_report', status: 409, reason: 'staff_report_exists' }); const result = await pushReportCandidate(candidate()); expect(result.status).toBe('failed'); const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes')); expect(String(update?.[1]?.[1])).toBe('failed'); // 终态 expect(update?.[1]?.[4]).toBeFalsy(); // retry=false(不是 pending) expect(String(update?.[1]?.[2])).toContain('staff_report_exists'); expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain('staff_report_exists'); warn.mockRestore(); }); }); describe('按行撤下(主系统 §4.5.18 ③)', () => { it('失效侦测命中 ⇒ 调 /void 成功后台账落 voided 终态', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockReset(); query .mockResolvedValueOnce({ rows: [] }) // 采集:无候选 .mockResolvedValueOnce({ rows: [{ id: '1', prep_id: 'p1' }], rowCount: 1 }) // 标记 stale .mockResolvedValueOnce({ rows: [{ id: '7', main_supplier_code: 'SUP1', their_report_id: 'their-1' }] }) // 待撤下 .mockResolvedValueOnce({ rows: [], rowCount: 1 }) .mockResolvedValueOnce({ rows: [{ n: 0 }] }); // 撤下成功 ⇒ 无遗留 voidReport.mockResolvedValue({ kind: 'voided', already: false }); const stat = await pushBranchReports({ branchCode: 'BR003' }); expect(stat.stale).toBe(0); // 已撤下 ⇒ 无遗留 expect(voidReport).toHaveBeenCalledWith({ supplierCode: 'SUP1', theirReportId: 'their-1' }); const voidedUpdate = query.mock.calls.find((c) => String(c[0]).includes("status = 'voided'")); expect(voidedUpdate).toBeTruthy(); }); it('撤下端点未就绪(404)⇒ **保持 stale** 并记原因,不报错', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockReset(); query .mockResolvedValueOnce({ rows: [] }) .mockResolvedValueOnce({ rows: [{ id: '1', prep_id: 'p1' }], rowCount: 1 }) .mockResolvedValueOnce({ rows: [{ id: '7', main_supplier_code: 'SUP1', their_report_id: 'their-1' }] }) .mockResolvedValueOnce({ rows: [], rowCount: 1 }) .mockResolvedValueOnce({ rows: [{ n: 1 }] }); voidReport.mockResolvedValue({ kind: 'not_found', status: 404, reason: 'not_found' }); const stat = await pushBranchReports({ branchCode: 'BR003' }); expect(stat.stale).toBe(1); const note = query.mock.calls.find((c) => String(c[0]).includes('撤下未生效') || String(c[1]?.[1] || '').includes('撤下未生效')); expect(note).toBeTruthy(); expect(query.mock.calls.some((c) => String(c[0]).includes("status = 'voided'"))).toBe(false); }); }); describe('调度器没有请求级上下文(2026-10-11 调度 tick 实测 42P01)', () => { it('pushBranchReports 必须在**租户上下文**里采集候选(去掉包裹即复发 42P01)', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; query.mockReset(); query.mockResolvedValue({ rows: [], rowCount: 0 }); await pushBranchReports({ branchCode: 'BR003' }); expect(tenantCtx).toHaveBeenCalledTimes(1); expect(tenantCtx.mock.calls[0][0]).toBe('BR003'); // 采集 SQL 必须发生在上下文回调**内部**:回调执行后才应有候选查询 const collectCall = query.mock.calls.find((c) => String(c[0]).includes('inventory_batch_report_matches')); expect(collectCall).toBeTruthy(); expect(tenantCtx.mock.invocationCallOrder[0]).toBeLessThan(query.mock.invocationCallOrder[0]); }); }); describe('撤下被拒:409 staff_report_exists(他们实测点⑦)', () => { it('该报告是主系统人工上传 ⇒ 台账转 **failed 终态** + 告警,避免每轮重试', async () => { process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); query.mockReset(); query .mockResolvedValueOnce({ rows: [] }) // ① 采集 .mockResolvedValueOnce({ rows: [], rowCount: 0 }) // ② 本轮无新转 stale .mockResolvedValueOnce({ rows: [{ id: '7', main_supplier_code: 'SUP1', their_report_id: 'staff-1' }] }) // ③ 历史 stale .mockResolvedValueOnce({ rows: [], rowCount: 1 }) // ④ 落 failed 终态 .mockResolvedValueOnce({ rows: [{ n: 0 }] }); // ⑤ 无遗留 stale voidReport.mockResolvedValue({ kind: 'blocked_by_staff_report', status: 409, reason: 'staff_report_exists' }); const stat = await pushBranchReports({ branchCode: 'BR003' }); const update = query.mock.calls.find((c) => String(c[0]).includes("status = 'failed'") && String(c[1]?.[1] || '').includes('staff_report_exists')); expect(update).toBeTruthy(); // 转终态并写明原因 expect(stat.stale).toBe(0); // 不再算"待撤下" ⇒ 下轮不会再试 expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain('staff_report_exists'); warn.mockRestore(); }); });