ifixkart-admin/New admin panel/ikixkart-dashboard/app/(admin)/crm-quotations/page.tsx
Adithiyan bbd3a3e959 feat: initial commit — full platform snapshot
- Backend: FastAPI app with all models, services, schemas, routes
- Admin Panel: Next.js dashboard with all modules
  (CRM, POS, repairs, warranties, billing, notifications, etc.)
- Ecommerce: storefront (submodule) + product catalog
- AI Agents: .agents/ skill library for Antigravity IDE
- Docs: architecture, billing, notification gateway markdown
- Submodules: Backend/OpenWA, Ecommerce/File 2/storefront
2026-10-13 12:59:47 +05:30

1242 lines
61 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 { 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<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[]>([]);
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<QuoteItem[]>([
{ 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<BulkQuotation | null>(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(
<div>
<p className="font-bold">Sales Quotation {newQuoteNum} dispatched via {dispatchAction}!</p>
<p className="text-xs">Lead has moved to <b>Stage 4: Quote Sent Leads</b></p>
</div>
);
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 (
<div className="p-6 space-y-6 max-w-7xl mx-auto">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-border pb-4">
<div>
<div className="flex items-center gap-2">
<span className="px-2.5 py-1 rounded-full text-xs font-bold bg-primary/10 text-primary border border-primary/20">
CRM Sales Module
</span>
<h1 className="text-2xl font-bold tracking-tight text-foreground flex items-center gap-2">
<FileText className="w-6 h-6 text-primary" />
CRM Customer Sales Quotations
</h1>
</div>
<p className="text-xs text-muted-foreground mt-1">
Create, manage, and dispatch official repair & device sales quotations directly to CRM customers via WhatsApp
</p>
</div>
<button
onClick={() => setIsModalOpen(true)}
className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-lg text-sm font-semibold hover:bg-primary/90 transition-colors shadow-sm cursor-pointer"
>
<Plus className="w-4 h-4" />
+ New Sales Quotation
</button>
</div>
{loading ? (
<div className="py-20 text-center text-muted-foreground animate-pulse">Loading CRM Sales Quotations...</div>
) : (
<div className="bg-card border border-border rounded-xl shadow-xs overflow-hidden">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-border bg-muted/40 text-[11px] font-bold uppercase tracking-wider text-muted-foreground">
<th className="p-4">Quote No.</th>
<th className="p-4">Customer Mobile</th>
<th className="p-4">Status</th>
<th className="p-4">Subtotal</th>
<th className="p-4">GST Tax (18%)</th>
<th className="p-4">Final Amount</th>
<th className="p-4">Date</th>
<th className="p-4 text-right">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-border text-xs">
{quotes.map((q) => (
<tr
key={q.quote_id}
onClick={() => {
setSelectedQuote(q);
setIsDrawerOpen(true);
}}
className="hover:bg-muted/40 transition-colors cursor-pointer"
>
<td className="p-4 font-mono font-bold text-primary flex items-center gap-1.5">
<FileText className="w-4 h-4 text-primary shrink-0" />
{q.quote_number}
</td>
<td className="p-4 font-semibold text-foreground">
{crmService.formatPhoneDisplay(q.customer_id)}
</td>
<td className="p-4">
<span className={`px-2.5 py-1 rounded-full text-[10px] font-bold uppercase ${
q.status === 'APPROVED' ? 'bg-emerald-500/10 text-emerald-600 border border-emerald-500/20' :
q.status === 'CONVERTED' || q.status === 'CONVERTED_TO_INVOICE' ? 'bg-blue-500/10 text-blue-600 border border-blue-500/20' :
q.status === 'SENT' ? 'bg-purple-500/10 text-purple-600 border border-purple-500/20' :
'bg-amber-500/10 text-amber-600 border border-amber-500/20'
}`}>
{q.status.replace(/_/g, ' ')}
</span>
</td>
<td className="p-4 text-foreground font-medium">₹{Number(q.subtotal).toLocaleString()}</td>
<td className="p-4 text-muted-foreground">₹{Number(q.tax_amount).toLocaleString()}</td>
<td className="p-4 font-bold text-foreground">₹{Number(q.grand_total).toLocaleString()}</td>
<td className="p-4 text-muted-foreground">{new Date(q.created_at).toLocaleDateString()}</td>
<td className="p-4 text-right" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-end gap-2">
<button
onClick={() => {
setSelectedQuote(q);
setIsDrawerOpen(true);
}}
className="bg-muted hover:bg-muted/80 text-foreground px-2.5 py-1.5 rounded-lg text-xs font-semibold border border-border inline-flex items-center gap-1 cursor-pointer"
title="View Details & Printable PDF"
>
<Eye className="w-3.5 h-3.5 text-primary" />
View
</button>
{q.status !== 'CONVERTED' && q.status !== 'CONVERTED_TO_INVOICE' ? (
<button
onClick={() => handleConvert(q.quote_id)}
className="bg-emerald-600 text-white hover:bg-emerald-700 px-3 py-1.5 rounded-lg text-xs font-semibold transition-colors inline-flex items-center gap-1 cursor-pointer"
>
<ArrowRight className="w-3.5 h-3.5" />
Convert to Invoice
</button>
) : (
<span className="text-xs text-muted-foreground font-medium px-2">Converted</span>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* Main Modal: New Sales Quotation Builder */}
{isModalOpen && (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto">
<div className="bg-card border border-border rounded-xl shadow-xl max-w-3xl w-full p-6 space-y-4 my-8">
<div className="flex items-center justify-between border-b border-border pb-3">
<h3 className="text-lg font-bold text-foreground flex items-center gap-2">
<Sparkles className="w-5 h-5 text-primary" />
Create Customer Sales Quotation
</h3>
<button onClick={() => setIsModalOpen(false)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-xs">
<div>
<label className="block font-medium mb-1">Customer Name *</label>
<input
type="text"
value={customerName}
onChange={(e) => 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"
/>
</div>
<div>
<label className="block font-medium mb-1">Customer Mobile *</label>
<div className="flex items-center gap-1 bg-muted border border-border rounded-lg p-2 text-foreground">
<span className="text-muted-foreground font-semibold">+91</span>
<input
type="text"
value={customerPhone}
onChange={(e) => setCustomerPhone(e.target.value)}
placeholder="9876543210"
className="w-full bg-transparent focus:outline-hidden font-semibold"
/>
</div>
</div>
<div>
<label className="block font-medium mb-1">Email Address</label>
<input
type="email"
value={customerEmail}
onChange={(e) => 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"
/>
</div>
</div>
<div className="text-xs">
<label className="block font-medium mb-1">Quotation Title / Subject</label>
<input
type="text"
value={quoteTitle}
onChange={(e) => setQuoteTitle(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground focus:outline-hidden font-semibold"
/>
</div>
{/* Line Items Table with Dual Selectors */}
<div className="space-y-3 text-xs">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 border-b border-border pb-2">
<span className="font-bold text-foreground flex items-center gap-1.5">
<FileText className="w-4 h-4 text-primary" />
Line Items & Repair Services
</span>
{/* Dual Add Options */}
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => setIsProductCatalogOpen(true)}
className="inline-flex items-center gap-1.5 bg-blue-600/10 hover:bg-blue-600/20 text-blue-600 dark:text-blue-400 border border-blue-500/30 px-3 py-1.5 rounded-lg font-bold transition-all shadow-2xs cursor-pointer"
>
<ShoppingBag className="w-3.5 h-3.5" />
<span>+ Add Product Catalog</span>
</button>
<button
type="button"
onClick={() => setIsRepairServiceOpen(true)}
className="inline-flex items-center gap-1.5 bg-emerald-600/10 hover:bg-emerald-600/20 text-emerald-600 dark:text-emerald-400 border border-emerald-500/30 px-3 py-1.5 rounded-lg font-bold transition-all shadow-2xs cursor-pointer"
>
<Wrench className="w-3.5 h-3.5" />
<span>+ Add Repair Service</span>
</button>
</div>
</div>
<div className="border border-border rounded-lg overflow-hidden">
<table className="w-full text-left">
<thead className="bg-muted/40 text-[10px] font-bold text-muted-foreground uppercase border-b border-border">
<tr>
<th className="p-2.5">Item / Service Description</th>
<th className="p-2.5 w-16 text-center">Qty</th>
<th className="p-2.5 w-28 text-right">Price (₹)</th>
<th className="p-2.5 w-28 text-right">Total (₹)</th>
<th className="p-2.5 w-10 text-center"></th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{items.map((item, idx) => (
<tr key={idx} className="hover:bg-muted/20">
<td className="p-2">
<input
type="text"
value={item.description}
onChange={(e) => handleItemChange(idx, 'description', e.target.value)}
className="w-full bg-transparent border-0 focus:outline-hidden text-xs font-medium"
/>
</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 bg-muted border border-border rounded-md p-1 text-center text-xs font-bold"
/>
</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 bg-muted border border-border rounded-md p-1 text-right text-xs font-bold"
/>
</td>
<td className="p-2 text-right font-bold text-foreground">
₹{((Number(item.qty) || 0) * (Number(item.unit_price) || 0)).toLocaleString()}
</td>
<td className="p-2 text-center">
<button
type="button"
onClick={() => handleRemoveItem(idx)}
className="text-rose-500 hover:text-rose-700 cursor-pointer"
>
<Trash2 className="w-3.5 h-3.5 mx-auto" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Inter-state Toggle */}
<div className="flex items-center gap-2 text-xs">
<input
type="checkbox"
id="crm-interstate-toggle"
checked={isInterstate}
onChange={(e) => setIsInterstate(e.target.checked)}
className="accent-primary cursor-pointer"
/>
<label htmlFor="crm-interstate-toggle" className="text-muted-foreground cursor-pointer">
Customer is <strong>outside Tamil Nadu</strong> (Apply IGST instead of CGST+SGST)
</label>
</div>
{/* Calculations Box */}
<div className="bg-muted/40 border border-border p-3.5 rounded-xl space-y-1.5 text-xs">
<div className="flex justify-between text-muted-foreground">
<span>Taxable Value (Excl. GST):</span>
<span className="font-semibold 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-semibold 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-semibold 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-semibold 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-semibold text-foreground">{roundOff > 0 ? '+' : ''}₹{roundOff.toFixed(2)}</span>
</div>
)}
<div className="flex justify-between text-sm font-bold text-foreground pt-1.5 border-t border-border">
<span>Grand Total Amount:</span>
<span className="text-primary text-base">₹{finalTotal.toLocaleString('en-IN')}</span>
</div>
</div>
{/* Terms */}
<div className="text-xs">
<label className="block font-medium mb-1">Warranty & Service Terms</label>
<textarea
rows={2}
value={terms}
onChange={(e) => setTerms(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground focus:outline-hidden text-xs"
/>
</div>
{/* Action Buttons */}
<div className="pt-2 flex items-center justify-end gap-2 border-t border-border">
<button
type="button"
onClick={() => setIsModalOpen(false)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted text-xs cursor-pointer"
>
Cancel
</button>
<button
type="button"
onClick={() => handleSaveQuotation('DRAFT')}
className="px-4 py-2 rounded-lg bg-amber-600 hover:bg-amber-700 text-white font-semibold text-xs flex items-center gap-1.5 cursor-pointer"
>
<CheckCircle2 className="w-4 h-4" /> Save Draft Quote
</button>
<button
type="button"
onClick={() => handleSaveQuotation('EMAIL')}
className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white font-bold text-xs flex items-center gap-1.5 shadow-sm cursor-pointer"
>
<MessageSquare className="w-4 h-4" /> Send Email
</button>
<button
type="button"
onClick={() => handleSaveQuotation('WHATSAPP')}
className="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-xs flex items-center gap-1.5 shadow-sm cursor-pointer"
>
<MessageSquare className="w-4 h-4" /> Send WhatsApp
</button>
<button
type="button"
onClick={() => handleSaveQuotation('BOTH')}
className="px-4 py-2 rounded-lg bg-purple-600 hover:bg-purple-700 text-white font-bold text-xs flex items-center gap-1.5 shadow-sm cursor-pointer"
>
<Sparkles className="w-4 h-4" /> Send Both
</button>
</div>
</div>
</div>
)}
{/* Dynamic Sub-Modal 1: Product Catalog Selector */}
{isProductCatalogOpen && (
<div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-2xl max-w-lg w-full p-6 space-y-4">
<div className="flex items-center justify-between border-b border-border pb-3">
<h3 className="text-base font-bold text-foreground flex items-center gap-2">
<ShoppingBag className="w-5 h-5 text-blue-500" />
Select Product from Live Catalog
</h3>
<button onClick={() => setIsProductCatalogOpen(false)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<div className="space-y-3 text-xs">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block font-medium mb-1">Select Brand</label>
<select
value={catBrandId}
onChange={(e) => {
const newBrandId = e.target.value;
setCatBrandId(newBrandId);
const brandObj = brands.find((b) => b.brand_id === newBrandId);
const types = brandObj?.device_types && brandObj.device_types.length > 0 ? brandObj.device_types : ['Mobile'];
if (types.length > 0) setCatDeviceType(types[0]);
}}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{brands.map((b) => (
<option key={b.brand_id} value={b.brand_id}>{b.name}</option>
))}
</select>
</div>
<div>
<label className="block font-medium mb-1">Supported Device Type</label>
<select
value={catDeviceType}
onChange={(e) => setCatDeviceType(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{catSupportedDeviceTypes.map((dt) => (
<option key={dt} value={dt}>{dt}</option>
))}
</select>
</div>
</div>
<div>
<label className="block font-medium mb-1">Device Model</label>
<select
value={catModelId}
onChange={(e) => setCatModelId(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{activeCatModels.map((m) => (
<option key={m.model_id} value={m.model_id}>{m.name} ({m.device_type || catDeviceType})</option>
))}
</select>
</div>
<div>
<label className="block font-medium mb-1">Product Component / Spare Part</label>
<select
value={catPartId}
onChange={(e) => setCatPartId(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{parts.map((p) => (
<option key={p.part_id} value={p.part_id}>
{p.name} — ₹{p.cost_price.toLocaleString()}
</option>
))}
</select>
</div>
{/* Dynamic Preview Box */}
{selectedPart && (
<div className="p-3 bg-blue-500/10 border border-blue-500/20 rounded-lg space-y-1">
<p className="text-[11px] text-blue-600 dark:text-blue-400 font-bold">Dynamic Product Summary Preview:</p>
<p className="font-semibold text-foreground">
{selectedCatBrandObj?.name} {(activeCatModels.find((m) => m.model_id === catModelId) || activeCatModels[0])?.name} - {selectedPart.name}
</p>
<p className="text-blue-600 font-bold text-sm">
₹{selectedPart.cost_price.toLocaleString()}
</p>
</div>
)}
<div className="pt-2 flex justify-end gap-2 border-t border-border">
<button
type="button"
onClick={() => setIsProductCatalogOpen(false)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted"
>
Cancel
</button>
<button
type="button"
onClick={handleAddProductFromCatalog}
className="px-4 py-2 rounded-lg bg-blue-600 text-white font-bold hover:bg-blue-700 flex items-center gap-1.5 cursor-pointer"
>
<Plus className="w-4 h-4" /> Add Product to Quote
</button>
</div>
</div>
</div>
</div>
)}
{/* Dynamic Sub-Modal 2: Repair Service Selector */}
{isRepairServiceOpen && (
<div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4">
<div className="bg-card border border-border rounded-xl shadow-2xl max-w-lg w-full p-6 space-y-4">
<div className="flex items-center justify-between border-b border-border pb-3">
<h3 className="text-base font-bold text-foreground flex items-center gap-2">
<Wrench className="w-5 h-5 text-emerald-500" />
Select Repair Service & Variant Grade
</h3>
<button onClick={() => setIsRepairServiceOpen(false)} className="text-muted-foreground hover:text-foreground">
<X className="w-5 h-5" />
</button>
</div>
<div className="space-y-3 text-xs">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block font-medium mb-1">Select Brand</label>
<select
value={svcBrandId}
onChange={(e) => {
const newBrandId = e.target.value;
setSvcBrandId(newBrandId);
const brandObj = brands.find((b) => b.brand_id === newBrandId);
const types = brandObj?.device_types && brandObj.device_types.length > 0 ? brandObj.device_types : ['Mobile'];
if (types.length > 0) setSvcDeviceType(types[0]);
}}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{brands.map((b) => (
<option key={b.brand_id} value={b.brand_id}>{b.name}</option>
))}
</select>
</div>
<div>
<label className="block font-medium mb-1">Supported Device Type</label>
<select
value={svcDeviceType}
onChange={(e) => setSvcDeviceType(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{svcSupportedDeviceTypes.map((dt) => (
<option key={dt} value={dt}>{dt}</option>
))}
</select>
</div>
</div>
<div>
<label className="block font-medium mb-1">Device Model</label>
<select
value={svcModelId}
onChange={(e) => setSvcModelId(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{activeSvcModels.map((m) => (
<option key={m.model_id} value={m.model_id}>{m.name} ({m.device_type || svcDeviceType})</option>
))}
</select>
</div>
<div>
<label className="block font-medium mb-1">Service Category</label>
<select
value={svcTypeId}
onChange={(e) => {
const newTypeId = e.target.value;
setSvcTypeId(newTypeId);
const vars = repairVariants.filter((v) => v.repair_service_id === newTypeId);
if (vars.length > 0) setSvcVariantId(vars[0].variant_id);
}}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{serviceTypes.map((st) => (
<option key={st.service_type_id} value={st.service_type_id}>{st.name}</option>
))}
</select>
</div>
<div>
<label className="block font-medium mb-1">Variant / Grade & Warranty</label>
<select
value={svcVariantId}
onChange={(e) => setSvcVariantId(e.target.value)}
className="w-full bg-muted border border-border rounded-lg p-2 text-foreground font-semibold"
>
{activeVariants.map((v) => (
<option key={v.variant_id} value={v.variant_id}>
{v.name} — ₹{v.price.toLocaleString()} ({v.warranty_days || 180} Days Warranty)
</option>
))}
</select>
</div>
{/* Dynamic Preview Box */}
{selectedVariant && (
<div className="p-3 bg-emerald-500/10 border border-emerald-500/20 rounded-lg space-y-1">
<p className="text-[11px] text-emerald-600 dark:text-emerald-400 font-bold">Dynamic Repair Service Preview:</p>
<p className="font-semibold text-foreground">
{selectedSvcBrandObj?.name} {(activeSvcModels.find((m) => m.model_id === svcModelId) || activeSvcModels[0])?.name} - {selectedSvcType?.name}
</p>
<p className="text-xs text-muted-foreground">
Variant Grade: {selectedVariant.name}
</p>
<p className="text-emerald-600 font-bold text-sm">
₹{selectedVariant.price.toLocaleString()}
</p>
</div>
)}
<div className="pt-2 flex justify-end gap-2 border-t border-border">
<button
type="button"
onClick={() => setIsRepairServiceOpen(false)}
className="px-4 py-2 rounded-lg border border-border font-medium hover:bg-muted"
>
Cancel
</button>
<button
type="button"
onClick={handleAddRepairService}
className="px-4 py-2 rounded-lg bg-emerald-600 text-white font-bold hover:bg-emerald-700 flex items-center gap-1.5 cursor-pointer"
>
<Plus className="w-4 h-4" /> Add Service to Quote
</button>
</div>
</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 rounded-full text-xs font-bold ${
selectedQuote.status === 'CONVERTED' || selectedQuote.status === 'CONVERTED_TO_INVOICE'
? 'bg-emerald-500/10 text-emerald-600 border border-emerald-500/20'
: selectedQuote.status === 'SENT'
? 'bg-blue-500/10 text-blue-600 border border-blue-500/20'
: 'bg-amber-500/10 text-amber-600 border border-amber-500/20'
}`}>
{selectedQuote.status}
</span>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => setIsPdfModalOpen(true)}
className="flex items-center gap-1.5 bg-primary text-white px-3.5 py-2 rounded-lg text-xs font-semibold hover:bg-primary/90 shadow-xs cursor-pointer"
>
<Printer className="w-4 h-4" />
Print / PDF Preview
</button>
{selectedQuote.status !== 'CONVERTED' && selectedQuote.status !== 'CONVERTED_TO_INVOICE' && (
<button
onClick={() => {
handleConvert(selectedQuote.quote_id);
setIsDrawerOpen(false);
}}
className="flex items-center gap-1.5 bg-emerald-600 text-white px-3.5 py-2 rounded-lg text-xs font-semibold hover:bg-emerald-700 shadow-xs cursor-pointer"
>
<ArrowRight className="w-4 h-4" />
Convert to Tax Invoice
</button>
)}
</div>
</div>
{/* Customer Information Card */}
<div className="p-4 bg-card border border-border rounded-xl space-y-2">
<h4 className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Customer Details</h4>
<div className="grid grid-cols-2 gap-3 text-sm">
<div>
<span className="text-xs text-muted-foreground block">Customer Name</span>
<p className="font-semibold text-foreground">{selectedQuote.customer_name || selectedQuote.customer_id}</p>
</div>
<div>
<span className="text-xs text-muted-foreground block">Mobile Contact</span>
<p className="font-semibold text-foreground">{selectedQuote.customer_phone || selectedQuote.customer_id}</p>
</div>
{selectedQuote.customer_email && (
<div>
<span className="text-xs text-muted-foreground block">Email Address</span>
<p className="font-medium text-foreground">{selectedQuote.customer_email}</p>
</div>
)}
<div>
<span className="text-xs text-muted-foreground block">Quote Date</span>
<p className="font-medium text-foreground">{new Date(selectedQuote.created_at).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' })}</p>
</div>
</div>
</div>
{/* Items Table */}
<div className="space-y-2">
<h4 className="text-xs font-bold text-muted-foreground uppercase tracking-wider">Quotation 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 || 'Service Item'}</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 className="p-3 font-medium text-foreground">CRM Device Repair & Hardware Service</td>
<td className="p-3 text-center text-muted-foreground">1</td>
<td className="p-3 text-right text-muted-foreground">₹{Number(selectedQuote.subtotal).toLocaleString()}</td>
<td className="p-3 text-right font-semibold text-foreground">₹{Number(selectedQuote.subtotal).toLocaleString()}</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% Total)</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>
{/* Terms & Notes */}
<div className="p-4 bg-card border border-border rounded-xl space-y-1 text-xs text-muted-foreground">
<span className="font-bold text-foreground block">Terms & Conditions</span>
<p>• Quotation valid for 15 days from date of issue.</p>
<p>• 6-Month warranty provided on genuine parts replaced.</p>
<p>• Free doorstep pick-up & delivery included across serviced locations.</p>
</div>
</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,
valid_until: new Date(Date.now() + 15 * 86400000).toISOString(),
status: selectedQuote.status,
customer_name: selectedQuote.customer_name || selectedQuote.customer_id,
customer_phone: selectedQuote.customer_phone || selectedQuote.customer_id,
customer_email: selectedQuote.customer_email || '',
company_name: selectedQuote.company_name || 'iFixKart Customer',
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 || 'Official Sales & Repair Quotation from iFixKart Platform.',
terms: '1. Quotation valid for 15 days from date of issue.\n2. Standard warranty applies to parts replaced.\n3. Goods once sold/repaired cannot be returned without original invoice.',
items: selectedQuote.items && selectedQuote.items.length > 0 ? selectedQuote.items.map((item: any) => ({
description: item.description || item.part_name || item.sku || 'Service Item',
sku: item.sku,
hsn_sac_code: item.hsn_sac_code || (item.sku?.includes('SVC') ? '998713' : '851770'),
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))
})) : [
{
description: 'CRM Device Repair & Hardware Service',
hsn_sac_code: '998713',
quantity: 1,
unit_price: selectedQuote.subtotal,
tax_percent: 18,
total_price: selectedQuote.subtotal
}
]
} : null}
/>
</div>
);
}
export default function CrmSalesQuotationsPage() {
return (
<Suspense fallback={<div className="p-6 text-center text-muted-foreground animate-pulse">Loading CRM Sales Quotations...</div>}>
<CrmSalesQuotationsContent />
</Suspense>
);
}