'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 { catalogService, BrandResponse, DeviceModelResponse, PartResponse, ServiceTypeResponse, RepairVariantResponse } from '@/services/api/catalogService'; import { FileText, Plus, ArrowRight, X, Trash2, MessageSquare, CheckCircle2, ShoppingBag, Wrench } from 'lucide-react'; import { toast } from 'sonner'; interface QuoteItem { description: string; qty: number; unit_price: number; } 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 ? `B2B Repair Quotation - ${paramCustomerName}` : 'Corporate Fleet Repair'); const [terms, setTerms] = useState('6-Month IMEI Warranty included. Free express doorstep pickup & return. Valid for 15 days.'); const [items, setItems] = useState([ { description: 'iPad Air 5th Gen Screen & Digitizer Replacement', qty: 5, unit_price: 8500 }, { description: 'High Capacity Original OEM Battery Replacement', qty: 5, unit_price: 2500 } ]); // 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(''); 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(data); } catch (err) { setQuotes([ { quotation_id: '1', tenant_id: 'tenant_default', quote_number: 'QT-2026-001', customer_id: 'c1', status: 'APPROVED', subtotal: 150000, tax_amount: 27000, final_amount: 177000, created_at: new Date().toISOString() }, { quotation_id: '2', tenant_id: 'tenant_default', quote_number: 'QT-2026-002', customer_id: 'c2', status: 'DRAFT', subtotal: 45000, tax_amount: 8100, final_amount: 53100, created_at: new Date().toISOString() } ]); } 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 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); } }; // 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 }]); 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 }]); toast.success(`Added repair service: ${desc}`); setIsRepairServiceOpen(false); }; const subtotal = items.reduce((sum, item) => sum + (Number(item.qty) || 0) * (Number(item.unit_price) || 0), 0); const gstTax = Math.round(subtotal * 0.18); const finalTotal = subtotal + gstTax; const handleSaveQuotation = async (sendWhatsApp: boolean = false) => { if (!customerName || !customerPhone) { toast.error('Please fill in Customer Name and Phone Number'); return; } const newQuoteNum = `QT-2026-${Math.floor(100 + Math.random() * 900)}`; try { const newQuote: BulkQuotation = { quotation_id: String(Date.now()), tenant_id: 'tenant_default', quote_number: newQuoteNum, customer_id: customerPhone, status: sendWhatsApp ? 'SENT' : 'DRAFT', subtotal, tax_amount: gstTax, final_amount: finalTotal, created_at: new Date().toISOString() }; try { await billingFinanceService.createQuotation({ quote_number: newQuoteNum, customer_name: customerName, customer_phone: customerPhone, customer_email: customerEmail, subtotal, tax_amount: gstTax, final_amount: finalTotal, items }); } catch (e) { // Fallback } setQuotes([newQuote, ...quotes]); if (leadId) { try { await crmService.updateLeadStatus( leadId, sendWhatsApp ? 'QUOTE_SENT' : 'QUOTE_DRAFT', `${sendWhatsApp ? 'Quotation dispatched' : 'Draft quotation saved'}: ${quoteTitle} (₹${finalTotal.toLocaleString()})` ); } catch (e) {} } if (sendWhatsApp) { toast.loading(`Sending quotation ${newQuoteNum} via WhatsApp...`, { id: 'wa-send' }); const res = await openwaService.sendQuotationWhatsApp({ customerName, customerPhone, quoteTitle, amount: finalTotal, terms }); toast.dismiss('wa-send'); if (res.success) { toast.success(`Quotation ${newQuoteNum} dispatched via WhatsApp!`); router.push(`/whatsapp-web?phone=${res.chatId}`); } else { toast.error(`Quotation saved, but WhatsApp dispatch failed: ${res.error}`); } } 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(); } }; return (

B2B Bulk Quotations & GST Invoicing

Generate corporate repair quotes, apply 6-month IMEI warranties, and convert to GST Tax Invoices

{loading ? (
Loading B2B Quotations...
) : (
{quotes.map((q) => ( ))}
Quote Number Status Subtotal GST Tax (18%) Final Amount Created Date Actions
{q.quote_number} {q.status.replace(/_/g, ' ')} ₹{Number(q.subtotal).toLocaleString()} ₹{Number(q.tax_amount).toLocaleString()} ₹{Number(q.final_amount).toLocaleString()} {new Date(q.created_at).toLocaleDateString()} {q.status !== 'CONVERTED_TO_INVOICE' ? ( ) : ( Converted )}
)} {/* Main Modal: New B2B Quotation Builder */} {isModalOpen && (

Create New B2B Quotation

setCustomerName(e.target.value)} placeholder="Company / Contact Name" className="w-full bg-muted border border-border rounded-lg p-2 text-foreground focus:outline-hidden" />
+91 setCustomerPhone(e.target.value)} placeholder="9876543210" className="w-full bg-transparent focus:outline-hidden" />
setCustomerEmail(e.target.value)} placeholder="billing@company.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-medium" />
{/* Line Items Table with Dual Selectors */}
Line Items & Spare Parts {/* 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()}
{/* Calculations Box */}
Subtotal (Excl. Tax): ₹{subtotal.toLocaleString()}
GST Tax (18% SGST + CGST): ₹{gstTax.toLocaleString()}
Grand Total Amount: ₹{finalTotal.toLocaleString()}
{/* Terms */}