/** * 批次报告推送(第九批「批次报告同步」我方推送侧)。 * * 设计: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 { 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(); 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, 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 { 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 { 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); }); }