import { supabase } from '../supabase/client'; import { getQuoteSheetApi, listQuoteSheetsApi } from './workflowApi'; import { getStatementLinesApi, fetchDeliveryPrintLinesApi } from './workflowApi'; import type { OrderExportRow, QuoteExportRow, StatementExportRow, DeliveryExportRow, } from './exportColumnPresets'; import { formatChinaDateTime } from './chinaDate'; import { formatCustomerDeliveryDeadlineDateTime } from './customerDeliveryDeadline'; function positivePrice(v: unknown): number { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; } async function loadQuoteCostMapByCustomer(customerCode: string): Promise> { const code = String(customerCode || '').trim(); if (!code) return new Map(); try { const list = await listQuoteSheetsApi({ view: 'active', customerCode: code, limit: 10 }); const sheets = (list.data || []) as Array<{ quote_sheet_code?: string }>; const map = new Map(); for (const sheet of sheets) { if (!sheet?.quote_sheet_code) continue; const detail = await getQuoteSheetApi(sheet.quote_sheet_code); const items = ( detail.data as { items?: Array<{ sku_code?: string; cost_price?: number }>; } )?.items || []; for (const row of items) { const sku = String(row.sku_code || '').trim(); if (!sku) continue; const cost = positivePrice(row.cost_price); const prev = map.get(sku) || 0; if (cost > 0 && cost >= prev) map.set(sku, cost); else if (!map.has(sku)) map.set(sku, cost); } } return map; } catch { return new Map(); } } export async function buildOrderExportRows( orders: OrderExportRow[], expandItems: boolean ): Promise { if (!expandItems || orders.length === 0) { return orders; } type OrderItemRow = { id?: string; order_code: string; sku_code?: string; item_name?: string; quantity?: number; unit?: string; price?: number; locked_price?: number; amount?: number; unit_cost?: number; processing_method?: string; category_name?: string; supplier_code?: string; }; const orderCodes = orders.map((o) => o.order_code).filter(Boolean); const { data: items, error } = await supabase .from('order_items') .select( 'id, order_code, sku_code, item_name, quantity, unit, price, locked_price, amount, unit_cost, processing_method, category_name, supplier_code' ) .in('order_code', orderCodes); if (error) throw error; const orderItems = (items || []) as OrderItemRow[]; const skuCodes = [...new Set(orderItems.map((i) => i.sku_code).filter(Boolean))] as string[]; let skuMap = new Map(); if (skuCodes.length) { const { data: skus } = await supabase.from('skus').select('sku_code, sku_name').in('sku_code', skuCodes); skuMap = new Map((skus || []).map((s: { sku_code: string; sku_name: string }) => [s.sku_code, s.sku_name])); } const supplierCodes = [ ...new Set(orderItems.map((i) => String(i.supplier_code || '').trim()).filter(Boolean)), ]; let supplierNameMap = new Map(); if (supplierCodes.length) { const { data: suppliers } = await supabase .from('suppliers') .select('supplier_code, company_name') .in('supplier_code', supplierCodes); supplierNameMap = new Map( (suppliers || []).map((s: { supplier_code: string; company_name: string }) => [ s.supplier_code, s.company_name, ]) ); } const { data: preps } = await supabase .from('supplier_preparations') .select('order_code, sku_code, supplier_code, purchase_price, is_stockout') .in('order_code', orderCodes); const { data: purchases } = await supabase .from('purchase_orders') .select('order_code, sku_code, source_id, actual_price, purchase_price, purchase_status') .in('order_code', orderCodes); // 与服务端筛选一致:按 order+sku 取 MAX(purchase_price) const prepByOrderSku = new Map(); for (const prep of preps || []) { if (prep.is_stockout) continue; const price = positivePrice(prep.purchase_price); if (price <= 0) continue; const keySku = `${prep.order_code}|${prep.sku_code}`; prepByOrderSku.set(keySku, Math.max(prepByOrderSku.get(keySku) || 0, price)); } const purchaseByItemId = new Map(); const purchaseByOrderSku = new Map(); for (const po of purchases || []) { if (Number(po.purchase_status) < 20) continue; const price = positivePrice(po.actual_price) || positivePrice(po.purchase_price); if (price <= 0) continue; if (po.source_id) purchaseByItemId.set(String(po.source_id), price); const key = `${po.order_code}|${po.sku_code}`; purchaseByOrderSku.set(key, Math.max(purchaseByOrderSku.get(key) || 0, price)); } const customerCodes = [ ...new Set(orders.map((o) => String(o.customer_code || '').trim()).filter(Boolean)), ]; const quoteCostByCustomer = new Map>(); await Promise.all( customerCodes.map(async (code) => { quoteCostByCustomer.set(code, await loadQuoteCostMapByCustomer(code)); }) ); const itemsByOrder = new Map(); orderItems.forEach((item) => { const list = itemsByOrder.get(item.order_code) || []; list.push(item); itemsByOrder.set(item.order_code, list); }); const resolveCostPrice = ( _order: OrderExportRow, item: { id?: string; sku_code?: string; unit_cost?: number; } ): number => { if (item.unit_cost != null && Number.isFinite(Number(item.unit_cost))) { return Math.max(0, Number(item.unit_cost) || 0); } const sku = String(item.sku_code || ''); const prepHit = positivePrice(prepByOrderSku.get(`${_order.order_code}|${sku}`)); if (prepHit > 0) return prepHit; const byId = item.id ? positivePrice(purchaseByItemId.get(String(item.id))) : 0; if (byId > 0) return byId; const byOrderSku = positivePrice(purchaseByOrderSku.get(`${_order.order_code}|${sku}`)); if (byOrderSku > 0) return byOrderSku; const customer = String(_order.customer_code || '').trim(); return positivePrice(quoteCostByCustomer.get(customer)?.get(sku)); }; const rows: OrderExportRow[] = []; for (const order of orders) { const orderItems = itemsByOrder.get(order.order_code) || []; if (orderItems.length === 0) { rows.push(order); continue; } let matched = 0; for (const item of orderItems) { const salePrice = positivePrice((item as { locked_price?: number }).locked_price) || positivePrice(item.price) || 0; const costPrice = resolveCostPrice(order, item); matched += 1; const qty = Number(item.quantity) || 0; const amount = item.amount != null && Number(item.amount) !== 0 ? Number(item.amount) : Math.round(qty * salePrice * 100) / 100; rows.push({ ...order, sku_code: item.sku_code, sku_name: item.item_name || skuMap.get(String(item.sku_code || '')) || item.sku_code, item_name: item.item_name, quantity: item.quantity, unit: item.unit, price: salePrice, cost_price: costPrice, amount, processing_method: item.processing_method, category_name: item.category_name, supplier_name: supplierNameMap.get(String(item.supplier_code || '')) || item.supplier_code || undefined, }); } if (matched === 0) { rows.push(order); } } return rows; } export async function buildQuoteExportRows( sheets: Array<{ quote_sheet_code: string; title?: string | null; version_no?: number; quote_cycle?: string | null; customer_names?: string | null; approval_status?: number; effective_at?: string | null; expires_at?: string | null; items?: Array<{ sku_code: string; sku_name?: string; unit?: string; price: number; cost_price?: number; sale_price?: number; }>; customers?: Array<{ customer_code: string; company_name: string }>; }>, expandItems: boolean ): Promise { const rows: QuoteExportRow[] = []; for (const sheet of sheets) { let detail = sheet; if (expandItems && !sheet.items?.length) { try { const { data } = await getQuoteSheetApi(sheet.quote_sheet_code); detail = { ...sheet, ...(data as typeof sheet) }; } catch { detail = sheet; } } const header: QuoteExportRow = { quote_sheet_code: sheet.quote_sheet_code, title: sheet.title || undefined, version_no: sheet.version_no, quote_cycle: sheet.quote_cycle || undefined, customer_names: sheet.customer_names || (detail.customers || []).map((c) => c.company_name).join('、') || undefined, approval_status: sheet.approval_status, effective_at: sheet.effective_at || undefined, expires_at: sheet.expires_at || undefined, }; if (!expandItems || !(detail.items || []).length) { rows.push(header); continue; } for (const item of detail.items || []) { rows.push({ ...header, sku_code: item.sku_code, sku_name: item.sku_name, unit: item.unit, price: item.price, cost_price: item.cost_price, sale_price: item.sale_price ?? item.price, }); } } return rows; } export async function buildStatementExportRows( statements: StatementExportRow[], statementType: 'customer' | 'supplier', expandItems: boolean ): Promise { if (!expandItems) { return statementType === 'customer' ? appendCustomerStatementSummary(statements) : statements; } const rows: StatementExportRow[] = []; for (const statement of statements) { try { const { data } = await getStatementLinesApi(statement.statement_no, statementType); const lines = (data || []) as Array<{ order_code?: string; sku_code?: string; sku_name?: string; quantity?: number; unit_price?: number; line_amount?: number; price_source?: string; category_name?: string; }>; if (!lines.length) { rows.push(statement); continue; } for (const line of lines) { rows.push({ ...statement, order_code: line.order_code, sku_code: line.sku_code, sku_name: line.sku_name, quantity: line.quantity, unit_price: line.unit_price, line_amount: line.line_amount, price_source: line.price_source, category_name: line.category_name, }); } } catch { rows.push(statement); } } return statementType === 'customer' ? appendCustomerStatementSummary(rows) : rows; } function appendCustomerStatementSummary(rows: StatementExportRow[]): StatementExportRow[] { if (!rows.length) return rows; const statementTotals = new Map(); for (const row of rows) { if (row.is_summary_row || !row.statement_no) continue; statementTotals.set(row.statement_no, Number(row.total_amount || 0)); } const grandTotal = [...statementTotals.values()].reduce((sum, amount) => sum + amount, 0); if (!statementTotals.size) { const headerTotal = rows.reduce((sum, row) => sum + Number(row.total_amount || 0), 0); if (headerTotal <= 0) return rows; return [ ...rows, { statement_no: '', party_code: '', party_name: '合计', cycle_code: '', total_amount: Math.round(headerTotal * 100) / 100, is_summary_row: true, }, ]; } return [ ...rows, { statement_no: '', party_code: '', party_name: '合计', cycle_code: '', total_amount: Math.round(grandTotal * 100) / 100, is_summary_row: true, }, ]; } export async function buildDeliveryExportRows( tasks: Array<{ task_code?: string; order_code: string; customer_code?: string; customer_name?: string; customer_phone?: string; address?: string; delivery_person?: string; delivery_person_phone?: string; status?: string; estimated_time?: string; delivery_date?: string | null; actual_time?: string; items?: Array<{ sku_name: string; quantity: number; unit: string }>; }>, expandItems: boolean ): Promise { const rows: DeliveryExportRow[] = []; if (!expandItems || tasks.length === 0) { for (const task of tasks) { rows.push({ task_code: task.task_code, order_code: task.order_code, customer_code: task.customer_code, customer_name: task.customer_name, customer_phone: task.customer_phone, address: task.address, delivery_person: task.delivery_person, delivery_person_phone: task.delivery_person_phone, status: task.status, estimated_time: formatCustomerDeliveryDeadlineDateTime(task.delivery_date, task.estimated_time) || task.estimated_time || '', actual_time: task.actual_time ? formatChinaDateTime(task.actual_time) : '', }); } return rows; } const orderCodes = tasks.map((t) => t.order_code).filter(Boolean); const { lines } = await fetchDeliveryPrintLinesApi(orderCodes); const linesByOrder = new Map(); for (const line of lines) { const list = linesByOrder.get(line.order_code) || []; list.push(line); linesByOrder.set(line.order_code, list); } for (const task of tasks) { const header: DeliveryExportRow = { task_code: task.task_code, order_code: task.order_code, customer_code: task.customer_code, customer_name: task.customer_name, customer_phone: task.customer_phone, address: task.address, delivery_person: task.delivery_person, delivery_person_phone: task.delivery_person_phone, status: task.status, estimated_time: formatCustomerDeliveryDeadlineDateTime(task.delivery_date, task.estimated_time) || task.estimated_time || '', actual_time: task.actual_time ? formatChinaDateTime(task.actual_time) : '', }; const orderLines = linesByOrder.get(task.order_code) || []; if (!orderLines.length) { rows.push(header); continue; } let seq = 0; for (const line of orderLines) { seq += 1; rows.push({ ...header, seq_no: seq, sku_code: line.sku_code, sku_name: line.sku_name, customer_alias: line.customer_alias || undefined, category_name: line.category_name || undefined, spec: line.spec || undefined, origin: line.origin || undefined, quantity: line.quantity, unit: line.unit, price: line.price, amount: line.amount, actual_amount: line.actual_amount ?? undefined, picked_qty: line.picked_qty, loaded_qty: line.loaded_qty, inspection_actual_qty: line.inspection_actual_qty, weigh_qty: line.weigh_qty, weigh_unit: line.weigh_unit || undefined, base_unit: line.base_unit || undefined, weigh_qty_base: line.weigh_qty_base, delivery_qty: line.delivery_qty, box_no: line.box_no || undefined, box_count: line.box_count, processing_method: line.processing_method || undefined, supplier_name: line.supplier_name || undefined, is_extra_dish: Boolean(line.is_extra_dish), }); } } return rows; }