主系统回执:§4.5.18(其 da2643ec)+ §4.5.19(其 2fc473f9)。逐条落地:
① **复核他们的日期修复(只读,已通过)**:真对接 token 调 GET /api/supplier/quality-reports?days=7,
我 E2E 报告回显 produced_at=2026-10-08 / compare_at=2026-10-11 / delivery_date=2026-10-11(修前 10-07/10-10)
⇒ 与库真值一致;无需回补(我们只存他们回执的 data.id,从不把回显当权威)。
② **护栏 A:409 staff_report_exists ⇒ 终态 + 告警、不重试**(他们保护人工报告,机器推送不覆盖)
· 新增 outcome kind `blocked_by_staff_report`;台账落 `failed` + last_error 写明"改行挂靠或等其撤下"
· 回执映射现在与他们 §2.12.9 表完全一致:200/404(ignored)/409(终态)/400(终态)/401(换 token)/5xx(退避)
③ **按行撤下:确认按他们的 void 语义做**(§2.12.12 已回执请其开工)
· 新增客户端 `voidSupplierBatchReport` → `POST /api/supplier/quality-reports/:id/void`(从端点表取基路径,不硬编码 URL)
· 失效侦测命中(台账 stored 但候选消失)⇒ **自动调 /void**;成功 ⇒ 台账落终态 `voided`(迁移 20261037 扩 CHECK);
404(端点未就绪/报告不存在)⇒ 保持 stale 并记原因、**不重试风暴** ⇒ **他们端点一上线,下轮对账自动清历史 stale,无需再改我方代码**
· 选择 void 而非"只解挂靠"的理由已写明(一行一条报告行;文件要服务别的行就在正确的行重新登记)
④ `batch_no`:接受他们建议——一行跨多批次时**保持 null**(我方台账 our_batch_nos 记全)
验证:server tsc ✅;回归 40 例(服务 22 + 调用层 18)全绿(新增:409 终态、stale→voided、404 保持 stale、
void 回执映射 200/already/404/401/503);全量 380 文件 / 2418 用例 ⇒ 失败 25 文件
= 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice;门禁同基线。
236 lines
11 KiB
TypeScript
236 lines
11 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||
|
||
/**
|
||
* 第九批:**主系统调用层**的报文守卫(契约 §2.12.9 ①②③)。
|
||
*
|
||
* 服务层已钉住"传什么参数",这里钉住**真正发出去的 HTTP 报文**:
|
||
* · 登记 body = 蛇形字段,且**只有** `preparation_id` / `files` / `report_type` + 四个来源字段;
|
||
* **绝不出现** `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<string, any>;
|
||
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<string, any>).body as Record<string, unknown>;
|
||
expect(Object.keys(body).sort()).toEqual(
|
||
['batch_no', 'files', 'preparation_id', 'produced_at', 'product_names', 'report_type', 'testing_org'].sort()
|
||
);
|
||
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<string, any>).body as Record<string, unknown>;
|
||
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<string, any>;
|
||
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('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' });
|
||
});
|
||
});
|