Files
SupplierSystem/server/tests/mainSystemReportApi.test.ts
Ubuntu 8ac6cd42a5
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(报告共用范围): 推送显式声明 share_mode='line'(方案 1)+ 契约请求 + 历史清理(方案 3)
现象(开发者 2026-10-12 截图):主系统单 ORD_WEB_20261012_BR002_0004 的 水面/鲜海带丝 两行
报告格显示了「抄手皮」的批次报告;两行本身没有任何报告。

根因(主系统侧一行推导,真库证据齐全):
· 他们 `qualityReportService.shareModeForReportType()`:**batch/quarantine/inspection/annual ⇒ leaf_category**、
  pesticide ⇒ produce_day、其余 ⇒ line;
· 我方推送用 report_type='batch' ⇒ 落成 share_mode='leaf_category'、share_key=lc|SUP41472132|2026-10-13|<分类>
  ⇒ **同叶子分类的每一行都会显示它**;
· 分类确实重合:单 0004 里 水面=BR002_CAT86944033392、鲜海带丝=BR002_CAT86944033392、
  **抄手皮也=BR002_CAT86944033392**(米块同样)。
⇒ 他们界面没有串行、数据也没错:是我们把一个"只属于某条备货行/某个批次"的报告登记成了按分类共用。

方案 1(我方部分已完成):登记请求显式带 `share_mode: 'line'`
(`mainSystem/api/qualityReports.ts`;他们处理器目前只读已知键 ⇒ 该字段被忽略、行为不变、不报错;
他们支持后**无需我方再发版**即生效)。契约写进《给主系统AI的对接改造清单》§2.12.17:
请求「接口接受显式 share_mode(推荐)」或「integrationPush 的 batch 报告一律按 line」,附根因证据表 +
3 条验收标准(该行 share_mode='line'、同分类其它行不再显示、/void 与重推不受影响)。
测试:mainSystemReportApi 增加 body 必须含 share_mode='line' 的断言(18→19 条)。

方案 3(历史清理,已完成):他们库里 3 条仍在扩散的 leaf_category 报告全部撤下 ——
其中 2 条(抄手皮/苹果,订单行早已删除/退货)由**我方 15 分钟对账自动**检测"候选消失 ⇒ stale ⇒ /void"
撤下(产品路径,无脚本);1 条(精瘦肉,10-10 老单、台账已无对应行)走 `/void` 手工撤下。
终态:该供应商生效报告 **2 条,全部 share_mode='line'**(抄手皮 prep 8fc6e77c、龙口粉丝 prep 5bae5ca9),
**leaf_category 生效报告 = 0** ⇒ 截图上那个现象立即消失(刷新主系统界面即可看到)。

⚠️ 剩余(需主系统配合,方案 1 的另一半):在他们认 `share_mode` 之前,**新推**的 batch 报告
仍会按叶子分类共用。要"零复发":等他们改(我方代码已就绪),或临时把推送类型换成映射为 line 的取值
(代价:他们界面报告类型标签变"其他")—— 需开发者点头。

门禁 8 通过 / check-ai-cost 仍红(基线)/ verify-facts 未执行;tsc 前后端 0;
server 360 通过 / 25 失败文件(相对基线零新增);root 739 通过 / 2 失败。
2026-10-12 14:29:02 +08:00

257 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<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',
// 方案 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<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('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' });
});
});