Files
SupplierSystem/server/tests/mainSystemReportPush.test.ts
T
Ubuntu 5f932c0518
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
feat(对接): 报告"修正同步"补齐 —— 指纹纳入批次集合 + 失效侦测告警 + 向主系统提"按行撤下"
开发者提问:「我这边发现报告和入库商品绑定错了,做修正后主系统能收到吗?」
核对后结论是**一半能、一半不能**(契约真空,非实现 bug):
  · ① 换成正确报告 / 补换文件(该行文件集变化)⇒ 已能同步(完整集重推 + 对方 latest wins,E2E 实测过)
  · ② 同集换绑(文件没变、只改批次归属)⇒ 原来**静默不同步** ⇒ 本轮修
  · ③ 从某行撤下 ⇒ 主系统**没有"撤下"接口**(其 discard 只对暂存态开放,正常态 409 not_staging;
    内部 voidQualityReport + voidPrepLinksForReport 未暴露)⇒ 我方**失效侦测**兜底 + 向其提契约请求

本轮落地:
  · **B 指纹纳入批次集合**:filesFingerprint(paths, batchNos) = sha256(文件集 + 批次集合),台账加
    our_batch_nos;换绑即重推一次(刷新对方 batch_no),代价只是多推同内容(latest wins 无副作用)
  · **C 失效侦测**:台账已 stored 但候选消失(报告解绑/作废)⇒ 标 `stale` + stale_at + 告警
    (调度日志 `⚠️ 修正后待清理(stale) N`);**只在候选未被 limit 截断时判定**(否则误报);
    `stale` 可复活(候选回来 ⇒ upsert 置回 pending 重推)
  · **A 契约请求**:清单 §2.12.11 请他们开放「按行撤下」(复用其内部 voidQualityReport+清关联),
    含建议形态/幂等/权限/验收;他们不开放则维持 stale + 人工兜底,不改链路
  · 迁移 20261036:加 our_batch_nos / stale_at / 扩展 status CHECK 到 'stale'

验证:server tsc ✅;回归 33 例(服务 19 + 调用层 14)全绿;全量 380 文件 / 2411 用例 ⇒ 失败 25 文件
= 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice;门禁同基线。
2026-10-11 15:47:49 +08:00

305 lines
14 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_nos: ['STK202610107YRQEO'],
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'], ['STK202610107YRQEO']),
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, stale: 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'); // 只用分拣选定的批次
});
it('候选按 (prep_id, report_type) **聚合**,不按批次分组(E2E 踩过:分组会让后推覆盖前推)', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
query.mockResolvedValueOnce({ rows: [] });
await collectReportPushCandidates({ branchCode: 'BR003' });
const sql = String(query.mock.calls[0]?.[0] || '');
// GROUP BY 里**不能**出现 h.batch_no(否则同一行多批次会被拆成多条候选、互相作废)
const groupBy = sql.slice(sql.indexOf('GROUP BY'), sql.indexOf('ORDER BY'));
expect(groupBy).not.toContain('h.batch_no');
expect(groupBy).toContain('l.prep_id');
// 多批次时 batch_no 留空(对方是单值列、≤50 字符,无法表达多个)
expect(sql).toContain('count(DISTINCT h.batch_no) = 1');
expect(sql).toContain('array_agg(DISTINCT unnest_name)');
});
});
describe('幂等:指纹未变不重推,变了推完整集', () => {
it('指纹稳定:与顺序无关、去重', () => {
expect(filesFingerprint(['b.pdf', 'a.pdf', 'a.pdf'])).toBe(filesFingerprint(['a.pdf', 'b.pdf']));
});
it('③ 换绑(文件没变、批次变了)⇒ 指纹必须变(否则修正静默丢失)', () => {
expect(filesFingerprint(['a.pdf'], ['STK-A'])).not.toBe(filesFingerprint(['a.pdf'], ['STK-B']));
expect(filesFingerprint(['a.pdf'], ['STK-A'])).toBe(filesFingerprint(['a.pdf'], ['STK-A']));
});
it('③ 同集换绑 ⇒ 触发重推(不是 skipped)', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
// 台账里旧指纹对应批次 STK-OLD,本次候选批次 STK-NEW(文件相同)
query.mockResolvedValueOnce({
rows: [ledgerRow({ file_fingerprint: filesFingerprint(['batch/a.pdf'], ['STK-OLD']), status: 'stored' })],
rowCount: 1,
});
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' });
register.mockResolvedValue({ kind: 'stored', theirReportId: 'their-2', status: 200, payload: {} });
const result = await pushReportCandidate(candidate({ batch_nos: ['STK-NEW'] }));
expect(result.status).toBe('stored');
expect(register).toHaveBeenCalledTimes(1);
});
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('候选消失且未被截断 ⇒ 标记 stale + 告警', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
query.mockReset();
query
.mockResolvedValueOnce({ rows: [] }) // 采集:无候选
.mockResolvedValueOnce({ rows: [{ id: '99', prep_id: 'p1' }], rowCount: 1 }); // 失效侦测 UPDATE
const stat = await pushBranchReports({ branchCode: 'BR003' });
expect(stat.candidates).toBe(0);
expect(stat.stale).toBe(1);
const sql = String(query.mock.calls[1]?.[0] || '');
expect(sql).toContain("SET status = 'stale'");
expect(sql).toContain("status = 'stored'");
expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain('候选消失');
warn.mockRestore();
});
it('候选数触到 limit(可能被截断)⇒ **不**做失效判定(避免误报)', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
query.mockReset();
const many = Array.from({ length: 2 }, (_, i) =>
({ ...candidate({ prep_id: `00000000-0000-0000-0000-00000000000${i}` }), our_file_paths: ['batch/a.pdf'] }));
query.mockResolvedValueOnce({ rows: many.map(() => ({
branch_code: 'BR003', main_branch_code: 'BR002', main_supplier_code: 'SUP41472132',
prep_id: '11111111-1111-1111-1111-111111111111', main_order_code: null, our_order_code: null,
our_order_item_id: null, payload_report_type: 'batch', requires_report: 'false', batch_no: 'STK-A',
batch_nos: ['STK-A'], report_ids: [], our_file_paths: ['batch/a.pdf'], produced_at: null,
testing_org: null, product_names: [],
})) });
query.mockResolvedValue({ rows: [ledgerRow({ status: 'stored' })], rowCount: 1 });
register.mockResolvedValue({ kind: 'stored', theirReportId: 'x', status: 200, payload: {} });
upload.mockResolvedValue({ kind: 'ok', path: 'rnd.pdf' });
await pushBranchReports({ branchCode: 'BR003', limit: 2 });
const usedStaleSql = query.mock.calls.some((c) => String(c[0]).includes("SET status = 'stale'"));
expect(usedStaleSql).toBe(false);
});
});
describe('定时兜底', () => {
it('开关关闭 ⇒ 不查分公司、零出站', async () => {
const summary = await runReportPushReconcile();
expect(summary).toEqual({ branches: 0, stored: 0, ignored: 0, failed: 0, stale: 0 });
expect(query).not.toHaveBeenCalled();
});
});