import { readFileSync } from 'node:fs'; import path from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 库存「修改批次」弹窗里的报告:**按批次直传**(不再解析匹配)与**修改类型/编号**。 * * 设计:`docs/design/20261021-库存批次报告按批次直传与修改.md` * * 三条易复发缺陷在这里钉住: * ① 页级上传虽然传了 `report_type`,服务端曾硬编码 `'batch'` ⇒ 选农残也存成批次; * ② 批次已确定时还走「解析 → 猜批次 → 人工确认」是多余步骤,直传必须落 * `status = 30` + `match_source = 'manual'` 的关联行; * ③ 修改只能改类型/编号,且必须校验报告属于当前分公司、编号不撞同分公司唯一索引。 */ const H = vi.hoisted(() => ({ query: vi.fn(), connect: vi.fn(), getObject: vi.fn(async () => ({ buffer: Buffer.from('%PDF-1.4'), contentType: 'application/pdf', })), })); 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), }), })); // OCR 降级:不连 LLM(元数据留空,不影响绑定) vi.mock('../src/services/llmService', () => ({ hasRuntimeConfig: vi.fn(async () => false), callWithImage: vi.fn(), callWithFile: vi.fn(), })); vi.mock('../src/services/promptRegistryService', () => ({ resolvePrompt: vi.fn(async () => ({ systemPrompt: '' })), })); vi.mock('../src/services/auditService', () => ({ writeAuditLog: vi.fn(async () => undefined), })); import { createInventoryBatchReportsForInventory, normalizeBatchReportType, updateInventoryBatchReport, } from '../src/services/inventoryBatchReportService'; const BRANCH = 'SUP35143228'; const INVENTORY_ID = '11111111-1111-1111-1111-111111111111'; type SqlCall = [string, unknown[]?]; function clientWith(handlers: { selectReport?: (params: unknown[]) => { rows: unknown[]; rowCount: number }; duplicate?: boolean; }) { const client = { query: vi.fn(async (sql: string, params?: unknown[]) => { 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 }; } if (/SELECT 1 FROM inventory_batch_reports/i.test(sql)) { return { rows: handlers.duplicate ? [{ '?column?': 1 }] : [], rowCount: handlers.duplicate ? 1 : 0 }; } if (/FROM inventory_batch_reports/i.test(sql) && /FOR UPDATE/i.test(sql)) { return handlers.selectReport?.(params || []) ?? { rows: [], rowCount: 0 }; } return { rows: [], rowCount: 0 }; }), release: vi.fn(), }; return client; } function callsOf(client: { query: ReturnType }, pattern: RegExp): SqlCall[] { return (client.query.mock.calls as SqlCall[]).filter(([sql]) => pattern.test(String(sql))); } beforeEach(() => { H.query.mockReset(); H.connect.mockReset(); H.getObject.mockClear(); }); describe('normalizeBatchReportType', () => { it('只放行四种报告类型,未知值兜底 batch', () => { expect(normalizeBatchReportType('batch')).toBe('batch'); expect(normalizeBatchReportType('PESTICIDE')).toBe('pesticide'); expect(normalizeBatchReportType(' quarantine ')).toBe('quarantine'); expect(normalizeBatchReportType('annual')).toBe('annual'); expect(normalizeBatchReportType('whatever')).toBe('batch'); expect(normalizeBatchReportType(null)).toBe('batch'); }); }); describe('createInventoryBatchReportsForInventory(按批次直传)', () => { it('落库即已确认,并写 manual 关联行指向该批次', async () => { 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-01', sku_name: '去皮青笋', }, ], rowCount: 1, }; } if (/FROM inventory_batch_report_matches m/i.test(sql)) { return { rows: [ { id: 'report-1', report_no: '2026-001', report_type: 'pesticide', status: 30, file_paths: [`${BRANCH}/abc.pdf`], uploaded_at: '2026-10-21 10:00', }, ], rowCount: 1, }; } return { rows: [], rowCount: 0 }; }); const client = clientWith({}); H.connect.mockResolvedValue(client); const out = await createInventoryBatchReportsForInventory({ inventoryId: INVENTORY_ID, files: [`${BRANCH}/abc.pdf`], branchCode: BRANCH, reportType: 'pesticide', reportNo: '2026-001', uploadedBy: 'user-1', }); const [insertSql, insertParams] = callsOf(client, /INSERT INTO inventory_batch_reports/i)[0]; expect(insertSql).toContain('inventory_batch_reports'); // report_type 必须来自入参(改前硬编码 'batch',选农残也存成批次) expect(insertParams?.[2]).toBe('pesticide'); // 直传 = 已确认 expect(insertParams?.[9]).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('去皮青笋'); expect(matchParams?.[4]).toBe('STK001'); expect(out).toHaveLength(1); expect(out[0].report_type).toBe('pesticide'); }); it('批次不属于当前分公司 ⇒ 400,且不落库', async () => { H.query.mockResolvedValue({ rows: [], rowCount: 0 }); const client = clientWith({}); H.connect.mockResolvedValue(client); await expect( createInventoryBatchReportsForInventory({ inventoryId: INVENTORY_ID, files: [`${BRANCH}/abc.pdf`], branchCode: BRANCH, }) ).rejects.toMatchObject({ status: 400, code: 'invalid_inventory' }); expect(client.query).not.toHaveBeenCalled(); }); it('他分支文件 key ⇒ 归属断言拒绝(403),不读对象', async () => { await expect( createInventoryBatchReportsForInventory({ inventoryId: INVENTORY_ID, files: ['SUP37831443/abc.pdf'], branchCode: BRANCH, }) ).rejects.toMatchObject({ status: 403 }); expect(H.getObject).not.toHaveBeenCalled(); }); }); describe('updateInventoryBatchReport(修改类型/编号)', () => { it('只改传入字段,保留原值', async () => { const client = clientWith({ selectReport: () => ({ rows: [{ id: 'report-1', report_type: 'batch', report_no: 'OLD' }], rowCount: 1, }), }); H.connect.mockResolvedValue(client); const out = await updateInventoryBatchReport({ reportId: 'report-1', branchCode: BRANCH, reportType: 'quarantine', }); const [, params] = callsOf(client, /UPDATE inventory_batch_reports/i)[0]; expect(params).toEqual(['report-1', BRANCH, 'quarantine', 'OLD']); expect(out).toMatchObject({ report_type: 'quarantine', report_no: 'OLD' }); }); it('编号打成空串 = 清空', async () => { const client = clientWith({ selectReport: () => ({ rows: [{ id: 'report-1', report_type: 'batch', report_no: 'OLD' }], rowCount: 1, }), }); H.connect.mockResolvedValue(client); const out = await updateInventoryBatchReport({ reportId: 'report-1', branchCode: BRANCH, reportNo: '', }); expect(out.report_no).toBeNull(); }); it('编号撞同分公司唯一索引 ⇒ 400 report_no_exists(不是 500)', async () => { const client = clientWith({ selectReport: () => ({ rows: [{ id: 'report-1', report_type: 'batch', report_no: null }], rowCount: 1, }), duplicate: true, }); H.connect.mockResolvedValue(client); await expect( updateInventoryBatchReport({ reportId: 'report-1', branchCode: BRANCH, reportNo: 'DUP' }) ).rejects.toMatchObject({ status: 400, code: 'report_no_exists' }); }); it('报告不属于当前分公司 ⇒ 404', async () => { const client = clientWith({ selectReport: () => ({ rows: [], rowCount: 0 }) }); H.connect.mockResolvedValue(client); await expect( updateInventoryBatchReport({ reportId: 'report-1', branchCode: BRANCH, reportType: 'annual' }) ).rejects.toMatchObject({ status: 404 }); expect(callsOf(client, /UPDATE inventory_batch_reports/i)).toHaveLength(0); }); }); /** * 源码契约:路由必须把 `report_type` 转发下去(改前前端传了、路由没转发、服务端硬编码), * 且直传/修改两个入口都在。 */ describe('批次报告路由契约', () => { const routes = readFileSync( path.join(__dirname, '../src/modules/workflow/routes/inventoryRoutes.ts'), 'utf8' ); it('页级上传转发 report_type', () => { expect(routes).toContain('reportType: req.body?.report_type'); }); it('提供按批次直传与修改两个入口', () => { expect(routes).toContain("'/inventory/batch-reports/bind'"); expect(routes).toContain("router.patch('/inventory/batch-reports/:id'"); expect(routes).toContain('createInventoryBatchReportsForInventory'); expect(routes).toContain('updateInventoryBatchReport'); }); });