Improve product analytics UI
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m48s

This commit is contained in:
Cauê Faleiros
2026-07-01 10:57:33 -03:00
parent a26bc8813e
commit f5e2de9a35
6 changed files with 417 additions and 76 deletions

View File

@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { useParams, Link, useOutletContext } from 'react-router-dom';
import { ArrowLeft, Package, DollarSign } from 'lucide-react';
import { ArrowLeft, Package, DollarSign, ReceiptText, Warehouse } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import DateRangePicker from '../components/DateRangePicker';
import RefreshStatus from '../components/RefreshStatus';
@@ -11,6 +11,9 @@ const CHART_GRID_COLOR = 'var(--chart-grid)';
const CHART_AXIS_COLOR = 'var(--chart-axis)';
const CHART_CURSOR_COLOR = 'var(--chart-cursor)';
const CHART_DETAIL_BAR_COLOR = 'var(--chart-detail-bar)';
const VARIANT_BAR_COLOR = '#52DFA0';
type ProductChartMetric = 'quantity' | 'revenue' | 'ticket';
const formatDateKey = (date: Date) => {
const year = date.getFullYear();
@@ -21,19 +24,36 @@ const formatDateKey = (date: Date) => {
type CustomTooltipProps = {
active?: boolean;
payload?: Array<{ value: number }>;
payload?: Array<{
value: number;
payload?: ProductDetailsAnalytics['chartData'][number] & { selectedValue?: number };
}>;
label?: string;
metric: ProductChartMetric;
formatCurrency: (value: number) => string;
formatNumber: (value: number) => string;
};
const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
const CustomTooltip = ({ active, payload, label, metric, formatCurrency, formatNumber }: CustomTooltipProps) => {
if (active && payload && payload.length) {
const point = payload[0].payload;
const value = payload[0].value;
const displayValue = metric === 'quantity' ? `${formatNumber(value)} un.` : formatCurrency(value);
return (
<div
className="rounded-xl border p-3 shadow-lg"
style={{ backgroundColor: 'var(--chart-tooltip-bg)', borderColor: 'var(--chart-tooltip-border)' }}
>
<p className="font-bold mb-1" style={{ color: CHART_DETAIL_BAR_COLOR }}>{label}</p>
<p className="m-0" style={{ color: 'var(--chart-tooltip-text)' }}>Vendas: {payload[0].value}</p>
<p className="m-0 font-semibold" style={{ color: 'var(--chart-tooltip-text)' }}>{displayValue}</p>
{point && (
<div className="mt-2 space-y-1 text-xs" style={{ color: 'var(--chart-axis)' }}>
<p className="m-0">Unidades: {formatNumber(point.quantitySold ?? point.value ?? 0)}</p>
<p className="m-0">Receita: {formatCurrency(point.revenue ?? 0)}</p>
<p className="m-0">Pedidos: {formatNumber(point.orderCount ?? 0)}</p>
</div>
)}
</div>
);
}
@@ -56,8 +76,8 @@ const ProductDetailsSkeleton = () => (
<div className="skeleton h-10 w-64" />
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{[0, 1].map(item => (
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
{[0, 1, 2, 3].map(item => (
<div key={`product-details-kpi-skeleton-${item}`} className="bg-dark-card p-6 rounded-2xl border border-dark-border shadow-sm">
<div className="flex justify-between gap-6">
<div className="w-full">
@@ -74,6 +94,15 @@ const ProductDetailsSkeleton = () => (
<div className="skeleton h-5 w-56" />
<div className="mt-8 skeleton h-[400px] w-full" />
</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="skeleton h-5 w-44" />
<div className="mt-5 space-y-3">
{[0, 1, 2, 3].map(item => (
<div key={`product-variant-skeleton-${item}`} className="skeleton h-12 w-full" />
))}
</div>
</div>
</div>
);
@@ -85,6 +114,7 @@ const ProductDetails = () => {
}>();
const [details, setDetails] = useState<ProductDetailsAnalytics | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [chartMetric, setChartMetric] = useState<ProductChartMetric>('quantity');
useEffect(() => {
let isMounted = true;
@@ -118,6 +148,10 @@ const ProductDetails = () => {
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
};
const formatNumber = (value: number) => {
return new Intl.NumberFormat('pt-BR').format(value);
};
if (isLoading && !details) {
return <ProductDetailsSkeleton />;
}
@@ -131,9 +165,44 @@ const ProductDetails = () => {
);
}
const { productInfo, chartData, totalSold, totalRevenue } = details;
const { productInfo, chartData, totalSold, totalRevenue, totalOrders = 0, averageTicket = 0, variantBreakdown = [] } = details;
const isRefreshing = isLoading && Boolean(details);
const isSingleDayRange = formatDateKey(dateRange.start) === formatDateKey(dateRange.end);
const metricConfig = {
quantity: {
label: 'Unidades',
title: `Volume por ${isSingleDayRange ? 'Horário' : 'Data'}`,
subtitle: 'Quantidade vendida no período selecionado.',
tickFormatter: (value: number) => formatNumber(value)
},
revenue: {
label: 'Receita',
title: `Receita por ${isSingleDayRange ? 'Horário' : 'Data'}`,
subtitle: 'Faturamento do produto no período selecionado.',
tickFormatter: (value: number) => value >= 1000 ? `${formatNumber(value / 1000)}k` : formatCurrency(value)
},
ticket: {
label: 'Ticket médio',
title: `Ticket médio por ${isSingleDayRange ? 'Horário' : 'Data'}`,
subtitle: 'Receita média por pedido neste produto.',
tickFormatter: (value: number) => value >= 1000 ? `${formatNumber(value / 1000)}k` : formatCurrency(value)
}
} satisfies Record<ProductChartMetric, {
label: string;
title: string;
subtitle: string;
tickFormatter: (value: number) => string;
}>;
const selectedMetric = metricConfig[chartMetric];
const metricChartData = chartData.map(point => ({
...point,
selectedValue: chartMetric === 'quantity'
? (point.quantitySold ?? point.value)
: chartMetric === 'revenue'
? (point.revenue ?? 0)
: (point.averageTicket ?? 0)
}));
const maxVariantQuantity = Math.max(...variantBreakdown.map(variant => variant.quantitySold), 0);
return (
<div className="space-y-6">
@@ -163,11 +232,11 @@ const ProductDetails = () => {
<RefreshStatus isRefreshing={isRefreshing} />
<div className={isRefreshing ? 'refreshing-content space-y-6' : 'space-y-6'} aria-busy={isRefreshing}>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="grid grid-cols-1 gap-4 md:grid-cols-4">
<div className="bg-dark-card p-6 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
<div>
<p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Unidades Vendidas</p>
<p className="text-3xl font-bold text-dark-text">{totalSold}</p>
<p className="text-3xl font-bold text-dark-text">{formatNumber(totalSold)}</p>
</div>
<div className="p-3 bg-brand-primary/10 rounded-xl text-brand-primary">
<Package size={24} />
@@ -182,15 +251,57 @@ const ProductDetails = () => {
<DollarSign size={24} />
</div>
</div>
<div className="bg-dark-card p-6 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
<div>
<p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Ticket Médio</p>
<p className="text-3xl font-bold text-dark-text">{formatCurrency(averageTicket)}</p>
</div>
<div className="p-3 bg-sky-500/10 rounded-xl text-sky-500">
<ReceiptText size={24} />
</div>
</div>
<div className="bg-dark-card p-6 rounded-2xl border border-dark-border flex items-center justify-between shadow-sm">
<div>
<p className="text-xs font-bold text-dark-muted uppercase tracking-widest mb-1">Estoque</p>
<p className="text-3xl font-bold text-dark-text">{formatNumber(productInfo.stock)}</p>
</div>
<div className="p-3 bg-purple-500/10 rounded-xl text-purple-400">
<Warehouse size={24} />
</div>
</div>
</div>
<div className="bg-white dark:bg-dark-card border border-zinc-200 dark:border-dark-border rounded-2xl p-6 shadow-sm">
<h3 className="text-lg font-bold mb-8 text-zinc-900 dark:text-dark-text">
Volume de Vendas por {isSingleDayRange ? 'Horário' : 'Data'}
</h3>
<div className="mb-8 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
<div>
<h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">{selectedMetric.title}</h3>
<p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">{selectedMetric.subtitle}</p>
</div>
<div className="flex w-fit rounded-xl border border-dark-border bg-dark-input p-1">
{(Object.keys(metricConfig) as ProductChartMetric[]).map(metric => (
<button
key={metric}
type="button"
onClick={() => setChartMetric(metric)}
className={`cursor-pointer rounded-lg px-3 py-1.5 text-xs font-bold transition-colors ${
chartMetric === metric
? 'bg-dark-card text-dark-text shadow-sm'
: 'text-dark-muted hover:text-dark-text'
}`}
>
{metricConfig[metric].label}
</button>
))}
</div>
</div>
{metricChartData.length === 0 ? (
<div className="flex h-[360px] items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
Nenhuma venda no período selecionado.
</div>
) : (
<div className="h-[400px] w-full">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: isSingleDayRange ? 24 : 80 }}>
<AreaChart data={metricChartData} margin={{ top: 5, right: 30, left: 20, bottom: isSingleDayRange ? 24 : 80 }}>
<defs>
<linearGradient id="productVolumeGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={CHART_DETAIL_BAR_COLOR} stopOpacity={0.38} />
@@ -205,11 +316,11 @@ const ProductDetails = () => {
textAnchor={isSingleDayRange ? 'middle' : 'end'}
height={isSingleDayRange ? 24 : 80}
/>
<YAxis stroke={CHART_AXIS_COLOR} fontSize={12} tickLine={false} axisLine={false} />
<Tooltip content={<CustomTooltip />} cursor={{ fill: CHART_CURSOR_COLOR }} />
<YAxis stroke={CHART_AXIS_COLOR} fontSize={12} tickLine={false} axisLine={false} tickFormatter={(value) => selectedMetric.tickFormatter(Number(value))} />
<Tooltip content={<CustomTooltip metric={chartMetric} formatCurrency={formatCurrency} formatNumber={formatNumber} />} cursor={{ fill: CHART_CURSOR_COLOR }} />
<Area
type="monotone"
dataKey="value"
dataKey="selectedValue"
stroke={CHART_DETAIL_BAR_COLOR}
strokeWidth={2.25}
fill="url(#productVolumeGradient)"
@@ -219,6 +330,61 @@ const ProductDetails = () => {
</AreaChart>
</ResponsiveContainer>
</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 flex-col gap-2 md:flex-row md:items-end md:justify-between">
<div>
<h3 className="text-lg font-bold text-zinc-900 dark:text-dark-text">Variações do Produto</h3>
<p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">Tamanhos, cores ou SKUs parecidos no mesmo período.</p>
</div>
<span className="text-xs font-bold uppercase tracking-widest text-zinc-400 dark:text-dark-muted">
{formatNumber(totalOrders)} {totalOrders === 1 ? 'pedido' : 'pedidos'}
</span>
</div>
{variantBreakdown.length === 0 ? (
<div className="flex h-32 items-center justify-center text-sm font-semibold text-zinc-500 dark:text-dark-muted">
Nenhuma variação encontrada para este produto.
</div>
) : (
<div className="space-y-3">
{variantBreakdown.map(variant => {
const width = maxVariantQuantity ? Math.max(4, (variant.quantitySold / maxVariantQuantity) * 100) : 0;
return (
<div key={variant.id} className="rounded-xl border border-dark-border bg-dark-input/45 p-4">
<div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">
<div className="min-w-0">
<div className="truncate text-sm font-bold text-dark-text">{variant.name}</div>
<div className="mt-1 text-[11px] font-medium text-dark-muted">#{variant.id}</div>
</div>
<div className="flex shrink-0 gap-5 text-right text-xs">
<div>
<div className="font-bold text-dark-text">{formatNumber(variant.quantitySold)} un.</div>
<div className="text-dark-muted">vendidas</div>
</div>
<div>
<div className="font-bold text-brand-primary">{formatCurrency(variant.revenue)}</div>
<div className="text-dark-muted">receita</div>
</div>
</div>
</div>
<div className="mt-3 h-2 overflow-hidden rounded-full bg-dark-border">
<div
className="h-full rounded-full"
style={{
width: `${width}%`,
backgroundColor: VARIANT_BAR_COLOR,
opacity: 0.72
}}
/>
</div>
</div>
);
})}
</div>
)}
</div>
</div>
</div>

View File

@@ -7,24 +7,68 @@ import type { DateRange, ProductAnalyticsItem } from '../types';
import { exportToCSV, fetchProductAnalytics } from '../dataService';
import type { ProductSummary } from '../analytics/products';
type ProductHealth = {
label: string;
className: string;
};
const getDateOnlyTime = (value?: string | null) => {
if (!value) return 0;
const date = new Date(`${String(value).slice(0, 10)}T00:00:00`);
return Number.isNaN(date.getTime()) ? 0 : date.getTime();
};
const getProductHealth = (product: ProductSummary, dateRange: DateRange): ProductHealth => {
const endTime = new Date(dateRange.end.getFullYear(), dateRange.end.getMonth(), dateRange.end.getDate()).getTime();
const startTime = new Date(dateRange.start.getFullYear(), dateRange.start.getMonth(), dateRange.start.getDate()).getTime();
const rangeDays = Math.max(1, Math.round((endTime - startTime) / 86400000) + 1);
const lastSaleTime = getDateOnlyTime(product.lastSaleDate);
const firstSaleTime = getDateOnlyTime(product.firstSaleDate);
const daysSinceLastSale = lastSaleTime ? Math.max(0, Math.round((endTime - lastSaleTime) / 86400000)) : Infinity;
const daysSinceFirstSale = firstSaleTime ? Math.max(0, Math.round((endTime - firstSaleTime) / 86400000)) : Infinity;
if (product.totalSold > 0 && product.stock > 0 && product.stock <= Math.max(3, product.totalSold * 0.15)) {
return { label: 'Estoque baixo', className: 'border-amber-500/35 bg-amber-500/10 text-amber-700 dark:text-amber-300' };
}
if (!product.totalSold) {
return { label: 'Sem venda', className: 'border-zinc-500/25 bg-zinc-500/10 text-zinc-600 dark:text-zinc-400' };
}
if (daysSinceFirstSale <= Math.min(14, rangeDays)) {
return { label: 'Novo', className: 'border-cyan-500/35 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300' };
}
if (daysSinceLastSale <= Math.max(1, Math.min(7, Math.ceil(rangeDays * 0.2)))) {
return { label: 'Quente', className: 'border-emerald-500/35 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300' };
}
if (daysSinceLastSale > Math.max(14, Math.ceil(rangeDays * 0.55))) {
return { label: 'Esfriando', className: 'border-orange-500/35 bg-orange-500/10 text-orange-700 dark:text-orange-300' };
}
return { label: 'Estável', className: 'border-sky-500/35 bg-sky-500/10 text-sky-700 dark:text-sky-300' };
};
const ProductTableSkeleton = () => (
<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 produtos">
<div className="border-b border-zinc-100 p-4 dark:border-dark-border">
<div className="grid grid-cols-[120px_1.5fr_120px_100px_140px_110px] gap-6">
{[0, 1, 2, 3, 4, 5].map(item => (
<div className="grid grid-cols-[120px_1.5fr_120px_120px_100px_140px_110px] gap-6">
{[0, 1, 2, 3, 4, 5, 6].map(item => (
<div key={`products-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={`products-row-skeleton-${row}`} className="grid grid-cols-[120px_1.5fr_120px_100px_140px_110px] gap-6 px-6 py-4">
<div key={`products-row-skeleton-${row}`} className="grid grid-cols-[120px_1.5fr_120px_120px_100px_140px_110px] gap-6 px-6 py-4">
<div className="skeleton h-4" />
<div>
<div className="skeleton h-4 w-4/5" />
<div className="skeleton mt-2 h-3 w-32" />
</div>
<div className="skeleton h-4" />
<div className="skeleton h-7 rounded-full" />
<div className="skeleton h-4" />
<div className="skeleton h-4" />
<div className="skeleton h-7 rounded-lg" />
@@ -79,7 +123,9 @@ const Products = () => {
totalSold: product.quantitySold,
revenue: product.revenue,
lastPrice: product.lastPrice,
stock: product.stock
stock: product.stock,
firstSaleDate: product.firstSaleDate,
lastSaleDate: product.lastSaleDate
}));
const filteredProducts = normalizedSearch
? products.filter(product =>
@@ -139,6 +185,8 @@ const Products = () => {
'Descrição': product.name,
'Preço Atual (R$)': product.lastPrice.toFixed(2).replace('.', ','),
'Total Vendido (un.)': product.totalSold,
'Status': getProductHealth(product, dateRange).label,
'Estoque': product.stock,
'Receita Gerada (R$)': product.revenue.toFixed(2).replace('.', ',')
}));
exportToCSV(exportData, `produtos_${new Date().toISOString().split('T')[0]}.csv`);
@@ -165,42 +213,52 @@ const Products = () => {
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">ID Produto</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Descrição</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Total Vendido</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Status</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Estoque</th>
<th className="px-6 py-4 font-bold uppercase tracking-wider text-[10px]">Receita Gerada</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((product) => (
<tr key={product.id} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors group">
<td className="px-6 py-2.5 font-mono text-[11px] text-zinc-400 dark:text-dark-muted">#{product.id}</td>
<td className="px-6 py-2.5">
<div className="font-semibold text-zinc-900 dark:text-dark-text">{product.name}</div>
<div className="text-[10px] text-zinc-400 dark:text-dark-muted font-medium">Preço Atual: {formatCurrency(product.lastPrice)}</div>
</td>
<td className="px-6 py-2.5">
<div className="flex items-center gap-2">
<Package className="w-3.5 h-3.5 text-zinc-400 dark:text-dark-muted" />
<span className="font-bold text-zinc-900 dark:text-dark-text">{product.totalSold} un.</span>
</div>
</td>
<td className="px-6 py-2.5">
<span className="font-bold text-zinc-900 dark:text-dark-text">
{product.stock} un.
</span>
</td>
<td className="px-6 py-2.5 text-brand-primary font-bold">{formatCurrency(product.revenue)}</td>
<td className="px-6 py-2.5 text-right">
<Link
to={`/products/${product.id}`}
className="inline-flex items-center text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity bg-brand-primary/10 px-3 py-1.5 rounded-lg cursor-pointer"
>
<TrendingUp className="w-3.5 h-3.5 mr-1.5" />
Ver Gráfico
</Link>
</td>
</tr>
))}
{paginatedData.map((product) => {
const health = getProductHealth(product, dateRange);
return (
<tr key={product.id} className="hover:bg-zinc-50/80 dark:hover:bg-dark-input/50 transition-colors group">
<td className="px-6 py-2.5 font-mono text-[11px] text-zinc-400 dark:text-dark-muted">#{product.id}</td>
<td className="px-6 py-2.5">
<div className="font-semibold text-zinc-900 dark:text-dark-text">{product.name}</div>
<div className="text-[10px] text-zinc-400 dark:text-dark-muted font-medium">Preço Atual: {formatCurrency(product.lastPrice)}</div>
</td>
<td className="px-6 py-2.5">
<div className="flex items-center gap-2">
<Package className="w-3.5 h-3.5 text-zinc-400 dark:text-dark-muted" />
<span className="font-bold text-zinc-900 dark:text-dark-text">{product.totalSold} un.</span>
</div>
</td>
<td className="px-6 py-2.5">
<span className={`inline-flex rounded-full border px-2.5 py-1 text-[11px] font-bold ${health.className}`}>
{health.label}
</span>
</td>
<td className="px-6 py-2.5">
<span className="font-bold text-zinc-900 dark:text-dark-text">
{product.stock} un.
</span>
</td>
<td className="px-6 py-2.5 text-brand-primary font-bold">{formatCurrency(product.revenue)}</td>
<td className="px-6 py-2.5 text-right">
<Link
to={`/products/${product.id}`}
className="inline-flex items-center text-xs font-bold text-brand-primary hover:opacity-80 transition-opacity bg-brand-primary/10 px-3 py-1.5 rounded-lg cursor-pointer"
>
<TrendingUp className="w-3.5 h-3.5 mr-1.5" />
Ver Gráfico
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>