import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 第九批:**主系统调用层**的报文守卫(契约 §2.12.9 ①②③)。 * * 服务层已钉住"传什么参数",这里钉住**真正发出去的 HTTP 报文**: * · 登记 body = 蛇形字段,且**只有** `preparation_id` / `files` / `report_type` / `share_mode` + 四个来源字段; * **绝不出现** `defer_coverage`(暂存态:既不覆盖也不展示)与派生字段(sku/order/branch/supplier/category/delivery); * · 上传是 multipart(字段名 `file`、`?path=` 是对象名),**用回执里的 `path`** 而不是我们传的名字; * · 回执映射:200 stored / 404 ignored / 401 token_expired / 5xx transient / 400 failed。 */ const requestMainSystem = vi.hoisted(() => vi.fn()); const getMainSystemToken = vi.hoisted(() => vi.fn()); vi.mock('../src/services/mainSystem/http', () => ({ requestMainSystem: (...args: unknown[]) => requestMainSystem(...args), })); vi.mock('../src/services/mainSystem/token', () => ({ getMainSystemToken: (...args: unknown[]) => getMainSystemToken(...args), })); import { MAIN_SYSTEM_REPORT_MAX_BYTES, isUploadableReportFileName, registerBatchReportOnPreparation, reportMimeFromFileName, uploadBatchReportFile, voidSupplierBatchReport, } from '../src/services/mainSystem/api/qualityReports'; beforeEach(() => { requestMainSystem.mockReset(); getMainSystemToken.mockReset(); getMainSystemToken.mockResolvedValue({ kind: 'ok', token: 'fake-token' }); }); describe('文件类型/大小前置校验(桶白名单:pdf + 图片,≤10MB)', () => { it('pdf 与常见图片放行;docx/xlsx 拒绝', () => { for (const ok of ['a.pdf', 'b.JPG', 'c.jpeg', 'd.png', 'e.webp', 'f.gif']) { expect(isUploadableReportFileName(ok)).toBe(true); } for (const bad of ['报告.docx', 'a.xlsx', 'noext', 'a.pdf.exe']) { expect(isUploadableReportFileName(bad)).toBe(false); } }); it('非白名单类型 ⇒ failed 且**不发请求**', async () => { const out = await uploadBatchReportFile({ supplierCode: 'SUP1', fileName: 'a.docx', buffer: Buffer.from('x') }); expect(out.kind).toBe('failed'); expect(requestMainSystem).not.toHaveBeenCalled(); }); it('超过 10MB ⇒ failed 且**不发请求**', async () => { const out = await uploadBatchReportFile({ supplierCode: 'SUP1', fileName: 'a.pdf', buffer: Buffer.alloc(MAIN_SYSTEM_REPORT_MAX_BYTES + 1), }); expect(out.kind).toBe('failed'); expect(requestMainSystem).not.toHaveBeenCalled(); }); }); describe('① 上传文件', () => { it('mime 按扩展名推断(传 octet-stream 会被对方桶白名单拒 —— E2E 实测)', () => { expect(reportMimeFromFileName('a.pdf')).toBe('application/pdf'); expect(reportMimeFromFileName('B.PNG')).toBe('image/png'); expect(reportMimeFromFileName('c.jpg')).toBe('image/jpeg'); expect(reportMimeFromFileName('d.webp')).toBe('image/webp'); }); it('走 multipart(formData.file)+ `?path=` 对象名,并**返回回执里的 path**', async () => { requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { path: 'rnd-9f2.pdf' } }); const out = await uploadBatchReportFile({ supplierCode: 'SUP1', fileName: 'jpg-20261008.pdf', buffer: Buffer.from('%PDF') }); expect(out).toEqual({ kind: 'ok', path: 'rnd-9f2.pdf', signedUrl: undefined }); const options = requestMainSystem.mock.calls[0][0] as Record; expect(options.endpoint).toBe('qualityReportUpload'); expect(options.method).toBe('POST'); expect(options.token).toBe('fake-token'); expect(options.query).toEqual({ path: 'jpg-20261008.pdf' }); expect(options.formData).toBeInstanceOf(FormData); const uploaded = options.formData.get('file') as File; expect(uploaded).toBeTruthy(); expect(uploaded.type).toBe('application/pdf'); // 不能是 octet-stream expect(options.body).toBeUndefined(); // multipart 与 JSON body 互斥 }); it('上传成功但回执缺 path ⇒ failed(不能拿我们自己的名字去登记)', async () => { requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: {} }); const out = await uploadBatchReportFile({ supplierCode: 'SUP1', fileName: 'a.pdf', buffer: Buffer.from('%PDF') }); expect(out.kind).toBe('failed'); }); }); describe('② 登记报告:报文只含契约允许字段', () => { it('body 字段与契约逐一对应,且**不含** defer_coverage 与派生字段', async () => { requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'their-7' } } }); const out = await registerBatchReportOnPreparation({ supplierCode: 'SUP41472132', preparationId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', files: ['rnd-1.pdf', 'rnd-2.jpg'], reportType: 'batch', batchNo: 'STK202610107YRQEO', producedAt: '2026-10-08', testingOrg: 'XX检测中心', productNames: ['香菇', '平菇'], }); expect(out).toEqual({ kind: 'stored', theirReportId: 'their-7', status: 200, payload: expect.anything() }); const body = (requestMainSystem.mock.calls[0][0] as Record).body as Record; expect(Object.keys(body).sort()).toEqual( [ 'batch_no', 'files', 'preparation_id', 'produced_at', 'product_names', 'report_type', // 方案 1(2026-10-12):显式声明**按行共用**,避免主系统按报告类型推导成 // `leaf_category`(叶子分类共用)⇒ 同分类的其它行也显示这份批次报告。 'share_mode', 'testing_org', ].sort() ); expect(body.share_mode).toBe('line'); expect(body.files).toEqual(['rnd-1.pdf', 'rnd-2.jpg']); expect(body.product_names).toEqual(['香菇', '平菇']); expect(body.report_type).toBe('batch'); expect(body.defer_coverage).toBeUndefined(); for (const forbidden of ['sku_code', 'order_code', 'branch_code', 'supplier_code', 'category_code', 'delivery_date']) { expect(body[forbidden]).toBeUndefined(); } }); it('batch_no 超长按 50 截断(对方 >50 直接 400)', async () => { requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'x' } } }); await registerBatchReportOnPreparation({ supplierCode: 'SUP1', preparationId: 'p', files: ['a.pdf'], reportType: 'batch', batchNo: 'B'.repeat(80), }); const body = (requestMainSystem.mock.calls[0][0] as Record).body as Record; expect(String(body.batch_no)).toHaveLength(50); }); it('缺 preparation_id / files / report_type ⇒ failed(invalid_request),不发请求', async () => { for (const bad of [ { preparationId: '' }, { files: [] as string[] }, { reportType: '' }, ]) { const out = await registerBatchReportOnPreparation({ supplierCode: 'SUP1', preparationId: 'p', files: ['a.pdf'], reportType: 'batch', ...bad, }); expect(out.kind).toBe('failed'); } expect(requestMainSystem).not.toHaveBeenCalled(); }); }); describe('③ 回执映射(§2.12.9 ③)', () => { const base = { supplierCode: 'SUP1', preparationId: 'p', files: ['a.pdf'], reportType: 'batch' }; it('404 not_found ⇒ ignored(终态,不重推)', async () => { requestMainSystem.mockResolvedValue({ kind: 'rejected', status: 404, reason: 'not_found', payload: { error: 'not_found' }, }); await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'ignored', status: 404 }); }); it('400 invalid_report_type ⇒ failed(带可判别 error)', async () => { requestMainSystem.mockResolvedValue({ kind: 'rejected', status: 400, reason: 'invalid_report_type', payload: { error: 'invalid_report_type' }, }); await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'failed', status: 400, error: 'invalid_report_type', }); }); it('401 ⇒ token_expired(换 token 再试)', async () => { requestMainSystem.mockResolvedValue({ kind: 'rejected', status: 401, reason: 'invalid_token', payload: { error: 'invalid_token' }, }); await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'token_expired' }); }); it('503 ⇒ transient(退避重试)', async () => { requestMainSystem.mockResolvedValue({ kind: 'unavailable', status: 503, reason: 'HTTP 503', payload: null, }); await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'transient', status: 503 }); }); it('200 ⇒ stored 并带回对方 report_id', async () => { requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { id: 'their-9', status: 'active' } }, }); await expect(registerBatchReportOnPreparation(base)).resolves.toMatchObject({ kind: 'stored', theirReportId: 'their-9', }); }); }); describe('护栏 A:409 staff_report_exists 的映射(§4.5.19)', () => { it('409 ⇒ blocked_by_staff_report(终态,不进重试)', async () => { requestMainSystem.mockResolvedValue({ kind: 'rejected', status: 409, reason: 'staff_report_exists', payload: { error: 'staff_report_exists' }, }); await expect( registerBatchReportOnPreparation({ supplierCode: 'SUP1', preparationId: 'p', files: ['a.pdf'], reportType: 'batch' }) ).resolves.toMatchObject({ kind: 'blocked_by_staff_report', status: 409 }); }); }); describe('按行撤下:POST /api/supplier/quality-reports/:id/void(§4.5.18 ③)', () => { it('成功 ⇒ voided(带回 already 标志)', async () => { requestMainSystem.mockResolvedValue({ kind: 'ok', status: 200, data: {}, payload: { data: { status: 'voided', already: true } } }); await expect(voidSupplierBatchReport({ supplierCode: 'SUP1', theirReportId: 'r-1' })).resolves.toEqual({ kind: 'voided', already: true, }); const options = requestMainSystem.mock.calls[0][0] as Record; expect(options.endpoint).toBe('qualityReportRegister'); expect(options.path).toBe('/api/supplier/quality-reports/r-1/void'); expect(options.method).toBe('POST'); }); it('404 ⇒ not_found(端点未就绪或非本供应商;保持 stale,不重试风暴)', async () => { requestMainSystem.mockResolvedValue({ kind: 'rejected', status: 404, reason: 'not_found', payload: { error: 'not_found' } }); await expect(voidSupplierBatchReport({ supplierCode: 'SUP1', theirReportId: 'r-1' })).resolves.toMatchObject({ kind: 'not_found', status: 404, }); }); it('409 staff_report_exists ⇒ blocked_by_staff_report(终态,不重试)', async () => { requestMainSystem.mockResolvedValue({ kind: 'rejected', status: 409, reason: 'staff_report_exists', payload: { error: 'staff_report_exists' }, }); await expect(voidSupplierBatchReport({ supplierCode: 'SUP1', theirReportId: 'r-1' })).resolves.toMatchObject({ kind: 'blocked_by_staff_report', status: 409, }); }); it('401 ⇒ token_expired;503 ⇒ transient', async () => { requestMainSystem.mockResolvedValueOnce({ kind: 'rejected', status: 401, reason: 'invalid_token', payload: {} }); await expect(voidSupplierBatchReport({ supplierCode: 'SUP1', theirReportId: 'r-1' })).resolves.toMatchObject({ kind: 'token_expired' }); requestMainSystem.mockResolvedValueOnce({ kind: 'unavailable', status: 503, reason: 'HTTP 503', payload: null }); await expect(voidSupplierBatchReport({ supplierCode: 'SUP1', theirReportId: 'r-1' })).resolves.toMatchObject({ kind: 'transient' }); }); });