ifixkart-admin/app/(admin)/bulk-quotations/page.tsx

1044 lines
49 KiB
TypeScript

'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<BulkQuotation[]>([]);
const [loading, setLoading] = useState(true);
// Dynamic Catalog State
const [brands, setBrands] = useState<BrandResponse[]>([]);
const [deviceModels, setDeviceModels] = useState<DeviceModelResponse[]>([]);
const [parts, setParts] = useState<PartResponse[]>([]);
const [serviceTypes, setServiceTypes] = useState<ServiceTypeResponse[]>([]);
const [repairVariants, setRepairVariants] = useState<RepairVariantResponse[]>([]);
// 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<QuoteItem[]>([]);
// 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<BulkQuotation | null>(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 (
<div className="flex flex-col gap-5 min-w-0">
<div className="flex flex-wrap items-center justify-between gap-3 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<h1 className="text-lg font-semibold text-foreground">B2B quotations</h1>
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
{quotes.length}
</span>
</div>
<div className="flex items-center gap-2">
<button type="button" onClick={loadQuotations} className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer flex items-center justify-center" title="Reload">
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
</button>
<button type="button" onClick={() => setIsModalOpen(true)} className={primaryButton}>
<Plus className="w-3.5 h-3.5" />
New quotation
</button>
</div>
</div>
<div className={shell}>
{loading ? (
<div className="py-16 flex justify-center"><Loader2 className="w-6 h-6 text-primary animate-spin" /></div>
) : (
<div className="overflow-x-auto">
<table className="crm-data-table min-w-[860px]">
<thead>
<tr className="border-b border-border">
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Quote Number</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Status</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Subtotal</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">GST Tax (18%)</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Final Amount</th>
<th className="px-4 py-2.5 text-left font-medium text-muted-foreground">Created Date</th>
<th className="px-4 py-2.5 text-right font-medium text-muted-foreground">Actions</th>
</tr>
</thead>
<tbody>
{pager.items.length === 0 ? (
<tr>
<td colSpan={7} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No quotations yet</td>
</tr>
) : pager.items.map((q) => (
<tr
key={q.quote_id}
onClick={() => {
setSelectedQuote(q);
setIsDrawerOpen(true);
}}
className="hover:bg-muted/30 transition-colors cursor-pointer"
>
<td className="px-4 py-2.5 text-[13px] font-semibold text-foreground">
{q.quote_number}
</td>
<td className="px-4 py-2.5">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${quoteStatusClass(q.status)}`}>
{q.status.replace(/_/g, ' ')}
</span>
</td>
<td className="px-4 py-2.5 text-right text-[13px] text-foreground">₹{Number(q.subtotal).toLocaleString()}</td>
<td className="px-4 py-2.5 text-right text-[13px] text-muted-foreground">₹{Number(q.tax_amount).toLocaleString()}</td>
<td className="px-4 py-2.5 text-right text-[13px] font-semibold text-foreground">₹{Number(q.grand_total).toLocaleString()}</td>
<td className="px-4 py-2.5 text-[13px] text-muted-foreground">{formatCreated(q.created_at)}</td>
<td className="px-4 py-2.5 text-right" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-end gap-2">
<button
type="button"
onClick={() => {
setSelectedQuote(q);
setIsDrawerOpen(true);
}}
className={secondaryButton}
>
<Eye className="w-3.5 h-3.5" />
View
</button>
{q.status !== 'CONVERTED_TO_INVOICE' && q.status !== 'CONVERTED' ? (
<button
type="button"
onClick={() => handleConvert(q.quote_id)}
className={primaryButton}
>
<ArrowRight className="w-3.5 h-3.5" />
Convert to Invoice
</button>
) : (
<span className="text-[13px] text-muted-foreground">Converted</span>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{!loading && pager.items.length > 0 && <TablePagination {...pager} />}
</div>
{isModalOpen && (
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4 overflow-y-auto">
<div className="bg-card border border-border crm-radius-section shadow-xl max-w-3xl w-full p-5 space-y-4 my-8">
<div className="flex items-center justify-between">
<h3 className="text-base font-semibold text-foreground">Quotation</h3>
<button type="button" onClick={() => setIsModalOpen(false)} className="text-muted-foreground hover:text-foreground cursor-pointer" aria-label="Close">
<X className="w-4 h-4" />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Customer name</span>
<input
type="text"
value={customerName}
onChange={(e) => setCustomerName(e.target.value)}
placeholder="Name"
className={fieldClass}
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Phone</span>
<input
type="text"
value={customerPhone}
onChange={(e) => setCustomerPhone(e.target.value)}
placeholder="Phone"
className={fieldClass}
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Email</span>
<input
type="email"
value={customerEmail}
onChange={(e) => setCustomerEmail(e.target.value)}
placeholder="Email"
className={fieldClass}
/>
</label>
</div>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Title</span>
<input
type="text"
value={quoteTitle}
onChange={(e) => setQuoteTitle(e.target.value)}
placeholder="Quotation title"
className={fieldClass}
/>
</label>
<div className="space-y-3">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
<span className="text-[13px] font-semibold text-foreground">Line items</span>
<div className="flex items-center gap-2">
<button type="button" onClick={() => setIsProductCatalogOpen(true)} className={secondaryButton}>
<Plus className="w-3.5 h-3.5" />
Add product
</button>
<button type="button" onClick={() => setIsRepairServiceOpen(true)} className={secondaryButton}>
<Plus className="w-3.5 h-3.5" />
Add repair
</button>
</div>
</div>
<div className="border border-border crm-radius-section overflow-hidden">
<table className="w-full text-left">
<thead className="bg-muted/40 text-[11px] font-semibold text-muted-foreground uppercase border-b border-border">
<tr>
<th className="px-3 py-2">Description</th>
<th className="px-3 py-2 w-16 text-center">Qty</th>
<th className="px-3 py-2 w-28 text-right">Price</th>
<th className="px-3 py-2 w-28 text-right">Total</th>
<th className="px-3 py-2 w-10"></th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{items.length === 0 ? (
<tr>
<td colSpan={5} className="px-3 py-8 text-center text-[13px] text-muted-foreground">
No line items yet. Add a product or a repair.
</td>
</tr>
) : items.map((item, idx) => (
<tr key={idx}>
<td className="p-2">
<input
type="text"
value={item.description}
onChange={(e) => 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"
/>
</td>
<td className="p-2">
<input
type="number"
value={item.qty}
min={1}
onChange={(e) => 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"
/>
</td>
<td className="p-2">
<input
type="number"
value={item.unit_price}
onChange={(e) => 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"
/>
</td>
<td className="px-3 py-2 text-right text-[13px] font-semibold text-foreground">
₹{((Number(item.qty) || 0) * (Number(item.unit_price) || 0)).toLocaleString('en-IN')}
</td>
<td className="p-2 text-center">
<button
type="button"
onClick={() => handleRemoveItem(idx)}
className="text-muted-foreground hover:text-foreground cursor-pointer"
aria-label="Remove line"
>
<Trash2 className="w-3.5 h-3.5 mx-auto" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<label className="flex items-center gap-2 text-[13px] text-foreground cursor-pointer">
<input
type="checkbox"
id="bulk-interstate-toggle"
checked={isInterstate}
onChange={(e) => setIsInterstate(e.target.checked)}
className="accent-primary cursor-pointer"
/>
Customer is outside Tamil Nadu (IGST)
</label>
<div className="bg-muted/40 border border-border crm-radius-section p-3 space-y-1.5 text-[13px]">
<div className="flex justify-between text-muted-foreground">
<span>Taxable value</span>
<span className="font-medium text-foreground">₹{taxableSub.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
</div>
{isInterstate ? (
<div className="flex justify-between text-muted-foreground">
<span>IGST ({GST_RATE}%)</span>
<span className="font-medium text-foreground">₹{igst.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
</div>
) : (
<>
<div className="flex justify-between text-muted-foreground">
<span>CGST ({GST_RATE / 2}%)</span>
<span className="font-medium text-foreground">₹{cgst.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
</div>
<div className="flex justify-between text-muted-foreground">
<span>SGST ({GST_RATE / 2}%)</span>
<span className="font-medium text-foreground">₹{sgst.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</span>
</div>
</>
)}
{roundOff !== 0 && (
<div className="flex justify-between text-muted-foreground">
<span>Round off</span>
<span className="font-medium text-foreground">{roundOff > 0 ? '+' : ''}₹{roundOff.toFixed(2)}</span>
</div>
)}
<div className="flex justify-between text-[13px] font-semibold text-foreground pt-1.5 border-t border-border">
<span>Total</span>
<span>₹{finalTotal.toLocaleString('en-IN')}</span>
</div>
</div>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Terms</span>
<textarea
rows={2}
value={terms}
onChange={(e) => setTerms(e.target.value)}
placeholder="Warranty, validity, pickup terms"
className="w-full px-3 py-2 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary"
/>
</label>
<div className="flex flex-wrap items-center justify-end gap-2 border-t border-border pt-3">
<button type="button" onClick={() => setIsModalOpen(false)} className={secondaryButton}>
Cancel
</button>
<button type="button" onClick={() => handleSaveQuotation('DRAFT')} className={secondaryButton}>
Save draft
</button>
<button type="button" onClick={() => handleSaveQuotation('EMAIL')} className={primaryButton}>
Send email
</button>
<button type="button" onClick={() => handleSaveQuotation('WHATSAPP')} className={primaryButton}>
Send WhatsApp
</button>
<button type="button" onClick={() => handleSaveQuotation('BOTH')} className={primaryButton}>
Send both
</button>
</div>
</div>
</div>
)}
{isProductCatalogOpen && (
<div className="fixed inset-0 z-[60] bg-black/40 flex items-center justify-center p-4">
<div className="bg-card border border-border crm-radius-section shadow-xl max-w-lg w-full p-5 space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-base font-semibold text-foreground">Add product</h3>
<button type="button" onClick={() => setIsProductCatalogOpen(false)} className="text-muted-foreground hover:text-foreground cursor-pointer" aria-label="Close">
<X className="w-4 h-4" />
</button>
</div>
{brands.length === 0 && parts.length === 0 ? (
<p className="text-[13px] text-muted-foreground">No catalog products are available.</p>
) : (
<div className="space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Brand</span>
<CustomSelect
value={catBrandId}
onChange={(newBrandId) => {
setCatBrandId(newBrandId);
const brandObj = brands.find((b) => b.brand_id === newBrandId);
const types = deviceTypesFor(newBrandId, brandObj?.device_types);
const nextType = types[0] || '';
setCatDeviceType(nextType);
const nextModel = deviceModels.find((model) =>
model.brand_id === newBrandId && (!nextType || model.device_type?.toLowerCase() === nextType.toLowerCase())
);
setCatModelId(nextModel?.model_id || '');
}}
options={brands.map((brand) => ({ value: brand.brand_id, label: brand.name }))}
placeholder="Brand"
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Device type</span>
<CustomSelect
value={catDeviceType}
onChange={(nextType) => {
setCatDeviceType(nextType);
const nextModel = deviceModels.find((model) =>
model.brand_id === catBrandId && (!nextType || model.device_type?.toLowerCase() === nextType.toLowerCase())
);
setCatModelId(nextModel?.model_id || '');
}}
options={catSupportedDeviceTypes.map((deviceType) => ({ value: deviceType, label: deviceType }))}
placeholder="Device type"
/>
</label>
</div>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Model</span>
<CustomSelect
value={catModelId}
onChange={setCatModelId}
options={activeCatModels.map((model) => ({
value: model.model_id,
label: model.device_type ? `${model.name} (${model.device_type})` : model.name,
}))}
placeholder="Model"
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Part</span>
<CustomSelect
value={catPartId}
onChange={setCatPartId}
options={parts.map((part) => ({
value: part.part_id,
label: `${part.name} · ₹${Number(part.cost_price || 0).toLocaleString('en-IN')}`,
}))}
placeholder="Part"
/>
</label>
{selectedPart && (
<div className="p-3 border border-border crm-radius-section bg-muted/40 text-[13px]">
<p className="font-medium text-foreground">{selectedPart.name}</p>
<p className="text-muted-foreground mt-1">₹{Number(selectedPart.cost_price || 0).toLocaleString('en-IN')}</p>
</div>
)}
</div>
)}
<div className="flex justify-end gap-2 border-t border-border pt-3">
<button type="button" onClick={() => setIsProductCatalogOpen(false)} className={secondaryButton}>
Cancel
</button>
<button type="button" onClick={handleAddProductFromCatalog} disabled={!selectedPart} className={primaryButton}>
Add to quote
</button>
</div>
</div>
</div>
)}
{isRepairServiceOpen && (
<div className="fixed inset-0 z-[60] bg-black/40 flex items-center justify-center p-4">
<div className="bg-card border border-border crm-radius-section shadow-xl max-w-lg w-full p-5 space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-base font-semibold text-foreground">Add repair</h3>
<button type="button" onClick={() => setIsRepairServiceOpen(false)} className="text-muted-foreground hover:text-foreground cursor-pointer" aria-label="Close">
<X className="w-4 h-4" />
</button>
</div>
{serviceTypes.length === 0 && repairVariants.length === 0 ? (
<p className="text-[13px] text-muted-foreground">No repair services are available.</p>
) : (
<div className="space-y-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Brand</span>
<CustomSelect
value={svcBrandId}
onChange={(newBrandId) => {
setSvcBrandId(newBrandId);
const brandObj = brands.find((b) => b.brand_id === newBrandId);
const types = deviceTypesFor(newBrandId, brandObj?.device_types);
const nextType = types[0] || '';
setSvcDeviceType(nextType);
const nextModel = deviceModels.find((model) =>
model.brand_id === newBrandId && (!nextType || model.device_type?.toLowerCase() === nextType.toLowerCase())
);
setSvcModelId(nextModel?.model_id || '');
}}
options={brands.map((brand) => ({ value: brand.brand_id, label: brand.name }))}
placeholder="Brand"
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Device type</span>
<CustomSelect
value={svcDeviceType}
onChange={(nextType) => {
setSvcDeviceType(nextType);
const nextModel = deviceModels.find((model) =>
model.brand_id === svcBrandId && (!nextType || model.device_type?.toLowerCase() === nextType.toLowerCase())
);
setSvcModelId(nextModel?.model_id || '');
}}
options={svcSupportedDeviceTypes.map((deviceType) => ({ value: deviceType, label: deviceType }))}
placeholder="Device type"
/>
</label>
</div>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Model</span>
<CustomSelect
value={svcModelId}
onChange={setSvcModelId}
options={activeSvcModels.map((model) => ({
value: model.model_id,
label: model.device_type ? `${model.name} (${model.device_type})` : model.name,
}))}
placeholder="Model"
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Service</span>
<CustomSelect
value={svcTypeId}
onChange={(newTypeId) => {
setSvcTypeId(newTypeId);
const nextVariant = repairVariants.find((variant) => variant.repair_service_id === newTypeId);
setSvcVariantId(nextVariant?.variant_id || '');
}}
options={serviceTypes.map((service) => ({ value: service.service_type_id, label: service.name }))}
placeholder="Service"
/>
</label>
<label className="block">
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Variant</span>
<CustomSelect
value={svcVariantId}
onChange={setSvcVariantId}
options={activeVariants.map((variant) => ({
value: variant.variant_id,
label: variant.warranty_days
? `${variant.name} · ₹${Number(variant.price || 0).toLocaleString('en-IN')} · ${variant.warranty_days} days`
: `${variant.name} · ₹${Number(variant.price || 0).toLocaleString('en-IN')}`,
}))}
placeholder="Variant"
/>
</label>
{selectedVariant && (
<div className="p-3 border border-border crm-radius-section bg-muted/40 text-[13px]">
<p className="font-medium text-foreground">{selectedSvcType?.name || selectedVariant.name}</p>
<p className="text-muted-foreground mt-1">₹{Number(selectedVariant.price || 0).toLocaleString('en-IN')}</p>
</div>
)}
</div>
)}
<div className="flex justify-end gap-2 border-t border-border pt-3">
<button type="button" onClick={() => setIsRepairServiceOpen(false)} className={secondaryButton}>
Cancel
</button>
<button type="button" onClick={handleAddRepairService} disabled={!selectedVariant} className={primaryButton}>
Add to quote
</button>
</div>
</div>
</div>
)}
{/* SlideOver Detail Drawer */}
<SlideOver
open={isDrawerOpen && selectedQuote !== null}
onClose={() => setIsDrawerOpen(false)}
title={`Quotation ${selectedQuote?.quote_number || selectedQuote?.quote_id || ''}`}
icon={<FileText className="w-5 h-5 text-primary" />}
size="form"
>
{selectedQuote && (
<div className="p-6 space-y-6 flex-1 overflow-y-auto">
{/* Top Bar with Status & Actions */}
<div className="flex flex-wrap items-center justify-between gap-3 p-4 bg-muted/40 border border-border rounded-xl">
<div>
<span className="text-xs text-muted-foreground block mb-0.5">Status</span>
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${quoteStatusClass(selectedQuote.status)}`}>
{selectedQuote.status}
</span>
</div>
<div className="flex items-center gap-2">
<button type="button" onClick={() => setIsPdfModalOpen(true)} className={secondaryButton}>
<Printer className="w-3.5 h-3.5" />
Print
</button>
{selectedQuote.status !== 'CONVERTED' && selectedQuote.status !== 'CONVERTED_TO_INVOICE' && (
<button
type="button"
onClick={() => {
handleConvert(selectedQuote.quote_id);
setIsDrawerOpen(false);
}}
className={primaryButton}
>
Convert
</button>
)}
</div>
</div>
<div className="p-4 bg-card border border-border crm-radius-section space-y-2">
<h4 className="text-[11px] font-semibold text-muted-foreground uppercase">Customer</h4>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-[13px]">
<div>
<span className="text-[11px] text-muted-foreground block">Name</span>
<p className="font-semibold text-foreground">{selectedQuote.customer_name || selectedQuote.company_name || '—'}</p>
</div>
<div>
<span className="text-[11px] text-muted-foreground block">Phone</span>
<p className="font-semibold text-foreground">{selectedQuote.customer_phone || '—'}</p>
</div>
{selectedQuote.customer_email && (
<div>
<span className="text-[11px] text-muted-foreground block">Email</span>
<p className="font-medium text-foreground">{selectedQuote.customer_email}</p>
</div>
)}
{selectedQuote.gst_number && (
<div>
<span className="text-[11px] text-muted-foreground block">GSTIN</span>
<p className="font-mono font-medium text-foreground">{selectedQuote.gst_number}</p>
</div>
)}
<div>
<span className="text-[11px] text-muted-foreground block">Created</span>
<p className="text-foreground">{formatCreated(selectedQuote.created_at)}</p>
</div>
</div>
</div>
{/* Items Table */}
<div className="space-y-2">
<h4 className="text-[11px] font-semibold text-muted-foreground uppercase">Line items</h4>
<div className="border border-border rounded-xl overflow-hidden text-xs">
<table className="w-full text-left">
<thead className="bg-muted/50 border-b border-border text-muted-foreground font-semibold">
<tr>
<th className="p-3">Description</th>
<th className="p-3 text-center">Qty</th>
<th className="p-3 text-right">Unit Price</th>
<th className="p-3 text-right">Total</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{(selectedQuote.items && selectedQuote.items.length > 0) ? (
selectedQuote.items.map((item: any, idx: number) => (
<tr key={idx}>
<td className="p-3 font-medium text-foreground">{item.description || item.part_name || '—'}</td>
<td className="p-3 text-center text-muted-foreground">{item.quantity || item.qty || 1}</td>
<td className="p-3 text-right text-muted-foreground">₹{Number(item.unit_price || 0).toLocaleString()}</td>
<td className="p-3 text-right font-semibold text-foreground">₹{Number(item.total_price || (item.quantity || 1) * (item.unit_price || 0)).toLocaleString()}</td>
</tr>
))
) : (
<tr>
<td colSpan={4} className="p-3 text-muted-foreground">No line items</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
{/* Payment & Tax Summary */}
<div className="p-4 bg-muted/30 border border-border rounded-xl space-y-2 text-xs">
<div className="flex justify-between text-muted-foreground">
<span>Subtotal</span>
<span>₹{Number(selectedQuote.subtotal).toLocaleString()}</span>
</div>
<div className="flex justify-between text-muted-foreground">
<span>GST (18%)</span>
<span>₹{Number(selectedQuote.tax_amount).toLocaleString()}</span>
</div>
<div className="flex justify-between text-base font-bold text-foreground border-t border-border pt-2 mt-2">
<span>Grand Total</span>
<span className="text-primary">₹{Number(selectedQuote.grand_total).toLocaleString()}</span>
</div>
</div>
{selectedQuote.notes ? (
<div className="p-4 bg-card border border-border crm-radius-section text-[13px] text-muted-foreground">
<span className="font-semibold text-foreground block">Terms</span>
<p className="whitespace-pre-wrap mt-1">{selectedQuote.notes}</p>
</div>
) : null}
</div>
)}
</SlideOver>
{/* Printable PDF Preview Modal */}
<PrintableQuotationModal
isOpen={isPdfModalOpen}
onClose={() => setIsPdfModalOpen(false)}
data={selectedQuote ? {
quote_number: selectedQuote.quote_number || selectedQuote.quote_id,
created_at: selectedQuote.created_at,
status: selectedQuote.status,
customer_name: selectedQuote.customer_name || selectedQuote.customer_id,
customer_phone: selectedQuote.customer_phone || '',
customer_email: selectedQuote.customer_email || '',
company_name: selectedQuote.company_name || selectedQuote.customer_name || '',
gst_number: selectedQuote.gst_number || '',
subtotal: selectedQuote.subtotal,
discount_amount: selectedQuote.discount_amount || 0,
tax_amount: selectedQuote.tax_amount,
grand_total: selectedQuote.grand_total,
notes: selectedQuote.notes || '',
terms: selectedQuote.notes || '',
items: (selectedQuote.items || []).map((item: any) => ({
description: item.description || item.part_name || item.sku || '—',
sku: item.sku,
hsn_sac_code: item.hsn_sac_code,
quantity: item.quantity || item.qty || 1,
unit_price: item.unit_price || 0,
tax_percent: item.tax_percent || 18,
total_price: item.total_price || ((item.quantity || 1) * (item.unit_price || 0))
}))
} : null}
/>
</div>
);
}
export default function BulkQuotationsPage() {
return (
<Suspense fallback={<div className="py-16 text-center text-[13px] text-muted-foreground">Loading quotations</div>}>
<BulkQuotationsContent />
</Suspense>
);
}