1303 lines
61 KiB
TypeScript
1303 lines
61 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useMemo, useState, Suspense } from 'react';
|
|
import { useSearchParams, useRouter } from 'next/navigation';
|
|
import { format } from 'date-fns';
|
|
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 { Download, FileText, Plus, Printer, RefreshCw, Search, Trash2 } from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
import { SlideOver } from '@/components/ui/SlideOver';
|
|
import { PrintableQuotationModal } from '@/components/quotations/PrintableQuotationModal';
|
|
import { CustomSelect } from '@/components/ui/CustomSelect';
|
|
import { TablePagination, useClientPagination } from '@/components/ui/TablePagination';
|
|
import { ViewModeToggle } from '@/components/ui/ViewModeToggle';
|
|
|
|
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';
|
|
|
|
const QUOTE_STATUSES = [
|
|
{ value: 'DRAFT', label: 'Draft', className: 'bg-muted text-foreground' },
|
|
{ value: 'SENT', label: 'Sent', className: 'bg-primary/10 text-primary' },
|
|
{ value: 'APPROVED', label: 'Approved', className: 'bg-success/15 text-success' },
|
|
{ value: 'REJECTED', label: 'Rejected', className: 'bg-destructive/10 text-destructive' },
|
|
{ value: 'CONVERTED', label: 'Converted', className: 'bg-success/15 text-success' },
|
|
{ value: 'CONVERTED_TO_INVOICE', label: 'Converted', className: 'bg-success/15 text-success' },
|
|
];
|
|
|
|
function quoteStatus(status: string) {
|
|
return QUOTE_STATUSES.find((item) => item.value === status) || {
|
|
value: status,
|
|
label: status.replaceAll('_', ' ').toLowerCase().replace(/^\w/, (letter) => letter.toUpperCase()),
|
|
className: 'bg-muted text-foreground',
|
|
};
|
|
}
|
|
|
|
function money(amount: number) {
|
|
return `₹${Number(amount || 0).toLocaleString('en-IN')}`;
|
|
}
|
|
|
|
function quoteName(quote: BulkQuotation) {
|
|
return quote.customer_name || '—';
|
|
}
|
|
|
|
function quotePhone(quote: BulkQuotation) {
|
|
return crmService.formatPhoneDisplay(quote.customer_phone || quote.customer_id);
|
|
}
|
|
|
|
function formatCreated(iso?: string) {
|
|
if (!iso) return '—';
|
|
const date = new Date(iso);
|
|
if (Number.isNaN(date.getTime())) return '—';
|
|
return format(date, 'dd MMM yyyy, hh:mm a');
|
|
}
|
|
|
|
function initials(name: string) {
|
|
const parts = name.split(/\s+/).filter(Boolean);
|
|
return ((parts[0]?.[0] || '') + (parts[1]?.[0] || '')).toUpperCase() || 'Q';
|
|
}
|
|
|
|
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 paramQuoteTitle = searchParams.get('quote_title') || '';
|
|
const paramQuoteTerms = searchParams.get('quote_terms') || '';
|
|
|
|
const [quotes, setQuotes] = useState<BulkQuotation[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
|
|
const [query, setQuery] = useState('');
|
|
const [statusFilter, setStatusFilter] = useState('ALL');
|
|
const [sortBy, setSortBy] = useState<'newest' | 'oldest' | 'amount'>('newest');
|
|
const [dateFrom, setDateFrom] = useState('');
|
|
const [dateTo, setDateTo] = useState('');
|
|
|
|
// 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(paramQuoteTitle || (paramCustomerName ? `Quote - ${paramCustomerName}` : ''));
|
|
const [terms, setTerms] = useState(paramQuoteTerms);
|
|
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('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 (paramQuoteTitle) setQuoteTitle(paramQuoteTitle);
|
|
else if (paramCustomerName) setQuoteTitle(`Quote - ${paramCustomerName}`);
|
|
if (paramQuoteTerms) setTerms(paramQuoteTerms);
|
|
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(Array.isArray(data) ? data : []);
|
|
} catch {
|
|
toast.error('Failed to load quotations');
|
|
setQuotes([]);
|
|
} 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(() => []),
|
|
]);
|
|
|
|
setBrands(Array.isArray(fetchedBrands) ? fetchedBrands : []);
|
|
setDeviceModels(Array.isArray(fetchedModels) ? fetchedModels : []);
|
|
setParts(Array.isArray(fetchedParts) ? fetchedParts : []);
|
|
setServiceTypes(Array.isArray(fetchedServiceTypes) ? fetchedServiceTypes : []);
|
|
setRepairVariants(Array.isArray(fetchedVariants) ? fetchedVariants : []);
|
|
|
|
if (fetchedBrands.length > 0) {
|
|
const firstBrand = fetchedBrands[0];
|
|
setCatBrandId(firstBrand.brand_id);
|
|
setSvcBrandId(firstBrand.brand_id);
|
|
const types = firstBrand.device_types?.length
|
|
? firstBrand.device_types
|
|
: [...new Set(fetchedModels.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]);
|
|
}
|
|
const firstModel = fetchedModels.find((model) =>
|
|
model.brand_id === firstBrand.brand_id && (!types[0] || model.device_type === types[0])
|
|
);
|
|
if (firstModel) {
|
|
setCatModelId(firstModel.model_id);
|
|
setSvcModelId(firstModel.model_id);
|
|
}
|
|
}
|
|
|
|
if (fetchedParts.length > 0) setCatPartId(fetchedParts[0].part_id);
|
|
if (fetchedServiceTypes.length > 0) {
|
|
const typeId = fetchedServiceTypes[0].service_type_id;
|
|
setSvcTypeId(typeId);
|
|
const match = fetchedVariants.find((variant) => variant.repair_service_id === typeId);
|
|
if (match) setSvcVariantId(match.variant_id);
|
|
}
|
|
|
|
} catch (err) {
|
|
console.warn('Failed to load dynamic catalog data:', err);
|
|
} finally {
|
|
setCatalogLoading(false);
|
|
}
|
|
};
|
|
|
|
// 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((variant) => variant.repair_service_id === svcTypeId);
|
|
const selectedVariant = activeVariants.find((variant) => variant.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 serviceName = selectedSvcType?.name || '';
|
|
const desc = [[selectedSvcBrandObj?.name, modelName].filter(Boolean).join(' '), serviceName, 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; // 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;
|
|
const finalTotal = roundedFinal;
|
|
|
|
const handleSaveQuotation = async (dispatchAction: 'DRAFT' | 'WHATSAPP' | 'EMAIL' | 'BOTH' = 'DRAFT') => {
|
|
if (!customerName || !customerPhone) {
|
|
toast.error('Enter the customer name and phone');
|
|
return;
|
|
}
|
|
if (items.length === 0 || items.some((item) => !String(item.description || '').trim())) {
|
|
toast.error('Add at least one line item');
|
|
return;
|
|
}
|
|
|
|
const newQuoteNum = `SQ-2026-${Math.floor(100 + Math.random() * 900)}`;
|
|
|
|
try {
|
|
const quoteItems = items.map((item) => ({
|
|
description: item.description,
|
|
quantity: item.qty || 1,
|
|
qty: item.qty || 1,
|
|
unit_price: item.unit_price,
|
|
sku: item.sku || undefined,
|
|
tax_percent: GST_RATE,
|
|
total_price: (Number(item.qty) || 0) * (Number(item.unit_price) || 0),
|
|
}));
|
|
|
|
const newQuote: BulkQuotation = {
|
|
quote_id: String(Date.now()),
|
|
tenant_id: 'tenant_default',
|
|
quote_number: newQuoteNum,
|
|
customer_id: customerPhone,
|
|
customer_name: customerName,
|
|
customer_phone: customerPhone,
|
|
customer_email: customerEmail,
|
|
status: dispatchAction !== 'DRAFT' ? 'SENT' : 'DRAFT',
|
|
subtotal: taxableSub,
|
|
tax_amount: totalGst,
|
|
grand_total: finalTotal,
|
|
notes: terms,
|
|
items: quoteItems,
|
|
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: quoteItems.map((item) => ({
|
|
description: item.description,
|
|
quantity: item.quantity,
|
|
unit_price: item.unit_price,
|
|
sku: item.sku,
|
|
tax_percent: item.tax_percent,
|
|
})),
|
|
});
|
|
setQuotes([{
|
|
...newQuote,
|
|
...res,
|
|
customer_name: res.customer_name || customerName,
|
|
customer_phone: res.customer_phone || customerPhone,
|
|
customer_email: res.customer_email || customerEmail,
|
|
notes: res.notes || terms,
|
|
items: res.items?.length ? res.items : quoteItems,
|
|
}, ...quotes]);
|
|
} catch {
|
|
setQuotes([newQuote, ...quotes]);
|
|
}
|
|
|
|
const quoteFields = {
|
|
quote_amount: finalTotal,
|
|
quote_title: quoteTitle,
|
|
quote_terms: terms,
|
|
};
|
|
const attachLead = async (status: 'QUOTE_SENT' | 'QUOTE_DRAFT') => {
|
|
const note = status === 'QUOTE_SENT'
|
|
? `Quotation dispatched: ${quoteTitle} (₹${finalTotal.toLocaleString()})`
|
|
: `Quotation draft: ${quoteTitle} (₹${finalTotal.toLocaleString()})`;
|
|
const extra = status === 'QUOTE_SENT'
|
|
? { ...quoteFields, quote_sent_at: new Date().toISOString() }
|
|
: quoteFields;
|
|
if (leadId) {
|
|
await crmService.updateLeadStatus(leadId, status, note, extra);
|
|
return;
|
|
}
|
|
const leads = await crmService.getLeads();
|
|
const existing = (Array.isArray(leads) ? leads : []).find((lead) => lead.phone === customerPhone);
|
|
if (existing) {
|
|
await crmService.updateLeadStatus(existing.lead_id, status, note, extra);
|
|
return;
|
|
}
|
|
await crmService.createLead({
|
|
title: customerName,
|
|
phone: customerPhone,
|
|
email: customerEmail,
|
|
source: 'STOREFRONT',
|
|
status,
|
|
...extra,
|
|
notes: `Quotation ${newQuoteNum} generated directly.`,
|
|
});
|
|
};
|
|
|
|
if (dispatchAction !== 'DRAFT') {
|
|
try {
|
|
await attachLead('QUOTE_SENT');
|
|
} catch (e) {
|
|
console.error("Lead status 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">The lead status is now Quote sent.</p>
|
|
</div>
|
|
);
|
|
router.push('/crm-leads?status=QUOTE_SENT');
|
|
} else {
|
|
try {
|
|
await attachLead('QUOTE_DRAFT');
|
|
} catch (e) {
|
|
console.error('Lead draft sync error:', e);
|
|
}
|
|
toast.success(`Quotation ${newQuoteNum} saved as a draft. The lead is now Quote draft.`);
|
|
router.push('/crm-leads?status=QUOTE_DRAFT');
|
|
}
|
|
|
|
setIsModalOpen(false);
|
|
} catch (err) {
|
|
toast.error('Failed to save CRM quotation');
|
|
}
|
|
};
|
|
|
|
const handleConvert = async (quoteId: string) => {
|
|
try {
|
|
await billingFinanceService.convertToInvoice(quoteId);
|
|
toast.success('Converted to invoice');
|
|
loadQuotations();
|
|
} catch (err) {
|
|
toast.success('Converted to invoice');
|
|
loadQuotations();
|
|
}
|
|
};
|
|
|
|
const filtered = useMemo(() => {
|
|
const q = query.trim().toLowerCase();
|
|
const from = dateFrom ? new Date(`${dateFrom}T00:00:00`).getTime() : null;
|
|
const to = dateTo ? new Date(`${dateTo}T23:59:59`).getTime() : null;
|
|
const rows = quotes.filter((quote) => {
|
|
if (statusFilter === 'CONVERTED') {
|
|
if (quote.status !== 'CONVERTED' && quote.status !== 'CONVERTED_TO_INVOICE') return false;
|
|
} else if (statusFilter !== 'ALL' && quote.status !== statusFilter) {
|
|
return false;
|
|
}
|
|
const created = new Date(quote.created_at).getTime();
|
|
if (from && !Number.isNaN(created) && created < from) return false;
|
|
if (to && !Number.isNaN(created) && created > to) return false;
|
|
if (!q) return true;
|
|
const haystack = [quote.quote_number, quoteName(quote), quotePhone(quote), quote.customer_email, quoteStatus(quote.status).label]
|
|
.filter(Boolean)
|
|
.join(' ')
|
|
.toLowerCase();
|
|
return haystack.includes(q);
|
|
});
|
|
rows.sort((a, b) => {
|
|
if (sortBy === 'amount') return Number(b.grand_total || 0) - Number(a.grand_total || 0);
|
|
const aTime = new Date(a.created_at).getTime() || 0;
|
|
const bTime = new Date(b.created_at).getTime() || 0;
|
|
return sortBy === 'oldest' ? aTime - bTime : bTime - aTime;
|
|
});
|
|
return rows;
|
|
}, [quotes, query, statusFilter, sortBy, dateFrom, dateTo]);
|
|
|
|
const pager = useClientPagination(filtered);
|
|
|
|
const exportRows = (rows: BulkQuotation[]) => {
|
|
const header = ['Quote', 'Customer', 'Phone', 'Email', 'Status', 'Taxable', 'GST', 'Total', 'Created'];
|
|
const body = rows.map((quote) => [
|
|
quote.quote_number || quote.quote_id,
|
|
quoteName(quote),
|
|
quotePhone(quote),
|
|
quote.customer_email || '',
|
|
quoteStatus(quote.status).label,
|
|
String(quote.subtotal || 0),
|
|
String(quote.tax_amount || 0),
|
|
String(quote.grand_total || 0),
|
|
formatCreated(quote.created_at),
|
|
]);
|
|
const csv = [header, ...body]
|
|
.map((row) => row.map((cell) => `"${String(cell).replaceAll('"', '""')}"`).join(','))
|
|
.join('\n');
|
|
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
|
|
const url = URL.createObjectURL(blob);
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = 'quotations.csv';
|
|
link.click();
|
|
URL.revokeObjectURL(url);
|
|
};
|
|
|
|
const openQuote = (quote: BulkQuotation) => {
|
|
setSelectedQuote(quote);
|
|
setIsDrawerOpen(true);
|
|
};
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5 min-w-0">
|
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
|
<div className="flex items-center gap-2 min-w-0">
|
|
<h1 className="text-lg font-semibold text-foreground">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">
|
|
{filtered.length}
|
|
</span>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<button
|
|
type="button"
|
|
onClick={() => loadQuotations()}
|
|
className="w-9 h-9 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted flex items-center justify-center cursor-pointer"
|
|
title="Reload"
|
|
>
|
|
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
|
|
</button>
|
|
<button type="button" className={secondaryButton} onClick={() => exportRows(filtered)}>
|
|
<Download className="w-3.5 h-3.5" />
|
|
Export
|
|
</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}>
|
|
<div className="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-border">
|
|
<div className="relative flex-1 min-w-[180px] max-w-[320px]">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" />
|
|
<input
|
|
value={query}
|
|
onChange={(event) => setQuery(event.target.value)}
|
|
placeholder="Search"
|
|
className="h-9 w-full pl-9 pr-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary"
|
|
/>
|
|
</div>
|
|
<CustomSelect
|
|
value={sortBy}
|
|
onChange={(value) => setSortBy(value as typeof sortBy)}
|
|
aria-label="Sort quotations"
|
|
className="w-[160px]"
|
|
options={[
|
|
{ value: 'newest', label: 'Newest first' },
|
|
{ value: 'oldest', label: 'Oldest first' },
|
|
{ value: 'amount', label: 'Amount' },
|
|
]}
|
|
/>
|
|
<input type="date" value={dateFrom} onChange={(event) => setDateFrom(event.target.value)} className="h-9 px-3 bg-card border border-border crm-radius-section text-[13px] text-foreground focus:outline-none focus:border-primary" aria-label="From date" />
|
|
<input type="date" value={dateTo} onChange={(event) => setDateTo(event.target.value)} className="h-9 px-3 bg-card border border-border crm-radius-section text-[13px] text-foreground focus:outline-none focus:border-primary" aria-label="To date" />
|
|
<CustomSelect
|
|
value={statusFilter}
|
|
onChange={setStatusFilter}
|
|
aria-label="Quotation status"
|
|
className="w-[180px]"
|
|
options={[
|
|
{ value: 'ALL', label: 'All statuses' },
|
|
...QUOTE_STATUSES.filter((status) => status.value !== 'CONVERTED_TO_INVOICE').map((status) => ({
|
|
value: status.value,
|
|
label: status.label,
|
|
})),
|
|
]}
|
|
/>
|
|
<div className="ml-auto">
|
|
<ViewModeToggle value={viewMode} onChange={setViewMode} />
|
|
</div>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<p className="py-16 text-center text-[13px] text-muted-foreground">Loading quotations</p>
|
|
) : viewMode === 'grid' && filtered.length === 0 ? (
|
|
<p className="py-16 text-center text-[13px] text-muted-foreground">No quotations match this view.</p>
|
|
) : viewMode === 'grid' ? (
|
|
<div className="p-5">
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
|
{pager.items.map((quote) => {
|
|
const meta = quoteStatus(quote.status);
|
|
const name = quoteName(quote);
|
|
return (
|
|
<div key={quote.quote_id} className="crm-radius-section border border-border bg-card p-5 min-w-0 shadow-sm hover:shadow-md transition-shadow">
|
|
<div className="flex items-start gap-3 min-w-0">
|
|
<span className="w-10 h-10 rounded-full bg-primary/10 text-primary text-[12px] font-semibold flex items-center justify-center shrink-0">
|
|
{initials(name === '—' ? quote.quote_number : name)}
|
|
</span>
|
|
<div className="min-w-0">
|
|
<p className="text-[14px] font-semibold text-foreground truncate">{quote.quote_number || quote.quote_id}</p>
|
|
<p className="text-[12px] text-muted-foreground truncate mt-0.5">{name}</p>
|
|
</div>
|
|
</div>
|
|
<div className="mt-4 space-y-1.5 text-[12px] text-muted-foreground">
|
|
<p>Phone: {quotePhone(quote) || '—'}</p>
|
|
<p className="font-semibold text-foreground">{money(quote.grand_total)}</p>
|
|
<p>Created: {formatCreated(quote.created_at)}</p>
|
|
</div>
|
|
<div className="mt-4 flex items-center justify-between gap-2">
|
|
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${meta.className}`}>
|
|
{meta.label}
|
|
</span>
|
|
<div className="flex items-center gap-2">
|
|
<button type="button" onClick={() => openQuote(quote)} className="h-8 px-2.5 crm-radius-control border border-border bg-card text-foreground text-[12px] font-semibold cursor-pointer">
|
|
View
|
|
</button>
|
|
{quote.status !== 'CONVERTED' && quote.status !== 'CONVERTED_TO_INVOICE' && (
|
|
<button type="button" onClick={() => handleConvert(quote.quote_id)} className="h-8 px-2.5 crm-radius-control bg-primary text-white text-[12px] font-semibold cursor-pointer">
|
|
Convert
|
|
</button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<div className="overflow-x-auto">
|
|
<table className="crm-data-table min-w-[860px]">
|
|
<thead>
|
|
<tr className="border-y border-border">
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Quote</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Customer</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Status</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Total</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Created date</th>
|
|
<th className="text-right font-medium text-muted-foreground px-4 py-2.5">Action</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{pager.items.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={6} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No quotations match this view.</td>
|
|
</tr>
|
|
) : pager.items.map((quote) => {
|
|
const meta = quoteStatus(quote.status);
|
|
const name = quoteName(quote);
|
|
return (
|
|
<tr key={quote.quote_id} className="border-b border-border last:border-0">
|
|
<td className="px-4 py-3">
|
|
<div className="flex items-center gap-2.5 min-w-0">
|
|
<span className="w-8 h-8 rounded-full bg-primary/10 text-primary text-[11px] font-semibold flex items-center justify-center shrink-0">
|
|
{initials(name === '—' ? quote.quote_number : name)}
|
|
</span>
|
|
<p className="font-semibold text-foreground truncate">{quote.quote_number || quote.quote_id}</p>
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<p className="font-semibold text-foreground truncate">{name}</p>
|
|
<p className="text-[11px] text-muted-foreground">{quotePhone(quote) || quote.customer_email || '—'}</p>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${meta.className}`}>
|
|
{meta.label}
|
|
</span>
|
|
</td>
|
|
<td className="px-4 py-3 font-semibold text-foreground whitespace-nowrap">{money(quote.grand_total)}</td>
|
|
<td className="px-4 py-3 text-muted-foreground whitespace-nowrap">{formatCreated(quote.created_at)}</td>
|
|
<td className="px-4 py-3 text-right">
|
|
<div className="inline-flex items-center justify-end gap-2">
|
|
<button type="button" onClick={() => openQuote(quote)} className="h-8 px-2.5 crm-radius-control border border-border bg-card text-foreground text-[12px] font-semibold cursor-pointer whitespace-nowrap">
|
|
View
|
|
</button>
|
|
{quote.status !== 'CONVERTED' && quote.status !== 'CONVERTED_TO_INVOICE' ? (
|
|
<button type="button" onClick={() => handleConvert(quote.quote_id)} className="h-8 px-2.5 crm-radius-control bg-primary text-white text-[12px] font-semibold cursor-pointer whitespace-nowrap">
|
|
Convert
|
|
</button>
|
|
) : (
|
|
<span className="text-[12px] text-muted-foreground">Converted</span>
|
|
)}
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
|
|
{/* Main Modal: New Sales Quotation Builder */}
|
|
<SlideOver
|
|
open={isModalOpen}
|
|
onClose={() => setIsModalOpen(false)}
|
|
title="Quotation"
|
|
icon={<FileText className="w-4 h-4 text-primary shrink-0" />}
|
|
>
|
|
<div className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
|
|
|
|
<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="+91 9876543210"
|
|
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="name@email.com"
|
|
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="crm-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>
|
|
</SlideOver>
|
|
|
|
<SlideOver
|
|
open={isProductCatalogOpen}
|
|
onClose={() => setIsProductCatalogOpen(false)}
|
|
title="Add product"
|
|
icon={<FileText className="w-4 h-4 text-primary shrink-0" />}
|
|
>
|
|
<div className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
|
|
|
|
{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>
|
|
</SlideOver>
|
|
|
|
<SlideOver
|
|
open={isRepairServiceOpen}
|
|
onClose={() => setIsRepairServiceOpen(false)}
|
|
title="Add repair"
|
|
icon={<FileText className="w-4 h-4 text-primary shrink-0" />}
|
|
>
|
|
<div className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
|
|
|
|
{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>
|
|
|
|
{/* 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 ${quoteStatus(selectedQuote.status).className}`}>
|
|
{quoteStatus(selectedQuote.status).label}
|
|
</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>
|
|
|
|
{/* Customer Information Card */}
|
|
<div className="p-4 bg-card border border-border rounded-xl 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">{quoteName(selectedQuote)}</p>
|
|
</div>
|
|
<div>
|
|
<span className="text-[11px] text-muted-foreground block">Phone</span>
|
|
<p className="font-semibold text-foreground">{quotePhone(selectedQuote) || '—'}</p>
|
|
</div>
|
|
{selectedQuote.customer_email && (
|
|
<div>
|
|
<span className="text-[11px] text-muted-foreground block">Email</span>
|
|
<p className="text-foreground">{selectedQuote.customer_email}</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 || item.sku || '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 || item.qty || 1) * (item.unit_price || 0)).toLocaleString()}</td>
|
|
</tr>
|
|
))
|
|
) : (
|
|
<tr>
|
|
<td colSpan={4} className="p-6 text-center 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>Taxable value</span>
|
|
<span>{money(selectedQuote.subtotal)}</span>
|
|
</div>
|
|
<div className="flex justify-between text-muted-foreground">
|
|
<span>GST</span>
|
|
<span>{money(selectedQuote.tax_amount)}</span>
|
|
</div>
|
|
<div className="flex justify-between font-semibold text-foreground border-t border-border pt-2">
|
|
<span>Total</span>
|
|
<span>{money(selectedQuote.grand_total)}</span>
|
|
</div>
|
|
</div>
|
|
|
|
{selectedQuote.notes ? (
|
|
<div className="p-4 bg-card border border-border rounded-xl space-y-1 text-[13px] text-muted-foreground">
|
|
<span className="font-semibold text-foreground block">Terms</span>
|
|
<p className="whitespace-pre-wrap">{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: quoteName(selectedQuote),
|
|
customer_phone: quotePhone(selectedQuote),
|
|
customer_email: selectedQuote.customer_email || '',
|
|
company_name: selectedQuote.company_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 && selectedQuote.items.length > 0 ? selectedQuote.items.map((item: any) => ({
|
|
description: item.description || item.part_name || item.sku || 'Item',
|
|
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 || item.qty || 1) * (item.unit_price || 0))
|
|
})) : []
|
|
} : null}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function CrmSalesQuotationsPage() {
|
|
return (
|
|
<Suspense fallback={<div className="p-6 text-center text-muted-foreground">Loading quotations</div>}>
|
|
<CrmSalesQuotationsContent />
|
|
</Suspense>
|
|
);
|
|
}
|