Analytics: validated palette, bars for daily spend, Empty states, es-CR

Categories fold into 'Otros' past 5 slots (fixed hue order, never
cycled); daily spending excludes future-dated Tasa Cero cuotas; rate
chart gets a legend; PageHeader with the cycle selector as action.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Carlos Escalante
2026-07-04 12:43:57 -06:00
parent a95486481b
commit 2cf19f1880
2 changed files with 129 additions and 88 deletions

View File

@@ -10,6 +10,7 @@ from app.auth import get_current_user
from app.db import get_session from app.db import get_session
from app.models.models import Category, Transaction, TransactionType from app.models.models import Category, Transaction, TransactionType
from app.services.budget_projection import NOT_INSTALLMENT_ANCHOR, get_cycle_range from app.services.budget_projection import NOT_INSTALLMENT_ANCHOR, get_cycle_range
from app.timeutil import utcnow
from app.services.exchange_rate import get_converted_amount_expr from app.services.exchange_rate import get_converted_amount_expr
router = APIRouter(prefix="/analytics", tags=["analytics"]) router = APIRouter(prefix="/analytics", tags=["analytics"])
@@ -178,6 +179,9 @@ def daily_spending(
.where( .where(
Transaction.transaction_type == TransactionType.COMPRA, Transaction.transaction_type == TransactionType.COMPRA,
NOT_INSTALLMENT_ANCHOR, NOT_INSTALLMENT_ANCHOR,
# Tasa Cero generates future-dated cuotas; daily spending is
# about money already spent.
Transaction.date <= utcnow(),
) )
.group_by(func.date(Transaction.date)) .group_by(func.date(Transaction.date))
.order_by(func.date(Transaction.date)) .order_by(func.date(Transaction.date))

View File

@@ -11,14 +11,24 @@ import {
LineChart, LineChart,
Line, Line,
} from 'recharts'; } from 'recharts';
import { BarChart3 } from 'lucide-react'; import { BarChart3, ChartPie } from 'lucide-react';
import api, { getRateHistory } from '@/lib/api'; import api, { getRateHistory } from '@/lib/api';
import ErrorState from '@/components/ErrorState'; import ErrorState from '@/components/ErrorState';
import BillingCycleSelector from '@/components/BillingCycleSelector'; import BillingCycleSelector from '@/components/BillingCycleSelector';
import { PageHeader } from '@/components/page-header';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from '@/components/ui/empty';
import { import {
ChartContainer, ChartContainer,
ChartLegend,
ChartLegendContent,
ChartTooltip, ChartTooltip,
ChartTooltipContent, ChartTooltipContent,
type ChartConfig, type ChartConfig,
@@ -47,32 +57,68 @@ interface DailySpending {
count: number; count: number;
} }
const COLORS = [ /** Fixed categorical slots (validated palette). Never cycled: categories
'#B45309', '#16A34A', '#2563EB', '#DC2626', '#7C3AED', * beyond the 5th fold into "Otros" (muted). */
'#D97706', '#0F766E', '#DB2777', '#EA580C', '#4F46E5', const SERIES_VARS = [
'var(--chart-1)',
'var(--chart-2)',
'var(--chart-3)',
'var(--chart-4)',
'var(--chart-5)',
]; ];
const OTROS_COLOR = 'var(--muted-foreground)';
const MAX_SLICES = 5;
function formatCRC(value: number) { function formatCRC(value: number) {
return `${Math.round(value).toLocaleString('es-CR')}`; return `${Math.round(value).toLocaleString('es-CR')}`;
} }
/** Top 5 categories keep their own slice; the rest aggregate into "Otros". */
function foldCategories(cats: CategorySpending[]) {
if (cats.length <= MAX_SLICES) return cats;
const head = cats.slice(0, MAX_SLICES);
const rest = cats.slice(MAX_SLICES);
return [
...head,
{
category_id: null,
category_name: 'Otros',
total: rest.reduce((s, c) => s + c.total, 0),
count: rest.reduce((s, c) => s + c.count, 0),
percentage: +rest.reduce((s, c) => s + c.percentage, 0).toFixed(1),
},
];
}
function sliceColor(index: number, name: string) {
return name === 'Otros' ? OTROS_COLOR : SERIES_VARS[index % SERIES_VARS.length];
}
function ChartEmpty({ description }: { description: string }) {
return (
<Empty className="h-56">
<EmptyHeader>
<EmptyMedia variant="icon">
<ChartPie />
</EmptyMedia>
<EmptyTitle>Sin datos</EmptyTitle>
<EmptyDescription>{description}</EmptyDescription>
</EmptyHeader>
</Empty>
);
}
const trendChartConfig = { const trendChartConfig = {
total_crc: { total_crc: { label: 'Total CRC', color: 'var(--chart-1)' },
label: 'Total CRC',
color: 'var(--chart-1)',
},
} satisfies ChartConfig; } satisfies ChartConfig;
const rateChartConfig = { const rateChartConfig = {
sell_rate: { label: 'Venta', color: 'var(--chart-1)' }, sell_rate: { label: 'Venta', color: 'var(--chart-1)' },
buy_rate: { label: 'Compra', color: 'var(--chart-2)' }, buy_rate: { label: 'Compra', color: 'var(--chart-5)' },
} satisfies ChartConfig; } satisfies ChartConfig;
const dailyChartConfig = { const dailyChartConfig = {
total: { total: { label: 'Gasto diario', color: 'var(--chart-1)' },
label: 'Gasto Diario',
color: 'var(--chart-2)',
},
} satisfies ChartConfig; } satisfies ChartConfig;
export default function Analytics() { export default function Analytics() {
@@ -106,6 +152,7 @@ export default function Analytics() {
}); });
const byCategory = byCategoryQ.data ?? []; const byCategory = byCategoryQ.data ?? [];
const folded = foldCategories(byCategory);
const trend = trendQ.data ?? []; const trend = trendQ.data ?? [];
const daily = dailyQ.data ?? []; const daily = dailyQ.data ?? [];
const ratesQ = useQuery({ const ratesQ = useQuery({
@@ -125,27 +172,22 @@ export default function Analytics() {
dailyQ.refetch(); dailyQ.refetch();
}; };
// Build dynamic chart config for pie chart const pieChartConfig = folded.reduce<ChartConfig>((acc, cat, i) => {
const pieChartConfig = byCategory.reduce<ChartConfig>((acc, cat, i) => {
acc[cat.category_name] = { acc[cat.category_name] = {
label: cat.category_name, label: cat.category_name,
color: COLORS[i % COLORS.length], color: sliceColor(i, cat.category_name),
}; };
return acc; return acc;
}, {}); }, {});
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4"> <PageHeader
<div> icon={BarChart3}
<div className="flex items-center gap-2"> title="Analytics"
<BarChart3 className="w-5 h-5 text-primary" /> subtitle="Desglose y tendencias de gasto"
<h1 className="text-2xl font-bold font-heading">Analytics</h1> actions={<BillingCycleSelector value={cycle} onChange={setCycle} />}
</div> />
<p className="text-sm text-muted-foreground mt-1">Desglose y tendencias de gasto</p>
</div>
<BillingCycleSelector value={cycle} onChange={setCycle} />
</div>
{anyError && ( {anyError && (
<ErrorState <ErrorState
@@ -155,24 +197,22 @@ export default function Analytics() {
)} )}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Spending by Category - Donut */} {/* Gasto por categoría — donut */}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="text-sm uppercase tracking-wider text-muted-foreground"> <CardTitle className="text-sm font-medium text-muted-foreground">
Spending by Category Gasto por categoría
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{byCategory.length === 0 ? ( {folded.length === 0 ? (
<div className="h-64 flex items-center justify-center text-muted-foreground text-sm"> <ChartEmpty description="Sin gastos en este período." />
Sin datos para este período
</div>
) : ( ) : (
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
<ChartContainer data-sensitive config={pieChartConfig} className="h-[260px] w-full"> <ChartContainer data-sensitive config={pieChartConfig} className="h-[260px] w-full">
<PieChart> <PieChart>
<Pie <Pie
data={byCategory} data={folded}
dataKey="total" dataKey="total"
nameKey="category_name" nameKey="category_name"
cx="50%" cx="50%"
@@ -180,10 +220,12 @@ export default function Analytics() {
innerRadius={60} innerRadius={60}
outerRadius={100} outerRadius={100}
paddingAngle={2} paddingAngle={2}
strokeWidth={0} strokeWidth={2}
stroke="var(--background)"
isAnimationActive={false}
> >
{byCategory.map((_, i) => ( {folded.map((cat, i) => (
<Cell key={i} fill={COLORS[i % COLORS.length]} /> <Cell key={cat.category_name} fill={sliceColor(i, cat.category_name)} />
))} ))}
</Pie> </Pie>
<ChartTooltip <ChartTooltip
@@ -198,11 +240,11 @@ export default function Analytics() {
{/* Legend */} {/* Legend */}
<div className="grid grid-cols-2 gap-x-6 gap-y-1.5 mt-2 w-full max-w-md"> <div className="grid grid-cols-2 gap-x-6 gap-y-1.5 mt-2 w-full max-w-md">
{byCategory.slice(0, 10).map((cat, i) => ( {folded.map((cat, i) => (
<div key={cat.category_name} className="flex items-center gap-2 text-xs"> <div key={cat.category_name} className="flex items-center gap-2 text-xs">
<div <div
className="w-2.5 h-2.5 rounded-full flex-shrink-0" className="w-2.5 h-2.5 rounded-full flex-shrink-0"
style={{ background: COLORS[i % COLORS.length] }} style={{ background: sliceColor(i, cat.category_name) }}
/> />
<span className="text-muted-foreground truncate">{cat.category_name}</span> <span className="text-muted-foreground truncate">{cat.category_name}</span>
<span data-sensitive className="text-muted-foreground/60 ml-auto">{cat.percentage}%</span> <span data-sensitive className="text-muted-foreground/60 ml-auto">{cat.percentage}%</span>
@@ -214,26 +256,20 @@ export default function Analytics() {
</CardContent> </CardContent>
</Card> </Card>
{/* Monthly Trend - Bar */} {/* Gasto mensual — barras por ciclo */}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="text-sm uppercase tracking-wider text-muted-foreground"> <CardTitle className="text-sm font-medium text-muted-foreground">
Monthly Spending (CRC) Gasto mensual por ciclo (CRC)
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{trend.length === 0 ? ( {trend.length === 0 ? (
<div className="h-64 flex items-center justify-center text-muted-foreground text-sm"> <ChartEmpty description="Todavía no hay ciclos con datos." />
No data
</div>
) : ( ) : (
<ChartContainer data-sensitive config={trendChartConfig} className="h-[300px] w-full"> <ChartContainer data-sensitive config={trendChartConfig} className="h-[300px] w-full">
<BarChart data={trend}> <BarChart data={trend}>
<XAxis <XAxis dataKey="label" axisLine={false} tickLine={false} />
dataKey="label"
axisLine={false}
tickLine={false}
/>
<YAxis <YAxis
axisLine={false} axisLine={false}
tickLine={false} tickLine={false}
@@ -246,36 +282,39 @@ export default function Analytics() {
/> />
} }
/> />
<Bar dataKey="total_crc" fill="var(--color-total_crc)" radius={[4, 4, 0, 0]} /> <Bar
dataKey="total_crc"
fill="var(--color-total_crc)"
radius={[4, 4, 0, 0]}
isAnimationActive={false}
/>
</BarChart> </BarChart>
</ChartContainer> </ChartContainer>
)} )}
</CardContent> </CardContent>
</Card> </Card>
{/* Daily Spending - Line */} {/* Gasto diario — barras */}
<Card className="lg:col-span-2"> <Card className="lg:col-span-2">
<CardHeader> <CardHeader>
<CardTitle className="text-sm uppercase tracking-wider text-muted-foreground"> <CardTitle className="text-sm font-medium text-muted-foreground">
Daily Spending Gasto diario
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{daily.length === 0 ? ( {daily.length === 0 ? (
<div className="h-48 flex items-center justify-center text-muted-foreground text-sm"> <ChartEmpty description="Sin gastos en este período." />
Sin datos para este período
</div>
) : ( ) : (
<ChartContainer data-sensitive config={dailyChartConfig} className="h-[240px] w-full"> <ChartContainer data-sensitive config={dailyChartConfig} className="h-[240px] w-full">
<LineChart data={daily}> <BarChart data={daily}>
<XAxis <XAxis
dataKey="date" dataKey="date"
axisLine={false} axisLine={false}
tickLine={false} tickLine={false}
tickFormatter={(v) => { minTickGap={24}
const d = new Date(v); tickFormatter={(v) =>
return `${d.getMonth() + 1}/${d.getDate()}`; new Date(v).toLocaleDateString('es-CR', { month: 'short', day: 'numeric' })
}} }
/> />
<YAxis <YAxis
axisLine={false} axisLine={false}
@@ -292,36 +331,34 @@ export default function Analytics() {
/> />
} }
/> />
<Line <Bar
type="monotone"
dataKey="total" dataKey="total"
stroke="var(--color-total)" fill="var(--color-total)"
strokeWidth={2} radius={[2, 2, 0, 0]}
dot={{ fill: 'var(--color-total)', r: 3 }} isAnimationActive={false}
activeDot={{ r: 5 }}
/> />
</LineChart> </BarChart>
</ChartContainer> </ChartContainer>
)} )}
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
{/* Top categories summary */} {/* Categorías principales */}
{byCategory.length > 0 && ( {byCategory.length > 0 && (
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="text-sm uppercase tracking-wider text-muted-foreground"> <CardTitle className="text-sm font-medium text-muted-foreground">
Top Categories Categorías principales
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="space-y-3"> <div className="space-y-3">
{byCategory.slice(0, 8).map((cat, i) => ( {folded.map((cat, i) => (
<div key={cat.category_name} className="flex items-center gap-3"> <div key={cat.category_name} className="flex items-center gap-3">
<div <div
className="w-3 h-3 rounded-full flex-shrink-0" className="w-3 h-3 rounded-full flex-shrink-0"
style={{ background: COLORS[i % COLORS.length] }} style={{ background: sliceColor(i, cat.category_name) }}
/> />
<span className="text-sm flex-1">{cat.category_name}</span> <span className="text-sm flex-1">{cat.category_name}</span>
<span data-sensitive className="text-xs text-muted-foreground">{cat.count} txns</span> <span data-sensitive className="text-xs text-muted-foreground">{cat.count} txns</span>
@@ -332,8 +369,8 @@ export default function Analytics() {
<div <div
className="h-1.5 rounded-full" className="h-1.5 rounded-full"
style={{ style={{
width: `${cat.percentage}%`, width: `${Math.min(100, cat.percentage)}%`,
background: COLORS[i % COLORS.length], background: sliceColor(i, cat.category_name),
}} }}
/> />
</div> </div>
@@ -343,28 +380,25 @@ export default function Analytics() {
</CardContent> </CardContent>
</Card> </Card>
)} )}
{/* Exchange rate history */}
{/* Tipo de cambio */}
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle className="text-sm uppercase tracking-wider text-muted-foreground"> <CardTitle className="text-sm font-medium text-muted-foreground">
Tipo de Cambio USD/CRC (90 días) Tipo de cambio USD/CRC (90 días)
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{(ratesQ.data?.length ?? 0) < 2 ? ( {(ratesQ.data?.length ?? 0) < 2 ? (
<div className="h-40 flex items-center justify-center text-muted-foreground text-sm"> <ChartEmpty description="Sin historial suficiente." />
Sin historial suficiente
</div>
) : ( ) : (
<ChartContainer <ChartContainer config={rateChartConfig} className="h-[200px] w-full">
config={rateChartConfig}
className="h-[200px] w-full"
>
<LineChart data={ratesQ.data}> <LineChart data={ratesQ.data}>
<XAxis <XAxis
dataKey="day" dataKey="day"
axisLine={false} axisLine={false}
tickLine={false} tickLine={false}
minTickGap={24}
tickFormatter={(v) => tickFormatter={(v) =>
new Date(v).toLocaleDateString('es-CR', { new Date(v).toLocaleDateString('es-CR', {
month: 'short', month: 'short',
@@ -385,19 +419,22 @@ export default function Analytics() {
/> />
} }
/> />
<ChartLegend content={<ChartLegendContent />} />
<Line <Line
type="monotone" type="monotone"
dataKey="sell_rate" dataKey="sell_rate"
stroke="var(--chart-1)" stroke="var(--color-sell_rate)"
dot={false} dot={false}
strokeWidth={2} strokeWidth={2}
isAnimationActive={false}
/> />
<Line <Line
type="monotone" type="monotone"
dataKey="buy_rate" dataKey="buy_rate"
stroke="var(--chart-2)" stroke="var(--color-buy_rate)"
dot={false} dot={false}
strokeWidth={2} strokeWidth={2}
isAnimationActive={false}
/> />
</LineChart> </LineChart>
</ChartContainer> </ChartContainer>