主系统已回执「可以开工」(其 §2.12.9 最终契约 / §4.5.17 逐条回执,接收侧提交 c24f4881)。
按契约实现我方推送侧,**未新开端点**:文件走他们 `/api/storage/quality-reports/upload`(multipart),
登记走 `/api/supplier/quality-reports`(按备货行逐条)。
**三重门禁(开发者要求"没绑定就别传、不能造成混乱")**:
① 分公司 ↔ 主系统有 active 绑定(未绑定 ⇒ 连 token 都取不到 ⇒ 物理上发不出去)
② 该行是主系统下发的(`main_system_order_import_items` 有 prep_id 对照)
③ 该批次已人工确认关联到报告
未满足 ⇒ **零出站**(采集 SQL 里就用 JOIN 卡死,且开关关闭时连候选都不查)
**幂等(B4=我方台账去重)**:新表 `public.main_system_report_pushes`,唯一键 `(prep_id, report_type)` +
**完整文件集指纹**:指纹未变 ⇒ 不重推;指纹变了(事后补充)⇒ 按**完整文件集**重推一次
(对方 latest wins:同 (prep, type) 再登记会作废旧报告,所以不能只推新增文件)。
**契约硬语义(单测钉死)**:绝不传 `defer_coverage`(暂存态:既不覆盖也不展示);
绝不传 sku/order/branch/supplier/category/delivery(对方按行派生);`report_type` 按行要求的类型
(`qualityReportType`,本轮给拉取映射补上;取不到且该行要求报告时**不猜、跳过**);
回执映射 200 stored / 404 ignored(终态) / 400 failed(终态) / 401 换 token / 5xx 退避重试。
**触发点三处**:① 分拣完成(pickingService 成功路径,旁路 fire-and-forget)
② 报告确认关联(inventoryRoutes confirm 路由)③ scheduler tick 定时兜底(默认关 ⇒ 零出站)。
**真环境冒烟(对照主系统 3001,已跑通)**:
· 上传 ⇒ `{"kind":"ok","path":"4019fbdf…png"}`(用他们回执里的 path 登记)
· 登记 ⇒ **200** `data.id=0de8d009-d28e-4124-a333-5bef819b6dac`
`order_code/BR002/sku_code/supplier_code` 全由他们从备货行派生;我们传的
`batch_no=STK202610107YRQEO`、`product_name=香菇、平菇`、`testing_org=XX检测中心` 都正确落库;
`share_key` **不以 `st|` 开头**(= 正常覆盖态,非 defer)
· 我方台账回执:`order_code=ORD_WEB_20261010_BR002_0001`、`prep_id=b4e7fd80-668d-4f9b-b69f-dcb3fddc623e`
· ⚠️ **发现对方一处回显缺陷(已坐实,待他们修)**:`POST /api/supplier/quality-reports` 回执里
`produced_at` 比传入/库里少一天(我们传 2026-10-08、他们库 `tenant_br002.quality_reports.produced_at`
实测 = 2026-10-08,但回执 JSON = 2026-10-07);`compare_at` 同样(库 2026-10-11 / 回执 2026-10-10)
⇒ 是他们 date 列的**序列化时区**问题(值没存错,只在回显),与他们清单 §2.12.9 ⑦-1
"与你们传的一致"这条判定相冲突,需他们确认修
验证:server tsc ✅;新增 27 例(服务 14 + 调用层 13)全绿;全量 380 文件 / 2405 用例 ⇒ 失败 25 文件
= 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice;门禁同基线。
设计:docs/design/20261011-批次报告推送主系统.md;冒烟脚本:server/scripts/smoke-main-system-report-push.ts
187 lines
8.1 KiB
TypeScript
187 lines
8.1 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,
|
||
uploadBatchReportFile,
|
||
} 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('走 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);
|
||
expect(options.formData.get('file')).toBeTruthy();
|
||
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',
|
||
});
|
||
});
|
||
});
|