ifixkart-admin/app/(admin)/crm-deals/page.tsx

412 lines
18 KiB
TypeScript

'use client';
import { useEffect, useMemo, useState, type ReactNode } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { Download, Plus, RefreshCw, Search, X } from 'lucide-react';
import { toast } from 'sonner';
import { crmService, CrmDeal } from '@/services/api/crmService';
import { TablePagination, useClientPagination } from '@/components/ui/TablePagination';
import { CustomSelect } from '@/components/ui/CustomSelect';
import { ViewModeToggle } from '@/components/ui/ViewModeToggle';
const STAGES = [
{ value: 'NEW', label: 'New', className: 'bg-primary/10 text-primary' },
{ value: 'CONTACTED', label: 'Contacted', className: 'bg-warning/15 text-warning' },
{ value: 'PROPOSAL_SENT', label: 'Proposal sent', className: 'bg-primary/10 text-primary' },
{ value: 'NEGOTIATING', label: 'Negotiating', className: 'bg-warning/15 text-warning' },
{ value: 'CLOSED_WON', label: 'Closed won', className: 'bg-success/15 text-success' },
{ value: 'CLOSED_LOST', label: 'Closed lost', className: 'bg-destructive/10 text-destructive' },
] as const;
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 stageMeta(stage: string) {
return STAGES.find((item) => item.value === stage) || {
value: stage,
label: stage.replaceAll('_', ' ').toLowerCase().replace(/^\w/, (letter) => letter.toUpperCase()),
className: 'bg-muted text-foreground',
};
}
function dealValue(deal: CrmDeal) {
const amount = Number(deal.value ?? deal.estimated_value ?? 0);
return Number.isFinite(amount) ? amount : 0;
}
function money(amount: number) {
return `₹${amount.toLocaleString('en-IN')}`;
}
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 formatDay(iso?: string) {
if (!iso) return '';
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return '';
return format(date, 'dd MMM yyyy');
}
function initials(name: string) {
const parts = name.split(/\s+/).filter(Boolean);
return ((parts[0]?.[0] || '') + (parts[1]?.[0] || '')).toUpperCase() || 'D';
}
export default function CrmDealsPage() {
const router = useRouter();
const [deals, setDeals] = useState<CrmDeal[]>([]);
const [loading, setLoading] = useState(true);
const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
const [query, setQuery] = useState('');
const [stageFilter, setStageFilter] = useState('ALL');
const [sortBy, setSortBy] = useState<'newest' | 'oldest' | 'name' | 'value'>('newest');
const [dateFrom, setDateFrom] = useState('');
const [dateTo, setDateTo] = useState('');
const [showAdd, setShowAdd] = useState(false);
const [creating, setCreating] = useState(false);
const [draft, setDraft] = useState({ title: '', value: '', stage: 'NEW' });
useEffect(() => {
loadDeals();
}, []);
const loadDeals = async () => {
try {
setLoading(true);
const data = await crmService.getDeals();
setDeals(Array.isArray(data) ? data : []);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Failed to load deals';
toast.error(message);
setDeals([]);
} 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 = deals.filter((deal) => {
if (stageFilter !== 'ALL' && deal.stage !== stageFilter) return false;
const created = new Date(deal.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 = [deal.title, stageMeta(deal.stage).label, deal.notes]
.filter(Boolean)
.join(' ')
.toLowerCase();
return haystack.includes(q);
});
rows.sort((a, b) => {
if (sortBy === 'name') return (a.title || '').localeCompare(b.title || '');
if (sortBy === 'value') return dealValue(b) - dealValue(a);
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;
}, [deals, query, stageFilter, sortBy, dateFrom, dateTo]);
const pager = useClientPagination(filtered);
const pipelineValue = filtered.reduce((sum, deal) => sum + dealValue(deal), 0);
const exportRows = (rows: CrmDeal[]) => {
const header = ['Title', 'Value', 'Stage', 'Expected close', 'Created', 'Notes'];
const body = rows.map((deal) => [
deal.title || '',
String(dealValue(deal)),
stageMeta(deal.stage).label,
formatDay(deal.expected_close_date),
formatCreated(deal.created_at),
deal.notes || '',
]);
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 = 'deals.csv';
link.click();
URL.revokeObjectURL(url);
};
const createDeal = async (event: React.FormEvent) => {
event.preventDefault();
const amount = Number(draft.value);
if (!draft.title.trim() || !Number.isFinite(amount)) {
toast.error('Enter a title and a value');
return;
}
try {
setCreating(true);
await crmService.createDeal({
title: draft.title.trim(),
value: amount,
estimated_value: amount,
stage: draft.stage,
});
setShowAdd(false);
setDraft({ title: '', value: '', stage: 'NEW' });
toast.success('Deal saved');
await loadDeals();
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : 'Failed to create deal');
} finally {
setCreating(false);
}
};
const openLeads = () => router.push('/crm-leads');
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">Deals</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>
<span className="text-[13px] text-muted-foreground">Pipeline {money(pipelineValue)}</span>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => loadDeals()}
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" className={primaryButton} onClick={() => setShowAdd(true)}>
<Plus className="w-3.5 h-3.5" />
New deal
</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 deals"
className="w-[160px]"
options={[
{ value: 'newest', label: 'Newest first' },
{ value: 'oldest', label: 'Oldest first' },
{ value: 'name', label: 'Name' },
{ value: 'value', label: 'Value' },
]}
/>
<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={stageFilter}
onChange={setStageFilter}
aria-label="Deal stage"
className="w-[180px]"
options={[
{ value: 'ALL', label: 'All stages' },
...STAGES.map((stage) => ({ value: stage.value, label: stage.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 deals</p>
) : viewMode === 'grid' && filtered.length === 0 ? (
<p className="py-16 text-center text-[13px] text-muted-foreground">No deals 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((deal) => {
const meta = stageMeta(deal.stage);
const closeDate = formatDay(deal.expected_close_date);
return (
<button
key={deal.deal_id}
type="button"
onClick={openLeads}
className="crm-radius-section border border-border bg-card p-5 min-w-0 shadow-sm hover:shadow-md transition-shadow text-left cursor-pointer"
>
<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(deal.title || 'Deal')}
</span>
<div className="min-w-0">
<p className="text-[14px] font-semibold text-foreground truncate">{deal.title || 'Untitled deal'}</p>
<p className="text-[13px] font-semibold text-foreground mt-0.5">{money(dealValue(deal))}</p>
</div>
</div>
<div className="mt-4 space-y-1.5 text-[12px] text-muted-foreground">
{closeDate && <p>Expected close: {closeDate}</p>}
<p>Created: {formatCreated(deal.created_at)}</p>
{deal.notes && <p className="line-clamp-2">{deal.notes}</p>}
</div>
<div className="mt-4">
<span className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${meta.className}`}>
{meta.label}
</span>
</div>
</button>
);
})}
</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">Deal</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Value</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Stage</th>
<th className="text-left font-medium text-muted-foreground px-4 py-2.5">Expected close</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 deals match this view.</td>
</tr>
) : pager.items.map((deal) => {
const meta = stageMeta(deal.stage);
return (
<tr key={deal.deal_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(deal.title || 'Deal')}
</span>
<div className="min-w-0">
<p className="font-semibold text-foreground truncate">{deal.title || 'Untitled deal'}</p>
{deal.notes && <p className="text-[11px] text-muted-foreground truncate">{deal.notes}</p>}
</div>
</div>
</td>
<td className="px-4 py-3 font-semibold text-foreground whitespace-nowrap">{money(dealValue(deal))}</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 text-muted-foreground whitespace-nowrap">{formatDay(deal.expected_close_date) || '—'}</td>
<td className="px-4 py-3 text-muted-foreground whitespace-nowrap">{formatCreated(deal.created_at)}</td>
<td className="px-4 py-3 text-right">
<button
type="button"
onClick={openLeads}
className="h-8 px-2.5 crm-radius-control border border-border bg-card text-foreground text-[12px] font-semibold cursor-pointer whitespace-nowrap"
>
Open leads
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
<TablePagination {...pager} />
</div>
<Modal open={showAdd} title="New deal" onClose={() => setShowAdd(false)}>
<form onSubmit={createDeal} className="space-y-3">
<Field label="Title">
<input
required
value={draft.title}
onChange={(event) => setDraft({ ...draft, title: event.target.value })}
className={`${field} w-full`}
/>
</Field>
<Field label="Value">
<input
required
type="number"
min={0}
value={draft.value}
onChange={(event) => setDraft({ ...draft, value: event.target.value })}
placeholder="0"
className={`${field} w-full`}
/>
</Field>
<Field label="Stage">
<CustomSelect
value={draft.stage}
onChange={(value) => setDraft({ ...draft, stage: value })}
aria-label="Deal stage"
options={STAGES.map((stage) => ({ value: stage.value, label: stage.label }))}
/>
</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 deal'}</button>
</div>
</form>
</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>
);
}