What-if savings planner page (wishlist #7)

New Planificador page: the current savings pace (prefilled from the
live budget projection's monthly net, editable) versus a scenario with
extra monthly savings, both compounded at a configurable annual rate
over a 1-40 year horizon — side-by-side totals and growth curves.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Carlos Escalante
2026-06-12 18:07:02 -06:00
parent 84f0256b7c
commit c3c14f54c5
3 changed files with 211 additions and 0 deletions

View File

@@ -24,6 +24,7 @@ import Pensions from "./pages/Pensions";
import Proyecciones from "./pages/Proyecciones"; import Proyecciones from "./pages/Proyecciones";
import ServiciosMunicipales from "./pages/ServiciosMunicipales"; import ServiciosMunicipales from "./pages/ServiciosMunicipales";
import SyncStatus from "./pages/SyncStatus"; import SyncStatus from "./pages/SyncStatus";
import Planificador from "./pages/Planificador";
function ProtectedRoute({ children }: { children: React.ReactNode }) { function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { isAuthenticated, isLoading } = useAuth(); const { isAuthenticated, isLoading } = useAuth();
@@ -58,6 +59,7 @@ function AppRoutes() {
<Route path="/pensions" element={<Pensions />} /> <Route path="/pensions" element={<Pensions />} />
<Route path="/servicios-municipales" element={<ServiciosMunicipales />} /> <Route path="/servicios-municipales" element={<ServiciosMunicipales />} />
<Route path="/sync" element={<SyncStatus />} /> <Route path="/sync" element={<SyncStatus />} />
<Route path="/planificador" element={<Planificador />} />
<Route path="/transactions" element={<Navigate to="/budget" replace />} /> <Route path="/transactions" element={<Navigate to="/budget" replace />} />
<Route path="/transfers" element={<Navigate to="/budget" replace />} /> <Route path="/transfers" element={<Navigate to="/budget" replace />} />
</Route> </Route>

View File

@@ -2,6 +2,7 @@ import { useState, useEffect } from "react";
import { Link, Outlet, useLocation, useNavigate } from "react-router-dom"; import { Link, Outlet, useLocation, useNavigate } from "react-router-dom";
import { import {
Sparkles, Sparkles,
Telescope,
Calculator, Calculator,
BarChart3, BarChart3,
Landmark, Landmark,
@@ -55,6 +56,7 @@ const navSections: NavSection[] = [
{ to: "/salarios", icon: Landmark, label: "Salarios" }, { to: "/salarios", icon: Landmark, label: "Salarios" },
{ to: "/pensions", icon: PiggyBank, label: "Pensiones" }, { to: "/pensions", icon: PiggyBank, label: "Pensiones" },
{ to: "/proyecciones", icon: TrendingUp, label: "Proyecciones" }, { to: "/proyecciones", icon: TrendingUp, label: "Proyecciones" },
{ to: "/planificador", icon: Telescope, label: "Planificador" },
{ to: "/analytics", icon: BarChart3, label: "Analytics" }, { to: "/analytics", icon: BarChart3, label: "Analytics" },
], ],
}, },

View File

@@ -0,0 +1,207 @@
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Line, LineChart, XAxis, YAxis } from 'recharts';
import { Telescope } from 'lucide-react';
import { getYearlyProjection } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig,
} from '@/components/ui/chart';
const MIN_YEAR = 2026;
const chartConfig = {
baseline: { label: 'Ritmo actual', color: 'var(--chart-2)' },
scenario: { label: 'Escenario', color: 'var(--chart-1)' },
} satisfies ChartConfig;
const formatCRC = (v: number) =>
`${Math.round(v).toLocaleString('es-CR')}`;
/** What-if planner (wishlist #7): compare the current savings pace against a
* scenario with extra monthly savings, both compounded monthly. The baseline
* pace comes from the live budget projection (annual net / 12) and is
* editable so scenarios can start from any assumption. */
export default function Planificador() {
const currentYear = Math.max(MIN_YEAR, new Date().getFullYear());
const projectionQ = useQuery({
queryKey: ['budget', 'projection', currentYear],
queryFn: () => getYearlyProjection(currentYear).then((r) => r.data),
});
const projectedMonthlyNet = projectionQ.data
? Math.round(projectionQ.data.annual_net / 12)
: null;
const [baseMonthly, setBaseMonthly] = useState<string | null>(null);
const [extraMonthly, setExtraMonthly] = useState('50000');
const [years, setYears] = useState('5');
const [annualRate, setAnnualRate] = useState('5');
// Until the user edits it, the baseline follows the live projection.
const effectiveBase =
baseMonthly !== null
? parseFloat(baseMonthly) || 0
: projectedMonthlyNet ?? 0;
const { series, baselineEnd, scenarioEnd } = useMemo(() => {
const horizon = Math.min(Math.max(parseInt(years, 10) || 0, 1), 40) * 12;
const extra = parseFloat(extraMonthly) || 0;
const r = (parseFloat(annualRate) || 0) / 100 / 12;
let baseline = 0;
let scenario = 0;
const points: { month: number; label: string; baseline: number; scenario: number }[] = [];
for (let m = 1; m <= horizon; m++) {
baseline = baseline * (1 + r) + effectiveBase;
scenario = scenario * (1 + r) + effectiveBase + extra;
if (m % 3 === 0 || m === horizon) {
points.push({
month: m,
label: m % 12 === 0 ? `${m / 12} a` : `${m} m`,
baseline: Math.round(baseline),
scenario: Math.round(scenario),
});
}
}
return {
series: points,
baselineEnd: Math.round(baseline),
scenarioEnd: Math.round(scenario),
};
}, [effectiveBase, extraMonthly, years, annualRate]);
return (
<div className="space-y-6">
<div className="flex items-center gap-3">
<Telescope className="w-6 h-6 text-primary" aria-hidden="true" />
<div>
<h1 className="text-2xl font-bold tracking-tight">Planificador</h1>
<p className="text-sm text-muted-foreground">
¿Qué pasa si ahorrás un poco más cada mes?
</p>
</div>
</div>
<Card>
<CardContent className="p-4 grid grid-cols-2 lg:grid-cols-4 gap-4">
<div className="space-y-1">
<Label className="text-xs">Ahorro mensual actual ()</Label>
<Input
type="number"
step="10000"
value={baseMonthly ?? (projectedMonthlyNet ?? '')}
placeholder={projectionQ.isPending ? 'Calculando…' : '0'}
onChange={(e) => setBaseMonthly(e.target.value)}
/>
<p className="text-[11px] text-muted-foreground">
Prellenado con tu proyección de {currentYear}
</p>
</div>
<div className="space-y-1">
<Label className="text-xs">Ahorro extra mensual ()</Label>
<Input
type="number"
step="10000"
min="0"
value={extraMonthly}
onChange={(e) => setExtraMonthly(e.target.value)}
/>
</div>
<div className="space-y-1">
<Label className="text-xs">Horizonte (años)</Label>
<Input
type="number"
min="1"
max="40"
value={years}
onChange={(e) => setYears(e.target.value)}
/>
</div>
<div className="space-y-1">
<Label className="text-xs">Rendimiento anual (%)</Label>
<Input
type="number"
min="0"
max="30"
step="0.5"
value={annualRate}
onChange={(e) => setAnnualRate(e.target.value)}
/>
</div>
</CardContent>
</Card>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card>
<CardContent className="p-4">
<p className="text-xs text-muted-foreground uppercase tracking-wider">
Ritmo actual
</p>
<p data-sensitive className="text-xl font-bold font-mono">
{formatCRC(baselineEnd)}
</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<p className="text-xs text-muted-foreground uppercase tracking-wider">
Escenario
</p>
<p data-sensitive className="text-xl font-bold font-mono text-primary">
{formatCRC(scenarioEnd)}
</p>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<p className="text-xs text-muted-foreground uppercase tracking-wider">
Diferencia
</p>
<p data-sensitive className="text-xl font-bold font-mono text-emerald-500">
+{formatCRC(scenarioEnd - baselineEnd)}
</p>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle className="text-sm uppercase tracking-wider text-muted-foreground">
Crecimiento comparado
</CardTitle>
</CardHeader>
<CardContent>
<ChartContainer data-sensitive config={chartConfig} className="h-[300px] w-full">
<LineChart data={series}>
<XAxis dataKey="label" axisLine={false} tickLine={false} />
<YAxis
axisLine={false}
tickLine={false}
width={56}
tickFormatter={(v) => `${(v / 1_000_000).toFixed(1)}M`}
/>
<ChartTooltip
content={
<ChartTooltipContent formatter={(value) => formatCRC(Number(value))} />
}
/>
<Line type="monotone" dataKey="baseline" stroke="var(--chart-2)" dot={false} strokeWidth={2} />
<Line type="monotone" dataKey="scenario" stroke="var(--chart-1)" dot={false} strokeWidth={2} />
</LineChart>
</ChartContainer>
<p className="text-xs text-muted-foreground mt-2">
Aporte compuesto mensualmente. El ritmo actual usa el balance neto
proyectado de tu presupuesto; ambos escenarios asumen que lo ahorrado
se invierte al rendimiento indicado.
</p>
</CardContent>
</Card>
</div>
);
}