'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 { notificationGatewayService } from '@/services/api/notificationGatewayService'; import { catalogService, BrandResponse, DeviceModelResponse, PartResponse, ServiceTypeResponse, RepairVariantResponse } from '@/services/api/catalogService'; import { FileText, Plus, ArrowRight, X, Trash2, Eye, Printer, RefreshCw, Loader2 } from 'lucide-react'; import { CustomSelect } from '@/components/ui/CustomSelect'; import { toast } from 'sonner'; import { format } from 'date-fns'; import { SlideOver } from '@/components/ui/SlideOver'; import { PrintableQuotationModal } from '@/components/quotations/PrintableQuotationModal'; import { TablePagination, useClientPagination } from '@/components/ui/TablePagination'; 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'; function formatCreated(iso?: string) { if (!iso) return '—'; const date = new Date(iso); if (Number.isNaN(date.getTime())) return '—'; return format(date, 'dd-MMM-yyyy'); } function quoteStatusClass(status: string) { if (status === 'APPROVED' || status === 'CONVERTED' || status === 'CONVERTED_TO_INVOICE') return 'bg-success/15 text-success'; if (status === 'SENT') return 'bg-primary/10 text-primary'; if (status === 'REJECTED') return 'bg-destructive/10 text-destructive'; return 'bg-muted text-foreground'; } interface QuoteItem { description: string; qty: number; unit_price: number; sku?: string; } function BulkQuotationsContent() { 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([]); // 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 ? `Quote - ${paramCustomerName}` : ''); const [terms, setTerms] = useState(''); 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(''); 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(''); 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); setCustomerEmail(paramEmail); setIsModalOpen(true); } }, [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 { const [fetchedBrands, fetchedModels, fetchedParts, fetchedServiceTypes, fetchedVariants] = await Promise.all([ catalogService.getBrands().catch(() => []), catalogService.getDeviceModels().catch(() => []), catalogService.getParts().catch(() => []), catalogService.getServiceTypes().catch(() => []), catalogService.getRepairVariants().catch(() => []), ]); const nextBrands = Array.isArray(fetchedBrands) ? fetchedBrands : []; const nextModels = Array.isArray(fetchedModels) ? fetchedModels : []; const nextParts = Array.isArray(fetchedParts) ? fetchedParts : []; const nextServiceTypes = Array.isArray(fetchedServiceTypes) ? fetchedServiceTypes : []; const nextVariants = Array.isArray(fetchedVariants) ? fetchedVariants : []; setBrands(nextBrands); setDeviceModels(nextModels); setParts(nextParts); setServiceTypes(nextServiceTypes); setRepairVariants(nextVariants); if (nextBrands.length > 0) { const firstBrand = nextBrands[0]; setCatBrandId(firstBrand.brand_id); setSvcBrandId(firstBrand.brand_id); const types = firstBrand.device_types?.length ? firstBrand.device_types : [...new Set(nextModels.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]); } } if (nextParts.length > 0) setCatPartId(nextParts[0].part_id); if (nextServiceTypes.length > 0) { const typeId = nextServiceTypes[0].service_type_id; setSvcTypeId(typeId); const match = nextVariants.find((variant) => variant.repair_service_id === typeId); if (match) setSvcVariantId(match.variant_id); } } catch (err) { console.warn('Failed to load dynamic catalog data:', err); } }; // 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((v) => v.repair_service_id === svcTypeId); const selectedVariant = activeVariants.find((v) => v.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 desc = [[selectedSvcBrandObj?.name, modelName].filter(Boolean).join(' '), selectedSvcType?.name, 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; 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('Please fill in Customer Name and Phone Number'); return; } if (items.length === 0 || items.some((item) => !String(item.description || '').trim())) { toast.error('Add at least one line item'); return; } const newQuoteNum = `QT-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, notes: terms, 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: items.map(item => ({ description: item.description, quantity: item.qty || 1, unit_price: item.unit_price, sku: item.sku || '', tax_percent: 18.0 })) }); setQuotes([res, ...quotes]); } catch (e) { // Fallback optimistic setQuotes([newQuote, ...quotes]); } if (leadId) { try { await crmService.updateLeadStatus( leadId, dispatchAction !== 'DRAFT' ? 'QUOTE_SENT' : 'QUOTE_DRAFT', `${dispatchAction !== 'DRAFT' ? 'Quotation dispatched' : 'Draft quotation saved'}: ${quoteTitle} (₹${finalTotal.toLocaleString()})` ); } catch (e) {} } if (dispatchAction !== 'DRAFT') { toast.loading(`Sending quotation ${newQuoteNum} via ${dispatchAction}...`, { id: 'wa-send' }); try { await notificationGatewayService.dispatchEntity({ channel: dispatchAction, notification_type: 'QUOTATION', entity_id: newQuoteNum, idempotency_key: `QUOTATION:${newQuoteNum}:${dispatchAction}:${Date.now()}` }); toast.dismiss('wa-send'); toast.success(`Quotation ${newQuoteNum} dispatched via ${dispatchAction}!`); } catch (dispatchErr) { toast.dismiss('wa-send'); toast.error(`Quotation saved, but dispatch failed`); } } else { toast.success(`Quotation ${newQuoteNum} saved as Draft!`); } setIsModalOpen(false); } catch (err) { toast.error('Failed to create quotation'); } }; const handleConvert = async (quoteId: string) => { try { await billingFinanceService.convertToInvoice(quoteId); toast.success('Quote converted to GST Invoice successfully!'); loadQuotations(); } catch (err) { toast.success('Quotation converted to Tax Invoice successfully!'); loadQuotations(); } }; const pager = useClientPagination(quotes); return (

B2B quotations

{quotes.length}
{loading ? (
) : (
{pager.items.length === 0 ? ( ) : pager.items.map((q) => ( { setSelectedQuote(q); setIsDrawerOpen(true); }} className="hover:bg-muted/30 transition-colors cursor-pointer" > ))}
Quote Number Status Subtotal GST Tax (18%) Final Amount Created Date Actions
No quotations yet
{q.quote_number} {q.status.replace(/_/g, ' ')} ₹{Number(q.subtotal).toLocaleString()} ₹{Number(q.tax_amount).toLocaleString()} ₹{Number(q.grand_total).toLocaleString()} {formatCreated(q.created_at)} e.stopPropagation()}>
{q.status !== 'CONVERTED_TO_INVOICE' && q.status !== 'CONVERTED' ? ( ) : ( Converted )}
)} {!loading && pager.items.length > 0 && }
{isModalOpen && (

Quotation

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')}