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