Files
SupplierSystem/server/tests/mainSystemReportPush.test.ts
T
Ubuntu fdbef63516 feat(对接): 批次报告推送到主系统(第九批)—— 真环境冒烟已通,三重门禁 + 台账去重
主系统已回执「可以开工」(其 §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
2026-10-11 15:15:47 +08:00

232 lines
10 KiB
TypeScript
Raw 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';
/**
* 批次报告推送(第九批)—— 契约守卫。
*
* 权威:`docs/给主系统AI的对接改造清单.md` §2.12.9(最终调用契约)/ §4.5.17(逐条回执)。
* 这里钉住五类**做反就要返工**的行为:
* ① 默认关 ⇒ 零出站;未绑定 / 非主系统下发的行 ⇒ 零出站(三重门禁);
* ② 幂等:文件集指纹未变 + 已终态 ⇒ **不重推**;指纹变了(事后补充)⇒ **推完整文件集**;
* ③ 请求体只含契约允许的字段(**绝不带** defer_coverage / sku_code / order_code / branch_code / supplier_code);
* ④ 回执映射:200 stored / 404 ignored(终态) / 400 failed(终态) / 5xx transient(重试);
* ⑤ 上传前置校验:仅 pdf+图片、单文件 ≤10MB。
*/
const query = vi.hoisted(() => vi.fn());
const getObject = vi.hoisted(() => vi.fn());
const upload = vi.hoisted(() => vi.fn());
const register = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => query(...args) },
getRawPoolQuery: () => query,
}));
vi.mock('../src/services/storageProvider', () => ({
getStorageProvider: () => ({ getObject: (...args: unknown[]) => getObject(...args) }),
}));
vi.mock('../src/services/mainSystem/api/qualityReports', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/services/mainSystem/api/qualityReports')>();
return {
...actual,
uploadBatchReportFile: (...args: unknown[]) => upload(...args),
registerBatchReportOnPreparation: (...args: unknown[]) => register(...args),
};
});
import {
collectReportPushCandidates,
filesFingerprint,
isReportPushEnabled,
pushBranchReports,
pushReportCandidate,
runReportPushReconcile,
triggerReportPush,
type ReportPushCandidate,
} from '../src/services/mainSystemReportPushService';
function candidate(overrides: Partial<ReportPushCandidate> = {}): ReportPushCandidate {
return {
branch_code: 'BR003',
main_branch_code: 'BR002',
main_supplier_code: 'SUP41472132',
prep_id: '11111111-1111-1111-1111-111111111111',
main_order_code: 'ORD_WEB_20261010_BR002_0001',
our_order_code: 'ORD_API_20261010_BR003_0001',
our_order_item_id: '22222222-2222-2222-2222-222222222222',
report_type: 'batch',
our_file_paths: ['batch/a.pdf'],
report_ids: ['33333333-3333-3333-3333-333333333333'],
batch_no: 'STK202610107YRQEO',
produced_at: '2026-10-08',
testing_org: 'XX检测中心',
product_names: ['香菇', '平菇'],
...overrides,
};
}
/** 台账 INSERT ... RETURNING 的应答 */
function ledgerRow(patch: Partial<{ file_fingerprint: string; status: string; our_file_paths: string[]; their_file_paths: string[] }> = {}) {
return {
id: '99',
file_fingerprint: patch.file_fingerprint ?? filesFingerprint(['batch/a.pdf']),
status: patch.status ?? 'pending',
our_file_paths: patch.our_file_paths ?? [],
their_file_paths: patch.their_file_paths ?? [],
};
}
beforeEach(() => {
query.mockReset();
getObject.mockReset();
upload.mockReset();
register.mockReset();
delete process.env.MAIN_SYSTEM_REPORT_ENABLED;
query.mockResolvedValue({ rows: [ledgerRow()], rowCount: 1 });
getObject.mockResolvedValue({ buffer: Buffer.from('%PDF-1.4 test') });
});
describe('门禁:默认关 / 未绑定 ⇒ 零出站', () => {
it('开关未打开时 pushBranchReports 直接返回且**不查库**', async () => {
const stat = await pushBranchReports({ branchCode: 'BR003' });
expect(stat).toEqual({ candidates: 0, stored: 0, ignored: 0, failed: 0, skipped: 0, transient: 0 });
expect(query).not.toHaveBeenCalled();
expect(upload).not.toHaveBeenCalled();
expect(register).not.toHaveBeenCalled();
});
it('triggerReportPush(触发点入口)在关闭时同样零出站', () => {
triggerReportPush('BR003');
expect(query).not.toHaveBeenCalled();
expect(isReportPushEnabled()).toBe(false);
});
it('候选采集 SQL 把"绑定 + 主系统下发的行"写进 WHERE/JOIN(未绑定天然查不出来)', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
query.mockResolvedValueOnce({ rows: [] });
await collectReportPushCandidates({ branchCode: 'BR003' });
const sql = String(query.mock.calls[0]?.[0] || '');
expect(sql).toContain("b.status = 'active'"); // ① 必须有 active 绑定
expect(sql).toContain('l.prep_id IS NOT NULL'); // ② 必须是主系统下发的行(有 prep_id 对照)
expect(sql).toContain('r.status = 30'); // ③ 报告必须已人工确认
expect(sql).toContain('outbound_batches'); // 只用分拣选定的批次
});
});
describe('幂等:指纹未变不重推,变了推完整集', () => {
it('指纹稳定:与顺序无关、去重', () => {
expect(filesFingerprint(['b.pdf', 'a.pdf', 'a.pdf'])).toBe(filesFingerprint(['a.pdf', 'b.pdf']));
});
it('已 stored 且指纹未变 ⇒ 不调用任何出站接口', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
query.mockResolvedValueOnce({
rows: [ledgerRow({ status: 'stored', our_file_paths: ['batch/a.pdf'], their_file_paths: ['rnd-1.pdf'] })],
rowCount: 1,
});
const result = await pushReportCandidate(candidate());
expect(result.status).toBe('skipped');
expect(upload).not.toHaveBeenCalled();
expect(register).not.toHaveBeenCalled();
});
it('文件集变化(事后补充)⇒ 重推**完整文件集**(旧文件一起传)', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
const files = ['batch/a.pdf', 'batch/b.pdf'];
// 台账旧指纹只有 a.pdf ⇒ 与本次指纹不同 ⇒ 必须重推
query.mockResolvedValueOnce({
rows: [ledgerRow({ file_fingerprint: filesFingerprint(['batch/a.pdf']), status: 'stored', our_file_paths: ['batch/a.pdf'], their_file_paths: ['rnd-a.pdf'] })],
rowCount: 1,
});
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-new.pdf' });
register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-1', status: 200, payload: {} });
const result = await pushReportCandidate(candidate({ our_file_paths: files }));
expect(result.status).toBe('stored');
// a.pdf 命中缓存不重复上传;b.pdf 新上传 ⇒ 登记时必须带**完整集**
expect(upload).toHaveBeenCalledTimes(1);
const registered = register.mock.calls[0][0] as { files: string[] };
expect(registered.files).toEqual(['rnd-a.pdf', 'rnd-new.pdf']);
});
});
describe('契约字段:只传允许的,绝不带 defer_coverage 与派生字段', () => {
it('传给登记 API 的参数只含契约允许项(派生字段一律不带)', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' });
register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-1', status: 200, payload: {} });
await pushReportCandidate(candidate());
const input = register.mock.calls[0][0] as Record<string, unknown>;
expect(Object.keys(input).sort()).toEqual(
['batchNo', 'files', 'preparationId', 'producedAt', 'productNames', 'reportType', 'supplierCode', 'testingOrg'].sort()
);
expect(input.reportType).toBe('batch');
expect(input.files).toEqual(['rnd-1.pdf']);
// 契约 §2.12.9 ④-2/④-4:绝不出现这些键(含 defer_coverage)
for (const forbidden of ['deferCoverage', 'defer_coverage', 'skuCode', 'orderCode', 'branchCode', 'categoryCode', 'deliveryDate']) {
expect(input[forbidden]).toBeUndefined();
}
});
});
describe('回执映射(§2.12.9 ③)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' });
});
it('404 ⇒ ignored(终态,不再重推)', async () => {
register.mockResolvedValue({ kind: 'ignored', status: 404, reason: 'not_found' });
const result = await pushReportCandidate(candidate());
expect(result.status).toBe('ignored');
const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes'));
expect(String(update?.[1]?.[1])).toBe('ignored');
});
it('400 invalid_report_type ⇒ failed(终态 + 告警)', async () => {
register.mockResolvedValue({ kind: 'failed', status: 400, reason: '类型不支持', error: 'invalid_report_type' });
const result = await pushReportCandidate(candidate());
expect(result.status).toBe('failed');
});
it('5xx ⇒ transient(进重试:status 回到 pending + next_retry_at)', async () => {
register.mockResolvedValue({ kind: 'transient', status: 503, reason: 'main system down' });
const result = await pushReportCandidate(candidate());
expect(result.status).toBe('transient');
const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes'));
expect(String(update?.[1]?.[1])).toBe('pending');
expect(update?.[1]?.[4]).toBe(true); // retry=true
});
it('401 ⇒ 也按重试处理(换 token 再试)', async () => {
register.mockResolvedValue({ kind: 'token_expired', reason: 'invalid_token' });
const result = await pushReportCandidate(candidate());
expect(result.status).toBe('transient');
});
});
describe('上传前置校验(§2.12.9 ①)', () => {
beforeEach(() => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
});
it('非 pdf/图片 ⇒ failed 且**不上传**', async () => {
const result = await pushReportCandidate(candidate({ our_file_paths: ['batch/报告.docx'] }));
expect(result.status).toBe('failed');
expect(upload).not.toHaveBeenCalled();
});
it('我方对象缺失 ⇒ failed(不静默丢)', async () => {
getObject.mockResolvedValue(null);
const result = await pushReportCandidate(candidate());
expect(result.status).toBe('failed');
expect(upload).not.toHaveBeenCalled();
});
});
describe('定时兜底', () => {
it('开关关闭 ⇒ 不查分公司、零出站', async () => {
const summary = await runReportPushReconcile();
expect(summary).toEqual({ branches: 0, stored: 0, ignored: 0, failed: 0 });
expect(query).not.toHaveBeenCalled();
});
});