Add RFM segmentation analytics
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 3m12s

This commit is contained in:
Cauê Faleiros
2026-06-12 11:22:57 -03:00
parent 25ab6cd448
commit fe8d0ff105
10 changed files with 1231 additions and 14 deletions

View File

@@ -1,10 +1,66 @@
import { useMemo, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { Link, useOutletContext } from 'react-router-dom';
import { Search, ChevronRight, Filter, ChevronLeft, Download } from 'lucide-react';
import type { OrderData, DateRange } from '../types';
import { exportToCSV } from '../dataService';
import type { OrderData, DateRange, RfmAnalytics, RfmClient } from '../types';
import { exportToCSV, fetchRfmAnalytics } from '../dataService';
import DateRangePicker from '../components/DateRangePicker';
import { buildClientsSummary, type ClientSortOption } from '../analytics/clients';
import { buildClientsSummary, type ClientSortOption, type ClientSummary } from '../analytics/clients';
const clientTypeStyles: Record<string, string> = {
'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 = [
'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, ordersData } = useOutletContext<{
@@ -14,14 +70,69 @@ const Clients = () => {
}>();
const [searchTerm, setSearchTerm] = useState('');
const [sortBy, setSortBy] = useState<ClientSortOption>('recent');
const [clientTypeFilter, setClientTypeFilter] = useState('all');
const [rfmAnalytics, setRfmAnalytics] = useState<RfmAnalytics | null>(null);
// Pagination state
const [currentPage, setCurrentPage] = useState(1);
const [itemsPerPage, setItemsPerPage] = useState(10);
useEffect(() => {
let isMounted = true;
const loadRfm = async () => {
const data = await fetchRfmAnalytics(dateRange);
if (isMounted) setRfmAnalytics(data);
};
void loadRfm();
return () => {
isMounted = false;
};
}, [dateRange]);
const rfmClientsByIdentity = useMemo(() => {
const map = new Map<string, RfmClient>();
(rfmAnalytics?.clients || []).forEach(client => {
if (client.phone) map.set(`phone:${client.phone}`, client);
map.set(`name:${client.name.toLowerCase()}`, client);
});
return map;
}, [rfmAnalytics]);
const allClientsData = useMemo(() => {
const localClients = buildClientsSummary(ordersData, dateRange, searchTerm, sortBy);
const enrichedClients = localClients.map(client => {
const rfmClient = (client.phone && rfmClientsByIdentity.get(`phone:${client.phone}`)) ||
rfmClientsByIdentity.get(`name:${client.name.toLowerCase()}`);
if (!rfmClient) return client;
return {
...client,
clientType: backendSegmentToClientType[rfmClient.segmentKey] || client.clientType,
rfmScore: rfmClient.rfmScore,
rfmPriority: getRfmPriority(rfmClient)
};
});
return sortClients(enrichedClients, sortBy);
}, [searchTerm, sortBy, ordersData, dateRange, rfmClientsByIdentity]);
const clientsData = useMemo(() => {
return buildClientsSummary(ordersData, dateRange, searchTerm, sortBy);
}, [searchTerm, sortBy, ordersData, dateRange]);
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);
@@ -32,6 +143,11 @@ const Clients = () => {
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).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">
@@ -62,6 +178,9 @@ const Clients = () => {
<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 RFM</option>
<option value="items_desc">Mais Produtos</option>
<option value="items_asc">Menos Produtos</option>
</select>
@@ -86,7 +205,10 @@ const Clients = () => {
const exportData = clientsData.map(client => ({
'Nome do Cliente': client.name,
'Telefone/WhatsApp': client.phone || 'N/A',
'Tipo de Cliente': client.clientType,
'RFM': 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')
@@ -102,6 +224,35 @@ const Clients = () => {
</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 RFM sincronizada com a página RFM 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">
@@ -109,7 +260,10 @@ const Clients = () => {
<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]">RFM</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>
@@ -123,7 +277,25 @@ const Clients = () => {
</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">
{client.totalItems} un. ({client.orderCount} {client.orderCount === 1 ? 'pedido' : 'pedidos'})
</td>