import { readFileSync } from 'node:fs'; import path from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 小程序库存入库:上传批次报告 → **只解析不落库** → 勾选待入库行 → 入库成功后绑定。 * * 设计:`docs/design/20261021-小程序库存入库携带批次报告.md` * 开发者口径:报告可在入库时落库;一份可挂多行、一行可挂多份;**绑定失败不阻断入库**。 * * 这里钉住四条容易做错的: * ① 解析接口不得写库(否则用户放弃就留一堆待确认报告); * ② 绑定必须 `status=30` + `match_source='manual'`,且挂在入库后的 `inventory_id` 上; * ③ 绑定失败只回报、不抛错(入库已成功); * ④ 入库服务与小程序面板的接线不回退(`report_bindings` / 增量 setData)。 */ const H = vi.hoisted(() => ({ query: vi.fn(), connect: vi.fn(), getObject: vi.fn(async () => ({ buffer: Buffer.from('%PDF-1.4'), contentType: 'application/pdf', })), callWithFile: vi.fn(async () => ''), })); vi.mock('../src/db', () => ({ pool: { query: (...args: unknown[]) => H.query(...args), connect: (...args: unknown[]) => H.connect(...args), }, })); vi.mock('../src/services/storageProvider', () => ({ getStorageProvider: () => ({ getObject: (...args: unknown[]) => H.getObject(...args), putObject: vi.fn(), getReadRedirectUrl: vi.fn(async () => null), }), })); vi.mock('../src/services/llmService', () => ({ hasRuntimeConfig: vi.fn(async () => true), callWithImage: vi.fn(async () => ''), callWithFile: (...args: unknown[]) => H.callWithFile(...args), })); vi.mock('../src/services/promptRegistryService', () => ({ resolvePrompt: vi.fn(async () => ({ systemPrompt: 'stub' })), })); vi.mock('../src/services/auditService', () => ({ writeAuditLog: vi.fn(async () => undefined), })); import { attachBatchReportsToInventory, parseBatchReportForInbound, } from '../src/services/inventoryBatchReportService'; const BRANCH = 'SUP35143228'; const INVENTORY_ID = '22222222-2222-2222-2222-222222222222'; const FILE = `${BRANCH}/report.pdf`; type SqlCall = [string, unknown[]?]; function callsOf(client: { query: ReturnType }, pattern: RegExp): SqlCall[] { return (client.query.mock.calls as SqlCall[]).filter(([sql]) => pattern.test(String(sql))); } function makeClient(handlers: { duplicateReportNo?: boolean; existingReportId?: string } = {}) { return { query: vi.fn(async (sql: string) => { if (/SELECT id FROM inventory_batch_reports/i.test(sql)) { return handlers.existingReportId ? { rows: [{ id: handlers.existingReportId }], rowCount: 1 } : { rows: [], rowCount: 0 }; } if (/SELECT 1 FROM inventory_batch_reports/i.test(sql)) { return handlers.duplicateReportNo ? { rows: [{ '?column?': 1 }], rowCount: 1 } : { rows: [], rowCount: 0 }; } if (/INSERT INTO inventory_batch_reports/i.test(sql)) { return { rows: [{ id: 'report-1' }], rowCount: 1 }; } if (/INSERT INTO inventory_batch_report_matches/i.test(sql)) { return { rows: [], rowCount: 1 }; } return { rows: [], rowCount: 0 }; }), release: vi.fn(), }; } beforeEach(() => { H.query.mockReset(); H.connect.mockReset(); H.getObject.mockClear(); H.callWithFile.mockReset(); }); describe('parseBatchReportForInbound(只解析不落库)', () => { it('返回品名/生产日期,并给出唯一/未命中的行建议', async () => { H.callWithFile.mockResolvedValue( '{"product_names":["青笋","生菜","土豆"],"produced_at":"2026-10-15","testing_org":"某检测中心"}' ); const out = await parseBatchReportForInbound({ file: FILE, branchCode: BRANCH, lines: [{ name: '去皮青笋' }, { name: '生菜' }], }); expect(out.file_path).toBe(FILE); expect(out.product_names).toEqual(['青笋', '生菜', '土豆']); expect(out.produced_at).toBe('2026-10-15'); expect(out.testing_org).toBe('某检测中心'); expect(out.suggestions).toEqual([ { product_name: '青笋', line_indexes: [0], status: 'unique' }, { product_name: '生菜', line_indexes: [1], status: 'unique' }, { product_name: '土豆', line_indexes: [], status: 'none' }, ]); // 只解析:不得落库(pool.connect 一次都不能调) expect(H.connect).not.toHaveBeenCalled(); }); it('一个品名命中多行 ⇒ multi(不猜,交人工选)', async () => { H.callWithFile.mockResolvedValue('{"product_names":["青笋"]}'); const out = await parseBatchReportForInbound({ file: FILE, branchCode: BRANCH, lines: [{ name: '去皮青笋' }, { name: '青笋段' }], }); expect(out.suggestions[0]).toMatchObject({ line_indexes: [0, 1], status: 'multi' }); }); it('他分支文件 key ⇒ 403 且不读对象', async () => { await expect( parseBatchReportForInbound({ file: 'SUP37831443/report.pdf', branchCode: BRANCH, lines: [], }) ).rejects.toMatchObject({ status: 403 }); expect(H.getObject).not.toHaveBeenCalled(); }); }); describe('attachBatchReportsToInventory(入库后绑定)', () => { function mockInventoryFound() { H.query.mockImplementation(async (sql: string) => { if (/FROM inventory i/i.test(sql)) { return { rows: [ { id: INVENTORY_ID, sku_code: 'SKU1', batch_no: 'STK001', production_date: '2026-10-15', sku_name: '去皮青笋', }, ], rowCount: 1, }; } return { rows: [], rowCount: 0 }; }); } it('落库即已确认 + manual 关联,且元数据形状收敛', async () => { mockInventoryFound(); const client = makeClient(); H.connect.mockResolvedValue(client); const out = await attachBatchReportsToInventory({ inventoryId: INVENTORY_ID, branchCode: BRANCH, uploadedBy: 'user-1', reports: [ { file_path: FILE, report_type: 'pesticide', report_no: ' 2026-001 ', product_names: [' 青笋 ', '青笋', '', '土豆'], produced_at: '2026/10/15', testing_org: ' 某检测中心 ', }, ], }); expect(out).toEqual({ bound: 1, failed: [] }); const [, params] = callsOf(client, /INSERT INTO inventory_batch_reports/i)[0]; expect(params?.[2]).toBe('pesticide'); expect(params?.[4]).toEqual(['青笋', '土豆']); // 去空格 + 去重 expect(params?.[5]).toBe('2026-10-15'); // 日期归一 expect(params?.[7]).toBe(30); // 直绑即已确认 const [matchSql, matchParams] = callsOf( client, /INSERT INTO inventory_batch_report_matches/i )[0]; expect(matchSql).toContain("'manual'"); expect(matchParams?.[1]).toBe(INVENTORY_ID); expect(matchParams?.[3]).toBe('去皮青笋'); }); it('同一份报告挂多行 ⇒ 复用已有报告行,只补关联(不产生重复报告)', async () => { mockInventoryFound(); const client = makeClient({ existingReportId: 'report-existing' }); H.connect.mockResolvedValue(client); const out = await attachBatchReportsToInventory({ inventoryId: INVENTORY_ID, branchCode: BRANCH, reports: [{ file_path: FILE, report_type: 'pesticide', report_no: '2026-001' }], }); expect(out).toEqual({ bound: 1, failed: [] }); expect(callsOf(client, /INSERT INTO inventory_batch_reports/i)).toHaveLength(0); const [, matchParams] = callsOf(client, /INSERT INTO inventory_batch_report_matches/i)[0]; expect(matchParams?.[0]).toBe('report-existing'); expect(matchParams?.[1]).toBe(INVENTORY_ID); }); it('报告编号重复 ⇒ 该份 failed,**不抛错**(入库已成功)', async () => { mockInventoryFound(); const client = makeClient({ duplicateReportNo: true }); H.connect.mockResolvedValue(client); const out = await attachBatchReportsToInventory({ inventoryId: INVENTORY_ID, branchCode: BRANCH, reports: [{ file_path: FILE, report_type: 'batch', report_no: 'DUP' }], }); expect(out.bound).toBe(0); expect(out.failed).toHaveLength(1); expect(out.failed[0].error).toContain('DUP'); expect(callsOf(client, /INSERT INTO inventory_batch_reports/i)).toHaveLength(0); }); it('入库批次不存在 ⇒ 全部 failed,不抛错', async () => { H.query.mockResolvedValue({ rows: [], rowCount: 0 }); const out = await attachBatchReportsToInventory({ inventoryId: INVENTORY_ID, branchCode: BRANCH, reports: [{ file_path: FILE }], }); expect(out).toEqual({ bound: 0, failed: [{ file_path: FILE, error: '入库批次不存在' }] }); expect(H.connect).not.toHaveBeenCalled(); }); }); describe('接线契约(入库服务 + 移动端路由 + 小程序面板)', () => { const batchService = readFileSync( path.join(__dirname, '../src/services/stockInboundBatchService.ts'), 'utf8' ); const route = readFileSync( path.join(__dirname, '../src/routes/mobile/mobileInventoryRoutes.ts'), 'utf8' ); const panel = readFileSync( new URL('../../miniprogram/components/stock-inbound-panel/index.js', import.meta.url), 'utf8' ); const panelWxml = readFileSync( new URL('../../miniprogram/components/stock-inbound-panel/index.wxml', import.meta.url), 'utf8' ); it('批量入库在提交成功后绑定报告,并把结果回给前端', () => { expect(batchService).toContain('attachBatchReportsToInventory'); expect(batchService).toContain('report_bindings'); expect(batchService).toContain('reports?: InboundReportAttachment[] | null'); // 绑定环节抛错也不能把入库变成失败(开发者口径:入库必须成功) expect(batchService).toMatch(/try \{\s*const attached = await attachBatchReportsToInventory/); }); it('移动端有「只解析」路由,且不写库', () => { expect(route).toContain("'/inventory/batch-report/parse'"); expect(route).toContain('parseBatchReportForInbound'); expect(route).toContain('requireStockInboundRole'); }); it('小程序:附件挂在行上、按 key 定位、只做增量 setData', () => { expect(panel).toContain('openReportSheet'); expect(panel).toContain('parseStockInboundBatchReport'); // 增量补丁而不是整表重建(整表重建会把已识别行/附件冲掉) expect(panel).toContain('patch[`lines[${index}].reports`]'); expect(panel).toContain('reports: (Array.isArray(line.reports) ? line.reports : [])'); // 入库返回的报告绑定失败要提示去 Web 补挂 expect(panel).toContain('report_bindings'); expect(panel).toContain('已入库,报告未挂上'); }); it('小程序:报告弹层入口与行内标记都在模板里', () => { expect(panelWxml).toContain('bindtap="openReportSheet"'); expect(panelWxml).toContain('class="report-chip"'); expect(panelWxml).toContain('catchtap="applyReportToLines"'); }); });