Improve chart readability and drilldowns
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m11s
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 1m11s
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useOutletContext, useNavigate } from 'react-router-dom';
|
||||
import { AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
|
||||
import { AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Line } from 'recharts';
|
||||
import { DollarSign, ShoppingCart, TrendingUp } from 'lucide-react';
|
||||
import DateRangePicker from '../components/DateRangePicker';
|
||||
import RefreshStatus from '../components/RefreshStatus';
|
||||
import type { DashboardAnalytics, OrderData, DateRange } from '../types';
|
||||
import { applyDashboardColors, buildDashboardMetrics } from '../analytics/dashboard';
|
||||
import { fetchDashboardAnalytics } from '../dataService';
|
||||
import { averageRecentValues, formatDateBucketLabel, formatDateBucketLongLabel, getAutoDateBucket, getDateBucketKey, getMovingAverageWindow, type DateBucket } from '../chartUtils';
|
||||
|
||||
const formatCurrency = (value: number) => {
|
||||
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(value);
|
||||
@@ -23,20 +24,6 @@ const formatCompactCurrency = (value: number) => {
|
||||
return formatNumber(value);
|
||||
};
|
||||
|
||||
const formatDateTick = (value: string) => {
|
||||
if (!value) return '';
|
||||
const date = new Date(`${value}T00:00:00`);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: '2-digit' }).format(date);
|
||||
};
|
||||
|
||||
const formatDateLabel = (value: string) => {
|
||||
if (!value) return '';
|
||||
const date = new Date(`${value}T00:00:00`);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return new Intl.DateTimeFormat('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(date);
|
||||
};
|
||||
|
||||
const formatHourKey = (hour: number) => `${String(hour).padStart(2, '0')}h`;
|
||||
|
||||
const formatDateKey = (date: Date) => {
|
||||
@@ -80,7 +67,8 @@ type SellerTimeSeriesSeller = {
|
||||
|
||||
type SellerTimeSeriesChartData = {
|
||||
date: string;
|
||||
[key: string]: string | number;
|
||||
movingAverage?: number;
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
|
||||
type SellerMetricConfig = {
|
||||
@@ -253,9 +241,11 @@ type SellerMetricTooltipProps = {
|
||||
focusedSellerId: string | null;
|
||||
sellers: SellerTimeSeriesSeller[];
|
||||
metricConfig: SellerMetricConfig;
|
||||
isHourly: boolean;
|
||||
dateBucket: DateBucket;
|
||||
};
|
||||
|
||||
const SellerMetricTooltip = ({ active, payload, label, focusedSellerId, sellers, metricConfig }: SellerMetricTooltipProps) => {
|
||||
const SellerMetricTooltip = ({ active, payload, label, focusedSellerId, sellers, metricConfig, isHourly, dateBucket }: SellerMetricTooltipProps) => {
|
||||
if (!active || !payload?.length) return null;
|
||||
|
||||
const sellersByKey = new Map(sellers.map(seller => [seller.seriesKey, seller]));
|
||||
@@ -279,7 +269,9 @@ const SellerMetricTooltip = ({ active, payload, label, focusedSellerId, sellers,
|
||||
className="min-w-56 rounded-xl border p-3 shadow-lg"
|
||||
style={{ backgroundColor: 'var(--chart-tooltip-bg)', borderColor: 'var(--chart-tooltip-border)' }}
|
||||
>
|
||||
<p className="mb-2 text-xs font-bold uppercase tracking-wide text-dark-muted">{formatDateLabel(String(label || ''))}</p>
|
||||
<p className="mb-2 text-xs font-bold uppercase tracking-wide text-dark-muted">
|
||||
{isHourly ? String(label || '') : formatDateBucketLongLabel(String(label || ''), dateBucket)}
|
||||
</p>
|
||||
<div className="space-y-2 text-sm" style={{ color: 'var(--chart-tooltip-text)' }}>
|
||||
{rows.length ? rows.map(({ seller, value }) => (
|
||||
<div key={`seller-tooltip-${seller.id}`} className="flex items-center justify-between gap-4">
|
||||
@@ -310,6 +302,7 @@ const Dashboard = () => {
|
||||
const [isMetricsLoading, setIsMetricsLoading] = useState(true);
|
||||
const [focusedSellerId, setFocusedSellerId] = useState<string | null>(null);
|
||||
const [sellerMetric, setSellerMetric] = useState<SellerMetricKey>('revenue');
|
||||
const [selectedSellerBucket, setSelectedSellerBucket] = useState<string | null>(null);
|
||||
|
||||
const loadDashboardMetrics = useCallback(async (range: DateRange, options?: { force?: boolean }) => {
|
||||
setIsMetricsLoading(true);
|
||||
@@ -374,6 +367,7 @@ const Dashboard = () => {
|
||||
const sellerTimeSeries = useMemo(() => {
|
||||
const isSingleDayRange = formatDateKey(dateRange.start) === formatDateKey(dateRange.end);
|
||||
const isHourly = isSingleDayRange && chartSellerRevenueByHour.length > 0;
|
||||
const dateBucket = getAutoDateBucket(dateRange);
|
||||
const activeTrendPoints = isHourly
|
||||
? chartSellerRevenueByHour.map(point => ({
|
||||
...point,
|
||||
@@ -438,7 +432,7 @@ const Dashboard = () => {
|
||||
return row;
|
||||
});
|
||||
|
||||
return { sellers, chartData, isFallback: true, isHourly };
|
||||
return { sellers, chartData, isFallback: true, isHourly, dateBucket, movingAverageWindow: 0 };
|
||||
}
|
||||
|
||||
const sellersById = new Map<string, Omit<SellerTimeSeriesSeller, 'seriesKey' | 'total'>>();
|
||||
@@ -446,6 +440,7 @@ const Dashboard = () => {
|
||||
|
||||
activeTrendPoints.forEach(point => {
|
||||
const id = point.id || point.name;
|
||||
const bucketKey = isHourly ? point.date : getDateBucketKey(point.date, dateBucket);
|
||||
const existing = sellersById.get(id);
|
||||
sellersById.set(id, {
|
||||
id,
|
||||
@@ -455,10 +450,10 @@ const Dashboard = () => {
|
||||
orders: (existing?.orders || 0) + (point.orders || 0)
|
||||
});
|
||||
|
||||
if (!valuesByDate.has(point.date)) {
|
||||
valuesByDate.set(point.date, new Map());
|
||||
if (!valuesByDate.has(bucketKey)) {
|
||||
valuesByDate.set(bucketKey, new Map());
|
||||
}
|
||||
const dateValues = valuesByDate.get(point.date);
|
||||
const dateValues = valuesByDate.get(bucketKey);
|
||||
if (dateValues) {
|
||||
const existingValue = dateValues.get(id);
|
||||
dateValues.set(id, {
|
||||
@@ -497,11 +492,38 @@ const Dashboard = () => {
|
||||
return row;
|
||||
});
|
||||
|
||||
return { sellers, chartData, isFallback: false, isHourly };
|
||||
}, [chartOrdersBySeller, chartRevenueBySeller, chartSellerRevenueByDate, chartSellerRevenueByHour, dateRange.end, dateRange.start, sellerColorMap, sellerMetric]);
|
||||
const movingAverageWindow = isHourly ? 0 : getMovingAverageWindow(dateBucket);
|
||||
const totals = chartData.map(row => (
|
||||
sellers.reduce((total, seller) => total + Number(row[seller.seriesKey] || 0), 0)
|
||||
));
|
||||
if (movingAverageWindow > 1) {
|
||||
chartData.forEach((row, index) => {
|
||||
row.movingAverage = averageRecentValues(totals, index, movingAverageWindow);
|
||||
});
|
||||
}
|
||||
|
||||
return { sellers, chartData, isFallback: false, isHourly, dateBucket, movingAverageWindow };
|
||||
}, [chartOrdersBySeller, chartRevenueBySeller, chartSellerRevenueByDate, chartSellerRevenueByHour, dateRange, sellerColorMap, sellerMetric]);
|
||||
|
||||
const focusedSeller = focusedSellerId ? sellerTimeSeries.sellers.find(seller => seller.id === focusedSellerId) : null;
|
||||
const effectiveFocusedSellerId = focusedSeller?.id || null;
|
||||
const selectedSellerRow = selectedSellerBucket
|
||||
? sellerTimeSeries.chartData.find(row => row.date === selectedSellerBucket)
|
||||
: null;
|
||||
const selectedSellerBreakdown = selectedSellerRow
|
||||
? sellerTimeSeries.sellers
|
||||
.map(seller => ({
|
||||
seller,
|
||||
value: Number(selectedSellerRow[seller.seriesKey] || 0)
|
||||
}))
|
||||
.filter(item => item.value > 0)
|
||||
.sort((a, b) => b.value - a.value)
|
||||
: [];
|
||||
const selectedSellerBucketLabel = selectedSellerRow
|
||||
? sellerTimeSeries.isHourly
|
||||
? selectedSellerRow.date
|
||||
: formatDateBucketLongLabel(selectedSellerRow.date, sellerTimeSeries.dateBucket)
|
||||
: '';
|
||||
|
||||
const handleManualRefresh = () => {
|
||||
void loadDashboardMetrics(dateRange, { force: true });
|
||||
@@ -580,7 +602,11 @@ const Dashboard = () => {
|
||||
? 'Evolução por horário no dia selecionado.'
|
||||
: sellerTimeSeries.isFallback
|
||||
? sellerMetricConfig.fallbackDescription
|
||||
: sellerMetricConfig.trendDescription}
|
||||
: sellerTimeSeries.dateBucket === 'day'
|
||||
? `${sellerMetricConfig.trendDescription} Média móvel de 7 dias.`
|
||||
: sellerTimeSeries.dateBucket === 'week'
|
||||
? 'Evolução agrupada por semana. Média móvel de 4 semanas.'
|
||||
: 'Evolução agrupada por mês. Média móvel de 3 meses.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
@@ -616,7 +642,13 @@ const Dashboard = () => {
|
||||
<div>
|
||||
<div className="h-96 min-w-0">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={sellerTimeSeries.chartData} margin={{ top: 14, right: 24, left: 4, bottom: 12 }}>
|
||||
<AreaChart
|
||||
data={sellerTimeSeries.chartData}
|
||||
margin={{ top: 14, right: 24, left: 4, bottom: 12 }}
|
||||
onClick={(event) => {
|
||||
if (event?.activeLabel) setSelectedSellerBucket(String(event.activeLabel));
|
||||
}}
|
||||
>
|
||||
<defs>
|
||||
{sellerTimeSeries.sellers.map(seller => (
|
||||
<linearGradient key={`seller-gradient-${seller.seriesKey}`} id={`seller-gradient-${seller.seriesKey}`} x1="0" y1="0" x2="0" y2="1">
|
||||
@@ -634,7 +666,11 @@ const Dashboard = () => {
|
||||
axisLine={false}
|
||||
minTickGap={sellerTimeSeries.isHourly ? 10 : 18}
|
||||
interval={sellerTimeSeries.isHourly ? 2 : undefined}
|
||||
tickFormatter={formatDateTick}
|
||||
tickFormatter={(value) => (
|
||||
sellerTimeSeries.isHourly
|
||||
? String(value)
|
||||
: formatDateBucketLabel(String(value), sellerTimeSeries.dateBucket)
|
||||
)}
|
||||
/>
|
||||
<YAxis
|
||||
stroke={CHART_AXIS_COLOR}
|
||||
@@ -645,9 +681,24 @@ const Dashboard = () => {
|
||||
width={54}
|
||||
/>
|
||||
<Tooltip
|
||||
content={<SellerMetricTooltip focusedSellerId={effectiveFocusedSellerId} sellers={sellerTimeSeries.sellers} metricConfig={sellerMetricConfig} />}
|
||||
content={<SellerMetricTooltip focusedSellerId={effectiveFocusedSellerId} sellers={sellerTimeSeries.sellers} metricConfig={sellerMetricConfig} isHourly={sellerTimeSeries.isHourly} dateBucket={sellerTimeSeries.dateBucket} />}
|
||||
cursor={{ stroke: CHART_AXIS_COLOR, strokeDasharray: '4 4' }}
|
||||
/>
|
||||
{!sellerTimeSeries.isHourly && !sellerTimeSeries.isFallback && sellerTimeSeries.movingAverageWindow > 1 && (
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="movingAverage"
|
||||
name="Média móvel"
|
||||
stroke="var(--chart-label)"
|
||||
strokeWidth={2.5}
|
||||
strokeDasharray="6 5"
|
||||
dot={false}
|
||||
activeDot={false}
|
||||
isAnimationActive
|
||||
animationBegin={160}
|
||||
animationDuration={700}
|
||||
/>
|
||||
)}
|
||||
{sellerTimeSeries.sellers.map(seller => {
|
||||
const isFocused = effectiveFocusedSellerId === seller.id;
|
||||
const isDimmed = Boolean(effectiveFocusedSellerId && !isFocused);
|
||||
@@ -688,6 +739,46 @@ const Dashboard = () => {
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
{selectedSellerRow && (
|
||||
<div className="mt-4 rounded-xl border border-dark-border bg-dark-input/45 p-4">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div>
|
||||
<h4 className="text-sm font-bold text-dark-text">{selectedSellerBucketLabel}</h4>
|
||||
<p className="mt-1 text-xs font-semibold text-dark-muted">
|
||||
Quebra por vendedor no ponto selecionado.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedSellerBucket(null)}
|
||||
className="h-8 rounded-lg border border-dark-border bg-dark-card px-3 text-xs font-bold text-dark-muted transition-colors hover:text-dark-text"
|
||||
>
|
||||
Limpar
|
||||
</button>
|
||||
</div>
|
||||
{selectedSellerBreakdown.length ? (
|
||||
<div className="mt-4 grid gap-2 md:grid-cols-2 xl:grid-cols-3">
|
||||
{selectedSellerBreakdown.slice(0, 6).map(({ seller, value }) => (
|
||||
<button
|
||||
key={`seller-drill-${seller.id}`}
|
||||
type="button"
|
||||
onClick={() => setFocusedSellerId(current => current === seller.id ? null : seller.id)}
|
||||
className="flex min-w-0 cursor-pointer items-center justify-between gap-3 rounded-lg border border-dark-border bg-dark-card px-3 py-2 text-left transition-colors hover:border-brand-primary"
|
||||
>
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: seller.fill }} />
|
||||
<span className="truncate text-xs font-bold text-dark-text">{seller.name}</span>
|
||||
</span>
|
||||
<span className="shrink-0 text-xs font-bold text-dark-muted">{sellerMetricConfig.formatTick(value)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-4 text-sm font-semibold text-dark-muted">Sem valores nesse ponto.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative mt-5 border-t border-dark-border pt-3">
|
||||
<div className="flex h-8 items-center gap-5 overflow-x-auto overflow-y-hidden whitespace-nowrap pr-8 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
{sellerTimeSeries.sellers.map(seller => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams, Link, useOutletContext } from 'react-router-dom';
|
||||
import { Package, DollarSign, ReceiptText, Warehouse } from 'lucide-react';
|
||||
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import { AreaChart, Area, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import BackButton from '../components/BackButton';
|
||||
import DateRangePicker from '../components/DateRangePicker';
|
||||
import RefreshStatus from '../components/RefreshStatus';
|
||||
@@ -9,6 +9,7 @@ import type { DateRange, ProductDetailsAnalytics } from '../types';
|
||||
import { fetchProductDetailsAnalytics } from '../dataService';
|
||||
import { parseProductName } from '../productParsing';
|
||||
import { formatColorLabel } from '../displayFormatters';
|
||||
import { averageRecentValues, formatDateBucketLabel, formatDateBucketLongLabel, getAutoDateBucket, getMovingAverageWindow, getRangeDayCount, getDateBucketKey, type DateBucket } from '../chartUtils';
|
||||
|
||||
const CHART_GRID_COLOR = 'var(--chart-grid)';
|
||||
const CHART_AXIS_COLOR = 'var(--chart-axis)';
|
||||
@@ -18,6 +19,11 @@ const VARIANT_BAR_COLOR = '#52DFA0';
|
||||
|
||||
type ProductChartMetric = 'quantity' | 'revenue' | 'ticket';
|
||||
|
||||
type ProductMetricChartPoint = ProductDetailsAnalytics['chartData'][number] & {
|
||||
selectedValue: number;
|
||||
movingAverage?: number;
|
||||
};
|
||||
|
||||
const formatDateKey = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
@@ -29,26 +35,31 @@ type CustomTooltipProps = {
|
||||
active?: boolean;
|
||||
payload?: Array<{
|
||||
value: number;
|
||||
payload?: ProductDetailsAnalytics['chartData'][number] & { selectedValue?: number };
|
||||
dataKey?: string;
|
||||
payload?: ProductMetricChartPoint;
|
||||
}>;
|
||||
label?: string;
|
||||
metric: ProductChartMetric;
|
||||
formatCurrency: (value: number) => string;
|
||||
formatNumber: (value: number) => string;
|
||||
isHourly: boolean;
|
||||
dateBucket: DateBucket;
|
||||
};
|
||||
|
||||
const CustomTooltip = ({ active, payload, label, metric, formatCurrency, formatNumber }: CustomTooltipProps) => {
|
||||
const CustomTooltip = ({ active, payload, label, metric, formatCurrency, formatNumber, isHourly, dateBucket }: CustomTooltipProps) => {
|
||||
if (active && payload && payload.length) {
|
||||
const point = payload[0].payload;
|
||||
const value = payload[0].value;
|
||||
const primaryPayload = payload.find(item => item.dataKey === 'selectedValue') || payload[0];
|
||||
const point = primaryPayload.payload;
|
||||
const value = primaryPayload.value;
|
||||
const displayValue = metric === 'quantity' ? `${formatNumber(value)} un.` : formatCurrency(value);
|
||||
const displayLabel = isHourly ? String(label || '') : formatDateBucketLongLabel(String(label || ''), dateBucket);
|
||||
|
||||
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="font-bold mb-1" style={{ color: CHART_DETAIL_BAR_COLOR }}>{displayLabel}</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)' }}>
|
||||
@@ -118,6 +129,7 @@ const ProductDetails = () => {
|
||||
const [details, setDetails] = useState<ProductDetailsAnalytics | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [chartMetric, setChartMetric] = useState<ProductChartMetric>('quantity');
|
||||
const [selectedProductBucket, setSelectedProductBucket] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
@@ -171,22 +183,34 @@ const ProductDetails = () => {
|
||||
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 isHourlyChart = isSingleDayRange && chartData.some(point => /h$|:/.test(point.date));
|
||||
const dateBucket = isHourlyChart ? 'day' : getAutoDateBucket(dateRange);
|
||||
const periodDays = getRangeDayCount(dateRange);
|
||||
const dailyAverageSold = totalSold / periodDays;
|
||||
const projectedStockDays = dailyAverageSold > 0 ? productInfo.stock / dailyAverageSold : null;
|
||||
const stockActionLabel = projectedStockDays === null
|
||||
? 'Sem venda no período'
|
||||
: projectedStockDays <= 7
|
||||
? 'Reposição crítica'
|
||||
: projectedStockDays <= 21
|
||||
? 'Planejar reposição'
|
||||
: 'Estoque confortável';
|
||||
const metricConfig = {
|
||||
quantity: {
|
||||
label: 'Unidades',
|
||||
title: `Volume por ${isSingleDayRange ? 'Horário' : 'Data'}`,
|
||||
title: `Volume por ${isHourlyChart ? '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'}`,
|
||||
title: `Receita por ${isHourlyChart ? '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'}`,
|
||||
title: `Ticket médio por ${isHourlyChart ? 'Horário' : 'Data'}`,
|
||||
subtitle: 'Receita média por pedido neste produto.',
|
||||
tickFormatter: (value: number) => value >= 1000 ? `${formatNumber(value / 1000)}k` : formatCurrency(value)
|
||||
}
|
||||
@@ -197,14 +221,62 @@ const ProductDetails = () => {
|
||||
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 metricChartData = (() => {
|
||||
const bucketMap = new Map<string, ProductMetricChartPoint>();
|
||||
|
||||
chartData.forEach(point => {
|
||||
const sourceKey = isHourlyChart ? point.date : getDateBucketKey(point.date, dateBucket);
|
||||
const current = bucketMap.get(sourceKey) || {
|
||||
date: sourceKey,
|
||||
value: 0,
|
||||
quantitySold: 0,
|
||||
revenue: 0,
|
||||
orderCount: 0,
|
||||
averageTicket: 0,
|
||||
selectedValue: 0
|
||||
};
|
||||
const quantity = point.quantitySold ?? point.value ?? 0;
|
||||
const revenue = point.revenue ?? 0;
|
||||
const orderCount = point.orderCount ?? 0;
|
||||
|
||||
current.value = (current.value || 0) + quantity;
|
||||
current.quantitySold = (current.quantitySold || 0) + quantity;
|
||||
current.revenue = (current.revenue || 0) + revenue;
|
||||
current.orderCount = (current.orderCount || 0) + orderCount;
|
||||
current.averageTicket = current.orderCount ? current.revenue / current.orderCount : 0;
|
||||
bucketMap.set(sourceKey, current);
|
||||
});
|
||||
|
||||
const rows = [...bucketMap.values()]
|
||||
.filter(point => (point.quantitySold || point.value || point.revenue || point.orderCount))
|
||||
.sort((a, b) => a.date.localeCompare(b.date))
|
||||
.map(point => ({
|
||||
...point,
|
||||
selectedValue: chartMetric === 'quantity'
|
||||
? (point.quantitySold ?? point.value)
|
||||
: chartMetric === 'revenue'
|
||||
? (point.revenue ?? 0)
|
||||
: (point.averageTicket ?? 0)
|
||||
}));
|
||||
|
||||
const movingAverageWindow = isHourlyChart ? 0 : getMovingAverageWindow(dateBucket);
|
||||
if (movingAverageWindow > 1) {
|
||||
const values = rows.map(point => point.selectedValue);
|
||||
rows.forEach((point, index) => {
|
||||
point.movingAverage = averageRecentValues(values, index, movingAverageWindow);
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
})();
|
||||
const selectedProductPoint = selectedProductBucket
|
||||
? metricChartData.find(point => point.date === selectedProductBucket)
|
||||
: null;
|
||||
const selectedProductBucketLabel = selectedProductPoint
|
||||
? isHourlyChart
|
||||
? selectedProductPoint.date
|
||||
: formatDateBucketLongLabel(selectedProductPoint.date, dateBucket)
|
||||
: '';
|
||||
const maxVariantQuantity = Math.max(...variantBreakdown.map(variant => variant.quantitySold), 0);
|
||||
|
||||
return (
|
||||
@@ -237,6 +309,7 @@ const ProductDetails = () => {
|
||||
<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">{formatNumber(totalSold)}</p>
|
||||
<p className="mt-1 text-xs font-semibold text-dark-muted">{formatNumber(dailyAverageSold)} un./dia</p>
|
||||
</div>
|
||||
<div className="p-3 bg-brand-primary/10 rounded-xl text-brand-primary">
|
||||
<Package size={24} />
|
||||
@@ -264,6 +337,9 @@ const ProductDetails = () => {
|
||||
<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>
|
||||
<p className="mt-1 text-xs font-semibold text-dark-muted">
|
||||
{projectedStockDays === null ? stockActionLabel : `${formatNumber(projectedStockDays)} dias · ${stockActionLabel}`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-3 bg-purple-500/10 rounded-xl text-purple-400">
|
||||
<Warehouse size={24} />
|
||||
@@ -275,7 +351,15 @@ const ProductDetails = () => {
|
||||
<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>
|
||||
<p className="mt-1 text-sm font-medium text-zinc-500 dark:text-dark-muted">
|
||||
{isHourlyChart
|
||||
? selectedMetric.subtitle
|
||||
: dateBucket === 'day'
|
||||
? `${selectedMetric.subtitle} Média móvel de 7 dias.`
|
||||
: dateBucket === 'week'
|
||||
? 'Valores agrupados por semana com média móvel de 4 semanas.'
|
||||
: 'Valores agrupados por mês com média móvel de 3 meses.'}
|
||||
</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 => (
|
||||
@@ -301,7 +385,13 @@ const ProductDetails = () => {
|
||||
) : (
|
||||
<div className="h-[400px] w-full">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={metricChartData} margin={{ top: 5, right: 30, left: 20, bottom: isSingleDayRange ? 24 : 80 }}>
|
||||
<AreaChart
|
||||
data={metricChartData}
|
||||
margin={{ top: 5, right: 30, left: 20, bottom: 28 }}
|
||||
onClick={(event) => {
|
||||
if (event?.activeLabel) setSelectedProductBucket(String(event.activeLabel));
|
||||
}}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="productVolumeGradient" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor={CHART_DETAIL_BAR_COLOR} stopOpacity={0.38} />
|
||||
@@ -311,13 +401,13 @@ const ProductDetails = () => {
|
||||
<CartesianGrid strokeDasharray="3 3" stroke={CHART_GRID_COLOR} vertical={false} />
|
||||
<XAxis
|
||||
dataKey="date" stroke={CHART_AXIS_COLOR} fontSize={10} tickLine={false} axisLine={false}
|
||||
interval={isSingleDayRange ? 2 : 0}
|
||||
angle={isSingleDayRange ? 0 : -45}
|
||||
textAnchor={isSingleDayRange ? 'middle' : 'end'}
|
||||
height={isSingleDayRange ? 24 : 80}
|
||||
minTickGap={18}
|
||||
tickFormatter={(value) => (
|
||||
isHourlyChart ? String(value) : formatDateBucketLabel(String(value), dateBucket)
|
||||
)}
|
||||
/>
|
||||
<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 }} />
|
||||
<Tooltip content={<CustomTooltip metric={chartMetric} formatCurrency={formatCurrency} formatNumber={formatNumber} isHourly={isHourlyChart} dateBucket={dateBucket} />} cursor={{ fill: CHART_CURSOR_COLOR }} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="selectedValue"
|
||||
@@ -327,10 +417,61 @@ const ProductDetails = () => {
|
||||
dot={{ r: 3, strokeWidth: 2, fill: 'var(--color-dark-card)', stroke: CHART_DETAIL_BAR_COLOR }}
|
||||
activeDot={{ r: 5, strokeWidth: 2, fill: CHART_DETAIL_BAR_COLOR, stroke: 'var(--color-dark-card)' }}
|
||||
/>
|
||||
{!isHourlyChart && metricChartData.some(point => point.movingAverage !== undefined) && (
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="movingAverage"
|
||||
name="Média móvel"
|
||||
stroke="var(--chart-label)"
|
||||
strokeWidth={2.5}
|
||||
strokeDasharray="6 5"
|
||||
dot={false}
|
||||
activeDot={false}
|
||||
/>
|
||||
)}
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
{selectedProductPoint && (
|
||||
<div className="mt-4 rounded-xl border border-dark-border bg-dark-input/45 p-4">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
|
||||
<div>
|
||||
<h4 className="text-sm font-bold text-dark-text">{selectedProductBucketLabel}</h4>
|
||||
<p className="mt-1 text-xs font-semibold text-dark-muted">Detalhe do ponto selecionado.</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSelectedProductBucket(null)}
|
||||
className="h-8 rounded-lg border border-dark-border bg-dark-card px-3 text-xs font-bold text-dark-muted transition-colors hover:text-dark-text"
|
||||
>
|
||||
Limpar
|
||||
</button>
|
||||
</div>
|
||||
<div className="mt-4 grid gap-3 md:grid-cols-5">
|
||||
<div>
|
||||
<div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Unidades</div>
|
||||
<div className="mt-1 text-sm font-bold text-dark-text">{formatNumber(selectedProductPoint.quantitySold ?? selectedProductPoint.value ?? 0)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Receita</div>
|
||||
<div className="mt-1 text-sm font-bold text-dark-text">{formatCurrency(selectedProductPoint.revenue ?? 0)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Pedidos</div>
|
||||
<div className="mt-1 text-sm font-bold text-dark-text">{formatNumber(selectedProductPoint.orderCount ?? 0)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Ticket</div>
|
||||
<div className="mt-1 text-sm font-bold text-dark-text">{formatCurrency(selectedProductPoint.averageTicket ?? 0)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-[10px] font-bold uppercase tracking-widest text-dark-muted">Cobertura</div>
|
||||
<div className="mt-1 text-sm font-bold text-dark-text">{projectedStockDays === null ? '-' : `${formatNumber(projectedStockDays)} dias`}</div>
|
||||
</div>
|
||||
</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">
|
||||
|
||||
Reference in New Issue
Block a user