Files
SupplierSystem/server/tests/mainSystemReportPush.test.ts
T
Ubuntu 9e4546f2a0
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(对接): E2E 第 2 轮 —— 真链路+修正路径全通,并修掉「历史 stale 永不撤下」
开发者要求「测试一下」。开关临时打开(进程级,不动 .env),用真入库+真报告+真确认+分拣 fixture,
调**调度器真正调的函数** runReportPushReconcile(),再只读核主系统库:

  ✅ 定时对账入口推送成功:{branches:2, stored:1}
  ✅ 主系统库真到达:tenant_br002.quality_reports status=10 / source_party=supplier /
     batch_no=STK20261011HHFCUN / 1 个文件
  ✅ 模拟「挂错行后修正」(解掉报告↔批次关联)⇒ 对账 candidates:0 / stale:1,自动调 /void(其端点未上线)⇒ 404
  ✅ 台账优雅降级:status=stale + stale_at + last_error「撤下未生效(404,端点未就绪或报告不存在)」

  ❗**E2E 第 ⑪ 步抓到我一个真 bug**:第二次对账 stale 变 0 且**不再尝试撤下**
    ⇒ 对方 /void 上线后,历史 stale 行**永远清不掉**(只能新触发才能走到撤下分支)。
    修:detectStaleLedgerRows **每轮都处理全部 stale 行**(不再"仅本轮新转才走"),
        且 `stale` 计数改为「**仍未撤下**数」——运维看这个才有意义。
    复验:修复后第二次/第三次对账都是 stale:1,每轮都调 /void ⇒ **端点一上线即自动清**,无需再改代码。

回归:新增"历史 stale 即使本轮无新转也要继续尝试撤下"用例(按新语义重排 mock);41 例全绿;
全量 380 文件 / 2419 用例 ⇒ 失败 25 文件 = 基线 24 + 另一条工作线遗留的 zeroCostClearsPlanPrice;tsc ✅。
测试数据:本地 E2E 造数据已清理(库存/报告/分拣回 0),保留 1 条 stale 台账行作为"待撤下"活证据。
设计:docs/design/20261011-批次报告推送主系统.md §14
2026-10-11 20:32:10 +08:00

378 lines
19 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());
const voidReport = 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),
voidSupplierBatchReport: (...args: unknown[]) => voidReport(...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();
voidReport.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 + 告警(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 }) // ② 标记 stale
.mockResolvedValueOnce({ rows: [] }) // ③ 无带对方报告 id 的 stale ⇒ 不撤下
.mockResolvedValueOnce({ rows: [{ n: 1 }] }); // ④ 仍未撤下 = 1
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('历史 stale 行即使本轮无新转,也要**继续尝试撤下**(E2E 第 ⑪ 步踩到的 bug)', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
query.mockReset();
query
.mockResolvedValueOnce({ rows: [] }) // ① 采集
.mockResolvedValueOnce({ rows: [], rowCount: 0 }) // ② 本轮无新转 stale
.mockResolvedValueOnce({ rows: [{ id: '7', main_supplier_code: 'SUP1', their_report_id: 'their-old' }] }) // ③ 历史 stale
.mockResolvedValueOnce({ rows: [], rowCount: 1 }) // ④ 记"撤下未生效"原因
.mockResolvedValueOnce({ rows: [{ n: 1 }] }); // ⑤ 仍未撤下
voidReport.mockResolvedValue({ kind: 'not_found', status: 404, reason: 'HTTP 404' });
const stat = await pushBranchReports({ branchCode: 'BR003' });
expect(voidReport).toHaveBeenCalledWith({ supplierCode: 'SUP1', theirReportId: 'their-old' });
expect(stat.stale).toBe(1);
});
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();
});
});
describe('护栏 A(主系统 §4.5.19):人工报告不可被机器覆盖', () => {
it('409 staff_report_exists ⇒ 终态 failed + 告警,不重试', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
upload.mockResolvedValue({ kind: 'ok', path: 'rnd-1.pdf' });
register.mockResolvedValue({ kind: 'blocked_by_staff_report', status: 409, reason: 'staff_report_exists' });
const result = await pushReportCandidate(candidate());
expect(result.status).toBe('failed');
const update = query.mock.calls.find((c) => String(c[0]).includes('UPDATE public.main_system_report_pushes'));
expect(String(update?.[1]?.[1])).toBe('failed'); // 终态
expect(update?.[1]?.[4]).toBeFalsy(); // retry=false(不是 pending)
expect(String(update?.[1]?.[2])).toContain('staff_report_exists');
expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain('staff_report_exists');
warn.mockRestore();
});
});
describe('按行撤下(主系统 §4.5.18 ③)', () => {
it('失效侦测命中 ⇒ 调 /void 成功后台账落 voided 终态', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
query.mockReset();
query
.mockResolvedValueOnce({ rows: [] }) // 采集:无候选
.mockResolvedValueOnce({ rows: [{ id: '1', prep_id: 'p1' }], rowCount: 1 }) // 标记 stale
.mockResolvedValueOnce({ rows: [{ id: '7', main_supplier_code: 'SUP1', their_report_id: 'their-1' }] }) // 待撤下
.mockResolvedValueOnce({ rows: [], rowCount: 1 })
.mockResolvedValueOnce({ rows: [{ n: 0 }] }); // 撤下成功 ⇒ 无遗留
voidReport.mockResolvedValue({ kind: 'voided', already: false });
const stat = await pushBranchReports({ branchCode: 'BR003' });
expect(stat.stale).toBe(0); // 已撤下 ⇒ 无遗留
expect(voidReport).toHaveBeenCalledWith({ supplierCode: 'SUP1', theirReportId: 'their-1' });
const voidedUpdate = query.mock.calls.find((c) => String(c[0]).includes("status = 'voided'"));
expect(voidedUpdate).toBeTruthy();
});
it('撤下端点未就绪(404)⇒ **保持 stale** 并记原因,不报错', async () => {
process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true';
query.mockReset();
query
.mockResolvedValueOnce({ rows: [] })
.mockResolvedValueOnce({ rows: [{ id: '1', prep_id: 'p1' }], rowCount: 1 })
.mockResolvedValueOnce({ rows: [{ id: '7', main_supplier_code: 'SUP1', their_report_id: 'their-1' }] })
.mockResolvedValueOnce({ rows: [], rowCount: 1 })
.mockResolvedValueOnce({ rows: [{ n: 1 }] });
voidReport.mockResolvedValue({ kind: 'not_found', status: 404, reason: 'not_found' });
const stat = await pushBranchReports({ branchCode: 'BR003' });
expect(stat.stale).toBe(1);
const note = query.mock.calls.find((c) => String(c[0]).includes('撤下未生效') || String(c[1]?.[1] || '').includes('撤下未生效'));
expect(note).toBeTruthy();
expect(query.mock.calls.some((c) => String(c[0]).includes("status = 'voided'"))).toBe(false);
});
});