912 lines
43 KiB
TypeScript
912 lines
43 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 {
|
|
catalogService,
|
|
BrandResponse,
|
|
DeviceModelResponse,
|
|
PartResponse,
|
|
ServiceTypeResponse,
|
|
RepairVariantResponse
|
|
} from '@/services/api/catalogService';
|
|
import { FileText, Plus, ArrowRight, X, Trash2, MessageSquare, CheckCircle2, ShoppingBag, Wrench, Sparkles } from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
|
|
interface QuoteItem {
|
|
description: string;
|
|
qty: number;
|
|
unit_price: number;
|
|
}
|
|
|
|
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 [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('');
|
|
|
|
useEffect(() => {
|
|
loadQuotations();
|
|
loadCatalogData();
|
|
|
|
if (leadId || paramCustomerName || paramPhone) {
|
|
setCustomerName(paramCustomerName);
|
|
setCustomerPhone(paramPhone);
|
|
setCustomerEmail(paramEmail);
|
|
if (paramCustomerName) {
|
|
setQuoteTitle(`Sales Quote - ${paramCustomerName}`);
|
|
}
|
|
setIsModalOpen(true);
|
|
}
|
|
}, [searchParams]);
|
|
|
|
const loadQuotations = async () => {
|
|
try {
|
|
setLoading(true);
|
|
const data = await billingFinanceService.getQuotations();
|
|
setQuotes(data);
|
|
} catch (err) {
|
|
setQuotes([
|
|
{
|
|
quotation_id: 'sq-101',
|
|
tenant_id: 'tenant_default',
|
|
quote_number: 'SQ-2026-001',
|
|
customer_id: '9988776655',
|
|
status: 'SENT',
|
|
subtotal: 15300,
|
|
tax_amount: 2754,
|
|
final_amount: 18054,
|
|
created_at: new Date().toISOString()
|
|
},
|
|
{
|
|
quotation_id: 'sq-102',
|
|
tenant_id: 'tenant_default',
|
|
quote_number: 'SQ-2026-002',
|
|
customer_id: '9812345678',
|
|
status: 'DRAFT',
|
|
subtotal: 8500,
|
|
tax_amount: 1530,
|
|
final_amount: 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 }]);
|
|
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 = `SQ-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()})`,
|
|
{
|
|
quote_amount: finalTotal,
|
|
quote_title: quoteTitle,
|
|
quote_terms: terms,
|
|
quote_sent_at: sendWhatsApp ? new Date().toISOString() : undefined
|
|
}
|
|
);
|
|
} 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(`Sales 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(`Sales Quotation ${newQuoteNum} saved as Draft!`);
|
|
}
|
|
|
|
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.quotation_id} className="hover:bg-muted/30 transition-colors">
|
|
<td className="p-4 font-mono font-bold text-primary">
|
|
{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' :
|
|
q.status === 'CONVERTED_TO_INVOICE' ? 'bg-blue-500/10 text-blue-600' :
|
|
q.status === 'SENT' ? 'bg-purple-500/10 text-purple-600' :
|
|
'bg-amber-500/10 text-amber-600'
|
|
}`}>
|
|
{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.final_amount).toLocaleString()}</td>
|
|
<td className="p-4 text-muted-foreground">{new Date(q.created_at).toLocaleDateString()}</td>
|
|
<td className="p-4 text-right">
|
|
{q.status !== 'CONVERTED_TO_INVOICE' ? (
|
|
<button
|
|
onClick={() => handleConvert(q.quotation_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">Converted</span>
|
|
)}
|
|
</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>
|
|
|
|
{/* 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>Subtotal (Excl. Tax):</span>
|
|
<span className="font-semibold text-foreground">₹{subtotal.toLocaleString()}</span>
|
|
</div>
|
|
<div className="flex justify-between text-muted-foreground">
|
|
<span>GST Tax (18% SGST + CGST):</span>
|
|
<span className="font-semibold text-foreground">₹{gstTax.toLocaleString()}</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()}</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(false)}
|
|
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(true)}
|
|
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 Quote via WhatsApp
|
|
</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>
|
|
)}
|
|
</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>
|
|
);
|
|
}
|