开发者要求"测试一下代码是否正确、业务流程是否真的跑通"。用**真服务**补齐链路 (真独立入库 → 真批次报告上传+人工确认;分拣明细为 fixture,本地库没有分拣任务), 调用**触发点同一个函数** pushBranchReports(),并只读核对主系统库: · 候选 1 条(prep 41ef5891 / type batch / 文件集并集 5) · 第一次推送 **stored**(对方报告 id 912b8d83-…) · 主系统库 tenant_br007.quality_reports:status=10、source_party=supplier、5 个文件 ✅ 真到达 · 再推一次 **skipped**(指纹未变、零出站)⇒ 幂等生效 · **事后补充**:加第 2 个文件重推 ⇒ 对方库旧报告 912b8d83 → status=20(void)、 新报告 59c78b8b → status=10(active) 且带**完整集 6 个文件** ✅ latest wins 语义正确 E2E 抓到并修掉 3 个真 bug(单测测不出,均已补回归): 1. 台账 UPDATE 里同一参数既赋 varchar 又参与文本比较 ⇒ PG "inconsistent types deduced for parameter $2" (推送全失败且 attempts 不增长)⇒ 参数显式定型 `$2::varchar` / `$2::text` / `$5::boolean` 2. 上传 mime 传成 application/octet-stream ⇒ 被对方桶白名单拒("不允许的文件类型") ⇒ 新增 reportMimeFromFileName,按扩展名推断 pdf/jpeg/png/webp/gif 3. 候选**按批次分组** ⇒ 同一行多批次各推一条、后推作废前推 ⇒ 改为按 (prep_id, report_type) 聚合**完整文件集**;多批次时 batch_no 留空(对方单值列 ≤50 字符无法表达) 未验到的部分(如实记录):`outbound_batches` 是本地 fixture ⇒ "分拣完成触发"这一跳只验到 "函数被调用 + 候选正确",真实分拣链待有数据后补验。 E2E 造的本地数据已清理(库存/报告/分拣/台账回 0);主系统侧 3 份联调报告保留供其核 §2.12.9 ⑦-3。 验证:server tsc ✅;新增回归后 29 例全绿(服务 15 + 调用层 14);全量 380 文件 / 2407 用例 ⇒ 失败 25 文件 = 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice;门禁同基线。
246 lines
11 KiB
TypeScript
246 lines
11 KiB
TypeScript
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'); // 只用分拣选定的批次
|
||
});
|
||
|
||
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('已 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();
|
||
});
|
||
});
|