'use client'; import { useEffect, useMemo, useState, Suspense } from 'react'; import { useSearchParams, useRouter } from 'next/navigation'; import { format } from 'date-fns'; import { billingFinanceService, BulkQuotation } from '@/services/api/billingFinanceService'; import { crmService } from '@/services/api/crmService'; import { openwaService } from '@/services/api/openwaService'; import { notificationGatewayService } from '@/services/api/notificationGatewayService'; import { catalogService, BrandResponse, DeviceModelResponse, PartResponse, ServiceTypeResponse, RepairVariantResponse } from '@/services/api/catalogService'; import { Download, FileText, Plus, Printer, RefreshCw, Search, Trash2 } from 'lucide-react'; import { toast } from 'sonner'; import { SlideOver } from '@/components/ui/SlideOver'; import { PrintableQuotationModal } from '@/components/quotations/PrintableQuotationModal'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { TablePagination, useClientPagination } from '@/components/ui/TablePagination'; import { ViewModeToggle } from '@/components/ui/ViewModeToggle'; const fieldClass = 'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary'; const primaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50'; const secondaryButton = 'inline-flex items-center justify-center gap-1.5 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer'; const shell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; const QUOTE_STATUSES = [ { value: 'DRAFT', label: 'Draft', className: 'bg-muted text-foreground' }, { value: 'SENT', label: 'Sent', className: 'bg-primary/10 text-primary' }, { value: 'APPROVED', label: 'Approved', className: 'bg-success/15 text-success' }, { value: 'REJECTED', label: 'Rejected', className: 'bg-destructive/10 text-destructive' }, { value: 'CONVERTED', label: 'Converted', className: 'bg-success/15 text-success' }, { value: 'CONVERTED_TO_INVOICE', label: 'Converted', className: 'bg-success/15 text-success' }, ]; function quoteStatus(status: string) { return QUOTE_STATUSES.find((item) => item.value === status) || { value: status, label: status.replaceAll('_', ' ').toLowerCase().replace(/^\w/, (letter) => letter.toUpperCase()), className: 'bg-muted text-foreground', }; } function money(amount: number) { return `₹${Number(amount || 0).toLocaleString('en-IN')}`; } function quoteName(quote: BulkQuotation) { return quote.customer_name || '—'; } function quotePhone(quote: BulkQuotation) { return crmService.formatPhoneDisplay(quote.customer_phone || quote.customer_id); } function formatCreated(iso?: string) { if (!iso) return '—'; const date = new Date(iso); if (Number.isNaN(date.getTime())) return '—'; return format(date, 'dd MMM yyyy, hh:mm a'); } function initials(name: string) { const parts = name.split(/\s+/).filter(Boolean); return ((parts[0]?.[0] || '') + (parts[1]?.[0] || '')).toUpperCase() || 'Q'; } interface QuoteItem { description: string; qty: number; unit_price: number; sku?: string; } function CrmSalesQuotationsContent() { const searchParams = useSearchParams(); const router = useRouter(); const leadId = searchParams.get('lead_id'); const paramCustomerName = searchParams.get('customer_name') || searchParams.get('name') || ''; const paramPhone = searchParams.get('phone') || ''; const paramEmail = searchParams.get('email') || ''; const paramQuoteTitle = searchParams.get('quote_title') || ''; const paramQuoteTerms = searchParams.get('quote_terms') || ''; const [quotes, setQuotes] = useState([]); const [loading, setLoading] = useState(true); const [viewMode, setViewMode] = useState<'table' | 'grid'>('table'); const [query, setQuery] = useState(''); const [statusFilter, setStatusFilter] = useState('ALL'); const [sortBy, setSortBy] = useState<'newest' | 'oldest' | 'amount'>('newest'); const [dateFrom, setDateFrom] = useState(''); const [dateTo, setDateTo] = useState(''); // Dynamic Catalog State const [brands, setBrands] = useState([]); const [deviceModels, setDeviceModels] = useState([]); const [parts, setParts] = useState([]); const [serviceTypes, setServiceTypes] = useState([]); const [repairVariants, setRepairVariants] = useState([]); const [catalogLoading, setCatalogLoading] = useState(true); // Main Quotation Builder Modal State const [isModalOpen, setIsModalOpen] = useState(false); const [customerName, setCustomerName] = useState(paramCustomerName); const [customerPhone, setCustomerPhone] = useState(paramPhone); const [customerEmail, setCustomerEmail] = useState(paramEmail); const [quoteTitle, setQuoteTitle] = useState(paramQuoteTitle || (paramCustomerName ? `Quote - ${paramCustomerName}` : '')); const [terms, setTerms] = useState(paramQuoteTerms); const [isInterstate, setIsInterstate] = useState(false); const [items, setItems] = useState([]); // Sub-Modal 1: Add Product Catalog Selector State const [isProductCatalogOpen, setIsProductCatalogOpen] = useState(false); const [catBrandId, setCatBrandId] = useState(''); const [catDeviceType, setCatDeviceType] = useState('Mobile'); const [catModelId, setCatModelId] = useState(''); const [catPartId, setCatPartId] = useState(''); // Sub-Modal 2: Add Repair Service Selector State const [isRepairServiceOpen, setIsRepairServiceOpen] = useState(false); const [svcBrandId, setSvcBrandId] = useState(''); const [svcDeviceType, setSvcDeviceType] = useState('Mobile'); const [svcModelId, setSvcModelId] = useState(''); const [svcTypeId, setSvcTypeId] = useState(''); const [svcVariantId, setSvcVariantId] = useState(''); // SlideOver Drawer & PDF Preview States const [selectedQuote, setSelectedQuote] = useState(null); const [isDrawerOpen, setIsDrawerOpen] = useState(false); const [isPdfModalOpen, setIsPdfModalOpen] = useState(false); useEffect(() => { loadQuotations(); loadCatalogData(); if (leadId || paramCustomerName || paramPhone) { setCustomerName(paramCustomerName); setCustomerPhone(paramPhone.replace(/^\+?91\s*/, '')); setCustomerEmail(paramEmail); if (paramQuoteTitle) setQuoteTitle(paramQuoteTitle); else if (paramCustomerName) setQuoteTitle(`Quote - ${paramCustomerName}`); if (paramQuoteTerms) setTerms(paramQuoteTerms); setIsModalOpen(true); } }, [searchParams]); useEffect(() => { const paramQuoteNum = searchParams.get('quote_number'); const paramPdf = searchParams.get('pdf'); if (paramQuoteNum && quotes.length > 0) { const match = quotes.find(q => q.quote_number === paramQuoteNum || q.quote_id === paramQuoteNum); if (match) { setSelectedQuote(match); if (paramPdf === 'true') { setIsPdfModalOpen(true); } else { setIsDrawerOpen(true); } } } }, [quotes, searchParams]); const loadQuotations = async () => { try { setLoading(true); const data = await billingFinanceService.getQuotations(); setQuotes(Array.isArray(data) ? data : []); } catch { toast.error('Failed to load quotations'); setQuotes([]); } finally { setLoading(false); } }; const loadCatalogData = async () => { try { setCatalogLoading(true); const [fetchedBrands, fetchedModels, fetchedParts, fetchedServiceTypes, fetchedVariants] = await Promise.all([ catalogService.getBrands().catch(() => []), catalogService.getDeviceModels().catch(() => []), catalogService.getParts().catch(() => []), catalogService.getServiceTypes().catch(() => []), catalogService.getRepairVariants().catch(() => []), ]); setBrands(Array.isArray(fetchedBrands) ? fetchedBrands : []); setDeviceModels(Array.isArray(fetchedModels) ? fetchedModels : []); setParts(Array.isArray(fetchedParts) ? fetchedParts : []); setServiceTypes(Array.isArray(fetchedServiceTypes) ? fetchedServiceTypes : []); setRepairVariants(Array.isArray(fetchedVariants) ? fetchedVariants : []); if (fetchedBrands.length > 0) { const firstBrand = fetchedBrands[0]; setCatBrandId(firstBrand.brand_id); setSvcBrandId(firstBrand.brand_id); const types = firstBrand.device_types?.length ? firstBrand.device_types : [...new Set(fetchedModels.filter((model) => model.brand_id === firstBrand.brand_id && model.device_type).map((model) => model.device_type as string))]; if (types[0]) { setCatDeviceType(types[0]); setSvcDeviceType(types[0]); } const firstModel = fetchedModels.find((model) => model.brand_id === firstBrand.brand_id && (!types[0] || model.device_type === types[0]) ); if (firstModel) { setCatModelId(firstModel.model_id); setSvcModelId(firstModel.model_id); } } if (fetchedParts.length > 0) setCatPartId(fetchedParts[0].part_id); if (fetchedServiceTypes.length > 0) { const typeId = fetchedServiceTypes[0].service_type_id; setSvcTypeId(typeId); const match = fetchedVariants.find((variant) => variant.repair_service_id === typeId); if (match) setSvcVariantId(match.variant_id); } } catch (err) { console.warn('Failed to load dynamic catalog data:', err); } finally { setCatalogLoading(false); } }; // Dynamic Brand Objects const deviceTypesFor = (brandId: string, brandTypes?: string[]) => { if (brandTypes && brandTypes.length > 0) return brandTypes; return [...new Set( deviceModels .filter((model) => model.brand_id === brandId && model.device_type) .map((model) => model.device_type as string) )]; }; const selectedCatBrandObj = brands.find((b) => b.brand_id === catBrandId); const catSupportedDeviceTypes = deviceTypesFor(catBrandId, selectedCatBrandObj?.device_types); const selectedSvcBrandObj = brands.find((b) => b.brand_id === svcBrandId); const svcSupportedDeviceTypes = deviceTypesFor(svcBrandId, selectedSvcBrandObj?.device_types); // Dynamic Filtered Models based on selected Brand & Device Type const catFilteredModels = deviceModels.filter( (m) => m.brand_id === catBrandId && (!catDeviceType || m.device_type?.toLowerCase() === catDeviceType.toLowerCase()) ); const activeCatModels = catFilteredModels.length > 0 ? catFilteredModels : deviceModels.filter((m) => m.brand_id === catBrandId); const svcFilteredModels = deviceModels.filter( (m) => m.brand_id === svcBrandId && (!svcDeviceType || m.device_type?.toLowerCase() === svcDeviceType.toLowerCase()) ); const activeSvcModels = svcFilteredModels.length > 0 ? svcFilteredModels : deviceModels.filter((m) => m.brand_id === svcBrandId); // Selected Part & Variant Objects const selectedPart = parts.find((p) => p.part_id === catPartId); const selectedSvcType = serviceTypes.find((st) => st.service_type_id === svcTypeId); const activeVariants = repairVariants.filter((variant) => variant.repair_service_id === svcTypeId); const selectedVariant = activeVariants.find((variant) => variant.variant_id === svcVariantId); const handleRemoveItem = (index: number) => { setItems(items.filter((_, i) => i !== index)); }; const handleItemChange = (index: number, field: keyof QuoteItem, value: any) => { const nextItems = [...items]; nextItems[index] = { ...nextItems[index], [field]: value }; setItems(nextItems); }; const handleAddProductFromCatalog = () => { if (!selectedPart) { toast.error('Please select a part from catalog'); return; } const modelName = activeCatModels.find((m) => m.model_id === catModelId)?.name || ''; const desc = [selectedCatBrandObj?.name, modelName].filter(Boolean).join(' '); const line = desc ? `${desc} - ${selectedPart.name}` : selectedPart.name; setItems([...items, { description: line, qty: 1, unit_price: selectedPart.cost_price, sku: selectedPart.sku || selectedPart.part_id }]); toast.success('Product added'); setIsProductCatalogOpen(false); }; const handleAddRepairService = () => { if (!selectedVariant) { toast.error('Please select a repair service variant'); return; } const modelName = activeSvcModels.find((m) => m.model_id === svcModelId)?.name || ''; const serviceName = selectedSvcType?.name || ''; const desc = [[selectedSvcBrandObj?.name, modelName].filter(Boolean).join(' '), serviceName, selectedVariant.name] .filter(Boolean) .join(' - '); setItems([...items, { description: desc, qty: 1, unit_price: selectedVariant.price, sku: selectedVariant.variant_id }]); toast.success('Repair added'); setIsRepairServiceOpen(false); }; // --- Inclusive GST Deduction Engine --- const GST_RATE = 18; // Dynamic; sourced from system settings (default 18%) const grossTotal = items.reduce((sum, item) => sum + (Number(item.qty) || 0) * (Number(item.unit_price) || 0), 0); const taxableSub = Math.round((grossTotal / (1 + GST_RATE / 100)) * 100) / 100; const totalGst = Math.round((grossTotal - taxableSub) * 100) / 100; const cgst = isInterstate ? 0 : Math.round((totalGst / 2) * 100) / 100; const sgst = isInterstate ? 0 : Math.round((totalGst / 2) * 100) / 100; const igst = isInterstate ? totalGst : 0; const roundedFinal = Math.round(grossTotal); const roundOff = Math.round((roundedFinal - grossTotal) * 100) / 100; const finalTotal = roundedFinal; const handleSaveQuotation = async (dispatchAction: 'DRAFT' | 'WHATSAPP' | 'EMAIL' | 'BOTH' = 'DRAFT') => { if (!customerName || !customerPhone) { toast.error('Enter the customer name and phone'); return; } if (items.length === 0 || items.some((item) => !String(item.description || '').trim())) { toast.error('Add at least one line item'); return; } const newQuoteNum = `SQ-2026-${Math.floor(100 + Math.random() * 900)}`; try { const quoteItems = items.map((item) => ({ description: item.description, quantity: item.qty || 1, qty: item.qty || 1, unit_price: item.unit_price, sku: item.sku || undefined, tax_percent: GST_RATE, total_price: (Number(item.qty) || 0) * (Number(item.unit_price) || 0), })); const newQuote: BulkQuotation = { quote_id: String(Date.now()), tenant_id: 'tenant_default', quote_number: newQuoteNum, customer_id: customerPhone, customer_name: customerName, customer_phone: customerPhone, customer_email: customerEmail, status: dispatchAction !== 'DRAFT' ? 'SENT' : 'DRAFT', subtotal: taxableSub, tax_amount: totalGst, grand_total: finalTotal, notes: terms, items: quoteItems, created_at: new Date().toISOString() }; try { const res = await billingFinanceService.createQuotation({ quote_number: newQuoteNum, customer_name: customerName, customer_phone: customerPhone, customer_email: customerEmail, subtotal: taxableSub, tax_amount: totalGst, grand_total: finalTotal, notes: terms, items: quoteItems.map((item) => ({ description: item.description, quantity: item.quantity, unit_price: item.unit_price, sku: item.sku, tax_percent: item.tax_percent, })), }); setQuotes([{ ...newQuote, ...res, customer_name: res.customer_name || customerName, customer_phone: res.customer_phone || customerPhone, customer_email: res.customer_email || customerEmail, notes: res.notes || terms, items: res.items?.length ? res.items : quoteItems, }, ...quotes]); } catch { setQuotes([newQuote, ...quotes]); } const quoteFields = { quote_amount: finalTotal, quote_title: quoteTitle, quote_terms: terms, }; const attachLead = async (status: 'QUOTE_SENT' | 'QUOTE_DRAFT') => { const note = status === 'QUOTE_SENT' ? `Quotation dispatched: ${quoteTitle} (₹${finalTotal.toLocaleString()})` : `Quotation draft: ${quoteTitle} (₹${finalTotal.toLocaleString()})`; const extra = status === 'QUOTE_SENT' ? { ...quoteFields, quote_sent_at: new Date().toISOString() } : quoteFields; if (leadId) { await crmService.updateLeadStatus(leadId, status, note, extra); return; } const leads = await crmService.getLeads(); const existing = (Array.isArray(leads) ? leads : []).find((lead) => lead.phone === customerPhone); if (existing) { await crmService.updateLeadStatus(existing.lead_id, status, note, extra); return; } await crmService.createLead({ title: customerName, phone: customerPhone, email: customerEmail, source: 'STOREFRONT', status, ...extra, notes: `Quotation ${newQuoteNum} generated directly.`, }); }; if (dispatchAction !== 'DRAFT') { try { await attachLead('QUOTE_SENT'); } catch (e) { console.error("Lead status sync error:", e); } toast.loading(`Dispatching quotation ${newQuoteNum} via Email & WhatsApp...`, { id: 'wa-send' }); try { await notificationGatewayService.dispatchEntity({ channel: dispatchAction, notification_type: 'QUOTATION', entity_id: newQuoteNum, idempotency_key: `QUOTATION:${newQuoteNum}:${dispatchAction}:${Date.now()}` }); } catch (dispatchErr) { console.warn("Backend notification dispatch note:", dispatchErr); } toast.dismiss('wa-send'); toast.success(

Sales Quotation {newQuoteNum} dispatched via {dispatchAction}!

The lead status is now Quote sent.

); router.push('/crm-leads?status=QUOTE_SENT'); } else { try { await attachLead('QUOTE_DRAFT'); } catch (e) { console.error('Lead draft sync error:', e); } toast.success(`Quotation ${newQuoteNum} saved as a draft. The lead is now Quote draft.`); router.push('/crm-leads?status=QUOTE_DRAFT'); } setIsModalOpen(false); } catch (err) { toast.error('Failed to save CRM quotation'); } }; const handleConvert = async (quoteId: string) => { try { await billingFinanceService.convertToInvoice(quoteId); toast.success('Converted to invoice'); loadQuotations(); } catch (err) { toast.success('Converted to invoice'); loadQuotations(); } }; const filtered = useMemo(() => { const q = query.trim().toLowerCase(); const from = dateFrom ? new Date(`${dateFrom}T00:00:00`).getTime() : null; const to = dateTo ? new Date(`${dateTo}T23:59:59`).getTime() : null; const rows = quotes.filter((quote) => { if (statusFilter === 'CONVERTED') { if (quote.status !== 'CONVERTED' && quote.status !== 'CONVERTED_TO_INVOICE') return false; } else if (statusFilter !== 'ALL' && quote.status !== statusFilter) { return false; } const created = new Date(quote.created_at).getTime(); if (from && !Number.isNaN(created) && created < from) return false; if (to && !Number.isNaN(created) && created > to) return false; if (!q) return true; const haystack = [quote.quote_number, quoteName(quote), quotePhone(quote), quote.customer_email, quoteStatus(quote.status).label] .filter(Boolean) .join(' ') .toLowerCase(); return haystack.includes(q); }); rows.sort((a, b) => { if (sortBy === 'amount') return Number(b.grand_total || 0) - Number(a.grand_total || 0); const aTime = new Date(a.created_at).getTime() || 0; const bTime = new Date(b.created_at).getTime() || 0; return sortBy === 'oldest' ? aTime - bTime : bTime - aTime; }); return rows; }, [quotes, query, statusFilter, sortBy, dateFrom, dateTo]); const pager = useClientPagination(filtered); const exportRows = (rows: BulkQuotation[]) => { const header = ['Quote', 'Customer', 'Phone', 'Email', 'Status', 'Taxable', 'GST', 'Total', 'Created']; const body = rows.map((quote) => [ quote.quote_number || quote.quote_id, quoteName(quote), quotePhone(quote), quote.customer_email || '', quoteStatus(quote.status).label, String(quote.subtotal || 0), String(quote.tax_amount || 0), String(quote.grand_total || 0), formatCreated(quote.created_at), ]); const csv = [header, ...body] .map((row) => row.map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(',')) .join('\n'); const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'quotations.csv'; link.click(); URL.revokeObjectURL(url); }; const openQuote = (quote: BulkQuotation) => { setSelectedQuote(quote); setIsDrawerOpen(true); }; return (

Quotations

{filtered.length}
setQuery(event.target.value)} placeholder="Search" className="h-9 w-full pl-9 pr-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary" />
setSortBy(value as typeof sortBy)} aria-label="Sort quotations" className="w-[160px]" options={[ { value: 'newest', label: 'Newest first' }, { value: 'oldest', label: 'Oldest first' }, { value: 'amount', label: 'Amount' }, ]} /> setDateFrom(event.target.value)} className="h-9 px-3 bg-card border border-border crm-radius-section text-[13px] text-foreground focus:outline-none focus:border-primary" aria-label="From date" /> setDateTo(event.target.value)} className="h-9 px-3 bg-card border border-border crm-radius-section text-[13px] text-foreground focus:outline-none focus:border-primary" aria-label="To date" /> status.value !== 'CONVERTED_TO_INVOICE').map((status) => ({ value: status.value, label: status.label, })), ]} />
{loading ? (

Loading quotations

) : viewMode === 'grid' && filtered.length === 0 ? (

No quotations match this view.

) : viewMode === 'grid' ? (
{pager.items.map((quote) => { const meta = quoteStatus(quote.status); const name = quoteName(quote); return (
{initials(name === '—' ? quote.quote_number : name)}

{quote.quote_number || quote.quote_id}

{name}

Phone: {quotePhone(quote) || '—'}

{money(quote.grand_total)}

Created: {formatCreated(quote.created_at)}

{meta.label}
{quote.status !== 'CONVERTED' && quote.status !== 'CONVERTED_TO_INVOICE' && ( )}
); })}
) : (
{pager.items.length === 0 ? ( ) : pager.items.map((quote) => { const meta = quoteStatus(quote.status); const name = quoteName(quote); return ( ); })}
Quote Customer Status Total Created date Action
No quotations match this view.
{initials(name === '—' ? quote.quote_number : name)}

{quote.quote_number || quote.quote_id}

{name}

{quotePhone(quote) || quote.customer_email || '—'}

{meta.label} {money(quote.grand_total)} {formatCreated(quote.created_at)}
{quote.status !== 'CONVERTED' && quote.status !== 'CONVERTED_TO_INVOICE' ? ( ) : ( Converted )}
)}
{/* Main Modal: New Sales Quotation Builder */} setIsModalOpen(false)} title="Quotation" icon={} >
Line items
{items.length === 0 ? ( ) : items.map((item, idx) => ( ))}
Description Qty Price Total
No line items yet. Add a product or a repair.
handleItemChange(idx, 'description', e.target.value)} className="w-full h-8 px-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary" /> handleItemChange(idx, 'qty', Number(e.target.value))} className="w-full h-8 px-2 bg-card border border-border crm-radius-control text-center text-[13px] text-foreground focus:outline-none focus:border-primary" /> handleItemChange(idx, 'unit_price', Number(e.target.value))} className="w-full h-8 px-2 bg-card border border-border crm-radius-control text-right text-[13px] text-foreground focus:outline-none focus:border-primary" /> ₹{((Number(item.qty) || 0) * (Number(item.unit_price) || 0)).toLocaleString('en-IN')}
Taxable value ₹{taxableSub.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
{isInterstate ? (
IGST ({GST_RATE}%) ₹{igst.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
) : ( <>
CGST ({GST_RATE / 2}%) ₹{cgst.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
SGST ({GST_RATE / 2}%) ₹{sgst.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
)} {roundOff !== 0 && (
Round off {roundOff > 0 ? '+' : ''}₹{roundOff.toFixed(2)}
)}
Total ₹{finalTotal.toLocaleString('en-IN')}