import { pool } from '../db'; import { buildSignedStoragePath } from './storageSignedUrl'; import { QUALITY_REPORT_SELF_SUPPLIER_KEY, QUALITY_REPORT_STATUS, qualityReportPurchaserPartyKey, } from './qualityReportService'; import { normalizeInboundPhotoSupplier } from './orderInboundPhotosService'; export type QualityReportFileKind = 'image' | 'pdf' | 'other'; export type OrderQualityReportFile = { path: string; url: string; kind: QualityReportFileKind; }; const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif']); function trimText(value: unknown): string { return String(value || '').trim(); } export function classifyQualityReportFileKind(pathOrUrl: string): QualityReportFileKind { const clean = String(pathOrUrl || '') .split('?')[0] .split('#')[0] .trim(); const dot = clean.lastIndexOf('.'); const ext = dot >= 0 ? clean.slice(dot + 1).toLowerCase() : ''; if (ext === 'pdf') return 'pdf'; if (IMAGE_EXTS.has(ext)) return 'image'; return 'other'; } export function qualityReportCoversSku(input: { skuCode: string | null; categoryCode?: string | null; reportSku: string | null; reportCategory: string | null; shareMode: string | null; linkedSkus?: string[]; }): boolean { const sku = trimText(input.skuCode) || null; const linked = (input.linkedSkus || []).map(trimText).filter(Boolean); if (sku && trimText(input.reportSku) === sku) return true; if (sku && linked.includes(sku)) return true; const mode = trimText(input.shareMode); if (mode === 'manual') return false; if (mode === 'produce_day') return true; if (mode === 'leaf_category') { const cat = trimText(input.categoryCode) || null; const rcat = trimText(input.reportCategory) || null; return Boolean(cat && rcat && cat === rcat); } return false; } function linePartyKeys(supplierCode: string | null, purchaserCode: string | null): string[] { const normalized = normalizeInboundPhotoSupplier(supplierCode); if (normalized !== '_none') return [normalized]; const keys: string[] = []; const purchaser = trimText(purchaserCode); if (purchaser) keys.push(qualityReportPurchaserPartyKey(purchaser)); keys.push(QUALITY_REPORT_SELF_SUPPLIER_KEY); return keys; } function parseUuidList(raw: unknown): string[] { if (Array.isArray(raw)) { return raw.map((v) => String(v || '').trim()).filter(Boolean); } return []; } function groupKey(sku: string, supplier: string): string { return `${sku}|${normalizeInboundPhotoSupplier(supplier)}`; } type CandidateReport = { id: string; sku_code: string | null; category_code: string | null; share_mode: string | null; supplier_code: string | null; preparation_id: string | null; purchase_code: string | null; linked_sku_codes: string[]; file_paths: string[]; }; function mapCandidate(row: Record): CandidateReport { return { id: String(row.id), sku_code: row.sku_code != null ? trimText(row.sku_code) || null : null, category_code: row.category_code != null ? trimText(row.category_code) || null : null, share_mode: row.share_mode != null ? trimText(row.share_mode) || null : null, supplier_code: row.supplier_code != null ? trimText(row.supplier_code) || null : null, preparation_id: row.preparation_id != null ? String(row.preparation_id) : null, purchase_code: row.purchase_code != null ? trimText(row.purchase_code) || null : null, linked_sku_codes: Array.isArray(row.linked_sku_codes) ? row.linked_sku_codes.map((v) => String(v || '').trim()).filter(Boolean) : [], file_paths: Array.isArray(row.file_paths) ? row.file_paths.map((v) => String(v || '').trim()).filter(Boolean) : [], }; } export function assignReportIdsToLine(input: { skuCode: string | null; categoryCode: string | null; qualityReportIds: string[]; prepIds: string[]; purchaseCodes: string[]; partyKeys: string[]; reports: CandidateReport[]; prepLinkedReportIds: Set; }): string[] { const ids = new Set(); for (const id of input.qualityReportIds) { if (id) ids.add(id); } const prepSet = new Set(input.prepIds.filter(Boolean)); const poSet = new Set(input.purchaseCodes.map(trimText).filter(Boolean)); const partySet = new Set(input.partyKeys); for (const report of input.reports) { if (ids.has(report.id)) continue; if (report.preparation_id && prepSet.has(report.preparation_id)) { ids.add(report.id); continue; } if (report.purchase_code && poSet.has(report.purchase_code)) { ids.add(report.id); continue; } if (input.prepLinkedReportIds.has(report.id) && report.preparation_id && prepSet.has(report.preparation_id)) { ids.add(report.id); continue; } if (!partySet.has(trimText(report.supplier_code))) continue; if ( qualityReportCoversSku({ skuCode: input.skuCode, categoryCode: input.categoryCode, reportSku: report.sku_code, reportCategory: report.category_code, shareMode: report.share_mode, linkedSkus: report.linked_sku_codes, }) ) { ids.add(report.id); } } return [...ids]; } /** 备货链上的库报告:prep_links 的 report id,不要求 preparation_id 等于本行(库报告 preparation_id 常空) */ export function assignReportIdsToLineWithPrepLinks(input: { skuCode: string | null; categoryCode: string | null; qualityReportIds: string[]; prepIds: string[]; purchaseCodes: string[]; partyKeys: string[]; reports: CandidateReport[]; linkedReportIdsForLinePreps: string[]; }): string[] { const ids = new Set( assignReportIdsToLine({ ...input, prepLinkedReportIds: new Set(), }) ); for (const id of input.linkedReportIdsForLinePreps) { if (id) ids.add(id); } for (const report of input.reports) { if (ids.has(report.id)) continue; if (!input.linkedReportIdsForLinePreps.includes(report.id)) continue; ids.add(report.id); } return [...ids]; } export async function listOrderQualityReportFiles( orderCode: string, requestHost?: string | null ): Promise<{ items: Array<{ sku_code: string; supplier_code: string; files: OrderQualityReportFile[] }>; }> { const code = trimText(orderCode); if (!code) return { items: [] }; const header = await pool.query( `SELECT order_code, delivery_date::date::text AS delivery_date, branch_code FROM orders WHERE order_code = $1 LIMIT 1`, [code] ); if (!header.rows[0]) return { items: [] }; const deliveryDate = String(header.rows[0].delivery_date || '').slice(0, 10); if (!deliveryDate) return { items: [] }; const lineResult = await pool.query( `SELECT oi.id::text AS id, NULLIF(TRIM(oi.sku_code), '') AS sku_code, NULLIF(TRIM(oi.supplier_code), '') AS supplier_code, COALESCE( NULLIF(TRIM(oi.category_code), ''), NULLIF(TRIM(s.category_code), '') ) AS category_code, oi.quality_report_id::text AS quality_report_id, oi.quality_report_ids FROM order_items oi LEFT JOIN skus s ON s.sku_code = oi.sku_code WHERE oi.order_code = $1 AND COALESCE(oi.is_returned, false) = false`, [code] ); const lines = lineResult.rows as Array>; if (!lines.length) return { items: [] }; const lineIds = lines.map((r) => String(r.id)); const fulResult = await pool.query( `SELECT f.order_item_id::text AS order_item_id, f.supplier_preparation_id::text AS prep_id, NULLIF(TRIM(f.purchase_code), '') AS purchase_code FROM order_item_fulfillments f WHERE f.order_item_id = ANY($1::uuid[])`, [lineIds] ); const prepsByLine = new Map(); const posByLine = new Map(); const allPrepIds: string[] = []; const allPoCodes: string[] = []; for (const row of fulResult.rows) { const lid = String(row.order_item_id); if (row.prep_id) { const list = prepsByLine.get(lid) || []; list.push(String(row.prep_id)); prepsByLine.set(lid, list); allPrepIds.push(String(row.prep_id)); } if (row.purchase_code) { const list = posByLine.get(lid) || []; list.push(String(row.purchase_code)); posByLine.set(lid, list); allPoCodes.push(String(row.purchase_code)); } } const purchaserByPo = new Map(); if (allPoCodes.length) { const poRows = await pool.query( `SELECT purchase_code, NULLIF(TRIM(purchaser_code), '') AS purchaser_code FROM purchase_orders WHERE purchase_code = ANY($1::text[]) AND purchase_status <> 40`, [[...new Set(allPoCodes)]] ); for (const row of poRows.rows) { if (row.purchaser_code) { purchaserByPo.set(String(row.purchase_code), String(row.purchaser_code)); } } } const uuidIds = new Set(); for (const line of lines) { if (line.quality_report_id) uuidIds.add(String(line.quality_report_id)); for (const id of parseUuidList(line.quality_report_ids)) uuidIds.add(id); } const partyKeys = new Set(); for (const line of lines) { const lid = String(line.id); const pos = posByLine.get(lid) || []; let purchaser: string | null = null; for (const po of pos) { purchaser = purchaserByPo.get(po) || purchaser; } for (const key of linePartyKeys( line.supplier_code != null ? String(line.supplier_code) : null, purchaser )) { partyKeys.add(key); } } const reportParams: unknown[] = [QUALITY_REPORT_STATUS.active, deliveryDate]; const orParts: string[] = []; if (partyKeys.size) { reportParams.push([...partyKeys]); orParts.push( `(COALESCE(qr.report_date::date, qr.delivery_date::date) = $2::date AND qr.supplier_code = ANY($${reportParams.length}::text[]))` ); } if (uuidIds.size) { reportParams.push([...uuidIds]); orParts.push(`qr.id = ANY($${reportParams.length}::uuid[])`); } if (allPrepIds.length) { reportParams.push([...new Set(allPrepIds)]); orParts.push(`qr.preparation_id = ANY($${reportParams.length}::uuid[])`); } if (allPoCodes.length) { reportParams.push([...new Set(allPoCodes)]); orParts.push(`qr.purchase_code = ANY($${reportParams.length}::text[])`); } if (!orParts.length) { return { items: [] }; } const reportsResult = await pool.query( `SELECT qr.id, qr.sku_code, qr.category_code, qr.share_mode, qr.supplier_code, qr.preparation_id::text AS preparation_id, qr.purchase_code, qr.linked_sku_codes, qr.file_paths FROM quality_reports qr WHERE qr.status = $1 AND (${orParts.join(' OR ')})`, reportParams ); let reports = reportsResult.rows.map(mapCandidate); const linkedByPrep = new Map(); if (allPrepIds.length) { const links = await pool.query( `SELECT l.preparation_id::text AS prep_id, l.quality_report_id::text AS report_id FROM quality_report_prep_links l JOIN quality_reports qr ON qr.id = l.quality_report_id WHERE l.preparation_id = ANY($1::uuid[]) AND l.status = $2 AND qr.status = $2`, [[...new Set(allPrepIds)], QUALITY_REPORT_STATUS.active] ); const missingIds = new Set(); for (const row of links.rows) { const prepId = String(row.prep_id); const rid = String(row.report_id); const list = linkedByPrep.get(prepId) || []; list.push(rid); linkedByPrep.set(prepId, list); if (!reports.some((r) => r.id === rid)) missingIds.add(rid); } if (missingIds.size) { const extra = await pool.query( `SELECT id, sku_code, category_code, share_mode, supplier_code, preparation_id::text AS preparation_id, purchase_code, linked_sku_codes, file_paths FROM quality_reports WHERE id = ANY($1::uuid[]) AND status = $2`, [[...missingIds], QUALITY_REPORT_STATUS.active] ); reports = reports.concat(extra.rows.map(mapCandidate)); } } const byId = new Map(reports.map((r) => [r.id, r])); const grouped = new Map< string, { sku_code: string; supplier_code: string; files: OrderQualityReportFile[]; seen: Set } >(); const host = trimText(requestHost).replace(/\/+$/, ''); for (const line of lines) { const sku = trimText(line.sku_code); if (!sku) continue; const lid = String(line.id); const pos = posByLine.get(lid) || []; let purchaser: string | null = null; for (const po of pos) purchaser = purchaserByPo.get(po) || purchaser; const supplierRaw = line.supplier_code != null ? String(line.supplier_code) : null; const ids = assignReportIdsToLineWithPrepLinks({ skuCode: sku, categoryCode: line.category_code != null ? String(line.category_code) : null, qualityReportIds: [ ...parseUuidList(line.quality_report_ids), ...(line.quality_report_id ? [String(line.quality_report_id)] : []), ], prepIds: prepsByLine.get(lid) || [], purchaseCodes: pos, partyKeys: linePartyKeys(supplierRaw, purchaser), reports, linkedReportIdsForLinePreps: (prepsByLine.get(lid) || []).flatMap( (pid) => linkedByPrep.get(pid) || [] ), }); const supplier = normalizeInboundPhotoSupplier(supplierRaw); const key = groupKey(sku, supplier); let bucket = grouped.get(key); if (!bucket) { bucket = { sku_code: sku, supplier_code: supplier, files: [], seen: new Set() }; grouped.set(key, bucket); } for (const id of ids) { const report = byId.get(id); if (!report) continue; for (const filename of report.file_paths) { if (!filename || bucket.seen.has(filename)) continue; bucket.seen.add(filename); const path = buildSignedStoragePath('quality-reports', filename); const url = host && !path.startsWith('http') ? `${host}${path}` : path; bucket.files.push({ path: filename, url, kind: classifyQualityReportFileKind(filename), }); } } } return { items: [...grouped.values()] .filter((row) => row.files.length > 0) .map(({ sku_code, supplier_code, files }) => ({ sku_code, supplier_code, files })), }; }