Files
SupplierSystem/server/src/services/mainSystemReportPushService.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

407 lines
17 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.
/**
* 批次报告推送(第九批「批次报告同步」我方推送侧)。
*
* 设计:docs/design/20261011-批次报告推送主系统.md
* 契约(权威):docs/给主系统AI的对接改造清单.md §2.12.9 / §4.5.17。
*
* 三重门禁(开发者原话:「没有绑定、没有主系统下发的订单,报告就别传过去,不能造成混乱」):
* ① 该分公司与主系统**有 active 绑定**(否则连 token 都取不到 ⇒ 物理上发不出去);
* ② 该行**是主系统下发的**(我方台账 `main_system_order_import_items` 有 prep_id 对照);
* ③ 该批次**已人工确认**关联到报告。
*
* 幂等:台账 `main_system_report_pushes` 唯一键 `(prep_id, report_type)` + **完整文件集指纹**:
* 指纹未变 ⇒ 不重推;指纹变了(事后补充)⇒ 按**完整文件集**重推一次(主系统 latest wins)。
*/
import { createHash } from 'node:crypto';
import { pool } from '../db';
import { getStorageProvider } from './storageProvider';
import {
registerBatchReportOnPreparation,
uploadBatchReportFile,
isUploadableReportFileName,
} from './mainSystem/api/qualityReports';
/** 我方批次报告存放的桶(与 inventoryBatchReportService 一致) */
const REPORT_BUCKET = 'quality-reports';
export function isReportPushEnabled(): boolean {
return process.env.MAIN_SYSTEM_REPORT_ENABLED === 'true';
}
export type ReportPushCandidate = {
branch_code: string;
main_branch_code: string | null;
main_supplier_code: string;
prep_id: string;
main_order_code: string | null;
our_order_code: string | null;
our_order_item_id: string | null;
report_type: string;
/** 该行消耗批次命中的**全部**报告文件(我方对象键,已排序去重) */
our_file_paths: string[];
report_ids: 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');
}
/**
* 采集候选:报告(已确认)→ 入库批次 → 分拣选批 → 订单行 → 主系统备货行(prep_id)。
*
* ⚠️ 只认"分拣**实际选定/扣减**的批次"(`picking_items.outbound_batches`,形如
* `[{"batch_no":"STK…","qty":12.5}]`)—— 这正是开发者说的"分拣完毕选中了那几个批次"。
*/
export async function collectReportPushCandidates(input: {
branchCode: string;
limit?: number;
}): Promise<ReportPushCandidate[]> {
const branchCode = String(input.branchCode || '').trim();
if (!branchCode) return [];
const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200);
const result = await pool.query(
`WITH hit AS (
SELECT DISTINCT
pi.id AS picking_item_id,
inv.sku_code AS sku_code,
inv.batch_no AS batch_no,
r.id AS report_id,
r.file_paths AS file_paths,
r.produced_at AS produced_at,
r.testing_org AS testing_org,
r.product_names AS product_names
FROM inventory_batch_report_matches m
JOIN inventory_batch_reports r ON r.id = m.report_id AND r.status = 30
JOIN inventory inv ON inv.id = m.inventory_id
JOIN picking_items pi ON pi.sku_code = inv.sku_code
AND pi.branch_code = $1
AND jsonb_typeof(pi.outbound_batches) = 'array'
AND EXISTS (
SELECT 1 FROM jsonb_array_elements(pi.outbound_batches) e
WHERE e->>'batch_no' = inv.batch_no
)
)
SELECT l.branch_code,
l.main_branch_code,
l.main_supplier_code,
l.prep_id::text AS prep_id,
l.main_order_code,
l.our_order_code,
l.our_order_item_id::text AS our_order_item_id,
l.payload->>'qualityReportType' AS payload_report_type,
COALESCE(l.payload->>'requiresQualityReport', 'false') AS requires_report,
h.batch_no,
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,
(array_agg(DISTINCT h.testing_org))[1] AS testing_org
FROM hit h
JOIN picking_items pi ON pi.id = h.picking_item_id
JOIN public.main_system_order_import_items l
ON l.our_order_item_id = pi.order_item_id
AND l.branch_code = $1
AND l.prep_id IS NOT NULL
JOIN public.main_supplier_bindings b
ON b.branch_code = l.branch_code
AND b.main_supplier_code = l.main_supplier_code
AND b.status = 'active'
LEFT JOIN LATERAL unnest(h.file_paths) AS unnest_path ON TRUE
GROUP BY l.branch_code, l.main_branch_code, l.main_supplier_code, l.prep_id,
l.main_order_code, l.our_order_code, l.our_order_item_id,
l.payload->>'qualityReportType', l.payload->>'requiresQualityReport', h.batch_no
ORDER BY l.prep_id
LIMIT $2`,
[branchCode, limit]
);
const productNamesByBranch = new Map<string, string[]>();
const out: ReportPushCandidate[] = [];
for (const row of result.rows as Record<string, unknown>[]) {
const requires = String(row.requires_report || '') === 'true';
const payloadType = String(row.payload_report_type || '').trim();
// 契约 §2.12.9 ④-3:按该行要求的类型传;该行不要求报告时才允许兜底 'batch'
const reportType = payloadType || (requires ? '' : 'batch');
if (!reportType) continue; // 需要报告但类型未知 ⇒ 等下一次导入刷新 payload(不猜)
const files = ((row.our_file_paths as string[]) || []).filter(Boolean).map(String);
if (!files.length) continue;
out.push({
branch_code: String(row.branch_code),
main_branch_code: row.main_branch_code ? String(row.main_branch_code) : null,
main_supplier_code: String(row.main_supplier_code),
prep_id: String(row.prep_id),
main_order_code: row.main_order_code ? String(row.main_order_code) : null,
our_order_code: row.our_order_code ? String(row.our_order_code) : null,
our_order_item_id: row.our_order_item_id ? String(row.our_order_item_id) : null,
report_type: reportType,
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,
produced_at: row.produced_at ? String(row.produced_at) : null,
testing_org: row.testing_org ? String(row.testing_org) : null,
product_names: productNamesByBranch.get(String(row.branch_code)) || [],
});
}
return out;
}
export type PushOneResult = {
status: 'stored' | 'ignored' | 'failed' | 'skipped' | 'transient';
reason?: string;
theirReportId?: string | null;
};
/** 单条候选:落台账 → (文件集变了才)上传 + 登记 → 回写状态 */
export async function pushReportCandidate(candidate: ReportPushCandidate): Promise<PushOneResult> {
const fingerprint = filesFingerprint(candidate.our_file_paths);
const ledger = await pool.query<{
id: string;
file_fingerprint: string;
status: string;
our_file_paths: string[] | null;
their_file_paths: string[] | null;
}>(
`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')
ON CONFLICT (prep_id, report_type) DO UPDATE SET
file_fingerprint = EXCLUDED.file_fingerprint,
our_file_paths = EXCLUDED.our_file_paths,
-- 文件集变了 ⇒ 回到 pending 重推完整集;没变则保持原状态(终态不复活)
status = CASE
WHEN public.main_system_report_pushes.file_fingerprint <> EXCLUDED.file_fingerprint
THEN 'pending'
ELSE public.main_system_report_pushes.status
END,
updated_at = NOW()
RETURNING id, file_fingerprint, status, our_file_paths, their_file_paths`,
[
candidate.branch_code,
candidate.main_branch_code,
candidate.main_supplier_code,
candidate.prep_id,
candidate.main_order_code,
candidate.our_order_code,
candidate.our_order_item_id,
candidate.report_type,
fingerprint,
candidate.our_file_paths,
]
);
const row = ledger.rows[0];
if (!row) return { status: 'failed', reason: '台账写入失败' };
// 指纹未变 + 已终态 ⇒ 不重推(幂等;ignored/failed 也不复活)
if (row.file_fingerprint === fingerprint && row.status !== 'pending') {
return { status: 'skipped', reason: `已 ${row.status}` };
}
// 文件上传:按"我方键 → 对方 path"同序缓存,避免重复上传
const ourPaths = candidate.our_file_paths;
const cachedOur = (row.our_file_paths || []).map(String);
const cachedTheir = (row.their_file_paths || []).map(String);
const theirPaths: string[] = [];
const uploadedOur: string[] = [];
const storage = getStorageProvider();
for (const ourPath of ourPaths) {
const cachedIdx = cachedOur.indexOf(ourPath);
if (cachedIdx >= 0 && cachedTheir[cachedIdx]) {
theirPaths.push(cachedTheir[cachedIdx]);
uploadedOur.push(ourPath);
continue;
}
const fileName = ourPath.split('/').pop() || ourPath;
if (!isUploadableReportFileName(fileName)) {
await markLedger(row.id, { status: 'failed', error: `主系统只收 pdf/图片:${fileName}`, httpStatus: 0 });
return { status: 'failed', reason: `不可上传的文件类型:${fileName}` };
}
const object = await storage.getObject(REPORT_BUCKET, ourPath);
if (!object?.buffer?.length) {
await markLedger(row.id, { status: 'failed', error: `我方对象缺失:${ourPath}`, httpStatus: 0 });
return { status: 'failed', reason: `我方对象缺失:${ourPath}` };
}
const uploaded = await uploadBatchReportFile({
supplierCode: candidate.main_supplier_code,
fileName,
buffer: object.buffer,
});
if (uploaded.kind === 'not_configured') {
return { status: 'skipped', reason: uploaded.reason };
}
if (uploaded.kind !== 'ok') {
const terminal = uploaded.kind === 'failed';
await markLedger(row.id, {
status: terminal ? 'failed' : 'pending',
error: uploaded.reason,
httpStatus: uploaded.status,
retry: !terminal,
});
return { status: terminal ? 'failed' : 'transient', reason: uploaded.reason };
}
theirPaths.push(uploaded.path);
uploadedOur.push(ourPath);
}
const registered = await registerBatchReportOnPreparation({
supplierCode: candidate.main_supplier_code,
preparationId: candidate.prep_id,
files: theirPaths,
reportType: candidate.report_type,
batchNo: candidate.batch_no,
producedAt: candidate.produced_at,
testingOrg: candidate.testing_org,
productNames: candidate.product_names,
});
if (registered.kind === 'stored') {
await markLedger(row.id, {
status: 'stored',
error: null,
httpStatus: registered.status,
theirReportId: registered.theirReportId,
ourFilePaths: uploadedOur,
theirFilePaths: theirPaths,
});
return { status: 'stored', theirReportId: registered.theirReportId };
}
if (registered.kind === 'ignored') {
// 对方不认识该行(不存在或不属于本 token 的供应商)⇒ 终态,永不重推
await markLedger(row.id, { status: 'ignored', error: registered.reason, httpStatus: 404 });
return { status: 'ignored', reason: registered.reason };
}
if (registered.kind === 'transient' || registered.kind === 'token_expired') {
await markLedger(row.id, {
status: 'pending',
error: registered.reason,
httpStatus: registered.kind === 'token_expired' ? 401 : registered.status,
retry: true,
});
return { status: 'transient', reason: registered.reason };
}
if (registered.kind === 'not_configured') return { status: 'skipped', reason: registered.reason };
await markLedger(row.id, {
status: 'failed',
error: `${registered.error}: ${registered.reason}`,
httpStatus: registered.status,
ourFilePaths: uploadedOur,
theirFilePaths: theirPaths,
});
return { status: 'failed', reason: registered.reason };
}
async function markLedger(
id: string,
patch: {
status: 'pending' | 'stored' | 'ignored' | 'failed';
error: string | null;
httpStatus: number;
retry?: boolean;
theirReportId?: string | null;
ourFilePaths?: string[];
theirFilePaths?: string[];
}
): Promise<void> {
await pool.query(
`UPDATE public.main_system_report_pushes
SET status = $2,
last_error = $3,
last_http_status = $4,
attempts = attempts + 1,
pushed_at = CASE WHEN $2 = 'stored' THEN NOW() ELSE pushed_at END,
next_retry_at = CASE WHEN $5 THEN NOW() + (LEAST(POWER(2, LEAST(attempts, 6))::int, 60) || ' minutes')::interval
ELSE NULL END,
their_report_id = COALESCE($6::uuid, their_report_id),
our_file_paths = COALESCE($7::text[], our_file_paths),
their_file_paths = COALESCE($8::text[], their_file_paths),
updated_at = NOW()
WHERE id = $1`,
[
id,
patch.status,
patch.error,
patch.httpStatus,
patch.retry === true,
patch.theirReportId ?? null,
patch.ourFilePaths ?? null,
patch.theirFilePaths ?? null,
]
);
}
/** 一个分公司推一轮(采集 + 逐条推) */
export async function pushBranchReports(input: { branchCode: string; limit?: number }): Promise<{
candidates: number;
stored: number;
ignored: number;
failed: number;
skipped: number;
transient: number;
}> {
const empty = { candidates: 0, stored: 0, ignored: 0, failed: 0, skipped: 0, transient: 0 };
if (!isReportPushEnabled()) return empty;
const branchCode = String(input.branchCode || '').trim();
if (!branchCode) return empty;
const candidates = await collectReportPushCandidates({ branchCode, limit: input.limit });
const stat = { ...empty, candidates: candidates.length };
for (const candidate of candidates) {
try {
const result = await pushReportCandidate(candidate);
if (result.status === 'stored') stat.stored += 1;
else if (result.status === 'ignored') stat.ignored += 1;
else if (result.status === 'failed') stat.failed += 1;
else if (result.status === 'transient') stat.transient += 1;
else stat.skipped += 1;
} catch (error: any) {
stat.failed += 1;
console.warn('[report-push] 推送异常:', error?.message || error);
}
}
return stat;
}
/**
* 定时对账兜底:对所有**有 active 绑定**的分公司推一轮。
* 未绑定分公司天然不在名单里(物理门禁)。
*/
export async function runReportPushReconcile(options?: { limitPerBranch?: number }): Promise<{
branches: number;
stored: number;
ignored: number;
failed: number;
}> {
const summary = { branches: 0, stored: 0, ignored: 0, failed: 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`
);
for (const row of branches.rows) {
summary.branches += 1;
const stat = await pushBranchReports({ branchCode: row.branch_code, limit: options?.limitPerBranch });
summary.stored += stat.stored;
summary.ignored += stat.ignored;
summary.failed += stat.failed;
}
return summary;
}
/**
* 触发点入口(旁路异步,绝不阻塞调用方):分拣完成/发车、报告确认、定时兜底都调它。
* 关闭开关 / 空分公司 / 未配置 ⇒ 立即返回(零出站)。
*/
export function triggerReportPush(branchCode: string | null | undefined): void {
if (!isReportPushEnabled()) return;
const code = String(branchCode || '').trim();
if (!code) return;
void pushBranchReports({ branchCode: code }).catch((error: any) => {
console.warn('[report-push] 触发推送失败(已吞,不影响主流程):', error?.message || error);
});
}