All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m29s
916 lines
42 KiB
TypeScript
916 lines
42 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
import { Link, useOutletContext } from 'react-router-dom';
|
|
import { Search, ChevronRight, Filter, X } from 'lucide-react';
|
|
import { BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
|
import PaginationControls from '../components/PaginationControls';
|
|
import RefreshStatus from '../components/RefreshStatus';
|
|
import type { ClientAnalyticsItem, ClientFilterOptions, ClientMetadataFilters, ClientPurchasePatternAnalytics, DateRange, RfmAnalytics, RfmClient } from '../types';
|
|
import { fetchClientAnalytics, fetchClientFilterOptions, fetchClientPurchasePatternAnalytics, fetchRfmAnalytics, getCachedClientAnalytics, getCachedClientFilterOptions, getCachedRfmAnalytics } from '../dataService';
|
|
import { endOfLocalDay, formatDateParam, parseLocalDateInput, rangeForDay, rangeForLastDays, rangeForPreviousDay, startOfLocalDay } from '../dateRanges';
|
|
import type { ClientSortOption, ClientSummary } from '../analytics/clients';
|
|
import { formatDisplayName, removeTrailingSellerId } from '../displayFormatters';
|
|
|
|
type ClientTypeStyle = {
|
|
bg: string;
|
|
border: string;
|
|
text: string;
|
|
};
|
|
|
|
type ThemeMode = 'dark' | 'offwhite';
|
|
|
|
const darkClientTypeStyles: Record<string, ClientTypeStyle> = {
|
|
'Sem análise': { bg: 'rgba(140, 146, 152, 0.08)', border: 'rgba(140, 146, 152, 0.24)', text: '#b3b7bb' },
|
|
'Campeão': { bg: 'rgba(24, 214, 181, 0.10)', border: 'rgba(24, 214, 181, 0.34)', text: '#18D6B5' },
|
|
'Potencial Leal': { bg: 'rgba(163, 230, 53, 0.10)', border: 'rgba(163, 230, 53, 0.34)', text: '#A3E635' },
|
|
'Novo Cliente': { bg: 'rgba(37, 194, 255, 0.10)', border: 'rgba(37, 194, 255, 0.34)', text: '#25C2FF' },
|
|
'Cliente Leal': { bg: 'rgba(110, 165, 255, 0.10)', border: 'rgba(110, 165, 255, 0.34)', text: '#6EA5FF' },
|
|
'Precisa de Atenção': { bg: 'rgba(255, 194, 71, 0.11)', border: 'rgba(255, 194, 71, 0.34)', text: '#FFC247' },
|
|
'Quase Dormindo': { bg: 'rgba(255, 138, 61, 0.11)', border: 'rgba(255, 138, 61, 0.34)', text: '#FF8A3D' },
|
|
'Em Risco': { bg: 'rgba(255, 93, 125, 0.11)', border: 'rgba(255, 93, 125, 0.34)', text: '#FF5D7D' },
|
|
'Hibernando': { bg: 'rgba(199, 125, 255, 0.11)', border: 'rgba(199, 125, 255, 0.34)', text: '#C77DFF' },
|
|
'Perdido': { bg: 'rgba(140, 146, 152, 0.08)', border: 'rgba(140, 146, 152, 0.24)', text: '#b3b7bb' }
|
|
};
|
|
|
|
const offwhiteClientTypeStyles: Record<string, ClientTypeStyle> = {
|
|
'Sem análise': { bg: 'rgba(117, 124, 130, 0.08)', border: 'rgba(117, 124, 130, 0.26)', text: '#757C82' },
|
|
'Campeão': { bg: 'rgba(19, 139, 117, 0.10)', border: 'rgba(19, 139, 117, 0.34)', text: '#138B75' },
|
|
'Potencial Leal': { bg: 'rgba(95, 143, 18, 0.11)', border: 'rgba(95, 143, 18, 0.34)', text: '#5F8F12' },
|
|
'Novo Cliente': { bg: 'rgba(11, 126, 168, 0.10)', border: 'rgba(11, 126, 168, 0.34)', text: '#0B7EA8' },
|
|
'Cliente Leal': { bg: 'rgba(53, 109, 204, 0.10)', border: 'rgba(53, 109, 204, 0.34)', text: '#356DCC' },
|
|
'Precisa de Atenção': { bg: 'rgba(163, 108, 0, 0.11)', border: 'rgba(163, 108, 0, 0.34)', text: '#A36C00' },
|
|
'Quase Dormindo': { bg: 'rgba(183, 91, 18, 0.11)', border: 'rgba(183, 91, 18, 0.34)', text: '#B75B12' },
|
|
'Em Risco': { bg: 'rgba(199, 54, 86, 0.10)', border: 'rgba(199, 54, 86, 0.34)', text: '#C73656' },
|
|
'Hibernando': { bg: 'rgba(140, 82, 214, 0.10)', border: 'rgba(140, 82, 214, 0.34)', text: '#8C52D6' },
|
|
'Perdido': { bg: 'rgba(117, 124, 130, 0.08)', border: 'rgba(117, 124, 130, 0.26)', text: '#757C82' }
|
|
};
|
|
|
|
const clientTypePillStyle = (style: ClientTypeStyle) => ({
|
|
backgroundColor: style.bg,
|
|
borderColor: style.border,
|
|
color: style.text
|
|
});
|
|
|
|
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 emptyClientFilters: ClientMetadataFilters = {
|
|
marketplace: '',
|
|
canal_venda: '',
|
|
seller: ''
|
|
};
|
|
|
|
const emptyClientFilterOptions: ClientFilterOptions = {
|
|
marketplaces: [],
|
|
salesChannels: [],
|
|
sellers: []
|
|
};
|
|
|
|
const dateFilterPresets = [
|
|
{ value: 'today', label: 'Hoje', getRange: () => rangeForDay(new Date()) },
|
|
{ value: 'yesterday', label: 'Ontem', getRange: () => rangeForPreviousDay() },
|
|
{ value: '7d', label: 'Últimos 7 dias', getRange: () => rangeForLastDays(7) },
|
|
{ value: '30d', label: 'Últimos 30 dias', getRange: () => rangeForLastDays(30) },
|
|
{ value: 'month', label: 'Este mês', getRange: () => {
|
|
const end = endOfLocalDay(new Date());
|
|
return { start: startOfLocalDay(new Date(end.getFullYear(), end.getMonth(), 1)), end };
|
|
} },
|
|
{ value: 'previous-month', label: 'Mês passado', getRange: () => {
|
|
const today = new Date();
|
|
return {
|
|
start: startOfLocalDay(new Date(today.getFullYear(), today.getMonth() - 1, 1)),
|
|
end: endOfLocalDay(new Date(today.getFullYear(), today.getMonth(), 0))
|
|
};
|
|
} },
|
|
{ value: '90d', label: 'Últimos 90 dias', getRange: () => rangeForLastDays(90) },
|
|
{ value: 'year', label: 'Este ano', getRange: () => {
|
|
const end = endOfLocalDay(new Date());
|
|
return { start: startOfLocalDay(new Date(end.getFullYear(), 0, 1)), end };
|
|
} },
|
|
{ value: 'all', label: 'Todo o período', getRange: () => ({
|
|
start: startOfLocalDay(new Date(2000, 0, 1)),
|
|
end: endOfLocalDay(new Date())
|
|
}) }
|
|
];
|
|
|
|
const filterSelectClassName = "w-full h-9 bg-dark-input border border-dark-border text-dark-text text-sm rounded-lg px-3 focus:outline-none focus:border-brand-primary transition-colors cursor-pointer";
|
|
const CHART_GRID_COLOR = 'var(--chart-grid)';
|
|
const CHART_AXIS_COLOR = 'var(--chart-axis)';
|
|
const CHART_CURSOR_COLOR = 'var(--chart-cursor)';
|
|
const WEEKDAY_BAR_COLOR = '#25C2FF';
|
|
const HOUR_BAR_COLOR = '#52DFA0';
|
|
|
|
type PatternTooltipProps = {
|
|
active?: boolean;
|
|
payload?: Array<{ value: number }>;
|
|
label?: string;
|
|
};
|
|
|
|
const PatternTooltip = ({ active, payload, label }: PatternTooltipProps) => {
|
|
if (!active || !payload?.length) return null;
|
|
|
|
const value = payload[0].value;
|
|
return (
|
|
<div className="rounded-xl bg-dark-card p-3 shadow-lg">
|
|
<p className="mb-1 font-bold text-brand-primary">{label}</p>
|
|
<p className="m-0 text-dark-text">
|
|
{value} {value === 1 ? 'pedido' : 'pedidos'}
|
|
</p>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const ClientPurchasePatternSkeleton = () => (
|
|
<section className="space-y-4" aria-label="Carregando padrão de compra">
|
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
|
|
<div>
|
|
<div className="skeleton h-5 w-44" />
|
|
<div className="skeleton mt-2 h-4 w-64" />
|
|
</div>
|
|
<div className="skeleton h-7 w-28 rounded-full" />
|
|
</div>
|
|
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
|
{[0, 1].map(item => (
|
|
<div key={`clients-pattern-skeleton-${item}`} className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
|
|
<div className="skeleton h-4 w-40" />
|
|
<div className="mt-5 flex h-56 items-end gap-3">
|
|
{[0, 1, 2, 3, 4, 5, 6].map(bar => (
|
|
<div key={`clients-pattern-bar-skeleton-${item}-${bar}`} className="skeleton flex-1" style={{ height: `${20 + ((bar * 17) % 65)}%` }} />
|
|
))}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</section>
|
|
);
|
|
|
|
const ClientsTableSkeleton = () => (
|
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm" aria-label="Carregando clientes">
|
|
<div className="border-b border-zinc-100 p-4 dark:border-dark-border">
|
|
<div className="grid grid-cols-[72px_1.4fr_150px_110px_140px_140px_170px_110px] gap-5">
|
|
{[0, 1, 2, 3, 4, 5, 6, 7].map(item => (
|
|
<div key={`clients-head-skeleton-${item}`} className="skeleton h-3" />
|
|
))}
|
|
</div>
|
|
</div>
|
|
<div className="divide-y divide-zinc-100 dark:divide-dark-border">
|
|
{[0, 1, 2, 3, 4, 5, 6, 7].map(row => (
|
|
<div key={`clients-row-skeleton-${row}`} className="grid grid-cols-[72px_1.4fr_150px_110px_140px_140px_170px_110px] gap-5 px-6 py-4">
|
|
<div className="skeleton h-7 w-7 rounded-full" />
|
|
<div className="skeleton h-4 w-4/5" />
|
|
<div className="skeleton h-7 rounded-full" />
|
|
<div className="flex gap-1">
|
|
<div className="skeleton h-6 w-6 rounded-md" />
|
|
<div className="skeleton h-6 w-6 rounded-md" />
|
|
<div className="skeleton h-6 w-6 rounded-md" />
|
|
</div>
|
|
<div className="skeleton h-4" />
|
|
<div className="skeleton h-4" />
|
|
<div className="skeleton h-4" />
|
|
<div className="skeleton h-4" />
|
|
</div>
|
|
))}
|
|
</div>
|
|
<div className="flex items-center justify-between border-t border-zinc-100 p-4 dark:border-dark-border">
|
|
<div className="skeleton h-4 w-48" />
|
|
<div className="skeleton h-8 w-56" />
|
|
</div>
|
|
</div>
|
|
);
|
|
|
|
const Clients = () => {
|
|
const { dateRange, setDateRange, themeMode } = useOutletContext<{
|
|
dateRange: DateRange,
|
|
setDateRange: (range: DateRange) => void,
|
|
themeMode?: ThemeMode
|
|
}>();
|
|
const clientTypeStyles = themeMode === 'offwhite' ? offwhiteClientTypeStyles : darkClientTypeStyles;
|
|
const [searchTerm, setSearchTerm] = useState('');
|
|
const [sortBy, setSortBy] = useState<ClientSortOption>('recent');
|
|
const [clientTypeFilter, setClientTypeFilter] = useState('all');
|
|
const [metadataFilters, setMetadataFilters] = useState<ClientMetadataFilters>(emptyClientFilters);
|
|
const initialFilterOptions = getCachedClientFilterOptions(dateRange);
|
|
const initialClientAnalytics = getCachedClientAnalytics(dateRange, emptyClientFilters);
|
|
const initialRfmAnalytics = getCachedRfmAnalytics(dateRange, emptyClientFilters);
|
|
const [filterOptions, setFilterOptions] = useState<ClientFilterOptions>(initialFilterOptions || emptyClientFilterOptions);
|
|
const [isFilterMenuOpen, setIsFilterMenuOpen] = useState(false);
|
|
const filterMenuRef = useRef<HTMLDivElement>(null);
|
|
const [rfmAnalytics, setRfmAnalytics] = useState<RfmAnalytics | null>(initialRfmAnalytics || null);
|
|
const [clientAnalytics, setClientAnalytics] = useState<ClientAnalyticsItem[]>(initialClientAnalytics || []);
|
|
const [isLoading, setIsLoading] = useState(!initialClientAnalytics);
|
|
const [isRfmLoading, setIsRfmLoading] = useState(!initialRfmAnalytics && Boolean(initialClientAnalytics));
|
|
const [purchasePattern, setPurchasePattern] = useState<ClientPurchasePatternAnalytics | null>(null);
|
|
const [isPatternLoading, setIsPatternLoading] = useState(true);
|
|
|
|
// Pagination state
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
const [itemsPerPage, setItemsPerPage] = useState(10);
|
|
|
|
useEffect(() => {
|
|
let isMounted = true;
|
|
|
|
const loadClients = async () => {
|
|
const cachedOptions = getCachedClientFilterOptions(dateRange);
|
|
const cachedClients = getCachedClientAnalytics(dateRange, metadataFilters);
|
|
const cachedRfm = getCachedRfmAnalytics(dateRange, metadataFilters);
|
|
const hasCachedClients = Boolean(cachedClients);
|
|
|
|
if (isMounted) {
|
|
if (cachedOptions) setFilterOptions(cachedOptions);
|
|
if (cachedClients) setClientAnalytics(cachedClients);
|
|
setRfmAnalytics(cachedRfm || null);
|
|
setIsLoading(!hasCachedClients);
|
|
setIsRfmLoading(!cachedRfm && hasCachedClients);
|
|
}
|
|
|
|
const filterOptionsPromise = fetchClientFilterOptions(dateRange, { force: true });
|
|
const clientsPromise = fetchClientAnalytics(dateRange, metadataFilters);
|
|
const rfmPromise = fetchRfmAnalytics(dateRange, metadataFilters);
|
|
const [options, clientsData] = await Promise.all([filterOptionsPromise, clientsPromise]);
|
|
|
|
if (isMounted) {
|
|
setFilterOptions(options);
|
|
setClientAnalytics(clientsData);
|
|
setIsLoading(false);
|
|
setIsRfmLoading(!cachedRfm);
|
|
}
|
|
|
|
const rfmData = await rfmPromise;
|
|
if (isMounted) {
|
|
setRfmAnalytics(rfmData);
|
|
setIsRfmLoading(false);
|
|
}
|
|
};
|
|
|
|
void loadClients();
|
|
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, [dateRange, metadataFilters]);
|
|
|
|
useEffect(() => {
|
|
let isMounted = true;
|
|
|
|
const loadPurchasePattern = async () => {
|
|
setIsPatternLoading(true);
|
|
const nextPattern = await fetchClientPurchasePatternAnalytics();
|
|
|
|
if (isMounted) {
|
|
setPurchasePattern(nextPattern);
|
|
setIsPatternLoading(false);
|
|
}
|
|
};
|
|
|
|
void loadPurchasePattern();
|
|
|
|
return () => {
|
|
isMounted = false;
|
|
};
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!isFilterMenuOpen) return;
|
|
|
|
const handlePointerDown = (event: PointerEvent) => {
|
|
if (!filterMenuRef.current?.contains(event.target as Node)) {
|
|
setIsFilterMenuOpen(false);
|
|
}
|
|
};
|
|
const handleKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') {
|
|
setIsFilterMenuOpen(false);
|
|
}
|
|
};
|
|
|
|
document.addEventListener('pointerdown', handlePointerDown);
|
|
document.addEventListener('keydown', handleKeyDown);
|
|
|
|
return () => {
|
|
document.removeEventListener('pointerdown', handlePointerDown);
|
|
document.removeEventListener('keydown', handleKeyDown);
|
|
};
|
|
}, [isFilterMenuOpen]);
|
|
|
|
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 rawClient = client as ClientAnalyticsItem & {
|
|
client_token?: string;
|
|
customer_key?: string;
|
|
last_purchase_date?: string;
|
|
order_count?: number;
|
|
quantity_purchased?: number;
|
|
total_spent?: number;
|
|
};
|
|
const rfmClient = rfmByCustomerKey.get(client.customerKey);
|
|
const orderCount = Number(client.orderCount ?? rawClient.order_count ?? 0);
|
|
const totalSpent = Number(client.totalSpent ?? rawClient.total_spent ?? 0);
|
|
const totalItems = Number(client.quantityPurchased ?? rawClient.quantity_purchased ?? 0);
|
|
const lastPurchaseDate = client.lastPurchaseDate ?? rawClient.last_purchase_date;
|
|
|
|
return {
|
|
customerKey: client.customerKey ?? rawClient.customer_key ?? '',
|
|
clientToken: client.clientToken ?? rawClient.client_token ?? '',
|
|
name: client.name,
|
|
phone: client.phone,
|
|
totalSpent,
|
|
averageTicket: orderCount ? totalSpent / orderCount : 0,
|
|
totalItems,
|
|
orderCount,
|
|
lastPurchase: lastPurchaseDate ? new Date(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 safeCurrentPage = Math.min(currentPage, totalPages || 1);
|
|
const startIndex = (safeCurrentPage - 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 datePresetValue = useMemo(() => {
|
|
const currentStart = formatDateParam(dateRange.start);
|
|
const currentEnd = formatDateParam(dateRange.end);
|
|
const preset = dateFilterPresets.find(option => {
|
|
const range = option.getRange();
|
|
return formatDateParam(range.start) === currentStart && formatDateParam(range.end) === currentEnd;
|
|
});
|
|
|
|
return preset?.value || 'custom';
|
|
}, [dateRange]);
|
|
|
|
const updateDatePreset = (value: string) => {
|
|
if (value === 'custom') return;
|
|
|
|
const preset = dateFilterPresets.find(option => option.value === value);
|
|
if (!preset) return;
|
|
|
|
setDateRange(preset.getRange());
|
|
setCurrentPage(1);
|
|
};
|
|
|
|
const updateDateStart = (value: string) => {
|
|
const nextStart = parseLocalDateInput(value);
|
|
if (!nextStart) return;
|
|
|
|
const start = startOfLocalDay(nextStart);
|
|
const end = dateRange.end < start ? endOfLocalDay(start) : dateRange.end;
|
|
setDateRange({ start, end });
|
|
setCurrentPage(1);
|
|
};
|
|
|
|
const updateDateEnd = (value: string) => {
|
|
const nextEnd = parseLocalDateInput(value);
|
|
if (!nextEnd) return;
|
|
|
|
const end = endOfLocalDay(nextEnd);
|
|
const start = dateRange.start > end ? startOfLocalDay(end) : dateRange.start;
|
|
setDateRange({ start, end });
|
|
setCurrentPage(1);
|
|
};
|
|
|
|
const selectClientType = (type: string) => {
|
|
setClientTypeFilter(current => current === type ? 'all' : type);
|
|
setCurrentPage(1);
|
|
};
|
|
|
|
const updateMetadataFilter = (key: keyof ClientMetadataFilters, value: string) => {
|
|
setMetadataFilters(current => ({
|
|
...current,
|
|
[key]: value
|
|
}));
|
|
setCurrentPage(1);
|
|
};
|
|
|
|
const resetMetadataFilters = () => {
|
|
setMetadataFilters(emptyClientFilters);
|
|
setClientTypeFilter('all');
|
|
setSortBy('recent');
|
|
setCurrentPage(1);
|
|
};
|
|
|
|
const getSellerOptionLabel = (seller: ClientFilterOptions['sellers'][number]) => {
|
|
return formatDisplayName(removeTrailingSellerId(seller.name || seller.id));
|
|
};
|
|
|
|
const marketplaceOptions = useMemo(() => {
|
|
if (!metadataFilters.marketplace || filterOptions.marketplaces.includes(metadataFilters.marketplace)) {
|
|
return filterOptions.marketplaces;
|
|
}
|
|
|
|
return [metadataFilters.marketplace, ...filterOptions.marketplaces];
|
|
}, [filterOptions.marketplaces, metadataFilters.marketplace]);
|
|
|
|
const salesChannelOptions = useMemo(() => {
|
|
if (!metadataFilters.canal_venda || filterOptions.salesChannels.includes(metadataFilters.canal_venda)) {
|
|
return filterOptions.salesChannels;
|
|
}
|
|
|
|
return [metadataFilters.canal_venda, ...filterOptions.salesChannels];
|
|
}, [filterOptions.salesChannels, metadataFilters.canal_venda]);
|
|
|
|
const sellerOptions = useMemo(() => {
|
|
if (!metadataFilters.seller || filterOptions.sellers.some(seller => seller.value === metadataFilters.seller)) {
|
|
return filterOptions.sellers;
|
|
}
|
|
|
|
const fallbackSeller = metadataFilters.seller.startsWith('id:')
|
|
? { value: metadataFilters.seller, id: metadataFilters.seller.slice(3), name: metadataFilters.seller.slice(3) }
|
|
: { value: metadataFilters.seller, id: '', name: metadataFilters.seller.replace(/^name:/, '') };
|
|
|
|
return [fallbackSeller, ...filterOptions.sellers];
|
|
}, [filterOptions.sellers, metadataFilters.seller]);
|
|
|
|
const activeMetadataFilters = useMemo(() => {
|
|
const filters = [];
|
|
const selectedSeller = sellerOptions.find(seller => seller.value === metadataFilters.seller);
|
|
|
|
if (metadataFilters.marketplace) {
|
|
filters.push({ key: 'marketplace' as const, label: `Marketplace: ${metadataFilters.marketplace}` });
|
|
}
|
|
|
|
if (metadataFilters.canal_venda) {
|
|
filters.push({ key: 'canal_venda' as const, label: `Canal: ${metadataFilters.canal_venda}` });
|
|
}
|
|
|
|
if (metadataFilters.seller) {
|
|
filters.push({ key: 'seller' as const, label: `Vendedor: ${selectedSeller ? getSellerOptionLabel(selectedSeller) : metadataFilters.seller}` });
|
|
}
|
|
|
|
return filters;
|
|
}, [metadataFilters, sellerOptions]);
|
|
const activeFilterCount = activeMetadataFilters.length +
|
|
(clientTypeFilter === 'all' ? 0 : 1) +
|
|
(sortBy === 'recent' ? 0 : 1);
|
|
const hasActiveFilters = activeFilterCount > 0;
|
|
const isRefreshing = isLoading && clientAnalytics.length > 0;
|
|
const shouldShowRfmLoading = isRfmLoading && clientAnalytics.length > 0;
|
|
const hasWeekdayPattern = purchasePattern?.purchaseWeekdays.some(day => day.value > 0) ?? false;
|
|
const hasHourPattern = purchasePattern?.purchaseHours.some(hour => hour.value > 0) ?? false;
|
|
const weekdayRangeLabel = purchasePattern?.weekdayRangeLabel || 'Todo período';
|
|
const hourRangeLabel = purchasePattern?.hourRangeLabel || 'Últimos 60 dias';
|
|
|
|
return (
|
|
<div className="space-y-6">
|
|
<div className="grid grid-cols-1 gap-4 2xl:grid-cols-[minmax(520px,1fr)_auto] 2xl:items-start">
|
|
<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 lg:whitespace-nowrap">Métricas de engajamento e histórico de consumo dos seus clientes.</p>
|
|
</div>
|
|
|
|
<div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
|
|
<div className="relative w-full sm:w-72">
|
|
<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 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>
|
|
|
|
<div ref={filterMenuRef} className="relative w-full sm:w-auto">
|
|
<button
|
|
type="button"
|
|
onClick={() => setIsFilterMenuOpen(open => !open)}
|
|
className={`flex w-full items-center justify-center gap-2 rounded-xl border px-4 py-2.5 text-sm font-medium shadow-sm transition-colors sm:w-auto ${
|
|
hasActiveFilters
|
|
? 'cursor-pointer border-brand-primary bg-brand-primary/10 text-brand-primary'
|
|
: 'cursor-pointer border-dark-border bg-dark-card text-dark-text hover:border-brand-primary'
|
|
}`}
|
|
>
|
|
<Filter className="h-4 w-4" />
|
|
Filtros
|
|
{hasActiveFilters && (
|
|
<span className="rounded-full bg-brand-primary px-1.5 py-0.5 text-[10px] font-bold text-brand-contrast">
|
|
{activeFilterCount}
|
|
</span>
|
|
)}
|
|
</button>
|
|
|
|
{isFilterMenuOpen && (
|
|
<div className="absolute right-0 top-full z-20 mt-2 w-[min(28rem,calc(100vw-2rem))] rounded-xl border border-dark-border bg-dark-card p-3 shadow-2xl">
|
|
<div className="mb-3 flex items-center justify-between">
|
|
<h3 className="text-sm font-bold text-dark-text">Filtros</h3>
|
|
<button
|
|
type="button"
|
|
onClick={() => setIsFilterMenuOpen(false)}
|
|
className="cursor-pointer rounded-lg p-1 text-dark-muted transition-colors hover:bg-dark-input hover:text-dark-text"
|
|
aria-label="Fechar filtros"
|
|
>
|
|
<X className="h-4 w-4" />
|
|
</button>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
Período
|
|
<select
|
|
value={datePresetValue}
|
|
onChange={(event) => updateDatePreset(event.target.value)}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
>
|
|
<option value="custom">Personalizado</option>
|
|
{dateFilterPresets.map(preset => (
|
|
<option key={preset.value} value={preset.value}>{preset.label}</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
Ordenação
|
|
<select
|
|
value={sortBy}
|
|
onChange={(e) => {
|
|
setSortBy(e.target.value as ClientSortOption);
|
|
setCurrentPage(1);
|
|
}}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
>
|
|
<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>
|
|
</label>
|
|
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
De
|
|
<input
|
|
type="date"
|
|
value={formatDateParam(dateRange.start)}
|
|
onChange={(event) => updateDateStart(event.target.value)}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
/>
|
|
</label>
|
|
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
Até
|
|
<input
|
|
type="date"
|
|
value={formatDateParam(dateRange.end)}
|
|
onChange={(event) => updateDateEnd(event.target.value)}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
/>
|
|
</label>
|
|
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
Marketplace
|
|
<select
|
|
value={metadataFilters.marketplace}
|
|
onChange={(event) => updateMetadataFilter('marketplace', event.target.value)}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
>
|
|
<option value="">Todos</option>
|
|
{marketplaceOptions.map(marketplace => (
|
|
<option key={marketplace} value={marketplace}>{marketplace}</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
Canal de venda
|
|
<select
|
|
value={metadataFilters.canal_venda}
|
|
onChange={(event) => updateMetadataFilter('canal_venda', event.target.value)}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
>
|
|
<option value="">Todos</option>
|
|
{salesChannelOptions.map(channel => (
|
|
<option key={channel} value={channel}>{channel}</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
Vendedor
|
|
<select
|
|
value={metadataFilters.seller}
|
|
onChange={(event) => updateMetadataFilter('seller', event.target.value)}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
>
|
|
<option value="">Todos</option>
|
|
{!sellerOptions.length && (
|
|
<option value="" disabled>Nenhum vendedor encontrado</option>
|
|
)}
|
|
{sellerOptions.map(seller => (
|
|
<option key={seller.value} value={seller.value}>{getSellerOptionLabel(seller)}</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
|
|
<label className="block text-xs font-bold uppercase tracking-wider text-dark-muted">
|
|
Tipo de cliente
|
|
<select
|
|
value={clientTypeFilter}
|
|
onChange={(event) => selectClientType(event.target.value)}
|
|
className={`${filterSelectClassName} mt-1`}
|
|
>
|
|
<option value="all">Todos</option>
|
|
{clientTypes.map(type => (
|
|
<option key={type} value={type}>
|
|
{type} ({clientTypeCounts[type] || 0})
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
</div>
|
|
|
|
<div className="mt-3 flex items-center justify-between border-t border-dark-border pt-3">
|
|
<button
|
|
type="button"
|
|
onClick={resetMetadataFilters}
|
|
disabled={!hasActiveFilters}
|
|
className="cursor-pointer text-sm font-bold text-dark-muted transition-colors hover:text-dark-text disabled:cursor-not-allowed disabled:opacity-40"
|
|
>
|
|
Limpar
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => setIsFilterMenuOpen(false)}
|
|
className="cursor-pointer rounded-xl bg-brand-primary px-4 py-2 text-sm font-bold text-brand-contrast transition-opacity hover:opacity-90"
|
|
>
|
|
Aplicar
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<RefreshStatus isRefreshing={isRefreshing} />
|
|
|
|
{isLoading && clientAnalytics.length === 0 ? (
|
|
<ClientsTableSkeleton />
|
|
) : (
|
|
<div className={`bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl overflow-hidden shadow-sm ${isRefreshing ? 'refreshing-content' : ''}`} aria-busy={isRefreshing}>
|
|
<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) => {
|
|
const clientTypeStyle = clientTypeStyles[client.clientType] || clientTypeStyles.Perdido;
|
|
|
|
return (
|
|
<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">
|
|
{shouldShowRfmLoading ? (
|
|
<span className="skeleton inline-flex h-7 w-24 rounded-full" />
|
|
) : (
|
|
<span
|
|
className="inline-flex rounded-full border px-3 py-1 text-xs font-bold"
|
|
style={clientTypePillStyle(clientTypeStyle)}
|
|
>
|
|
{client.clientType}
|
|
</span>
|
|
)}
|
|
</td>
|
|
<td className="px-6 py-2.5">
|
|
{shouldShowRfmLoading ? (
|
|
<div className="flex items-center gap-1">
|
|
{[0, 1, 2].map(item => (
|
|
<span key={`rfm-score-loading-${client.customerKey}-${item}`} className="skeleton h-6 w-6 rounded-md" />
|
|
))}
|
|
</div>
|
|
) : (
|
|
<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>
|
|
|
|
<PaginationControls
|
|
totalItems={clientsData.length}
|
|
currentPage={safeCurrentPage}
|
|
totalPages={totalPages}
|
|
pageSize={itemsPerPage}
|
|
pageSizeOptions={[10, 20, 50, 100]}
|
|
itemLabel="clientes"
|
|
pageSizeLabel="itens por página"
|
|
startIndex={startIndex}
|
|
endIndex={Math.min(startIndex + itemsPerPage, clientsData.length)}
|
|
onPageChange={setCurrentPage}
|
|
onPageSizeChange={(pageSize) => {
|
|
setItemsPerPage(pageSize);
|
|
setCurrentPage(1);
|
|
}}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
{isPatternLoading ? (
|
|
<ClientPurchasePatternSkeleton />
|
|
) : (
|
|
<section className="space-y-4">
|
|
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
|
|
<div>
|
|
<h2 className="text-lg font-bold text-zinc-900 dark:text-dark-text">Padrão de Compra</h2>
|
|
<p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">Quando os clientes costumam comprar, separando histórico de data e horário confiável.</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
|
|
<div className="mb-5 flex items-start justify-between gap-4">
|
|
<h3 className="text-sm font-bold uppercase tracking-widest text-zinc-500 dark:text-dark-muted">Compras por Dia</h3>
|
|
<span className="shrink-0 rounded-full border border-zinc-200 bg-white px-2.5 py-1 text-[10px] font-bold uppercase tracking-wide text-zinc-500 dark:border-dark-border dark:bg-dark-input dark:text-dark-muted">
|
|
{weekdayRangeLabel}
|
|
</span>
|
|
</div>
|
|
{hasWeekdayPattern ? (
|
|
<div className="h-56">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<BarChart data={purchasePattern?.purchaseWeekdays || []} margin={{ top: 8, right: 10, left: -18, bottom: 0 }}>
|
|
<CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
|
|
<XAxis dataKey="label" stroke={CHART_AXIS_COLOR} fontSize={11} tickLine={false} axisLine={false} />
|
|
<YAxis allowDecimals={false} stroke={CHART_AXIS_COLOR} fontSize={11} tickLine={false} axisLine={false} />
|
|
<Tooltip content={<PatternTooltip />} cursor={{ fill: CHART_CURSOR_COLOR }} />
|
|
<Bar dataKey="value" radius={[4, 4, 0, 0]} animationDuration={850} animationEasing="ease-out">
|
|
{(purchasePattern?.purchaseWeekdays || []).map(day => (
|
|
<Cell key={`clients-weekday-${day.label}`} fill={WEEKDAY_BAR_COLOR} fillOpacity={0.62} stroke={WEEKDAY_BAR_COLOR} strokeOpacity={0.9} strokeWidth={1.25} />
|
|
))}
|
|
</Bar>
|
|
</BarChart>
|
|
</ResponsiveContainer>
|
|
</div>
|
|
) : (
|
|
<div className="flex h-56 items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
|
|
Sem compras registradas.
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
|
|
<div className="mb-5 flex items-start justify-between gap-4">
|
|
<h3 className="text-sm font-bold uppercase tracking-widest text-zinc-500 dark:text-dark-muted">Compras por Horário</h3>
|
|
<span className="shrink-0 rounded-full border border-zinc-200 bg-white px-2.5 py-1 text-[10px] font-bold uppercase tracking-wide text-zinc-500 dark:border-dark-border dark:bg-dark-input dark:text-dark-muted">
|
|
{hourRangeLabel}
|
|
</span>
|
|
</div>
|
|
{hasHourPattern ? (
|
|
<div className="h-56">
|
|
<ResponsiveContainer width="100%" height="100%">
|
|
<BarChart data={purchasePattern?.purchaseHours || []} margin={{ top: 8, right: 10, left: -18, bottom: 0 }}>
|
|
<CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
|
|
<XAxis
|
|
dataKey="label"
|
|
stroke={CHART_AXIS_COLOR}
|
|
fontSize={10}
|
|
tickLine={false}
|
|
axisLine={false}
|
|
interval={0}
|
|
tickFormatter={(value) => Number(String(value).replace('h', '')) % 3 === 0 ? String(value) : ''}
|
|
/>
|
|
<YAxis allowDecimals={false} stroke={CHART_AXIS_COLOR} fontSize={11} tickLine={false} axisLine={false} />
|
|
<Tooltip content={<PatternTooltip />} cursor={{ fill: CHART_CURSOR_COLOR }} />
|
|
<Bar dataKey="value" radius={[4, 4, 0, 0]} animationDuration={850} animationEasing="ease-out">
|
|
{(purchasePattern?.purchaseHours || []).map(hour => (
|
|
<Cell key={`clients-hour-${hour.label}`} fill={HOUR_BAR_COLOR} fillOpacity={0.56} stroke={HOUR_BAR_COLOR} strokeOpacity={0.86} strokeWidth={1.1} />
|
|
))}
|
|
</Bar>
|
|
</BarChart>
|
|
</ResponsiveContainer>
|
|
</div>
|
|
) : (
|
|
<div className="flex h-56 items-center justify-center px-6 text-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
|
|
Sem horário de compra disponível.
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</section>
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default Clients;
|