/** * 批次报告推送(第九批「批次报告同步」我方推送侧)。 * * 设计: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 { runWithTenantDbContext } from './tenantDbContext'; import { getStorageProvider } from './storageProvider'; import { registerBatchReportOnPreparation, uploadBatchReportFile, isUploadableReportFileName, voidSupplierBatchReport, } 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_nos: string[]; batch_no: string | null; produced_at: string | null; testing_org: string | null; product_names: string[]; }; /** * 推送指纹:**完整文件集 + 该行消耗的批次集合**(任一变化即重推)。 * * 为什么纳入批次集合(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'); } /** * 采集候选:报告(已确认)→ 入库批次 → 分拣选批 → 订单行 → 主系统备货行(prep_id)。 * * ⚠️ 只认"分拣**实际选定/扣减**的批次"(`picking_items.outbound_batches`,形如 * `[{"batch_no":"STK…","qty":12.5}]`)—— 这正是开发者说的"分拣完毕选中了那几个批次"。 */ export async function collectReportPushCandidates(input: { branchCode: string; limit?: number; }): Promise { const branchCode = String(input.branchCode || '').trim(); if (!branchCode) return []; const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200); // ⚠️ 必须按 **(prep_id, report_type)** 聚合,而不是按批次:契约 §2.12.9 ④-1 要求"每次推该行该类型的 // **完整文件集**"(同键再登记会让对方把上一份作废,latest wins)⇒ 一行消耗多个批次时, // 这些批次的报告文件必须**并集成一条**推过去,否则后推的会覆盖前推的(E2E 实测踩到)。 const result = await pool.query( `WITH hit AS ( SELECT DISTINCT oi.id AS order_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 order_items oi ON oi.sku_code = inv.sku_code JOIN orders o ON o.order_code = oi.order_code WHERE oi.branch_code = $1 AND ( -- 源①:该行在分拣里**选定/计划**的批次(picking_items.outbound_batches) EXISTS ( SELECT 1 FROM picking_items pi WHERE pi.order_item_id = oi.id 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 ) ) OR -- 源②:**实际出库流水**(分拣出库 / 发车核货出库)—— 覆盖"没开分拣、入库后等配送员来拿 / 直接配送"的单。 -- 只有源①时这些单永远进不了候选(2026-10-11 开发者提问后补)。 EXISTS ( SELECT 1 FROM inventory_logs il WHERE il.related_order_code = o.order_code AND il.sku_code = inv.sku_code AND il.batch_no = inv.batch_no AND il.operation_type IN ('picking_out', 'delivery_loading_out') ) ) ) 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, -- 该行消耗的批次:只有一个时带上(对方 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, (array_agg(DISTINCT h.testing_org))[1] AS testing_org, array_agg(DISTINCT unnest_name) AS product_names FROM hit h JOIN public.main_system_order_import_items l ON l.our_order_item_id = h.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 LEFT JOIN LATERAL unnest(h.product_names) AS unnest_name 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' ORDER BY l.prep_id LIMIT $2`, [branchCode, limit] ); const out: ReportPushCandidate[] = []; for (const row of result.rows as Record[]) { 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, 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), }); } return out; } export type PushOneResult = { status: 'stored' | 'ignored' | 'failed' | 'skipped' | 'transient'; reason?: string; theirReportId?: string | null; }; /** 单条候选:落台账 → (文件集变了才)上传 + 登记 → 回写状态 */ export async function pushReportCandidate(candidate: ReportPushCandidate): Promise { const fingerprint = filesFingerprint(candidate.our_file_paths, candidate.batch_nos); 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, 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, 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() 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, candidate.batch_nos, ] ); 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 === 'blocked_by_staff_report') { // 护栏 A(主系统 §4.5.19):该行同类型已有**他们人工上传**的报告 ⇒ 我们不作废、不落库; // 终态 + 告警,绝不重试(否则每次对账都撞 409) await markLedger(row.id, { status: 'failed', error: `该行已有主系统人工报告(staff_report_exists)⇒ 改行挂靠或等其撤下:${registered.reason}`, httpStatus: 409, }); console.warn( `[report-push] ⚠️ 409 staff_report_exists:prep=${candidate.prep_id} type=${candidate.report_type} ` + `⇒ 主系统该行已有人工报告,本次不落库(终态,不重试)` ); return { status: 'failed', reason: registered.reason }; } 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 { await pool.query( // ⚠️ 参数必须显式定型:同一个 $2 既赋给 varchar 列、又参与文本比较,PG 会报 // "inconsistent types deduced for parameter $2"(E2E 实测踩到) `UPDATE public.main_system_report_pushes SET status = $2::varchar, last_error = $3::text, last_http_status = $4::int, attempts = attempts + 1, pushed_at = CASE WHEN $2::text = 'stored' THEN NOW() ELSE pushed_at END, next_retry_at = CASE WHEN $5::boolean 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, ] ); } /** * 失效侦测(修正同步的兜底,2026-10-11 开发者提问后补): * 台账里已 `stored`、但本轮**候选已消失** ⇒ 说明报告被解绑/作废(例如绑定改错后修正), * 而主系统那边**没有任何"撤下"能力**(其 discard 只对暂存态开放,见 §2.12.11)⇒ * 我们不能静默:标 `stale` + 告警,等主系统开放「按行撤下」后自动撤。 * * ⚠️ 只在**候选未被 limit 截断**时判定(否则"没进候选"可能只是被截断,会造成误报)。 */ async function detectStaleLedgerRows(input: { branchCode: string; candidates: ReportPushCandidate[]; truncated: boolean; }): Promise { 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 newlyStale = result.rowCount || 0; if (newlyStale > 0) { console.warn( `[report-push] ⚠️ ${input.branchCode}:${newlyStale} 条台账已登记但候选消失(报告解绑/作废)⇒ 标记 stale,` + `尝试按行撤下(主系统 §4.5.18 ③ 的 /void)` ); } // ⚠️ **每一轮都要处理全部 stale 行**(不能只在"本轮新转 stale"时才走):否则对方 /void 端点上线后, // 历史 stale 行永远等不到撤下(E2E 第 ⑪ 步实测踩到:第二次对账 stale 直接变 0、也不再调 /void)。 // 撤下是幂等的;端点未上线/报告不存在 ⇒ 保持 stale 等下一轮,不重试风暴。 const targets = await pool.query<{ id: string; main_supplier_code: string; their_report_id: string | null }>( `SELECT id::text, main_supplier_code, their_report_id::text FROM public.main_system_report_pushes WHERE branch_code = $1 AND status = 'stale' AND their_report_id IS NOT NULL`, [input.branchCode] ); for (const target of targets.rows) { try { const voided = await voidSupplierBatchReport({ supplierCode: target.main_supplier_code, theirReportId: String(target.their_report_id), }); if (voided.kind === 'voided') { await pool.query( `UPDATE public.main_system_report_pushes SET status = 'voided', last_error = NULL, updated_at = NOW() WHERE id = $1::bigint`, [target.id] ); console.log( `[report-push] ✅ 已按行撤下主系统报告 ${String(target.their_report_id).slice(0, 8)}…` + `${voided.already ? '(对方回 already=true,幂等命中)' : ''}` ); } else if (voided.kind === 'blocked_by_staff_report') { // 该报告是主系统人工上传的 ⇒ 我方无权撤下(他们 /void 的 409)⇒ 终态 + 告警,**不再重试** await pool.query( `UPDATE public.main_system_report_pushes SET status = 'failed', last_error = $2, updated_at = NOW() WHERE id = $1::bigint`, [target.id, `该报告由主系统人工上传,我方无权撤下(staff_report_exists)⇒ 需其人工处理:${voided.reason}`] ); console.warn( `[report-push] ⚠️ 撤下被拒(409 staff_report_exists):报告 ${String(target.their_report_id).slice(0, 8)}… ` + `是主系统人工上传的 ⇒ 转终态 failed,需人工联系主系统处理` ); } else if (voided.kind === 'not_found') { // 端点未上线 / 报告不属于本供应商 ⇒ 保持 stale,下一轮再试(不报错、不重试风暴) await pool.query( `UPDATE public.main_system_report_pushes SET last_error = $2, updated_at = NOW() WHERE id = $1::bigint`, [target.id, `撤下未生效(404,端点未就绪或报告不存在):${voided.reason}`] ); } else { await pool.query( `UPDATE public.main_system_report_pushes SET last_error = $2, updated_at = NOW() WHERE id = $1::bigint`, [target.id, `撤下暂态失败(下轮重试):${voided.reason}`] ); } } catch (error: any) { console.warn('[report-push] 撤下异常(忽略,下轮重试):', error?.message || error); } } // 返回**仍未撤下**的 stale 行数:运维看这个数才知道还有多少要人工跟进 const left = await pool.query<{ n: number }>( `SELECT count(*)::int AS n FROM public.main_system_report_pushes WHERE branch_code = $1 AND status = 'stale'`, [input.branchCode] ); return Number(left.rows[0]?.n) || 0; } /** 一个分公司推一轮(采集 + 逐条推 + 失效侦测) */ export async function pushBranchReports(input: { branchCode: string; limit?: number }): Promise<{ candidates: number; stored: number; ignored: number; failed: number; skipped: number; transient: number; stale: number; }> { 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 limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200); /** * ⚠️ **必须包租户上下文**:候选采集查的是租户 schema 里的表(`inventory_batch_report_matches` / * `inventory` / `picking_items`),而**调度器 tick 没有请求级上下文** ⇒ 不包就会 42P01 * (2026-10-11 首次开启开关后,调度 tick 实测报 `relation "inventory_batch_report_matches" does not exist`)。 * 在路由/服务请求内调用时,`runWithTenantDbContext` 会复用已存在的同分公司上下文(不会重复借连接)。 */ return runWithTenantDbContext(branchCode, async () => { const candidates = await collectReportPushCandidates({ branchCode, 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); } } stat.stale = await detectStaleLedgerRows({ branchCode, candidates, truncated: candidates.length >= limit, }); return stat; }); } /** * 定时对账兜底:对所有**有 active 绑定**的分公司推一轮。 * 未绑定分公司天然不在名单里(物理门禁)。 */ export async function runReportPushReconcile(options?: { limitPerBranch?: number }): Promise<{ branches: number; stored: number; ignored: number; failed: number; stale: number; }> { 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` ); 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; summary.stale += stat.stale; } 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); }); }