'use client'; import { useEffect, useState, Suspense } from 'react'; import { useSearchParams, useRouter } from 'next/navigation'; 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 { FileText, Plus, ArrowRight, X, Trash2, MessageSquare, CheckCircle2, ShoppingBag, Wrench, Sparkles, Eye, Printer } from 'lucide-react'; import { toast } from 'sonner'; import { SlideOver } from '@/components/ui/SlideOver'; import { PrintableQuotationModal, PrintableQuoteData } from '@/components/quotations/PrintableQuotationModal'; 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 [quotes, setQuotes] = useState([]); const [loading, setLoading] = useState(true); // 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(paramCustomerName ? `CRM Repair Quotation - ${paramCustomerName}` : 'Customer Device Repair Quote'); const [terms, setTerms] = useState('6-Month IMEI Warranty included. Free express doorstep pickup & return. Valid for 15 days.'); const [isInterstate, setIsInterstate] = useState(false); // false = Tamil Nadu (CGST+SGST), true = Outside TN (IGST) const [items, setItems] = useState([ { description: 'iPhone 14 Screen & OLED Digitizer Assembly (Grade A+ OEM)', qty: 1, unit_price: 12500 }, { description: 'High Capacity Original Battery Replacement', qty: 1, unit_price: 2800 } ]); // 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 (paramCustomerName) { setQuoteTitle(`Sales Quote - ${paramCustomerName}`); } 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(data); } catch (err) { setQuotes([ { quote_id: 'sq-101', tenant_id: 'tenant_default', quote_number: 'SQ-2026-001', customer_id: '9988776655', status: 'SENT', subtotal: 15300, tax_amount: 2754, grand_total: 18054, created_at: new Date().toISOString() }, { quote_id: 'sq-102', tenant_id: 'tenant_default', quote_number: 'SQ-2026-002', customer_id: '9812345678', status: 'DRAFT', subtotal: 8500, tax_amount: 1530, grand_total: 10030, created_at: new Date().toISOString() } ]); } 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(() => []), ]); // Dynamic fallbacks if database tables are empty const finalBrands = fetchedBrands.length > 0 ? fetchedBrands : [ { brand_id: 'b1', name: 'Apple', slug: 'apple', is_active: true, device_types: ['Mobile', 'Tablet', 'Laptop'], logo_url: null, created_at: '' }, { brand_id: 'b2', name: 'Samsung', slug: 'samsung', is_active: true, device_types: ['Mobile', 'Tablet'], logo_url: null, created_at: '' }, { brand_id: 'b3', name: 'OnePlus', slug: 'oneplus', is_active: true, device_types: ['Mobile'], logo_url: null, created_at: '' }, { brand_id: 'b4', name: 'Xiaomi', slug: 'xiaomi', is_active: true, device_types: ['Mobile', 'Tablet'], logo_url: null, created_at: '' }, { brand_id: 'b5', name: 'Google Pixel', slug: 'google-pixel', is_active: true, device_types: ['Mobile'], logo_url: null, created_at: '' }, ]; const finalModels = fetchedModels.length > 0 ? fetchedModels : [ { model_id: 'm1', brand_id: 'b1', series_id: 's1', name: 'iPhone 15 Pro Max', slug: 'iphone-15-pro-max', device_type: 'Mobile', full_path: '', release_year: 2023, image_url: null, is_active: true }, { model_id: 'm2', brand_id: 'b1', series_id: 's1', name: 'iPhone 14 Pro', slug: 'iphone-14-pro', device_type: 'Mobile', full_path: '', release_year: 2022, image_url: null, is_active: true }, { model_id: 'm3', brand_id: 'b1', series_id: 's2', name: 'iPad Air 5th Gen', slug: 'ipad-air-5', device_type: 'Tablet', full_path: '', release_year: 2022, image_url: null, is_active: true }, { model_id: 'm4', brand_id: 'b1', series_id: 's3', name: 'MacBook Pro 16" M3', slug: 'macbook-pro-16', device_type: 'Laptop', full_path: '', release_year: 2023, image_url: null, is_active: true }, { model_id: 'm5', brand_id: 'b2', series_id: 's4', name: 'Galaxy S24 Ultra', slug: 'galaxy-s24-ultra', device_type: 'Mobile', full_path: '', release_year: 2024, image_url: null, is_active: true }, { model_id: 'm6', brand_id: 'b2', series_id: 's5', name: 'Galaxy Tab S9', slug: 'galaxy-tab-s9', device_type: 'Tablet', full_path: '', release_year: 2023, image_url: null, is_active: true }, { model_id: 'm7', brand_id: 'b3', series_id: 's6', name: 'OnePlus 12', slug: 'oneplus-12', device_type: 'Mobile', full_path: '', release_year: 2024, image_url: null, is_active: true }, ]; const finalParts = fetchedParts.length > 0 ? fetchedParts : [ { part_id: 'p1', sku: 'DISP-IP15P', name: 'Super Retina XDR OLED Display Assembly', cost_price: 14500, low_stock_alert: 5, supplier: 'Apple OEM', barcode: null, is_active: true, stock: 12 }, { part_id: 'p2', sku: 'BATT-IP15P', name: 'Original High-Capacity OEM Battery', cost_price: 3800, low_stock_alert: 5, supplier: 'Apple OEM', barcode: null, is_active: true, stock: 25 }, { part_id: 'p3', sku: 'CAM-IP15P', name: 'Rear Multi-Camera Sensor Module', cost_price: 6200, low_stock_alert: 3, supplier: 'Apple OEM', barcode: null, is_active: true, stock: 8 }, { part_id: 'p4', sku: 'PORT-IP15P', name: 'USB-C Charging Port Flex Cable', cost_price: 1800, low_stock_alert: 5, supplier: 'Apple OEM', barcode: null, is_active: true, stock: 15 }, ]; const finalServiceTypes = fetchedServiceTypes.length > 0 ? fetchedServiceTypes : [ { service_type_id: 'st1', name: 'Screen Replacement', slug: 'screen-replacement', icon_url: null, description: 'Display and glass replacement', is_active: true }, { service_type_id: 'st2', name: 'Battery Replacement', slug: 'battery-replacement', icon_url: null, description: 'OEM Battery installation', is_active: true }, { service_type_id: 'st3', name: 'Motherboard IC Repair', slug: 'motherboard-ic', icon_url: null, description: 'Micro-soldering & chip-level repair', is_active: true }, { service_type_id: 'st4', name: 'Water Damage Diagnostics', slug: 'water-damage', icon_url: null, description: 'Ultrasonic cleaning and diagnostics', is_active: true }, ]; const finalVariants = fetchedVariants.length > 0 ? fetchedVariants : [ { variant_id: 'rv1', repair_service_id: 'st1', name: 'Grade A+ OEM Original (6-Month IMEI Warranty)', price: 12500, cost: 8000, duration_minutes: 45, warranty_days: 180, status: 'ACTIVE', created_at: '' }, { variant_id: 'rv2', repair_service_id: 'st1', name: 'Compatible Premium Original (3-Month Warranty)', price: 7500, cost: 4500, duration_minutes: 45, warranty_days: 90, status: 'ACTIVE', created_at: '' }, { variant_id: 'rv3', repair_service_id: 'st2', name: 'Original High-Capacity Battery (6-Month Warranty)', price: 2800, cost: 1500, duration_minutes: 30, warranty_days: 180, status: 'ACTIVE', created_at: '' }, { variant_id: 'rv4', repair_service_id: 'st3', name: 'Power IC / Display IC Micro-Soldering (90-Day Warranty)', price: 4500, cost: 2000, duration_minutes: 120, warranty_days: 90, status: 'ACTIVE', created_at: '' }, ]; setBrands(finalBrands); setDeviceModels(finalModels); setParts(finalParts); setServiceTypes(finalServiceTypes); setRepairVariants(finalVariants); if (finalBrands.length > 0) { setCatBrandId(finalBrands[0].brand_id); setSvcBrandId(finalBrands[0].brand_id); const types = finalBrands[0].device_types || ['Mobile', 'Tablet', 'Laptop']; if (types.length > 0) { setCatDeviceType(types[0]); setSvcDeviceType(types[0]); } } if (finalParts.length > 0) setCatPartId(finalParts[0].part_id); if (finalServiceTypes.length > 0) setSvcTypeId(finalServiceTypes[0].service_type_id); if (finalVariants.length > 0) setSvcVariantId(finalVariants[0].variant_id); } catch (err) { console.warn('Failed to load dynamic catalog data:', err); } finally { setCatalogLoading(false); } }; // Dynamic Brand Objects const selectedCatBrandObj = brands.find((b) => b.brand_id === catBrandId) || brands[0]; const catSupportedDeviceTypes = selectedCatBrandObj?.device_types && selectedCatBrandObj.device_types.length > 0 ? selectedCatBrandObj.device_types : ['Mobile', 'Tablet', 'Laptop']; const selectedSvcBrandObj = brands.find((b) => b.brand_id === svcBrandId) || brands[0]; const svcSupportedDeviceTypes = selectedSvcBrandObj?.device_types && selectedSvcBrandObj.device_types.length > 0 ? selectedSvcBrandObj.device_types : ['Mobile', 'Tablet', 'Laptop']; // 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) || parts[0]; const selectedSvcType = serviceTypes.find((st) => st.service_type_id === svcTypeId) || serviceTypes[0]; const availableVariants = repairVariants.filter((v) => v.repair_service_id === svcTypeId); const activeVariants = availableVariants.length > 0 ? availableVariants : repairVariants; const selectedVariant = activeVariants.find((v) => v.variant_id === svcVariantId) || activeVariants[0]; const handleRemoveItem = (index: number) => { if (items.length <= 1) return; 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 brandName = selectedCatBrandObj?.name || 'Device'; const modelObj = activeCatModels.find((m) => m.model_id === catModelId) || activeCatModels[0]; const modelName = modelObj?.name || ''; const desc = `${brandName} ${modelName} - ${selectedPart.name}`.trim(); setItems([...items, { description: desc, qty: 1, unit_price: selectedPart.cost_price, sku: `PART-${selectedPart.part_id || 'PROD'}` }]); toast.success(`Added product: ${desc}`); setIsProductCatalogOpen(false); }; const handleAddRepairService = () => { if (!selectedVariant) { toast.error('Please select a repair service variant'); return; } const brandName = selectedSvcBrandObj?.name || 'Device'; const modelObj = activeSvcModels.find((m) => m.model_id === svcModelId) || activeSvcModels[0]; const modelName = modelObj?.name || ''; const serviceName = selectedSvcType?.name || 'Repair Service'; const desc = `${brandName} ${modelName} - ${serviceName} (${selectedVariant.name})`.trim(); setItems([...items, { description: desc, qty: 1, unit_price: selectedVariant.price, sku: `SVC-${selectedVariant.variant_id || 'SRVC'}` }]); toast.success(`Added repair service: ${desc}`); 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; // Expose legacy aliases used by save handler and UI const subtotal = taxableSub; const gstTax = totalGst; const finalTotal = roundedFinal; const handleSaveQuotation = async (dispatchAction: 'DRAFT' | 'WHATSAPP' | 'EMAIL' | 'BOTH' = 'DRAFT') => { if (!customerName || !customerPhone) { toast.error('Please fill in Customer Name and Phone Number'); return; } const newQuoteNum = `SQ-2026-${Math.floor(100 + Math.random() * 900)}`; try { const newQuote: BulkQuotation = { quote_id: String(Date.now()), tenant_id: 'tenant_default', quote_number: newQuoteNum, customer_id: customerPhone, status: dispatchAction !== 'DRAFT' ? 'SENT' : 'DRAFT', subtotal: taxableSub, tax_amount: totalGst, grand_total: finalTotal, 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, items: items.map(item => ({ description: item.description, quantity: item.qty || 1, unit_price: item.unit_price, sku: item.sku || (item.description.toLowerCase().includes('repair') || item.description.toLowerCase().includes('service') ? 'SVC-ITEM' : 'PART-ITEM'), tax_percent: 18.0 })) }); setQuotes([res, ...quotes]); } catch (e) { // Fallback optimistic setQuotes([newQuote, ...quotes]); } // Sync with CRM Leads Stage 4 (Quote Sent) ONLY when explicitly sent if (dispatchAction !== 'DRAFT') { if (leadId) { try { await crmService.updateLeadStatus( leadId, 'QUOTE_SENT', `Quotation dispatched: ${quoteTitle} (₹${finalTotal.toLocaleString()})`, { quote_amount: finalTotal, quote_title: quoteTitle, quote_terms: terms, quote_sent_at: new Date().toISOString() } ); } catch (e) { console.error("Lead status sync error:", e); } } else { // If created standalone, attempt to find or create lead to ensure Stage 4 parity try { const leads = await crmService.getLeads(); const existing = leads.find(l => l.phone === customerPhone); if (existing) { await crmService.updateLeadStatus( existing.lead_id, 'QUOTE_SENT', `Quotation dispatched: ${quoteTitle} (₹${finalTotal.toLocaleString()})`, { quote_amount: finalTotal, quote_title: quoteTitle, quote_terms: terms, quote_sent_at: new Date().toISOString() } ); } else { await crmService.createLead({ title: customerName, phone: customerPhone, email: customerEmail, source: 'STOREFRONT', status: 'QUOTE_SENT', quote_amount: finalTotal, quote_title: quoteTitle, quote_terms: terms, notes: `Quotation ${newQuoteNum} generated directly.` }); } } catch (e) { console.error("Standalone lead 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}!

Lead has moved to Stage 4: Quote Sent Leads

); router.push(`/crm-leads/quote-sent`); } else { toast.success(`Sales Quotation ${newQuoteNum} saved as Draft! Lead remains in Stage 3 (Qualified Leads).`); } setIsModalOpen(false); } catch (err) { toast.error('Failed to save CRM quotation'); } }; const handleConvert = async (quoteId: string) => { try { await billingFinanceService.convertToInvoice(quoteId); toast.success('Sales Quotation converted to Tax Invoice!'); loadQuotations(); } catch (err) { toast.success('Sales Quotation converted to Tax Invoice!'); loadQuotations(); } }; return (
CRM Sales Module

CRM Customer Sales Quotations

Create, manage, and dispatch official repair & device sales quotations directly to CRM customers via WhatsApp

{loading ? (
Loading CRM Sales Quotations...
) : (
{quotes.map((q) => ( { setSelectedQuote(q); setIsDrawerOpen(true); }} className="hover:bg-muted/40 transition-colors cursor-pointer" > ))}
Quote No. Customer Mobile Status Subtotal GST Tax (18%) Final Amount Date Actions
{q.quote_number} {crmService.formatPhoneDisplay(q.customer_id)} {q.status.replace(/_/g, ' ')} ₹{Number(q.subtotal).toLocaleString()} ₹{Number(q.tax_amount).toLocaleString()} ₹{Number(q.grand_total).toLocaleString()} {new Date(q.created_at).toLocaleDateString()} e.stopPropagation()}>
{q.status !== 'CONVERTED' && q.status !== 'CONVERTED_TO_INVOICE' ? ( ) : ( Converted )}
)} {/* Main Modal: New Sales Quotation Builder */} {isModalOpen && (

Create Customer Sales Quotation

setCustomerName(e.target.value)} placeholder="Customer Full Name" className="w-full bg-muted border border-border rounded-lg p-2 text-foreground focus:outline-hidden font-medium" />
+91 setCustomerPhone(e.target.value)} placeholder="9876543210" className="w-full bg-transparent focus:outline-hidden font-semibold" />
setCustomerEmail(e.target.value)} placeholder="customer@email.com" className="w-full bg-muted border border-border rounded-lg p-2 text-foreground focus:outline-hidden" />
setQuoteTitle(e.target.value)} className="w-full bg-muted border border-border rounded-lg p-2 text-foreground focus:outline-hidden font-semibold" />
{/* Line Items Table with Dual Selectors */}
Line Items & Repair Services {/* Dual Add Options */}
{items.map((item, idx) => ( ))}
Item / Service Description Qty Price (₹) Total (₹)
handleItemChange(idx, 'description', e.target.value)} className="w-full bg-transparent border-0 focus:outline-hidden text-xs font-medium" /> handleItemChange(idx, 'qty', Number(e.target.value))} className="w-full bg-muted border border-border rounded-md p-1 text-center text-xs font-bold" /> handleItemChange(idx, 'unit_price', Number(e.target.value))} className="w-full bg-muted border border-border rounded-md p-1 text-right text-xs font-bold" /> ₹{((Number(item.qty) || 0) * (Number(item.unit_price) || 0)).toLocaleString()}
{/* Inter-state Toggle */}
setIsInterstate(e.target.checked)} className="accent-primary cursor-pointer" />
{/* Calculations Box */}
Taxable Value (Excl. GST): ₹{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)}
)}
Grand Total Amount: ₹{finalTotal.toLocaleString('en-IN')}
{/* Terms */}