All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m20s
380 lines
18 KiB
TypeScript
380 lines
18 KiB
TypeScript
import { useEffect, useMemo, useState } from 'react';
|
|
import { Link, useOutletContext } from 'react-router-dom';
|
|
import { Search, ChevronRight, Filter, ChevronLeft, Download } from 'lucide-react';
|
|
import type { ClientAnalyticsItem, DateRange, RfmAnalytics, RfmClient } from '../types';
|
|
import { exportToCSV, fetchClientAnalytics, fetchRfmAnalytics } from '../dataService';
|
|
import DateRangePicker from '../components/DateRangePicker';
|
|
import type { ClientSortOption, ClientSummary } from '../analytics/clients';
|
|
|
|
const clientTypeStyles: Record<string, string> = {
|
|
'Sem análise': 'border-zinc-600/30 bg-zinc-600/15 text-zinc-300',
|
|
'Campeão': 'border-emerald-500/30 bg-emerald-500/15 text-emerald-300',
|
|
'Potencial Leal': 'border-sky-500/30 bg-sky-500/15 text-sky-300',
|
|
'Novo Cliente': 'border-cyan-500/30 bg-cyan-500/15 text-cyan-300',
|
|
'Cliente Leal': 'border-blue-500/30 bg-blue-500/15 text-blue-300',
|
|
'Precisa de Atenção': 'border-amber-500/30 bg-amber-500/15 text-amber-300',
|
|
'Quase Dormindo': 'border-orange-500/30 bg-orange-500/15 text-orange-300',
|
|
'Em Risco': 'border-rose-500/30 bg-rose-500/15 text-rose-300',
|
|
'Hibernando': 'border-fuchsia-500/30 bg-fuchsia-500/15 text-fuchsia-300',
|
|
'Perdido': 'border-zinc-500/30 bg-zinc-500/15 text-zinc-300'
|
|
};
|
|
|
|
const clientTypes = [
|
|
'Sem análise',
|
|
'Campeão',
|
|
'Potencial Leal',
|
|
'Novo Cliente',
|
|
'Cliente Leal',
|
|
'Precisa de Atenção',
|
|
'Quase Dormindo',
|
|
'Em Risco',
|
|
'Hibernando',
|
|
'Perdido'
|
|
];
|
|
|
|
const backendSegmentToClientType: Record<string, string> = {
|
|
champions: 'Campeão',
|
|
potential_loyalists: 'Potencial Leal',
|
|
new_customers: 'Novo Cliente',
|
|
loyal_customers: 'Cliente Leal',
|
|
need_attention: 'Precisa de Atenção',
|
|
about_to_sleep: 'Quase Dormindo',
|
|
at_risk: 'Em Risco',
|
|
hibernating: 'Hibernando',
|
|
lost: 'Perdido'
|
|
};
|
|
|
|
const getRfmPriority = (client: Pick<RfmClient, 'recencyScore' | 'valueScore' | 'monetaryScore'>) => {
|
|
return (client.recencyScore * 100) + (client.valueScore * 10) + client.monetaryScore;
|
|
};
|
|
|
|
const sortClients = (clients: ClientSummary[], sortBy: ClientSortOption) => {
|
|
return [...clients].sort((a, b) => {
|
|
switch (sortBy) {
|
|
case 'recent': return b.lastPurchase - a.lastPurchase;
|
|
case 'spent_desc': return b.totalSpent - a.totalSpent;
|
|
case 'spent_asc': return a.totalSpent - b.totalSpent;
|
|
case 'ticket_desc': return b.averageTicket - a.averageTicket;
|
|
case 'ticket_asc': return a.averageTicket - b.averageTicket;
|
|
case 'rfm_priority': return b.rfmPriority - a.rfmPriority;
|
|
case 'items_desc': return b.totalItems - a.totalItems;
|
|
case 'items_asc': return a.totalItems - b.totalItems;
|
|
default: return 0;
|
|
}
|
|
});
|
|
};
|
|
|
|
const Clients = () => {
|
|
const { dateRange, setDateRange } = useOutletContext<{
|
|
dateRange: DateRange,
|
|
setDateRange: (range: DateRange) => void
|
|
}>();
|
|
const [searchTerm, setSearchTerm] = useState('');
|
|
const [sortBy, setSortBy] = useState<ClientSortOption>('recent');
|
|
const [clientTypeFilter, setClientTypeFilter] = useState('all');
|
|
const [rfmAnalytics, setRfmAnalytics] = useState<RfmAnalytics | null>(null);
|
|
const [clientAnalytics, setClientAnalytics] = useState<ClientAnalyticsItem[]>([]);
|
|
|
|
// Pagination state
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
|
|
|
useEffect(() => {
|
|
let isMounted = true;
|
|
|
|
const loadClients = async () => {
|
|
const clientsData = await fetchClientAnalytics(dateRange);
|
|
if (isMounted) {
|
|
setClientAnalytics(clientsData);
|
|
setRfmAnalytics(null);
|
|
}
|
|
|
|
const rfmData = await fetchRfmAnalytics(dateRange);
|
|
if (isMounted) {
|
|
setRfmAnalytics(rfmData);
|
|
}
|
|
};
|
|
|
|
void loadClients();
|
|
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, [dateRange]);
|
|
|
|
const allClientsData = useMemo(() => {
|
|
const normalizedSearch = searchTerm.trim().toLowerCase();
|
|
const rfmByCustomerKey = new Map((rfmAnalytics?.clients || []).map(client => [client.customerKey, client]));
|
|
const clients = clientAnalytics.map((client): ClientSummary => {
|
|
const rfmClient = rfmByCustomerKey.get(client.customerKey);
|
|
return {
|
|
customerKey: client.customerKey,
|
|
clientToken: client.clientToken,
|
|
name: client.name,
|
|
phone: client.phone,
|
|
totalSpent: client.totalSpent,
|
|
averageTicket: client.orderCount ? client.totalSpent / client.orderCount : 0,
|
|
totalItems: client.quantityPurchased,
|
|
orderCount: client.orderCount,
|
|
lastPurchase: client.lastPurchaseDate ? new Date(client.lastPurchaseDate).getTime() : 0,
|
|
clientType: rfmClient ? (backendSegmentToClientType[rfmClient.segmentKey] || rfmClient.segmentLabel) : 'Sem análise',
|
|
rfmScore: rfmClient?.rfmScore || '000',
|
|
rfmPriority: rfmClient ? getRfmPriority(rfmClient) : 0
|
|
};
|
|
});
|
|
|
|
const filteredClients = normalizedSearch
|
|
? clients.filter(client =>
|
|
client.name.toLowerCase().includes(normalizedSearch) ||
|
|
client.phone.toLowerCase().includes(normalizedSearch)
|
|
)
|
|
: clients;
|
|
|
|
return sortClients(filteredClients, sortBy);
|
|
}, [clientAnalytics, searchTerm, sortBy, rfmAnalytics]);
|
|
|
|
const clientsData = useMemo(() => {
|
|
if (clientTypeFilter === 'all') return allClientsData;
|
|
return allClientsData.filter(client => client.clientType === clientTypeFilter);
|
|
}, [allClientsData, clientTypeFilter]);
|
|
|
|
const clientTypeCounts = useMemo(() => {
|
|
return clientTypes.reduce<Record<string, number>>((counts, type) => {
|
|
counts[type] = allClientsData.filter(client => client.clientType === type).length;
|
|
return counts;
|
|
}, {});
|
|
}, [allClientsData]);
|
|
|
|
// Pagination logic
|
|
const totalPages = Math.ceil(clientsData.length / itemsPerPage);
|
|
const startIndex = (currentPage - 1) * itemsPerPage;
|
|
const paginatedData = clientsData.slice(startIndex, startIndex + itemsPerPage);
|
|
|
|
const formatCurrency = (value: number) => {
|
|
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
|
|
};
|
|
|
|
const formatNumber = (value: number) => {
|
|
return new Intl.NumberFormat('pt-BR').format(value);
|
|
};
|
|
|
|
const selectClientType = (type: string) => {
|
|
setClientTypeFilter(current => current === type ? 'all' : type);
|
|
setCurrentPage(1);
|
|
};
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<div className="flex flex-col xl:flex-row xl:items-center justify-between gap-4">
|
|
<div>
|
|
<h1 className="text-2xl font-bold mb-2 text-zinc-900 dark:text-dark-text">Clientes</h1>
|
|
<p className="text-zinc-500 dark:text-dark-muted font-medium">Métricas de engajamento e histórico de consumo dos seus clientes.</p>
|
|
</div>
|
|
|
|
<div className="flex flex-col sm:flex-row flex-wrap gap-3 items-center justify-start xl:justify-end">
|
|
<DateRangePicker
|
|
dateRange={dateRange}
|
|
onChange={(range) => {
|
|
setDateRange(range);
|
|
setCurrentPage(1);
|
|
}}
|
|
/>
|
|
|
|
<div className="relative">
|
|
<Filter className="absolute left-3 top-1/2 transform -translate-y-1/2 text-zinc-400 dark:text-dark-muted w-4 h-4" />
|
|
<select
|
|
value={sortBy}
|
|
onChange={(e) => {
|
|
setSortBy(e.target.value as ClientSortOption);
|
|
setCurrentPage(1);
|
|
}}
|
|
className="appearance-none bg-dark-card border border-dark-border text-dark-text text-sm rounded-xl pl-9 pr-8 py-2.5 focus:outline-none focus:border-brand-primary transition-colors shadow-sm cursor-pointer"
|
|
>
|
|
<option value="recent">Mais Recentes</option>
|
|
<option value="spent_desc">Maior Gasto</option>
|
|
<option value="spent_asc">Menor Gasto</option>
|
|
<option value="ticket_desc">Maior Ticket Médio</option>
|
|
<option value="ticket_asc">Menor Ticket Médio</option>
|
|
<option value="rfm_priority">Prioridade RFV</option>
|
|
<option value="items_desc">Mais Produtos</option>
|
|
<option value="items_asc">Menos Produtos</option>
|
|
</select>
|
|
</div>
|
|
|
|
<div className="relative w-full sm:w-auto">
|
|
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-zinc-400 dark:text-dark-muted w-5 h-5" />
|
|
<input
|
|
type="text"
|
|
placeholder="Buscar cliente..."
|
|
value={searchTerm}
|
|
onChange={(e) => {
|
|
setSearchTerm(e.target.value);
|
|
setCurrentPage(1);
|
|
}}
|
|
className="w-full sm:w-64 bg-dark-card border border-dark-border text-dark-text rounded-xl pl-10 pr-4 py-2.5 focus:outline-none focus:border-brand-primary hover:border-brand-primary transition-colors shadow-sm"
|
|
/>
|
|
</div>
|
|
|
|
<button
|
|
onClick={() => {
|
|
const exportData = clientsData.map(client => ({
|
|
'Nome do Cliente': client.name,
|
|
'Telefone/WhatsApp': client.phone || 'N/A',
|
|
'Tipo de Cliente': client.clientType,
|
|
'RFV': client.rfmScore,
|
|
'Total Gasto (R$)': client.totalSpent.toFixed(2).replace('.', ','),
|
|
'Ticket Médio (R$)': client.averageTicket.toFixed(2).replace('.', ','),
|
|
'Produtos Comprados': client.totalItems,
|
|
'Total de Pedidos': client.orderCount,
|
|
'Última Compra': new Date(client.lastPurchase).toLocaleDateString('pt-BR')
|
|
}));
|
|
exportToCSV(exportData, `clientes_${new Date().toISOString().split('T')[0]}.csv`);
|
|
}}
|
|
className="flex items-center justify-center gap-2 bg-dark-card border border-dark-border px-4 py-2.5 rounded-xl shadow-sm hover:border-brand-primary transition-colors text-sm font-medium text-dark-text cursor-pointer"
|
|
title="Exportar para CSV"
|
|
>
|
|
<Download size={16} className="text-brand-primary" />
|
|
<span className="hidden sm:inline">Exportar</span>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-4 shadow-sm">
|
|
<div className="mb-4">
|
|
<div>
|
|
<h2 className="text-sm font-bold text-zinc-900 dark:text-dark-text">Tipos de Clientes</h2>
|
|
<p className="text-xs font-semibold text-zinc-500 dark:text-dark-muted">
|
|
Classificação RFV sincronizada com a página RFV quando disponível.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-wrap gap-2">
|
|
{clientTypes.map(type => (
|
|
<button
|
|
key={type}
|
|
onClick={() => selectClientType(type)}
|
|
title={clientTypeFilter === type ? 'Clique para limpar o filtro' : `Filtrar por ${type}`}
|
|
className={`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-bold transition-all cursor-pointer hover:-translate-y-0.5 ${
|
|
clientTypeFilter === type
|
|
? `${clientTypeStyles[type]} ring-1 ring-current shadow-sm`
|
|
: clientTypeStyles[type]
|
|
}`}
|
|
>
|
|
<span>{type}</span>
|
|
<span className="rounded-full bg-black/20 px-2 py-0.5 text-[10px]">{clientTypeCounts[type] || 0}</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm">
|
|
<div className="overflow-x-auto">
|
|
<table className="w-full text-left text-sm">
|
|
<thead className="bg-zinc-50 dark:bg-dark-header border-b border-zinc-100 dark:border-dark-border text-zinc-500 dark:text-dark-muted">
|
|
<tr>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Posição</th>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Nome do Cliente</th>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Tipo</th>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">RFV</th>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Total Gasto</th>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Ticket Médio</th>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Produtos Comprados</th>
|
|
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px] text-right">Ações</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="divide-y divide-zinc-100 dark:divide-dark-border">
|
|
{paginatedData.map((client, index) => (
|
|
<tr key={client.customerKey} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors group">
|
|
<td className="px-6 py-2.5">
|
|
<span className="inline-flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold bg-zinc-100 dark:bg-dark-border text-zinc-500 dark:text-dark-muted">
|
|
{startIndex + index + 1}
|
|
</span>
|
|
</td>
|
|
<td className="px-6 py-2.5 font-semibold text-zinc-900 dark:text-dark-text">{client.name}</td>
|
|
<td className="px-6 py-2.5">
|
|
<span className={`inline-flex rounded-full border px-3 py-1 text-xs font-bold ${clientTypeStyles[client.clientType] || clientTypeStyles.Perdido}`}>
|
|
{client.clientType}
|
|
</span>
|
|
</td>
|
|
<td className="px-6 py-2.5">
|
|
<div className="flex items-center gap-1">
|
|
{client.rfmScore.split('').map((score, scoreIndex) => (
|
|
<span
|
|
key={`${client.name}-${scoreIndex}`}
|
|
className="inline-flex h-6 w-6 items-center justify-center rounded-md border border-dark-border bg-dark-input text-[11px] font-bold text-dark-text"
|
|
>
|
|
{score}
|
|
</span>
|
|
))}
|
|
</div>
|
|
</td>
|
|
<td className="px-6 py-2.5 text-brand-primary font-bold">{formatCurrency(client.totalSpent)}</td>
|
|
<td className="px-6 py-2.5 text-zinc-700 dark:text-dark-text font-semibold">{formatCurrency(client.averageTicket)}</td>
|
|
<td className="px-6 py-2.5 text-zinc-500 dark:text-dark-muted text-xs font-medium">
|
|
{formatNumber(client.totalItems)} un. ({formatNumber(client.orderCount)} {client.orderCount === 1 ? 'pedido' : 'pedidos'})
|
|
</td>
|
|
<td className="px-6 py-2.5 text-right">
|
|
<Link
|
|
to={`/clients/${encodeURIComponent(client.clientToken)}`}
|
|
className="inline-flex items-center text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity cursor-pointer"
|
|
>
|
|
Ver detalhes
|
|
<ChevronRight className="w-3.5 h-3.5 ml-1" />
|
|
</Link>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
|
|
{/* Pagination Controls */}
|
|
<div className="px-6 py-4 border-t border-zinc-100 dark:border-dark-border flex flex-col sm:flex-row items-center justify-between gap-4">
|
|
<div className="flex items-center gap-2 text-sm text-zinc-500 dark:text-dark-muted">
|
|
<span>Mostrar</span>
|
|
<select
|
|
value={itemsPerPage}
|
|
onChange={(e) => {
|
|
setItemsPerPage(Number(e.target.value));
|
|
setCurrentPage(1);
|
|
}}
|
|
className="bg-dark-card border border-dark-border rounded-lg px-2 py-1 focus:outline-none focus:border-brand-primary cursor-pointer text-dark-text"
|
|
>
|
|
<option value={10}>10</option>
|
|
<option value={20}>20</option>
|
|
<option value={50}>50</option>
|
|
<option value={100}>100</option>
|
|
</select>
|
|
<span>itens por página</span>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-4 text-sm">
|
|
<span className="text-zinc-500 dark:text-dark-muted">
|
|
Mostrando {clientsData.length > 0 ? startIndex + 1 : 0} a {Math.min(startIndex + itemsPerPage, clientsData.length)} de {clientsData.length} clientes
|
|
</span>
|
|
<div className="flex gap-1">
|
|
<button
|
|
onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
|
|
disabled={currentPage === 1}
|
|
className="p-1 rounded-lg border border-dark-border disabled:opacity-50 disabled:cursor-not-allowed hover:border-brand-primary transition-colors text-dark-muted hover:text-dark-text cursor-pointer bg-dark-card"
|
|
>
|
|
<ChevronLeft className="w-5 h-5" />
|
|
</button>
|
|
<button
|
|
onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
|
|
disabled={currentPage === totalPages || totalPages === 0}
|
|
className="p-1 rounded-lg border border-dark-border disabled:opacity-50 disabled:cursor-not-allowed hover:border-brand-primary transition-colors text-dark-muted hover:text-dark-text cursor-pointer bg-dark-card"
|
|
>
|
|
<ChevronRight className="w-5 h-5" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default Clients;
|