import { supabase } from '../supabase/client'; import { fetchCategoryRows, getLevel1CategoryDisplay, type CategoryRow } from './categories'; import { downloadExcelWorkbook } from './excelImportExport'; import { parseCustomerCodes } from './customerCodes'; import { assertSingleInvoiceExportCustomer } from './salesInvoiceExportJobs'; export type SalesInvoiceStatus = 'pending' | 'invoiced'; export interface SalesInvoiceOrderRow { order_code: string; delivery_date: string | null; customer_code: string | null; customer_name: string; total_amount: number; sales_invoice_status: SalesInvoiceStatus; sales_invoice_no: string | null; sales_invoiced_at: string | null; } export interface SalesInvoiceDetailLine { deliveryDate: string; customerName: string; categoryName: string; productName: string; unitPrice: number; quantity: number; unit: string; amount: number; taxCode: string; taxRate: number; } export interface SalesInvoiceSummaryLine { productName: string; categoryName: string; unit: string; unitPrice: number; quantity: number; amount: number; taxCode: string; taxRate: number; } const DETAIL_HEADERS = [ '收货日期', '商户名', '一级分类', '商品名', '单价(基本单位)', '下单数(基本单位)', '基本单位', '下单金额(成交)', ] as const; const SUMMARY_HEADERS = [ '商品名', '一级分类', '基本单位', '单价(基本单位)', '求和项:下单数(基本单位)', '求和项:下单金额(成交)', '税收编码', '税率', ] as const; export function monthRangeFromInput(monthValue: string): { start: string; end: string; monthLabel: string } { const [yearText, monthText] = monthValue.split('-'); const year = Number(yearText); const month = Number(monthText); if (!year || !month) { throw new Error('请选择有效的月份'); } const start = `${yearText}-${monthText.padStart(2, '0')}-01`; const lastDay = new Date(year, month, 0).getDate(); const end = `${yearText}-${monthText.padStart(2, '0')}-${String(lastDay).padStart(2, '0')}`; return { start, end, monthLabel: `${month}月` }; } function roundMoney(value: number): number { return Math.round(value * 100) / 100; } function roundQty(value: number): number { return Math.round(value * 1000) / 1000; } function summaryKey(line: Pick) { return [line.productName, line.categoryName, line.unit, String(line.unitPrice)].join('|'); } function compareSummary(a: SalesInvoiceSummaryLine, b: SalesInvoiceSummaryLine) { const byCategory = a.categoryName.localeCompare(b.categoryName, 'zh-CN'); if (byCategory !== 0) return byCategory; const byName = a.productName.localeCompare(b.productName, 'zh-CN'); if (byName !== 0) return byName; if (a.unitPrice !== b.unitPrice) return a.unitPrice - b.unitPrice; return a.unit.localeCompare(b.unit, 'zh-CN'); } export function buildSummaryLines(details: SalesInvoiceDetailLine[]): SalesInvoiceSummaryLine[] { const map = new Map(); for (const row of details) { const key = summaryKey(row); const existing = map.get(key); if (existing) { existing.quantity = roundQty(existing.quantity + row.quantity); existing.amount = roundMoney(existing.amount + row.amount); if (!existing.taxCode && row.taxCode) existing.taxCode = row.taxCode; continue; } map.set(key, { productName: row.productName, categoryName: row.categoryName, unit: row.unit, unitPrice: row.unitPrice, quantity: roundQty(row.quantity), amount: roundMoney(row.amount), taxCode: row.taxCode, taxRate: row.taxRate, }); } return Array.from(map.values()).sort(compareSummary); } function resolveCategoryName( categoryCode: string | null | undefined, categoryName: string | null | undefined, categoryRows: CategoryRow[] ): string { if (categoryCode) { const { level1Name } = getLevel1CategoryDisplay(categoryCode || undefined, categoryRows); if (level1Name) return level1Name; } return String(categoryName || '').trim() || '未分类'; } function buildExportFilename(customerName: string, monthLabel: string, totalAmount: number) { const shortName = customerName.split('-').pop()?.trim() || customerName.trim(); const safeName = shortName.replace(/[\\/:*?"<>|]/g, '').slice(0, 24); return `${safeName}${monthLabel}送货商品明细${totalAmount.toFixed(2)}.xlsx`; } export async function fetchSalesInvoiceOrders(input: { /** 空字符串 / 省略 = 全部客户 */ customerCode?: string | null; customerCodes?: string[]; startDate: string; endDate: string; status?: SalesInvoiceStatus | 'all'; }): Promise { let query = supabase .from('orders') .select( 'order_code, delivery_date, customer_code, total_amount, sales_invoice_status, sales_invoice_no, sales_invoiced_at, customers(company_name)' ) .gte('delivery_date', input.startDate) .lte('delivery_date', input.endDate) .gte('order_status', 50) .order('delivery_date', { ascending: false }) .order('order_code', { ascending: false }); const codes = input.customerCodes?.length ? parseCustomerCodes(input.customerCodes.join(',')) : parseCustomerCodes(input.customerCode); if (codes.length === 1) { query = query.eq('customer_code', codes[0]); } else if (codes.length > 1) { query = query.in('customer_code', codes); } if (input.status && input.status !== 'all') { query = query.eq('sales_invoice_status', input.status); } const { data, error } = await query; if (error) throw error; return (data || []).map((row: any) => ({ order_code: row.order_code, delivery_date: row.delivery_date, customer_code: row.customer_code, customer_name: row.customers?.company_name || row.customer_code || '', total_amount: Number(row.total_amount) || 0, sales_invoice_status: (row.sales_invoice_status === 'invoiced' ? 'invoiced' : 'pending') as SalesInvoiceStatus, sales_invoice_no: row.sales_invoice_no || null, sales_invoiced_at: row.sales_invoiced_at || null, })); } export async function loadSalesInvoiceDetailLines( orderCodes: string[], branchCode?: string | null ): Promise { const codes = [...new Set(orderCodes.filter(Boolean))]; if (!codes.length) return []; const [categoryRows, ordersResult, itemsResult] = await Promise.all([ fetchCategoryRows({ branchCode }), supabase .from('orders') .select('order_code, delivery_date, customers(company_name)') .in('order_code', codes), supabase .from('order_items') .select('order_code, sku_code, item_name, quantity, unit, price, amount, category_code, category_name') .in('order_code', codes), ]); if (ordersResult.error) throw ordersResult.error; if (itemsResult.error) throw itemsResult.error; const orderMap = new Map(); for (const row of ordersResult.data || []) { orderMap.set(row.order_code, { deliveryDate: String(row.delivery_date || '').slice(0, 10), customerName: (row as any).customers?.company_name || '', }); } const skuCodes = [ ...new Set((itemsResult.data || []).map((row: any) => row.sku_code).filter(Boolean)), ] as string[]; const skuTaxMap = new Map(); if (skuCodes.length) { const { data: skus, error } = await supabase .from('skus') .select('sku_code, sku_name, tax_code, tax_rate') .in('sku_code', skuCodes); if (error) throw error; for (const sku of skus || []) { skuTaxMap.set(sku.sku_code, { tax_code: String(sku.tax_code || '').trim(), tax_rate: Number(sku.tax_rate) || 0, sku_name: sku.sku_name || '', }); } } const lines: SalesInvoiceDetailLine[] = []; for (const item of itemsResult.data || []) { const order = orderMap.get(item.order_code); if (!order) continue; const skuMeta = item.sku_code ? skuTaxMap.get(item.sku_code) : undefined; const quantity = Number(item.quantity) || 0; const unitPrice = Number(item.price) || 0; const amount = roundMoney(Number(item.amount) || quantity * unitPrice); lines.push({ deliveryDate: order.deliveryDate, customerName: order.customerName, categoryName: resolveCategoryName(item.category_code, item.category_name, categoryRows), productName: String(item.item_name || skuMeta?.sku_name || item.sku_code || '未命名商品').trim(), unitPrice: roundMoney(unitPrice), quantity: roundQty(quantity), unit: String(item.unit || '斤').trim() || '斤', amount, taxCode: skuMeta?.tax_code || '', taxRate: skuMeta?.tax_rate ?? 0, }); } return lines.sort((a, b) => { const byDate = b.deliveryDate.localeCompare(a.deliveryDate); if (byDate !== 0) return byDate; const byCategory = a.categoryName.localeCompare(b.categoryName, 'zh-CN'); if (byCategory !== 0) return byCategory; return a.productName.localeCompare(b.productName, 'zh-CN'); }); } export function buildSalesInvoiceWorkbookSheets(details: SalesInvoiceDetailLine[]) { const totalAmount = roundMoney(details.reduce((sum, row) => sum + row.amount, 0)); const summary = buildSummaryLines(details); const taxFree = summary.filter((row) => (Number(row.taxRate) || 0) === 0); const taxable = summary.filter((row) => (Number(row.taxRate) || 0) > 0); const detailRows = details.map((row) => [ row.deliveryDate, row.customerName, row.categoryName, row.productName, row.unitPrice, row.quantity, row.unit, row.amount, ]); detailRows.push(['', '', '', '', '', '', '', totalAmount]); const toSummaryRows = (rows: SalesInvoiceSummaryLine[]) => rows.map((row) => [ row.productName, row.categoryName, row.unit, row.unitPrice, row.quantity, row.amount, row.taxCode, row.taxRate, ]); return { totalAmount, sheets: [ { name: '商品明细', headers: [...DETAIL_HEADERS], rows: detailRows }, { name: '数量汇总', headers: [...SUMMARY_HEADERS], rows: toSummaryRows(summary), textHeaders: ['税收编码'], }, { name: '免税', headers: [...SUMMARY_HEADERS], rows: toSummaryRows(taxFree), textHeaders: ['税收编码'], }, { name: '有税', headers: [...SUMMARY_HEADERS], rows: toSummaryRows(taxable), textHeaders: ['税收编码'], }, ], }; } export async function exportSalesInvoiceWorkbook(input: { /** 空 = 全部客户 */ customerCode?: string | null; customerName?: string | null; monthValue?: string; startDate?: string; endDate?: string; onlyPending?: boolean; orderCodes?: string[]; }) { let start = String(input.startDate || '').slice(0, 10); let end = String(input.endDate || '').slice(0, 10); let monthLabel = start && end ? (start === end ? start : `${start}至${end}`) : ''; if (input.monthValue) { const range = monthRangeFromInput(input.monthValue); start = start || range.start; end = end || range.end; monthLabel = range.monthLabel; } if (!start || !end) throw new Error('请选择有效日期'); const customerCode = assertSingleInvoiceExportCustomer(input.customerCode); const customerName = String(input.customerName || '').trim() || (customerCode ? customerCode : '全部客户'); const selectedCodes = [...new Set((input.orderCodes || []).filter(Boolean))]; let orders = await fetchSalesInvoiceOrders({ customerCode: customerCode || null, startDate: start, endDate: end, status: input.onlyPending === false ? 'all' : 'pending', }); if (selectedCodes.length) { const allow = new Set(selectedCodes); orders = orders.filter((row) => allow.has(row.order_code)); } if (!orders.length) { throw new Error(input.onlyPending === false ? '所选区间没有可导出的订单' : '所选区间没有未开票订单'); } const details = await loadSalesInvoiceDetailLines(orders.map((row) => row.order_code)); if (!details.length) { throw new Error('订单没有可导出的商品明细'); } const missingTaxCount = buildSummaryLines(details).filter((row) => !row.taxCode).length; if (missingTaxCount > 0) { console.warn(`有 ${missingTaxCount} 个汇总行缺少税收编码,请在商品管理中维护 tax_code`); } const workbook = buildSalesInvoiceWorkbookSheets(details); const filename = buildExportFilename(customerName, monthLabel, workbook.totalAmount); await downloadExcelWorkbook(filename, workbook.sheets); return { filename, orderCodes: orders.map((row) => row.order_code), totalAmount: workbook.totalAmount, detailCount: details.length, summaryCount: buildSummaryLines(details).length, missingTaxCount, }; } export async function markOrdersInvoiced(orderCodes: string[], invoiceNo?: string) { const codes = [...new Set(orderCodes.filter(Boolean))]; if (!codes.length) return; const now = new Date().toISOString(); const { error } = await supabase .from('orders') .update({ sales_invoice_status: 'invoiced', sales_invoice_no: invoiceNo?.trim() || null, sales_invoiced_at: now, }) .in('order_code', codes); if (error) throw error; } export async function markOrdersInvoicePending(orderCodes: string[]) { const codes = [...new Set(orderCodes.filter(Boolean))]; if (!codes.length) return; const { error } = await supabase .from('orders') .update({ sales_invoice_status: 'pending', sales_invoice_no: null, sales_invoiced_at: null, }) .in('order_code', codes); if (error) throw error; }