/** * 入库批次报告:仓库上传(图片 / PDF)→ OCR 解析 → 按「商品名 + 生产日期」匹配入库批次。 * * 设计:docs/design/20261029-入库批次报告上传与匹配.md * * 硬边界(勿破): * - **不复用 `quality_reports`**:那会进入验收「报告齐全」硬闸的覆盖计算 * (见 .cursor/rules/product-freeze.mdc)。本功能用独立表; * - **不写 `inventory`**:库存管理冻结,本服务只**读** `inventory` 做匹配; * - **本期不推主系统**(对接契约未定); * - OCR **复用**已登记提示词 `quality.report.meta`(不新增 AI 功能 / 提示词 / 计量点)。 * * 匹配键 = 商品名 + 生产日期;结果三态(唯一 / 多命中 / 未命中)+ **人工确认**才落关联。 */ import { pool } from '../db'; import { writeAuditLog } from './auditService'; import { getStorageProvider } from './storageProvider'; import { safeStorageFileName } from './storageBucketConfig'; import { buildSignedStoragePath } from './storageSignedUrl'; import { resolvePrompt } from './promptRegistryService'; import { callWithImage, callWithFile, hasRuntimeConfig } from './llmService'; import { extractAiProductNames, productNamesMatch } from './qualityReportService'; const REPORT_BUCKET = 'quality-reports'; const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif']); const STATUS_PENDING = 10; const STATUS_CONFIRMED = 30; /** 单次匹配扫描上限(按分公司 + 生产日期收窄,再在内存里做商品名模糊匹配) */ const CANDIDATE_SCAN_LIMIT = 2000; function trimText(v: unknown): string { return String(v ?? '').trim(); } /** '2026/10/9' / '2026年10月9日' / '20261009' / Date → 'YYYY-MM-DD';认不出→null */ function toDateOnly(v: unknown): string | null { if (v instanceof Date && !Number.isNaN(v.getTime())) { const y = v.getFullYear(); const m = String(v.getMonth() + 1).padStart(2, '0'); const d = String(v.getDate()).padStart(2, '0'); return `${y}-${m}-${d}`; } const t = trimText(v); if (!t) return null; const m = t.match(/^(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})/); if (m) return `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`; const compact = t.match(/^(\d{4})(\d{2})(\d{2})$/); if (compact) return `${compact[1]}-${compact[2]}-${compact[3]}`; return null; } function normalizeName(v: unknown): string { return trimText(v) .toLowerCase() .replace(/[\s\u3000]+/g, '') .replace(/[()()【】\[\]「」『』《》<>]/g, '') .replace(/[·•..]/g, ''); } type ParsedMeta = { product_names: string[]; produced_at: string | null; testing_org: string | null; ai_raw: Record | null; }; function emptyMeta(): ParsedMeta { return { product_names: [], produced_at: null, testing_org: null, ai_raw: null }; } /** * OCR 一份报告内容:图走视觉;PDF 走方舟文档理解。失败留空(降级不阻断,人工可手选批次)。 * 提示词沿用 `quality.report.meta`(已登记 AI 门槛)。 */ async function ocrReportContent( contentBase64: string, ext: string, branchCode: string ): Promise { const empty = emptyMeta(); const lower = ext.toLowerCase(); if (!IMAGE_EXTS.has(lower) && lower !== 'pdf') return empty; if (!contentBase64 || !(await hasRuntimeConfig({ branchCode }))) return empty; try { const prompt = await resolvePrompt('quality.report.meta', { branchCode }); let text: string | null = null; if (IMAGE_EXTS.has(lower)) { text = await callWithImage(prompt.systemPrompt, contentBase64, { branchCode }); } else { const dataUrl = contentBase64.startsWith('data:') ? contentBase64 : `data:application/pdf;base64,${contentBase64}`; text = await callWithFile(prompt.systemPrompt, dataUrl, { branchCode, filename: 'batch-report.pdf', mime: 'application/pdf', }); } if (!text) return empty; const jsonMatch = text.match(/\{[\s\S]*\}/); if (!jsonMatch) return empty; const raw = JSON.parse(jsonMatch[0]) as Record; return { product_names: extractAiProductNames(raw), produced_at: toDateOnly(raw.produced_at), testing_org: trimText(raw.testing_org) || trimText(raw.inspected_org) || null, ai_raw: raw, }; } catch (error) { console.warn( '[inventory-batch-report] OCR failed:', error instanceof Error ? error.message : error ); return empty; } } /** 从 `quality-reports` 桶读回上传对象(先经 multer 通道落存储)。 */ async function loadUploadedObject( path: string ): Promise<{ base64: string; ext: string } | null> { let safe: string; try { safe = safeStorageFileName(trimText(path)); } catch { return null; } if (!safe) return null; const obj = await getStorageProvider().getObject(REPORT_BUCKET, safe); if (!obj?.buffer?.length) return null; const ext = (safe.split('.').pop() || 'jpg').toLowerCase(); return { base64: obj.buffer.toString('base64'), ext }; } export interface BatchReportCandidate { inventory_id: string; sku_code: string | null; sku_name: string | null; batch_no: string | null; production_date: string | null; available_qty: number | null; unit: string | null; spec: string | null; storage_zone: string | null; /** exact = 商品名/编码全等;fuzzy = 包含命中(「疑似」) */ match_kind: 'exact' | 'fuzzy'; } export interface BatchReportProductMatch { product_name: string; status: 'unique' | 'multi' | 'none'; candidates: BatchReportCandidate[]; } export interface BatchReportConfirmedMatch { id: string; inventory_id: string; sku_code: string | null; product_name: string | null; batch_no: string | null; production_date: string | null; match_source: 'auto' | 'manual'; confirmed_at: string | null; } export interface InventoryBatchReportDto { id: string; report_no: string | null; report_type: string; file_paths: string[]; file_urls: string[]; product_names: string[]; produced_at: string | null; testing_org: string | null; status: number; ai_parsed: boolean; uploaded_at: string | null; confirmed: BatchReportConfirmedMatch[]; /** 候选只在「创建 / 取单条」时返回 */ matches?: BatchReportProductMatch[]; } type CandidateRow = { inventory_id: string; sku_code: string | null; sku_name: string | null; batch_no: string | null; production_date: string | null; available_qty: number | null; unit: string | null; spec: string | null; storage_zone: string | null; }; async function loadCandidateRows( branchCode: string, producedAt: string | null ): Promise { const params: unknown[] = [branchCode]; let dateFilter = ''; if (producedAt) { params.push(producedAt); dateFilter = ` AND i.production_date = $2::date`; } const result = await pool.query( `SELECT i.id AS inventory_id, i.sku_code, i.batch_no, i.production_date, i.available_qty, i.storage_zone, s.sku_name, s.unit, s.spec FROM inventory i LEFT JOIN skus s ON s.sku_code = i.sku_code WHERE i.branch_code = $1${dateFilter} ORDER BY i.available_qty DESC NULLS LAST, i.created_at DESC LIMIT ${CANDIDATE_SCAN_LIMIT}`, params ); return (result.rows as Record[]).map((row) => ({ inventory_id: String(row.inventory_id), sku_code: row.sku_code == null ? null : String(row.sku_code), sku_name: row.sku_name == null ? null : String(row.sku_name), batch_no: row.batch_no == null ? null : String(row.batch_no), production_date: toDateOnly(row.production_date), available_qty: row.available_qty == null ? null : Number(row.available_qty), unit: row.unit == null ? null : String(row.unit), spec: row.spec == null ? null : String(row.spec), storage_zone: row.storage_zone == null ? null : String(row.storage_zone), })); } /** 按「商品名 + 生产日期」给出每个品名的匹配建议(三态) */ function buildProductMatches( productNames: string[], producedAt: string | null, rows: CandidateRow[] ): BatchReportProductMatch[] { return productNames.map((name) => { const normalized = normalizeName(name); const hits = rows.filter( (row) => productNamesMatch(name, row.sku_name) || productNamesMatch(name, row.sku_code) ); const candidates: BatchReportCandidate[] = hits.map((row) => { const exact = normalized.length > 0 && (normalizeName(row.sku_name) === normalized || normalizeName(row.sku_code) === normalized); return { ...row, match_kind: exact ? 'exact' : 'fuzzy' }; }); return { product_name: name, status: candidates.length === 0 ? 'none' : candidates.length === 1 ? 'unique' : 'multi', candidates, }; }); } function mapReportRow( raw: Record, confirmed: BatchReportConfirmedMatch[] ): InventoryBatchReportDto { const paths = Array.isArray(raw.file_paths) ? raw.file_paths.map((p) => String(p)) : []; const fileUrls = paths.map((p) => { try { return buildSignedStoragePath(REPORT_BUCKET, safeStorageFileName(p)); } catch { return p; } }); return { id: String(raw.id), report_no: raw.report_no == null ? null : String(raw.report_no), report_type: raw.report_type == null ? 'batch' : String(raw.report_type), file_paths: paths, file_urls: fileUrls, product_names: Array.isArray(raw.product_names) ? raw.product_names.map((n) => String(n)) : [], produced_at: toDateOnly(raw.produced_at), testing_org: raw.testing_org == null ? null : String(raw.testing_org), status: Number(raw.status ?? STATUS_PENDING), ai_parsed: raw.ai_raw != null, uploaded_at: raw.uploaded_at ? String(raw.uploaded_at) : null, confirmed, }; } function mapConfirmedRows(rows: Record[]): BatchReportConfirmedMatch[] { return rows.map((row) => ({ id: String(row.id), inventory_id: String(row.inventory_id), sku_code: row.sku_code == null ? null : String(row.sku_code), product_name: row.product_name == null ? null : String(row.product_name), batch_no: row.batch_no == null ? null : String(row.batch_no), production_date: toDateOnly(row.production_date), match_source: row.match_source === 'manual' ? 'manual' : 'auto', confirmed_at: row.confirmed_at ? String(row.confirmed_at) : null, })); } async function loadConfirmedMatches(reportId: string): Promise { const result = await pool.query( `SELECT id, inventory_id, sku_code, product_name, batch_no, production_date, match_source, confirmed_at FROM inventory_batch_report_matches WHERE report_id = $1::uuid ORDER BY confirmed_at ASC`, [reportId] ); return mapConfirmedRows(result.rows as Record[]); } /** * 上传并解析:每个文件 → 一份报告(OCR + 匹配候选)。文件须先经存储通道上传到 * `quality-reports` 桶(前端 `uploadQualityReportFileApi`)。 */ export async function createInventoryBatchReports(input: { files: string[]; branchCode: string; uploadedBy?: string | null; reportNo?: string | null; }): Promise { const branchCode = trimText(input.branchCode); if (!branchCode) { throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required', }); } const files = (input.files || []).map((f) => trimText(f)).filter(Boolean); if (!files.length) { throw Object.assign(new Error('请先上传报告文件'), { status: 400, code: 'invalid_request' }); } const reportNo = trimText(input.reportNo) || null; // 1) 落存储对象读回 + OCR(在事务外做,避免长时间占用连接) const parsed: Array<{ path: string; meta: ParsedMeta }> = []; for (const path of files) { const obj = await loadUploadedObject(path); if (!obj) continue; const meta = await ocrReportContent(obj.base64, obj.ext, branchCode); let storedPath = path; try { storedPath = safeStorageFileName(path); } catch { /* 保留原值 */ } parsed.push({ path: storedPath, meta }); } if (!parsed.length) { throw Object.assign(new Error('报告文件读取失败,请重新上传'), { status: 400, code: 'file_unreadable', }); } // 2) 落库(一份文件一行) const client = await pool.connect(); const createdIds: string[] = []; try { await client.query('BEGIN'); for (let i = 0; i < parsed.length; i += 1) { const { path, meta } = parsed[i]; const rno = reportNo ? (parsed.length > 1 ? `${reportNo}-${i + 1}` : reportNo) : null; if (rno) { // 同分公司内报告编号唯一:提前拦下,给友好 400(否则撞唯一索引变 500) const dup = await client.query( `SELECT 1 FROM inventory_batch_reports WHERE branch_code = $1 AND report_no = $2 LIMIT 1`, [branchCode, rno] ); if (dup.rowCount) { throw Object.assign(new Error(`报告编号「${rno}」已存在,请换一个或留空`), { status: 400, code: 'report_no_exists', }); } } const inserted = await client.query( `INSERT INTO inventory_batch_reports (branch_code, report_no, report_type, file_paths, source_party, product_names, produced_at, testing_org, ai_raw, ai_parsed_at, status, uploaded_by) VALUES ($1, $2, 'batch', ARRAY[$3]::text[], 'warehouse', $4::text[], $5::date, $6, $7::jsonb, $8, $9, $10::uuid) RETURNING id`, [ branchCode, rno, path, meta.product_names, meta.produced_at, meta.testing_org, meta.ai_raw ? JSON.stringify(meta.ai_raw) : null, meta.ai_raw ? new Date().toISOString() : null, STATUS_PENDING, input.uploadedBy || null, ] ); createdIds.push(String(inserted.rows[0].id)); } await client.query('COMMIT'); } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); } try { await writeAuditLog({ operatorId: input.uploadedBy || null, operationType: 'inventory_batch_report_upload', targetTable: 'inventory_batch_reports', targetId: createdIds[0] || undefined, oldValue: null, newValue: { count: createdIds.length, files: parsed.map((p) => p.path) }, branchCode, actionCategory: 'inventory', }); } catch (auditError) { console.error('[inventoryBatchReport] writeAuditLog(upload) failed:', auditError); } // 3) 组装返回(带匹配候选) const out: InventoryBatchReportDto[] = []; for (const id of createdIds) { const row = await pool.query( `SELECT id, report_no, report_type, file_paths, product_names, produced_at, testing_org, ai_raw, status, uploaded_at FROM inventory_batch_reports WHERE id = $1::uuid`, [id] ); if (!row.rows[0]) continue; const report = mapReportRow(row.rows[0] as Record, []); const candidates = await loadCandidateRows(branchCode, report.produced_at); report.matches = buildProductMatches(report.product_names, report.produced_at, candidates); out.push(report); } return out; } export async function listInventoryBatchReports(input: { branchCode: string; limit?: number; }): Promise { const branchCode = trimText(input.branchCode); if (!branchCode) { throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required', }); } const limit = Math.min(Math.max(Number(input.limit) || 50, 1), 200); const result = await pool.query( `SELECT id, report_no, report_type, file_paths, product_names, produced_at, testing_org, ai_raw, status, uploaded_at FROM inventory_batch_reports WHERE branch_code = $1 ORDER BY uploaded_at DESC LIMIT $2`, [branchCode, limit] ); const rows = result.rows as Record[]; const out: InventoryBatchReportDto[] = []; for (const row of rows) { const report = mapReportRow(row, []); report.confirmed = await loadConfirmedMatches(report.id); out.push(report); } return out; } export async function getInventoryBatchReport(input: { reportId: string; branchCode: string; }): Promise { const reportId = trimText(input.reportId); const branchCode = trimText(input.branchCode); const result = await pool.query( `SELECT id, report_no, report_type, file_paths, product_names, produced_at, testing_org, ai_raw, status, uploaded_at FROM inventory_batch_reports WHERE id = $1::uuid AND branch_code = $2`, [reportId, branchCode] ); if (!result.rows[0]) return null; const report = mapReportRow(result.rows[0] as Record, []); report.confirmed = await loadConfirmedMatches(report.id); const candidates = await loadCandidateRows(branchCode, report.produced_at); report.matches = buildProductMatches(report.product_names, report.produced_at, candidates); return report; } /** * 人工确认匹配:**替换**该报告已有的关联行,并置为已确认。每条关联须落在本分公司的 `inventory` 上。 */ export async function confirmInventoryBatchReportMatches(input: { reportId: string; branchCode: string; operatorId?: string | null; matches: Array<{ inventoryId: string; productName?: string | null }>; }): Promise<{ report_id: string; confirmed: BatchReportConfirmedMatch[] }> { const reportId = trimText(input.reportId); const branchCode = trimText(input.branchCode); if (!reportId) { throw Object.assign(new Error('缺少报告'), { status: 400, code: 'invalid_request' }); } if (!branchCode) { throw Object.assign(new Error('请选择当前操作分公司'), { status: 400, code: 'branch_required', }); } const wanted = (input.matches || []) .map((m) => ({ inventoryId: trimText(m.inventoryId), productName: trimText(m.productName) || null })) .filter((m) => m.inventoryId); if (!wanted.length) { throw Object.assign(new Error('请至少选择一条入库批次'), { status: 400, code: 'invalid_request', }); } const client = await pool.connect(); try { await client.query('BEGIN'); const report = await client.query( `SELECT id, status FROM inventory_batch_reports WHERE id = $1::uuid AND branch_code = $2 FOR UPDATE`, [reportId, branchCode] ); if (!report.rowCount) { throw Object.assign(new Error('报告不存在或不属于当前分公司'), { status: 404, code: 'not_found', }); } // 去重并校验每个库存批次属于本分公司 const seen = new Set(); const rowsToInsert: Array<{ inventoryId: string; skuCode: string | null; batchNo: string | null; productionDate: string | null; productName: string | null; }> = []; for (const item of wanted) { if (seen.has(item.inventoryId)) continue; seen.add(item.inventoryId); const inv = await client.query( `SELECT id, sku_code, batch_no, production_date FROM inventory WHERE id = $1::uuid AND branch_code = $2`, [item.inventoryId, branchCode] ); if (!inv.rowCount) { throw Object.assign(new Error('所选入库批次不存在或不属于当前分公司'), { status: 400, code: 'invalid_inventory', }); } const row = inv.rows[0]; rowsToInsert.push({ inventoryId: item.inventoryId, skuCode: row.sku_code == null ? null : String(row.sku_code), batchNo: row.batch_no == null ? null : String(row.batch_no), productionDate: toDateOnly(row.production_date), productName: item.productName, }); } // 替换语义:先清掉本次未勾选的旧关联,再写入本次选择 await client.query( `DELETE FROM inventory_batch_report_matches WHERE report_id = $1::uuid AND NOT (inventory_id = ANY($2::uuid[]))`, [reportId, rowsToInsert.map((r) => r.inventoryId)] ); for (const r of rowsToInsert) { await client.query( `INSERT INTO inventory_batch_report_matches (report_id, inventory_id, sku_code, product_name, batch_no, production_date, match_source, confirmed_by) VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6::date, 'manual', $7::uuid) ON CONFLICT (report_id, inventory_id) DO UPDATE SET product_name = EXCLUDED.product_name, confirmed_by = EXCLUDED.confirmed_by, confirmed_at = NOW()`, [ reportId, r.inventoryId, r.skuCode, r.productName, r.batchNo, r.productionDate, input.operatorId || null, ] ); } await client.query( `UPDATE inventory_batch_reports SET status = $2 WHERE id = $1::uuid`, [reportId, STATUS_CONFIRMED] ); await client.query('COMMIT'); } catch (error) { await client.query('ROLLBACK').catch(() => undefined); throw error; } finally { client.release(); } const confirmed = await loadConfirmedMatches(reportId); try { await writeAuditLog({ operatorId: input.operatorId || null, operationType: 'inventory_batch_report_confirm', targetTable: 'inventory_batch_reports', targetId: reportId, oldValue: null, newValue: { matches: confirmed.length }, branchCode, actionCategory: 'inventory', }); } catch (auditError) { console.error('[inventoryBatchReport] writeAuditLog(confirm) failed:', auditError); } return { report_id: reportId, confirmed }; }