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;门禁同基线。
This commit is contained in:
@@ -185,3 +185,24 @@ E2E 造的本地数据已清理(库存/报告/分拣/台账均回 0);主
|
||||
| 版本 | 日期 | 变更 |
|
||||
|---|---|---|
|
||||
| v2 | 2026-10-11 | 真链路实测(§10):三个真 bug 修复(SQL 参数定型 / mime 推断 / 按 `(prep_id, report_type)` 聚合);勾掉联调验收;补"多批次时 batch_no 留空"口径 |
|
||||
|
||||
## 12. 修正同步与失效侦测(2026-10-11 开发者提问后补)
|
||||
|
||||
**问题**:「我的报告和入库商品绑定错了,我这边修正后,主系统那边能收到吗?」
|
||||
|
||||
| 修正形态 | 处理 |
|
||||
|---|---|
|
||||
| 换成正确报告 / 补换文件(该行文件集变化) | ✅ 已能同步(完整文件集重推 + 对方 latest wins;E2E 实测过) |
|
||||
| **同集换绑**(文件没变、只改批次归属) | ✅ 本轮修:**指纹 = sha256(完整文件集 + 该行批次集合)** ⇒ 换绑即重推(刷新对方 `batch_no`) |
|
||||
| **从某行撤下**(报告不再服务该行) | ⚠️ 主系统**没有"撤下"接口**(其 `discard` 只对暂存态开放,正常态 409 `not_staging`;内部 `voidQualityReport + voidPrepLinksForReport` 未暴露)⇒ 本轮做**失效侦测**:台账 `stored` 但候选消失 ⇒ 标 `stale` + `stale_at` + 告警(调度日志 `⚠️ 修正后待清理(stale) N`),**不再静默**;并已向主系统提契约请求(清单 §2.12.11) |
|
||||
|
||||
实现要点:
|
||||
- 指纹纳入批次集合(`filesFingerprint(paths, batchNos)`),台账加 `our_batch_nos`;
|
||||
- 失效侦测**只在候选未被 limit 截断时**判定(否则"没进候选"可能只是被截断 ⇒ 误报);
|
||||
- `stale` 是**可复活**状态:候选再次出现(指纹回来)⇒ upsert 把它置回 `pending` 重推。
|
||||
|
||||
## 13. 修订记录(补)
|
||||
|
||||
| 版本 | 日期 | 变更 |
|
||||
|---|---|---|
|
||||
| v3 | 2026-10-11 | §12:修正同步(指纹含批次集合)+ 失效侦测(`stale`)+ 向主系统提"按行撤下"契约请求(§2.12.11) |
|
||||
|
||||
@@ -816,6 +816,41 @@ prep_id = b4e7fd80-668d-4f9b-b69f-dcb3fddc623e
|
||||
- 已绑定的真实业务行目前只有导入台账里这几条(本地库 `inventory` / 分拣批次为空)⇒ 需要一条
|
||||
**真实分拣选批 + 批次报告确认**的数据才能验"分拣完成触发"这条链,我们会在有真实数据后补验并回执。
|
||||
|
||||
#### 2.12.11 我方追加契约请求(2026-10-11):**报告"修正/撤下"需要一条按行撤下的能力**
|
||||
|
||||
> 场景(开发者提问):「假设我发现我的报告和入库商品**绑定错了**,我这边做了修正,主系统那边能收到吗?」
|
||||
|
||||
**先把现状说清**(我方已实测/已核实):
|
||||
|
||||
| 修正形态 | 现在的效果 |
|
||||
|---|---|
|
||||
| ① 换成正确的报告(该行文件集**变了**) | ✅ **能收到**:我方按完整文件集重推 ⇒ 你们 latest wins(旧报告 void、新报告 active)。E2E 已实测 |
|
||||
| ② 补充/替换文件 | ✅ 同上 |
|
||||
| ③ 同集换绑(文件没变,只是改了批次归属) | ⚠️ 我方本轮已修:**指纹纳入批次集合** ⇒ 换绑也会重推一次(刷新你们 `batch_no`)⇒ 能收到 |
|
||||
| ④ 报告**从某行整个撤下**(误挂到别的行、修正后不再属于该行) | ❌ **收不到**:你们"latest wins"只覆盖"同 `(preparation_id, report_type)` 再登记",**没有"撤下"语义**;我方这边也没有任何撤回动作 ⇒ 你们那行的报告会**一直挂着**(我方只能标 `stale` + 告警,人工兜底) |
|
||||
|
||||
**我方已做的两件事(不需要你们配合)**:
|
||||
- 推送指纹从"文件集"扩展为"**文件集 + 该行批次集合**"⇒ ③ 类修正能同步;
|
||||
- 新增**失效侦测**:台账已登记但候选消失(④ 类)⇒ 标 `stale` + 调度日志告警(`⚠️ 修正后待清理(stale) N`),不再静默。
|
||||
|
||||
**请求你们评估:开放一条「按行撤下」的能力(方案 A)**
|
||||
|
||||
- **能力**:允许**上传方**(我们,走对接 token)把**自己上传的**某份报告从某个备货行上撤下;
|
||||
你们内部已有现成实现:`voidQualityReport(id)`(`status → voided`)**并** `voidPrepLinksForReport(id)`(清行关联)
|
||||
—— 只是**没有暴露成供应商/对接接口**;而现有的 `POST /api/supplier/quality-reports/:id/discard`
|
||||
**只允许暂存态**(`share_key` 以 `st|` 开头,即 `defer_coverage=true`),我们正常态调用会 **409 `not_staging`**。
|
||||
- **建议形态**(字段名你们定):`POST {BASE}/api/supplier/quality-reports/unlink`
|
||||
body `{ preparation_id, report_type }`(或 `{ quality_report_id }`)
|
||||
⇒ 语义:把该行该类型的**当前生效报告**置 void 并清行关联;
|
||||
幂等(已撤下 ⇒ 200 `{removed:false}`);只允许撤**本 token 供应商、source_party='supplier'** 的报告;
|
||||
不认识的行 ⇒ 404(我们按 `ignored` 处理)。
|
||||
- **我们的用法**:只在"失效侦测"命中时调用 —— 即我方台账 `stored` 但候选已消失(报告解绑/作废);
|
||||
成功后台账从 `stale` 转终态,审计留痕。
|
||||
- **若不开放**:请回一句,我们就维持"标 `stale` + 告警 + 人工联系你们处理",**不改**现有链路。
|
||||
|
||||
**验收(若开放)**:我方把某行的报告解绑 ⇒ 你们那行 `quality_report` 变 `null`、`report_covered=false`;
|
||||
重复撤下 ⇒ 200 幂等;撤销别家供应商的报告 ⇒ 403/404。
|
||||
|
||||
## 3. 第一批遗留小项(第一批清单中尚未交付的部分)
|
||||
|
||||
> 第一批的**已交付项**(`P0-2` / `P0-2b` / `P0-3` / `P1-4` / `P1-7`)已移入 §4.1,含各自回执。
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
-- 批次报告推送台账:支持「修正同步」与「失效侦测」(2026-10-11 追加)
|
||||
--
|
||||
-- 背景(开发者提问):报告与入库批次绑错了、我方修正后,主系统能收到吗?
|
||||
-- · 「文件集变化」的修正 ⇒ 已能同步(按完整文件集重推,对方 latest wins);
|
||||
-- · 「同集换绑」与「从某行撤下」⇒ 原实现**静默不同步**。本轮补两件事:
|
||||
-- B. 指纹纳入**批次集合** ⇒ 换绑(即使文件没变)也会重推一次,刷新对方 `batch_no`;
|
||||
-- C. `stale` 终态 + `stale_at` ⇒ 台账已登记、但**候选已消失**(报告解绑/作废)时标记告警,
|
||||
-- 不再静默;等主系统开放「按行撤下」(§2.12.11)后再自动撤。
|
||||
--
|
||||
-- 设计:docs/design/20261011-批次报告推送主系统.md(§12 修正同步与失效侦测)
|
||||
|
||||
ALTER TABLE public.main_system_report_pushes
|
||||
ADD COLUMN IF NOT EXISTS our_batch_nos TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[];
|
||||
|
||||
ALTER TABLE public.main_system_report_pushes
|
||||
ADD COLUMN IF NOT EXISTS stale_at TIMESTAMPTZ;
|
||||
|
||||
COMMENT ON COLUMN public.main_system_report_pushes.our_batch_nos IS
|
||||
'该行本次推送对应的入库批次集合(参与指纹:换绑即使文件不变也会重推,刷新对方 batch_no)';
|
||||
COMMENT ON COLUMN public.main_system_report_pushes.stale_at IS
|
||||
'失效侦测时间:台账已 stored 但候选已消失(报告解绑/作废)⇒ 标记告警,不再静默';
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
-- 扩展状态枚举:加 'stale'(原 CHECK 只允许 pending/stored/ignored/failed)
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM pg_constraint
|
||||
WHERE conrelid = 'public.main_system_report_pushes'::regclass
|
||||
AND conname = 'main_system_report_pushes_status_chk'
|
||||
) THEN
|
||||
ALTER TABLE public.main_system_report_pushes
|
||||
DROP CONSTRAINT main_system_report_pushes_status_chk;
|
||||
END IF;
|
||||
ALTER TABLE public.main_system_report_pushes
|
||||
ADD CONSTRAINT main_system_report_pushes_status_chk
|
||||
CHECK (status IN ('pending', 'stored', 'ignored', 'failed', 'stale'));
|
||||
END $$;
|
||||
@@ -40,16 +40,27 @@ export type ReportPushCandidate = {
|
||||
/** 该行消耗批次命中的**全部**报告文件(我方对象键,已排序去重) */
|
||||
our_file_paths: string[];
|
||||
report_ids: string[];
|
||||
/** 该行消耗的**全部**批次号(参与指纹:换绑即重推) */
|
||||
batch_nos: string[];
|
||||
batch_no: string | null;
|
||||
produced_at: string | null;
|
||||
testing_org: string | null;
|
||||
product_names: string[];
|
||||
};
|
||||
|
||||
/** 完整文件集指纹:我方对象键排序后 sha256(变了才重推) */
|
||||
export function filesFingerprint(paths: string[]): string {
|
||||
const sorted = [...new Set((paths || []).map((p) => String(p || '').trim()).filter(Boolean))].sort();
|
||||
return createHash('sha256').update(sorted.join('\n')).digest('hex');
|
||||
/**
|
||||
* 推送指纹:**完整文件集 + 该行消耗的批次集合**(任一变化即重推)。
|
||||
*
|
||||
* 为什么纳入批次集合(2026-10-11 开发者提问后补):
|
||||
* 报告与入库批次**绑错了**、我方重新确认修正后,若文件集恰好没变(同集换绑),
|
||||
* 只按文件算指纹会判「没变⇒不推」⇒ 主系统那边的 `batch_no` 永远是旧的、**修正静默丢失**。
|
||||
* 纳入批次集合后,换绑也会重推一次完整集(对方 latest wins ⇒ 作废旧报告、登记带新批次的),
|
||||
* 代价仅是多推一次同内容,无副作用。
|
||||
*/
|
||||
export function filesFingerprint(paths: string[], batchNos: string[] = []): string {
|
||||
const sortedFiles = [...new Set((paths || []).map((p) => String(p || '').trim()).filter(Boolean))].sort();
|
||||
const sortedBatches = [...new Set((batchNos || []).map((b) => String(b || '').trim()).filter(Boolean))].sort();
|
||||
return createHash('sha256').update(`${sortedFiles.join('\n')}\n--\n${sortedBatches.join('\n')}`).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,6 +112,7 @@ export async function collectReportPushCandidates(input: {
|
||||
COALESCE(l.payload->>'requiresQualityReport', 'false') AS requires_report,
|
||||
-- 该行消耗的批次:只有一个时带上(对方 batch_no 是单值且 ≤50 字符;多批次无法表达 ⇒ 留空)
|
||||
CASE WHEN count(DISTINCT h.batch_no) = 1 THEN min(h.batch_no) ELSE NULL END AS batch_no,
|
||||
array_remove(array_agg(DISTINCT h.batch_no), NULL) AS batch_nos,
|
||||
array_agg(DISTINCT h.report_id::text) AS report_ids,
|
||||
array_agg(DISTINCT unnest_path) AS our_file_paths,
|
||||
(array_agg(DISTINCT h.produced_at::text))[1] AS produced_at,
|
||||
@@ -147,6 +159,7 @@ export async function collectReportPushCandidates(input: {
|
||||
our_file_paths: [...new Set(files)].sort(),
|
||||
report_ids: ((row.report_ids as string[]) || []).map(String),
|
||||
batch_no: row.batch_no ? String(row.batch_no) : null,
|
||||
batch_nos: ((row.batch_nos as string[]) || []).filter(Boolean).map(String).sort(),
|
||||
produced_at: row.produced_at ? String(row.produced_at) : null,
|
||||
testing_org: row.testing_org ? String(row.testing_org) : null,
|
||||
product_names: ((row.product_names as string[]) || []).filter(Boolean).map(String),
|
||||
@@ -163,7 +176,7 @@ export type PushOneResult = {
|
||||
|
||||
/** 单条候选:落台账 → (文件集变了才)上传 + 登记 → 回写状态 */
|
||||
export async function pushReportCandidate(candidate: ReportPushCandidate): Promise<PushOneResult> {
|
||||
const fingerprint = filesFingerprint(candidate.our_file_paths);
|
||||
const fingerprint = filesFingerprint(candidate.our_file_paths, candidate.batch_nos);
|
||||
|
||||
const ledger = await pool.query<{
|
||||
id: string;
|
||||
@@ -174,15 +187,19 @@ export async function pushReportCandidate(candidate: ReportPushCandidate): Promi
|
||||
}>(
|
||||
`INSERT INTO public.main_system_report_pushes
|
||||
(branch_code, main_branch_code, main_supplier_code, prep_id, main_order_code, our_order_code,
|
||||
our_order_item_id, report_type, file_fingerprint, our_file_paths, status)
|
||||
VALUES ($1,$2,$3,$4::uuid,$5,$6,$7::uuid,$8,$9,$10,'pending')
|
||||
our_order_item_id, report_type, file_fingerprint, our_file_paths, our_batch_nos, status)
|
||||
VALUES ($1,$2,$3,$4::uuid,$5,$6,$7::uuid,$8,$9,$10,$11::text[],'pending')
|
||||
ON CONFLICT (prep_id, report_type) DO UPDATE SET
|
||||
file_fingerprint = EXCLUDED.file_fingerprint,
|
||||
our_file_paths = EXCLUDED.our_file_paths,
|
||||
-- 文件集变了 ⇒ 回到 pending 重推完整集;没变则保持原状态(终态不复活)
|
||||
our_batch_nos = EXCLUDED.our_batch_nos,
|
||||
-- 指纹变了(文件或批次变了)⇒ 回到 pending 重推完整集;此前被判失效的也复活重推;
|
||||
-- 其余保持原状态(终态不复活)
|
||||
status = CASE
|
||||
WHEN public.main_system_report_pushes.file_fingerprint <> EXCLUDED.file_fingerprint
|
||||
THEN 'pending'
|
||||
WHEN public.main_system_report_pushes.status = 'stale'
|
||||
THEN 'pending'
|
||||
ELSE public.main_system_report_pushes.status
|
||||
END,
|
||||
updated_at = NOW()
|
||||
@@ -198,6 +215,7 @@ export async function pushReportCandidate(candidate: ReportPushCandidate): Promi
|
||||
candidate.report_type,
|
||||
fingerprint,
|
||||
candidate.our_file_paths,
|
||||
candidate.batch_nos,
|
||||
]
|
||||
);
|
||||
const row = ledger.rows[0];
|
||||
@@ -344,7 +362,44 @@ async function markLedger(
|
||||
);
|
||||
}
|
||||
|
||||
/** 一个分公司推一轮(采集 + 逐条推) */
|
||||
/**
|
||||
* 失效侦测(修正同步的兜底,2026-10-11 开发者提问后补):
|
||||
* 台账里已 `stored`、但本轮**候选已消失** ⇒ 说明报告被解绑/作废(例如绑定改错后修正),
|
||||
* 而主系统那边**没有任何"撤下"能力**(其 discard 只对暂存态开放,见 §2.12.11)⇒
|
||||
* 我们不能静默:标 `stale` + 告警,等主系统开放「按行撤下」后自动撤。
|
||||
*
|
||||
* ⚠️ 只在**候选未被 limit 截断**时判定(否则"没进候选"可能只是被截断,会造成误报)。
|
||||
*/
|
||||
async function detectStaleLedgerRows(input: {
|
||||
branchCode: string;
|
||||
candidates: ReportPushCandidate[];
|
||||
truncated: boolean;
|
||||
}): Promise<number> {
|
||||
if (input.truncated) return 0;
|
||||
const keys = input.candidates.map((c) => `${c.prep_id}::${c.report_type}`);
|
||||
const result = await pool.query(
|
||||
`UPDATE public.main_system_report_pushes
|
||||
SET status = 'stale',
|
||||
stale_at = NOW(),
|
||||
last_error = '候选已消失(报告解绑/作废)⇒ 主系统侧报告未撤下,待其开放"按行撤下"后清理',
|
||||
updated_at = NOW()
|
||||
WHERE branch_code = $1
|
||||
AND status = 'stored'
|
||||
AND NOT ((prep_id::text || '::' || report_type) = ANY($2::text[]))
|
||||
RETURNING id, prep_id::text`,
|
||||
[input.branchCode, keys]
|
||||
);
|
||||
const stale = result.rowCount || 0;
|
||||
if (stale > 0) {
|
||||
console.warn(
|
||||
`[report-push] ⚠️ ${input.branchCode}:${stale} 条台账已登记但候选消失(报告解绑/作废)⇒ 标记 stale;` +
|
||||
`主系统侧报告仍在,需等其"按行撤下"能力或人工处理`
|
||||
);
|
||||
}
|
||||
return stale;
|
||||
}
|
||||
|
||||
/** 一个分公司推一轮(采集 + 逐条推 + 失效侦测) */
|
||||
export async function pushBranchReports(input: { branchCode: string; limit?: number }): Promise<{
|
||||
candidates: number;
|
||||
stored: number;
|
||||
@@ -352,12 +407,14 @@ export async function pushBranchReports(input: { branchCode: string; limit?: num
|
||||
failed: number;
|
||||
skipped: number;
|
||||
transient: number;
|
||||
stale: number;
|
||||
}> {
|
||||
const empty = { candidates: 0, stored: 0, ignored: 0, failed: 0, skipped: 0, transient: 0 };
|
||||
const empty = { candidates: 0, stored: 0, ignored: 0, failed: 0, skipped: 0, transient: 0, stale: 0 };
|
||||
if (!isReportPushEnabled()) return empty;
|
||||
const branchCode = String(input.branchCode || '').trim();
|
||||
if (!branchCode) return empty;
|
||||
const candidates = await collectReportPushCandidates({ branchCode, limit: input.limit });
|
||||
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
|
||||
const candidates = await collectReportPushCandidates({ branchCode, limit });
|
||||
const stat = { ...empty, candidates: candidates.length };
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
@@ -372,6 +429,11 @@ export async function pushBranchReports(input: { branchCode: string; limit?: num
|
||||
console.warn('[report-push] 推送异常:', error?.message || error);
|
||||
}
|
||||
}
|
||||
stat.stale = await detectStaleLedgerRows({
|
||||
branchCode,
|
||||
candidates,
|
||||
truncated: candidates.length >= limit,
|
||||
});
|
||||
return stat;
|
||||
}
|
||||
|
||||
@@ -384,8 +446,9 @@ export async function runReportPushReconcile(options?: { limitPerBranch?: number
|
||||
stored: number;
|
||||
ignored: number;
|
||||
failed: number;
|
||||
stale: number;
|
||||
}> {
|
||||
const summary = { branches: 0, stored: 0, ignored: 0, failed: 0 };
|
||||
const summary = { branches: 0, stored: 0, ignored: 0, failed: 0, stale: 0 };
|
||||
if (!isReportPushEnabled()) return summary;
|
||||
const branches = await pool.query<{ branch_code: string }>(
|
||||
`SELECT DISTINCT branch_code FROM public.main_supplier_bindings WHERE status = 'active' ORDER BY 1`
|
||||
@@ -396,6 +459,7 @@ export async function runReportPushReconcile(options?: { limitPerBranch?: number
|
||||
summary.stored += stat.stored;
|
||||
summary.ignored += stat.ignored;
|
||||
summary.failed += stat.failed;
|
||||
summary.stale += stat.stale;
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
@@ -489,10 +489,11 @@ async function runReportPushReconcile() {
|
||||
try {
|
||||
const { runReportPushReconcile: run } = await import('./mainSystemReportPushService');
|
||||
const summary = await run({ limitPerBranch: 50 });
|
||||
if (summary.stored || summary.ignored || summary.failed) {
|
||||
if (summary.stored || summary.ignored || summary.failed || summary.stale) {
|
||||
console.log(
|
||||
`[scheduler] 批次报告推送对账:分公司 ${summary.branches} 个,登记成功 ${summary.stored}、` +
|
||||
`对方不认识(ignored) ${summary.ignored}、失败 ${summary.failed}`
|
||||
`对方不认识(ignored) ${summary.ignored}、失败 ${summary.failed}` +
|
||||
`${summary.stale ? `、⚠️ 修正后待清理(stale) ${summary.stale}` : ''}`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -55,6 +55,7 @@ function candidate(overrides: Partial<ReportPushCandidate> = {}): ReportPushCand
|
||||
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检测中心',
|
||||
@@ -67,7 +68,7 @@ function candidate(overrides: Partial<ReportPushCandidate> = {}): ReportPushCand
|
||||
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']),
|
||||
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 ?? [],
|
||||
@@ -87,7 +88,7 @@ beforeEach(() => {
|
||||
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(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();
|
||||
@@ -130,6 +131,25 @@ describe('幂等:指纹未变不重推,变了推完整集', () => {
|
||||
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({
|
||||
@@ -236,10 +256,49 @@ describe('上传前置校验(§2.12.9 ①)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
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 });
|
||||
expect(summary).toEqual({ branches: 0, stored: 0, ignored: 0, failed: 0, stale: 0 });
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user