882 lines
39 KiB
TypeScript
882 lines
39 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useMemo, useState, type MouseEvent, type ReactNode } from 'react';
|
|
import { createPortal } from 'react-dom';
|
|
import { useRouter, useSearchParams } from 'next/navigation';
|
|
import { format } from 'date-fns';
|
|
import {
|
|
Download,
|
|
EllipsisVertical,
|
|
Plus,
|
|
RefreshCw,
|
|
Search,
|
|
X,
|
|
} from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
import { crmService, CrmLead } from '@/services/api/crmService';
|
|
import { notificationGatewayService } from '@/services/api/notificationGatewayService';
|
|
import { TablePagination, useClientPagination } from '@/components/ui/TablePagination';
|
|
import { CustomSelect } from '@/components/ui/CustomSelect';
|
|
import { ViewModeToggle } from '@/components/ui/ViewModeToggle';
|
|
|
|
const STATUSES = ['NEW', 'CONTACTED', 'QUALIFIED', 'QUOTE_DRAFT', 'QUOTE_SENT', 'CONVERTED', 'LOST'] as const;
|
|
|
|
const STATUS_META: Record<string, { label: string; className: string }> = {
|
|
NEW: { label: 'Not contacted', className: 'bg-primary/10 text-primary' },
|
|
CONTACTED: { label: 'Contacted', className: 'bg-warning/15 text-warning' },
|
|
QUALIFIED: { label: 'Qualified', className: 'bg-success/10 text-success' },
|
|
QUOTE_DRAFT: { label: 'Quote draft', className: 'bg-muted text-foreground' },
|
|
QUOTE_SENT: { label: 'Quote sent', className: 'bg-primary/10 text-primary' },
|
|
CONVERTED: { label: 'Closed', className: 'bg-success/15 text-success' },
|
|
LOST: { label: 'Lost', className: 'bg-destructive/10 text-destructive' },
|
|
};
|
|
|
|
const LOSS_REASONS = [
|
|
'Spam / Not Genuine Inquiry',
|
|
'Budget Mismatch',
|
|
'Competitor Chosen',
|
|
'Customer Unresponsive',
|
|
];
|
|
|
|
const shell =
|
|
'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0';
|
|
const field =
|
|
'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-2 h-9 px-4 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-2 h-9 px-3 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50';
|
|
|
|
function WhatsAppIcon({ className }: { className?: string }) {
|
|
return (
|
|
<svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
|
|
<path d="M12.04 2C6.58 2 2.15 6.4 2.15 11.83c0 1.74.46 3.44 1.34 4.94L2 22l5.39-1.41a10.1 10.1 0 0 0 4.65 1.15h.01c5.46 0 9.89-4.4 9.89-9.83C21.94 6.4 17.5 2 12.04 2zm5.76 13.89c-.24.68-1.4 1.3-1.94 1.38-.5.08-1.12.11-1.81-.11-.41-.14-.95-.31-1.64-.61-2.89-1.25-4.77-4.16-4.91-4.35-.14-.19-1.16-1.54-1.16-2.94s.73-2.08 1-2.37c.24-.27.64-.39 1.02-.39.12 0 .23 0 .33.01.3.01.45-.03.69.53.24.6.84 2.06.91 2.21.08.15.13.33.03.53-.1.2-.15.33-.3.51-.15.18-.31.4-.44.53-.15.15-.3.31-.13.61.17.3.76 1.25 1.63 2.03 1.12 1 2.06 1.31 2.36 1.46.3.15.47.13.65-.08.18-.2.74-.86.94-1.16.2-.3.4-.24.67-.14.27.1 1.72.81 2.01.96.3.15.49.22.56.34.08.13.08.73-.16 1.41z" />
|
|
</svg>
|
|
);
|
|
}
|
|
|
|
function leadName(lead: CrmLead) {
|
|
const named = [lead.first_name, lead.last_name].filter(Boolean).join(' ').trim();
|
|
return lead.title || named || 'Unnamed lead';
|
|
}
|
|
|
|
function initials(name: string) {
|
|
const parts = name.split(/\s+/).filter(Boolean);
|
|
return ((parts[0]?.[0] || '') + (parts[1]?.[0] || '')).toUpperCase() || 'L';
|
|
}
|
|
|
|
function statusLabel(status: string) {
|
|
return STATUS_META[status]?.label || status.replaceAll('_', ' ').toLowerCase();
|
|
}
|
|
|
|
function formatCreated(iso: string) {
|
|
const date = new Date(iso);
|
|
if (Number.isNaN(date.getTime())) return '—';
|
|
return format(date, 'dd MMM yyyy, hh:mm a');
|
|
}
|
|
|
|
function quoteSummary(lead: CrmLead) {
|
|
const amount = Number(lead.quote_amount);
|
|
const hasAmount = Number.isFinite(amount) && amount > 0;
|
|
if (!hasAmount && !lead.quote_title && !lead.quote_terms) return null;
|
|
return {
|
|
amount: hasAmount ? `₹${amount.toLocaleString('en-IN')}` : '',
|
|
title: lead.quote_title || '',
|
|
terms: lead.quote_terms || '',
|
|
};
|
|
}
|
|
|
|
function sourceLabel(source?: string) {
|
|
if (!source) return '—';
|
|
return source
|
|
.toLowerCase()
|
|
.split('_')
|
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
.join(' ');
|
|
}
|
|
|
|
function QuoteLines({ lead }: { lead: CrmLead }) {
|
|
const quote = quoteSummary(lead);
|
|
if (!quote) return null;
|
|
return (
|
|
<div className="space-y-0.5 text-[12px] text-muted-foreground">
|
|
{quote.amount && <p className="font-semibold text-foreground">{quote.amount}</p>}
|
|
{quote.title && <p className="truncate">{quote.title}</p>}
|
|
{quote.terms && <p className="line-clamp-2">Terms: {quote.terms}</p>}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
export default function LeadsWorkspace() {
|
|
const router = useRouter();
|
|
const searchParams = useSearchParams();
|
|
const [leads, setLeads] = useState<CrmLead[]>([]);
|
|
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' | 'name'>('newest');
|
|
const [dateFrom, setDateFrom] = useState('');
|
|
const [dateTo, setDateTo] = useState('');
|
|
const [selected, setSelected] = useState<string[]>([]);
|
|
const [bulkBusy, setBulkBusy] = useState(false);
|
|
const [bulkLostOpen, setBulkLostOpen] = useState(false);
|
|
const [menu, setMenu] = useState<{ id: string; top: number; right: number } | null>(null);
|
|
const [showAdd, setShowAdd] = useState(false);
|
|
const [creating, setCreating] = useState(false);
|
|
const [draft, setDraft] = useState({ title: '', phone: '', email: '', source: 'STOREFRONT' });
|
|
const [convertTarget, setConvertTarget] = useState<CrmLead | null>(null);
|
|
const [convertCategory, setConvertCategory] = useState<'ECOMMERCE' | 'SERVICE' | 'BOTH'>('BOTH');
|
|
const [dealTitle, setDealTitle] = useState('');
|
|
const [estimatedValue, setEstimatedValue] = useState(0);
|
|
const [converting, setConverting] = useState(false);
|
|
const [lostTarget, setLostTarget] = useState<CrmLead | null>(null);
|
|
const [lossReason, setLossReason] = useState(LOSS_REASONS[0]);
|
|
const [markingLost, setMarkingLost] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const requested = (searchParams.get('status') || '').toUpperCase();
|
|
if (requested && (requested === 'ALL' || requested in STATUS_META)) {
|
|
setStatusFilter(requested);
|
|
}
|
|
}, [searchParams]);
|
|
|
|
useEffect(() => {
|
|
loadLeads();
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!menu) return;
|
|
const close = () => setMenu(null);
|
|
window.addEventListener('click', close);
|
|
return () => window.removeEventListener('click', close);
|
|
}, [menu]);
|
|
|
|
const loadLeads = async () => {
|
|
try {
|
|
setLoading(true);
|
|
const groups = await Promise.all(
|
|
STATUSES.map(async (status) => {
|
|
try {
|
|
const rows = await crmService.getLeads(status);
|
|
return Array.isArray(rows) ? rows : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
})
|
|
);
|
|
const merged = new Map<string, CrmLead>();
|
|
groups.flat().forEach((lead) => {
|
|
if (lead?.lead_id) merged.set(lead.lead_id, lead);
|
|
});
|
|
setLeads([...merged.values()]);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
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 = leads.filter((lead) => {
|
|
if (statusFilter !== 'ALL' && lead.status !== statusFilter) return false;
|
|
const created = new Date(lead.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 = [leadName(lead), lead.email, lead.phone, lead.source, statusLabel(lead.status)]
|
|
.filter(Boolean)
|
|
.join(' ')
|
|
.toLowerCase();
|
|
return haystack.includes(q);
|
|
});
|
|
rows.sort((a, b) => {
|
|
if (sortBy === 'name') return leadName(a).localeCompare(leadName(b));
|
|
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;
|
|
}, [leads, query, statusFilter, sortBy, dateFrom, dateTo]);
|
|
|
|
const pager = useClientPagination(filtered);
|
|
|
|
const toggleSelected = (leadId: string) => {
|
|
setSelected((current) => (current.includes(leadId) ? current.filter((id) => id !== leadId) : [...current, leadId]));
|
|
};
|
|
|
|
const pageIds = pager.items.map((lead) => lead.lead_id);
|
|
const allPageSelected = pageIds.length > 0 && pageIds.every((id) => selected.includes(id));
|
|
|
|
const exportRows = (rows: CrmLead[]) => {
|
|
const header = ['Lead', 'Phone', 'Email', 'Status', 'Source', 'Created'];
|
|
const body = rows.map((lead) => [
|
|
leadName(lead),
|
|
lead.phone || '',
|
|
lead.email || '',
|
|
statusLabel(lead.status),
|
|
sourceLabel(lead.source),
|
|
formatCreated(lead.created_at),
|
|
]);
|
|
const csv = [header, ...body]
|
|
.map((line) => line.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 = 'leads.csv';
|
|
link.click();
|
|
URL.revokeObjectURL(url);
|
|
};
|
|
|
|
const changeStatus = async (lead: CrmLead, status: string, notes?: string) => {
|
|
try {
|
|
await crmService.updateLeadStatus(lead.lead_id, status, notes);
|
|
toast.success(`${leadName(lead)} marked ${statusLabel(status).toLowerCase()}`);
|
|
setMenu(null);
|
|
await loadLeads();
|
|
} catch {
|
|
toast.error('Could not update this lead');
|
|
}
|
|
};
|
|
|
|
const resendQuote = async (lead: CrmLead, channel: 'WHATSAPP' | 'EMAIL') => {
|
|
try {
|
|
const entityId = lead.quote_title?.match(/SQ-202\d-\d{3}/)?.[0] || lead.lead_id;
|
|
toast.loading(`Sending quotation by ${channel.toLowerCase()}...`, { id: 'resend' });
|
|
await notificationGatewayService.dispatchEntity({
|
|
channel,
|
|
notification_type: 'QUOTATION',
|
|
entity_id: entityId,
|
|
idempotency_key: `QUOTATION:${entityId}:${channel}:${Date.now()}`,
|
|
});
|
|
toast.success(`Quotation sent by ${channel.toLowerCase()}`, { id: 'resend' });
|
|
} catch {
|
|
toast.error('Could not send the quotation', { id: 'resend' });
|
|
}
|
|
};
|
|
|
|
const openQuotation = (lead: CrmLead, mode: 'send' | 'draft' = 'send') => {
|
|
const query = new URLSearchParams({
|
|
lead_id: lead.lead_id,
|
|
customer_name: leadName(lead),
|
|
name: leadName(lead),
|
|
phone: lead.phone || '',
|
|
email: lead.email || '',
|
|
mode,
|
|
});
|
|
if (lead.quote_title) query.set('quote_title', lead.quote_title);
|
|
if (lead.quote_terms) query.set('quote_terms', lead.quote_terms);
|
|
router.push(`/crm-quotations?${query.toString()}`);
|
|
};
|
|
|
|
const openWhatsApp = (lead: CrmLead) => {
|
|
const phone = (lead.phone || '').replace(/\D/g, '');
|
|
if (!phone) return;
|
|
router.push(`/whatsapp-web?phone=${phone}&name=${encodeURIComponent(leadName(lead))}`);
|
|
};
|
|
|
|
const createLead = async (event: React.FormEvent) => {
|
|
event.preventDefault();
|
|
try {
|
|
setCreating(true);
|
|
await crmService.createLead(draft);
|
|
toast.success('Lead added');
|
|
setShowAdd(false);
|
|
setDraft({ title: '', phone: '', email: '', source: 'STOREFRONT' });
|
|
await loadLeads();
|
|
} catch (err: unknown) {
|
|
toast.error(err instanceof Error ? err.message : 'Could not add the lead');
|
|
} finally {
|
|
setCreating(false);
|
|
}
|
|
};
|
|
|
|
const convertLead = async () => {
|
|
if (!convertTarget) return;
|
|
try {
|
|
setConverting(true);
|
|
const res = await crmService.convertLead(convertTarget.lead_id, {
|
|
category: convertCategory,
|
|
deal_title: dealTitle,
|
|
estimated_value: Number(estimatedValue) || 0,
|
|
customer_phone: convertTarget.phone,
|
|
customer_email: convertTarget.email || undefined,
|
|
customer_name: leadName(convertTarget),
|
|
notes: convertTarget.notes,
|
|
});
|
|
if (res.is_dual_customer) {
|
|
toast.success('Lead converted. This customer is in both store and repair.');
|
|
} else {
|
|
toast.success('Lead converted to a customer and deal');
|
|
}
|
|
setConvertTarget(null);
|
|
setStatusFilter('CONVERTED');
|
|
await loadLeads();
|
|
} catch {
|
|
toast.error('Could not convert this lead');
|
|
} finally {
|
|
setConverting(false);
|
|
}
|
|
};
|
|
|
|
const markLost = async () => {
|
|
if (!lostTarget) return;
|
|
try {
|
|
setMarkingLost(true);
|
|
await crmService.updateLeadStatus(lostTarget.lead_id, 'LOST', `Lead marked as lost. Reason: ${lossReason}`);
|
|
toast.success('Lead marked lost');
|
|
setLostTarget(null);
|
|
await loadLeads();
|
|
} catch {
|
|
toast.error('Could not update this lead');
|
|
} finally {
|
|
setMarkingLost(false);
|
|
}
|
|
};
|
|
|
|
const selectedLeads = filtered.filter((lead) => selected.includes(lead.lead_id));
|
|
|
|
const applyBulkStatus = async (status: string, notes?: string) => {
|
|
const targets = selectedLeads.filter((lead) => lead.status !== 'CONVERTED');
|
|
if (targets.length === 0) {
|
|
toast.error('Closed leads stay closed');
|
|
return;
|
|
}
|
|
try {
|
|
setBulkBusy(true);
|
|
await Promise.all(targets.map((lead) => crmService.updateLeadStatus(lead.lead_id, status, notes)));
|
|
toast.success(`Updated ${targets.length} lead${targets.length === 1 ? '' : 's'}`);
|
|
setSelected([]);
|
|
setBulkLostOpen(false);
|
|
await loadLeads();
|
|
} catch {
|
|
toast.error('Could not update the selected leads');
|
|
} finally {
|
|
setBulkBusy(false);
|
|
}
|
|
};
|
|
|
|
const actionsFor = (lead: CrmLead) => {
|
|
const items: Array<{ label: string; onClick: () => void }> = [];
|
|
const digits = (lead.phone || '').replace(/\D/g, '');
|
|
if (digits) {
|
|
items.push({ label: 'WhatsApp Web', onClick: () => openWhatsApp(lead) });
|
|
items.push({
|
|
label: 'WhatsApp chat',
|
|
onClick: () => window.open(`https://wa.me/${digits}`, '_blank', 'noopener,noreferrer'),
|
|
});
|
|
}
|
|
if (lead.status === 'NEW') items.push({ label: 'Mark contacted', onClick: () => changeStatus(lead, 'CONTACTED') });
|
|
if (lead.status === 'CONTACTED') items.push({ label: 'Mark qualified', onClick: () => changeStatus(lead, 'QUALIFIED') });
|
|
if (lead.status === 'QUALIFIED' || lead.status === 'QUOTE_DRAFT') {
|
|
items.push({ label: 'Send quote', onClick: () => openQuotation(lead, 'send') });
|
|
items.push({ label: 'Mark lost', onClick: () => { setLostTarget(lead); setMenu(null); } });
|
|
}
|
|
if (lead.status === 'QUALIFIED') {
|
|
items.push({ label: 'Save draft', onClick: () => openQuotation(lead, 'draft') });
|
|
}
|
|
if (lead.status === 'QUOTE_SENT') {
|
|
items.push({ label: 'Resend on WhatsApp', onClick: () => resendQuote(lead, 'WHATSAPP') });
|
|
items.push({ label: 'Resend by email', onClick: () => resendQuote(lead, 'EMAIL') });
|
|
items.push({
|
|
label: 'Quote declined',
|
|
onClick: () => changeStatus(lead, 'QUALIFIED', 'Customer rejected quotation offer. Reverted back to Qualified.'),
|
|
});
|
|
items.push({
|
|
label: 'Convert lead',
|
|
onClick: () => {
|
|
setConvertTarget(lead);
|
|
setConvertCategory('BOTH');
|
|
setDealTitle(lead.quote_title || leadName(lead));
|
|
setEstimatedValue(Number(lead.quote_amount) || 15000);
|
|
setMenu(null);
|
|
},
|
|
});
|
|
}
|
|
if (lead.status === 'CONVERTED') {
|
|
items.push({ label: 'View customers', onClick: () => router.push('/customers') });
|
|
items.push({ label: 'View deals', onClick: () => router.push('/crm-deals') });
|
|
}
|
|
if (lead.status === 'LOST') items.push({ label: 'Reopen', onClick: () => changeStatus(lead, 'NEW') });
|
|
return items;
|
|
};
|
|
|
|
const primaryStep = (lead: CrmLead) => {
|
|
if (lead.status === 'NEW') return { label: 'Mark contacted', onClick: () => changeStatus(lead, 'CONTACTED') };
|
|
if (lead.status === 'CONTACTED') return { label: 'Mark qualified', onClick: () => changeStatus(lead, 'QUALIFIED') };
|
|
if (lead.status === 'QUOTE_SENT') {
|
|
return {
|
|
label: 'Convert',
|
|
onClick: () => {
|
|
setConvertTarget(lead);
|
|
setConvertCategory('BOTH');
|
|
setDealTitle(lead.quote_title || leadName(lead));
|
|
setEstimatedValue(Number(lead.quote_amount) || 15000);
|
|
},
|
|
};
|
|
}
|
|
return null;
|
|
};
|
|
|
|
const renderStageButtons = (lead: CrmLead) => {
|
|
const step = primaryStep(lead);
|
|
if (!step) return null;
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={step.onClick}
|
|
className="h-8 px-2.5 crm-radius-control bg-primary text-white text-[12px] font-semibold cursor-pointer whitespace-nowrap"
|
|
>
|
|
{step.label}
|
|
</button>
|
|
);
|
|
};
|
|
|
|
const openLeadMenu = (leadId: string, event: MouseEvent<HTMLButtonElement>) => {
|
|
event.stopPropagation();
|
|
const rect = event.currentTarget.getBoundingClientRect();
|
|
setMenu((current) =>
|
|
current?.id === leadId
|
|
? null
|
|
: { id: leadId, top: rect.bottom + 4, right: Math.max(8, window.innerWidth - rect.right) }
|
|
);
|
|
};
|
|
|
|
const renderLeadMenu = (lead: CrmLead) => {
|
|
const actions = actionsFor(lead);
|
|
return (
|
|
<>
|
|
<button
|
|
type="button"
|
|
className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted inline-flex items-center justify-center cursor-pointer"
|
|
aria-label={`Actions for ${leadName(lead)}`}
|
|
onClick={(event) => openLeadMenu(lead.lead_id, event)}
|
|
>
|
|
<EllipsisVertical className="w-4 h-4" />
|
|
</button>
|
|
{menu?.id === lead.lead_id && actions.length > 0 && createPortal(
|
|
<div
|
|
className="fixed z-50 inline-flex flex-col items-stretch w-max rounded-lg border border-border bg-card shadow-md py-1 text-left"
|
|
style={{ top: menu.top, right: menu.right }}
|
|
onClick={(event) => event.stopPropagation()}
|
|
>
|
|
{actions.map((action) => (
|
|
<button
|
|
key={action.label}
|
|
type="button"
|
|
className="whitespace-nowrap px-3 py-2 text-[13px] text-foreground hover:bg-muted text-left cursor-pointer"
|
|
onClick={action.onClick}
|
|
>
|
|
{action.label}
|
|
</button>
|
|
))}
|
|
</div>,
|
|
document.body
|
|
)}
|
|
</>
|
|
);
|
|
};
|
|
|
|
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">Leads</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={() => loadLeads()} 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(selected.length ? leads.filter((lead) => selected.includes(lead.lead_id)) : filtered)}
|
|
>
|
|
<Download className="w-3.5 h-3.5" />
|
|
{selected.length ? `Export (${selected.length})` : 'Export'}
|
|
</button>
|
|
<button type="button" className={primaryButton} onClick={() => setShowAdd(true)}>
|
|
<Plus className="w-3.5 h-3.5" />
|
|
Add Lead
|
|
</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={`${field} w-full pl-9`}
|
|
/>
|
|
</div>
|
|
<CustomSelect
|
|
value={sortBy}
|
|
onChange={(value) => setSortBy(value as typeof sortBy)}
|
|
aria-label="Sort leads"
|
|
className="w-[160px]"
|
|
options={[
|
|
{ value: 'newest', label: 'Newest first' },
|
|
{ value: 'oldest', label: 'Oldest first' },
|
|
{ value: 'name', label: 'Name' },
|
|
]}
|
|
/>
|
|
<input type="date" value={dateFrom} onChange={(event) => setDateFrom(event.target.value)} className={`${field} crm-radius-section`} aria-label="From date" />
|
|
<input type="date" value={dateTo} onChange={(event) => setDateTo(event.target.value)} className={`${field} crm-radius-section`} aria-label="To date" />
|
|
<CustomSelect
|
|
value={statusFilter}
|
|
onChange={setStatusFilter}
|
|
aria-label="Lead status"
|
|
className="w-[180px]"
|
|
options={[
|
|
{ value: 'ALL', label: 'All statuses' },
|
|
...STATUSES.map((status) => ({ value: status, label: statusLabel(status) })),
|
|
]}
|
|
/>
|
|
<div className="ml-auto">
|
|
<ViewModeToggle
|
|
value={viewMode}
|
|
onChange={(mode) => {
|
|
setViewMode(mode);
|
|
setMenu(null);
|
|
}}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{selected.length > 0 && (
|
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 px-4 py-2.5 border-b border-border bg-primary/5">
|
|
<p className="text-[13px] font-semibold text-foreground">{selected.length} selected</p>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
<button type="button" className={secondaryButton} disabled={bulkBusy} onClick={() => exportRows(selectedLeads)}>
|
|
<Download className="w-3.5 h-3.5" />
|
|
Export selected
|
|
</button>
|
|
<button type="button" className={secondaryButton} disabled={bulkBusy} onClick={() => applyBulkStatus('CONTACTED')}>
|
|
Mark contacted
|
|
</button>
|
|
<button type="button" className={secondaryButton} disabled={bulkBusy} onClick={() => applyBulkStatus('QUALIFIED')}>
|
|
Mark qualified
|
|
</button>
|
|
<button type="button" className={secondaryButton} disabled={bulkBusy} onClick={() => setBulkLostOpen(true)}>
|
|
Mark lost
|
|
</button>
|
|
<button type="button" className={secondaryButton} disabled={bulkBusy} onClick={() => setSelected([])}>
|
|
Clear
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{loading ? (
|
|
<p className="py-16 text-center text-[13px] text-muted-foreground">Loading leads...</p>
|
|
) : viewMode === 'grid' && filtered.length === 0 ? (
|
|
<p className="py-16 text-center text-[13px] text-muted-foreground">No leads 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((lead) => {
|
|
const name = leadName(lead);
|
|
const meta = STATUS_META[lead.status] || { label: statusLabel(lead.status), className: 'bg-muted text-foreground' };
|
|
return (
|
|
<div
|
|
key={lead.lead_id}
|
|
className={`relative crm-radius-section border bg-card p-5 min-w-0 shadow-sm hover:shadow-md transition-shadow ${selected.includes(lead.lead_id) ? 'border-primary bg-primary/5' : 'border-border'}`}
|
|
>
|
|
<div className="absolute top-4 right-4 z-10">{renderLeadMenu(lead)}</div>
|
|
<div className="flex items-start gap-3 pr-8 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)}
|
|
</span>
|
|
<div className="min-w-0">
|
|
<p className="text-[14px] font-semibold text-foreground truncate">{name}</p>
|
|
<p className="text-[12px] text-muted-foreground truncate mt-0.5">{lead.email || 'No email'}</p>
|
|
</div>
|
|
</div>
|
|
<div className="mt-4 space-y-1.5 text-[12px] text-muted-foreground">
|
|
<div className="flex items-center gap-2">
|
|
<span>Phone: {crmService.formatPhoneDisplay(lead.phone)}</span>
|
|
{lead.phone && (
|
|
<button
|
|
type="button"
|
|
onClick={() => openWhatsApp(lead)}
|
|
aria-label="WhatsApp"
|
|
title="WhatsApp"
|
|
className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-[#25D366] text-white cursor-pointer"
|
|
>
|
|
<WhatsAppIcon className="w-3.5 h-3.5" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
<p>Source: {sourceLabel(lead.source)}</p>
|
|
<p>Created: {formatCreated(lead.created_at)}</p>
|
|
<QuoteLines lead={lead} />
|
|
</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">
|
|
{renderStageButtons(lead)}
|
|
<input
|
|
type="checkbox"
|
|
checked={selected.includes(lead.lead_id)}
|
|
onChange={() => toggleSelected(lead.lead_id)}
|
|
aria-label={`Select ${name}`}
|
|
className="w-3.5 h-3.5 rounded-[3px] border-border text-primary cursor-pointer"
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<div className="overflow-x-auto">
|
|
<table className="crm-data-table min-w-[1040px]">
|
|
<thead>
|
|
<tr className="border-y border-border">
|
|
<th className="px-4 py-2.5 w-10">
|
|
<input
|
|
type="checkbox"
|
|
checked={allPageSelected}
|
|
onChange={() => {
|
|
setSelected((current) =>
|
|
allPageSelected
|
|
? current.filter((id) => !pageIds.includes(id))
|
|
: [...new Set([...current, ...pageIds])]
|
|
);
|
|
}}
|
|
aria-label="Select leads on this page"
|
|
/>
|
|
</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Lead name</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Phone</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Lead status</th>
|
|
<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">Source</th>
|
|
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Created date</th>
|
|
<th className="w-px whitespace-nowrap text-center font-medium text-muted-foreground px-3 py-2.5">Action</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{pager.items.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={8} className="px-4 py-16 text-center text-[13px] text-muted-foreground whitespace-normal">No leads match this view.</td>
|
|
</tr>
|
|
) : pager.items.map((lead) => {
|
|
const name = leadName(lead);
|
|
const meta = STATUS_META[lead.status] || { label: statusLabel(lead.status), className: 'bg-muted text-foreground' };
|
|
return (
|
|
<tr key={lead.lead_id} className={`border-b border-border last:border-0 ${selected.includes(lead.lead_id) ? 'bg-primary/5' : ''}`}>
|
|
<td className="px-4 py-3">
|
|
<input
|
|
type="checkbox"
|
|
checked={selected.includes(lead.lead_id)}
|
|
onChange={() => toggleSelected(lead.lead_id)}
|
|
aria-label={`Select ${name}`}
|
|
/>
|
|
</td>
|
|
<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)}
|
|
</span>
|
|
<div className="min-w-0">
|
|
<p className="font-semibold text-foreground truncate">{name}</p>
|
|
<p className="text-[11px] text-muted-foreground truncate">{lead.email || 'No email'}</p>
|
|
</div>
|
|
</div>
|
|
</td>
|
|
<td className="px-4 py-3">
|
|
<div className="flex items-center gap-2">
|
|
<span className="text-foreground">{crmService.formatPhoneDisplay(lead.phone)}</span>
|
|
{lead.phone && (
|
|
<button
|
|
type="button"
|
|
onClick={() => openWhatsApp(lead)}
|
|
aria-label="WhatsApp"
|
|
title="WhatsApp"
|
|
className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-[#25D366] text-white cursor-pointer"
|
|
>
|
|
<WhatsAppIcon className="w-3.5 h-3.5" />
|
|
</button>
|
|
)}
|
|
</div>
|
|
</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 min-w-[140px]"><QuoteLines lead={lead} /></td>
|
|
<td className="px-4 py-3 text-muted-foreground">{sourceLabel(lead.source)}</td>
|
|
<td className="px-4 py-3 text-muted-foreground whitespace-nowrap">{formatCreated(lead.created_at)}</td>
|
|
<td className="w-px whitespace-nowrap px-3 py-3 text-center">
|
|
<div className="inline-flex items-center justify-center gap-2">
|
|
{renderStageButtons(lead)}
|
|
{renderLeadMenu(lead)}
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
);
|
|
})}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
|
|
<Modal open={showAdd} title="Add lead" onClose={() => setShowAdd(false)}>
|
|
<form onSubmit={createLead} className="space-y-3">
|
|
<Field label="Lead name">
|
|
<input required value={draft.title} onChange={(event) => setDraft({ ...draft, title: event.target.value })} className={`${field} w-full`} />
|
|
</Field>
|
|
<Field label="Phone">
|
|
<input required value={draft.phone} onChange={(event) => setDraft({ ...draft, phone: event.target.value })} placeholder="+91 9876543210" className={`${field} w-full`} />
|
|
</Field>
|
|
<Field label="Email">
|
|
<input type="email" value={draft.email} onChange={(event) => setDraft({ ...draft, email: event.target.value })} className={`${field} w-full`} />
|
|
</Field>
|
|
<Field label="Source">
|
|
<CustomSelect
|
|
value={draft.source}
|
|
onChange={(value) => setDraft({ ...draft, source: value })}
|
|
aria-label="Lead source"
|
|
options={[
|
|
{ value: 'STOREFRONT', label: 'Storefront' },
|
|
{ value: 'WHATSAPP', label: 'WhatsApp' },
|
|
{ value: 'WALK_IN', label: 'Walk-in' },
|
|
{ value: 'PHONE', label: 'Phone' },
|
|
]}
|
|
/>
|
|
</Field>
|
|
<div className="flex justify-end gap-2 pt-2">
|
|
<button type="button" className={secondaryButton} onClick={() => setShowAdd(false)}>Cancel</button>
|
|
<button type="submit" className={primaryButton} disabled={creating}>{creating ? 'Saving...' : 'Save lead'}</button>
|
|
</div>
|
|
</form>
|
|
</Modal>
|
|
|
|
<Modal open={convertTarget !== null} title="Convert lead" onClose={() => setConvertTarget(null)}>
|
|
{convertTarget && <div className="space-y-3">
|
|
<p className="text-[13px] text-muted-foreground">
|
|
{leadName(convertTarget)} · {crmService.formatPhoneDisplay(convertTarget.phone)}
|
|
</p>
|
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
|
{([
|
|
['ECOMMERCE', 'Store customer'],
|
|
['SERVICE', 'Repair customer'],
|
|
['BOTH', 'Both'],
|
|
] as const).map(([value, label]) => (
|
|
<button
|
|
key={value}
|
|
type="button"
|
|
onClick={() => setConvertCategory(value)}
|
|
className={`h-9 px-2 crm-radius-control border text-[13px] font-medium cursor-pointer ${
|
|
convertCategory === value ? 'border-primary bg-primary/10 text-primary' : 'border-border text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
{label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
<Field label="Deal title">
|
|
<input value={dealTitle} onChange={(event) => setDealTitle(event.target.value)} className={`${field} w-full`} />
|
|
</Field>
|
|
<Field label="Agreed amount (₹)">
|
|
<input type="number" value={estimatedValue} onChange={(event) => setEstimatedValue(Number(event.target.value))} className={`${field} w-full`} />
|
|
</Field>
|
|
<div className="flex justify-end gap-2 pt-2">
|
|
<button type="button" className={secondaryButton} onClick={() => setConvertTarget(null)}>Cancel</button>
|
|
<button type="button" className={primaryButton} disabled={converting} onClick={convertLead}>
|
|
{converting ? 'Saving...' : 'Convert'}
|
|
</button>
|
|
</div>
|
|
</div>}
|
|
</Modal>
|
|
|
|
<Modal open={bulkLostOpen} title="Mark selected leads lost" onClose={() => setBulkLostOpen(false)}>
|
|
<div className="space-y-3">
|
|
<p className="text-[13px] text-muted-foreground">{selected.length} lead{selected.length === 1 ? '' : 's'} selected. Closed leads stay closed.</p>
|
|
<Field label="Reason">
|
|
<CustomSelect
|
|
value={lossReason}
|
|
onChange={setLossReason}
|
|
aria-label="Loss reason"
|
|
options={LOSS_REASONS.map((reason) => ({ value: reason, label: reason }))}
|
|
/>
|
|
</Field>
|
|
<div className="flex justify-end gap-2 pt-2">
|
|
<button type="button" className={secondaryButton} onClick={() => setBulkLostOpen(false)}>Cancel</button>
|
|
<button
|
|
type="button"
|
|
className={primaryButton}
|
|
disabled={bulkBusy}
|
|
onClick={() => applyBulkStatus('LOST', `Lead marked as lost. Reason: ${lossReason}`)}
|
|
>
|
|
{bulkBusy ? 'Saving...' : 'Mark lost'}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</Modal>
|
|
|
|
<Modal open={lostTarget !== null} title="Mark lead lost" onClose={() => setLostTarget(null)}>
|
|
{lostTarget && <div className="space-y-3">
|
|
<p className="text-[13px] text-muted-foreground">{leadName(lostTarget)}</p>
|
|
<Field label="Reason">
|
|
<CustomSelect
|
|
value={lossReason}
|
|
onChange={setLossReason}
|
|
aria-label="Loss reason"
|
|
options={LOSS_REASONS.map((reason) => ({ value: reason, label: reason }))}
|
|
/>
|
|
</Field>
|
|
<div className="flex justify-end gap-2 pt-2">
|
|
<button type="button" className={secondaryButton} onClick={() => setLostTarget(null)}>Cancel</button>
|
|
<button type="button" className={primaryButton} disabled={markingLost} onClick={markLost}>
|
|
{markingLost ? 'Saving...' : 'Mark lost'}
|
|
</button>
|
|
</div>
|
|
</div>}
|
|
</Modal>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function Field({ label, children }: { label: string; children: ReactNode }) {
|
|
return (
|
|
<label className="block">
|
|
<span className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">{label}</span>
|
|
{children}
|
|
</label>
|
|
);
|
|
}
|
|
|
|
function Modal({ open, title, onClose, children }: { open: boolean; title: string; onClose: () => void; children: ReactNode }) {
|
|
if (!open) return null;
|
|
return (
|
|
<div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
|
|
<div className="bg-card border border-border crm-radius-section shadow-xl w-full max-w-lg p-5">
|
|
<div className="flex items-center justify-between mb-4">
|
|
<h2 className="text-base font-semibold text-foreground">{title}</h2>
|
|
<button type="button" onClick={onClose} className="text-muted-foreground hover:text-foreground cursor-pointer" aria-label="Close">
|
|
<X className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
{children}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|