From 4c58b8bab828ca1a14adfdb336c5f15d17ea3f50 Mon Sep 17 00:00:00 2001 From: le king fu Date: Wed, 15 Apr 2026 18:20:41 -0400 Subject: [PATCH] feat(reports/cartes): new KPI dashboard sub-report with sparklines, top movers, budget adherence and seasonality (#97) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New /reports/cartes page surfaces a dashboard-style snapshot of the reference month: - 4 KPI cards (income / expenses / net / savings rate) showing MoM and YoY deltas simultaneously, each with a 13-month sparkline highlighting the reference month - 12-month income vs expenses overlay chart (bars + net balance line) - Top 5 category increases + top 5 decreases MoM, clickable through to the category zoom report - Budget adherence card: on-target count + 3 worst overruns with progress bars - Seasonality card: reference month vs same calendar month averaged over the two previous years, with deviation indicator All data is fetched in a single getCartesSnapshot() service call that runs four queries concurrently (25-month flow, MoM category deltas, budget-vs-actual, seasonality). Missing months are filled with zeroes in the sparklines but preserved as null in the MoM/YoY deltas so the UI can distinguish "no data" from "zero spend". - Exported pure helpers: shiftMonth, defaultCartesReferencePeriod - 13 vitest cases covering zero data, MoM/YoY computation, January wrap-around, missing-month handling, division by zero for the savings rate, seasonality with and without history, top mover sign splitting and 5-cap Note: src/components/reports/CompareReferenceMonthPicker.tsx is a temporary duplicate — the canonical copy lives on the issue-96 branch (refactor: compare report). Once both branches merge the content is identical and git will dedupe. Keeping the local copy here means the Cartes branch builds cleanly on main without depending on #96. Closes #97 Co-Authored-By: Claude Opus 4.6 (1M context) --- CHANGELOG.fr.md | 3 + CHANGELOG.md | 3 + docs/architecture.md | 4 +- src/App.tsx | 2 + .../reports/cards/BudgetAdherenceCard.tsx | 111 +++++++ .../cards/IncomeExpenseOverlayChart.tsx | 97 ++++++ src/components/reports/cards/KpiCard.tsx | 139 ++++++++ src/components/reports/cards/KpiSparkline.tsx | 50 +++ .../reports/cards/SeasonalityCard.tsx | 106 ++++++ .../reports/cards/TopMoversList.tsx | 86 +++++ src/hooks/useCartes.test.ts | 25 ++ src/hooks/useCartes.ts | 103 ++++++ src/i18n/locales/en.json | 24 +- src/i18n/locales/fr.json | 24 +- src/pages/ReportsCartesPage.tsx | 120 +++++++ src/pages/ReportsPage.tsx | 10 +- src/services/reportService.cartes.test.ts | 229 +++++++++++++ src/services/reportService.ts | 311 ++++++++++++++++++ src/shared/types/index.ts | 81 +++++ 19 files changed, 1523 insertions(+), 5 deletions(-) create mode 100644 src/components/reports/cards/BudgetAdherenceCard.tsx create mode 100644 src/components/reports/cards/IncomeExpenseOverlayChart.tsx create mode 100644 src/components/reports/cards/KpiCard.tsx create mode 100644 src/components/reports/cards/KpiSparkline.tsx create mode 100644 src/components/reports/cards/SeasonalityCard.tsx create mode 100644 src/components/reports/cards/TopMoversList.tsx create mode 100644 src/hooks/useCartes.test.ts create mode 100644 src/hooks/useCartes.ts create mode 100644 src/pages/ReportsCartesPage.tsx create mode 100644 src/services/reportService.cartes.test.ts diff --git a/CHANGELOG.fr.md b/CHANGELOG.fr.md index 61e944f..7eaeefe 100644 --- a/CHANGELOG.fr.md +++ b/CHANGELOG.fr.md @@ -2,6 +2,9 @@ ## [Non publié] +### Ajouté +- **Rapport Cartes** (`/reports/cartes`) : nouveau sous-rapport de type tableau de bord dans le hub Rapports. Combine quatre cartes KPI (Revenus, Dépenses, Solde net, Taux d'épargne) affichant les deltas MoM et YoY simultanément avec une sparkline 13 mois dont le mois de référence est mis en évidence, un graphique overlay revenus vs dépenses sur 12 mois (barres + ligne de solde net), le top 5 des catégories en hausse et en baisse par rapport au mois précédent, une carte d'adhérence au budget (N/M dans la cible plus les 3 pires dépassements avec barres de progression) et une carte de saisonnalité qui compare le mois de référence à la moyenne du même mois sur les deux années précédentes. Toutes les données proviennent d'un seul appel `getCartesSnapshot()` qui exécute ses requêtes en parallèle (#97) + ### Modifié - **Rapport Comparables** (`/reports/compare`) : passage de trois onglets (MoM / YoY / Budget) à deux modes (Réel vs réel / Réel vs budget). La vue « Réel vs réel » affiche désormais un sélecteur de mois de référence en en-tête (défaut : mois précédent), un sous-toggle MoM ↔ YoY, et un graphique en barres groupées côte-à-côte (deux barres par catégorie : période de référence vs période comparée). Le `PeriodSelector` d'URL reste synchronisé avec le sélecteur de mois (#96) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23d39ef..52c4a1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] +### Added +- **Cartes report** (`/reports/cartes`): new dashboard-style sub-report in the Reports hub. Combines four KPI cards (income, expenses, net balance, savings rate) showing MoM and YoY deltas simultaneously with a 13-month sparkline highlighting the reference month, a 12-month income vs. expenses overlay chart (bars + net balance line), top 5 category increases and top 5 decreases vs. the previous month, a budget-adherence card (N/M on-target plus the three worst overruns with progress bars), and a seasonality card that compares the reference month against the same calendar month from the two previous years. All data comes from a single `getCartesSnapshot()` service call that runs its queries concurrently (#97) + ### Changed - **Compare report** (`/reports/compare`): reduced from three tabs (MoM / YoY / Budget) to two modes (Actual vs. actual / Actual vs. budget). The actual-vs-actual view now has an explicit reference-month dropdown in the header (defaults to the previous month), a MoM ↔ YoY sub-toggle, and a grouped side-by-side bar chart (two bars per category: reference period vs. comparison period). The URL `PeriodSelector` stays in sync with the reference month picker (#96) diff --git a/docs/architecture.md b/docs/architecture.md index 5415bec..93166c5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -125,7 +125,7 @@ Pour les **nouveaux profils**, le fichier `consolidated_schema.sql` contient le | `adjustmentService.ts` | Gestion des ajustements | | `budgetService.ts` | Gestion budgétaire | | `dashboardService.ts` | Agrégation données tableau de bord | -| `reportService.ts` | Génération de rapports : `getMonthlyTrends`, `getCategoryOverTime`, `getHighlights`, `getCompareMonthOverMonth`, `getCompareYearOverYear`, `getCategoryZoom` (CTE récursive bornée anti-cycle) | +| `reportService.ts` | Génération de rapports : `getMonthlyTrends`, `getCategoryOverTime`, `getHighlights`, `getCompareMonthOverMonth`, `getCompareYearOverYear`, `getCategoryZoom` (CTE récursive bornée anti-cycle), `getCartesSnapshot` (snapshot dashboard Cartes, requêtes parallèles) | | `dataExportService.ts` | Export de données (chiffré) | | `userPreferenceService.ts` | Stockage préférences utilisateur | | `logService.ts` | Capture des logs console (buffer circulaire, sessionStorage) | @@ -151,6 +151,7 @@ Chaque hook encapsule la logique d'état via `useReducer` : | `useTrends` | Rapport Tendances (sous-vue flux global / par catégorie) | | `useCompare` | Rapport Comparables (mode `actual`/`budget`, sous-toggle MoM ↔ YoY, mois de référence explicite avec wrap-around janvier) | | `useCategoryZoom` | Rapport Zoom catégorie avec rollup sous-catégories | +| `useCartes` | Rapport Cartes (snapshot KPI + sparklines + top movers + budget + saisonnalité via `getCartesSnapshot`) | | `useDataExport` | Export de données | | `useTheme` | Thème clair/sombre | | `useUpdater` | Mise à jour de l'application (gated par entitlement licence) | @@ -289,6 +290,7 @@ Le routing est défini dans `App.tsx`. Toutes les pages sont englobées par `App | `/reports/trends` | `ReportsTrendsPage` | Tendances (flux global + par catégorie) | | `/reports/compare` | `ReportsComparePage` | Comparables (MoM / YoY / Réel vs budget) | | `/reports/category` | `ReportsCategoryPage` | Zoom catégorie avec rollup + édition contextuelle de mots-clés | +| `/reports/cartes` | `ReportsCartesPage` | Tableau de bord KPI avec sparklines, top movers, budget et saisonnalité | | `/settings` | `SettingsPage` | Paramètres | | `/docs` | `DocsPage` | Documentation in-app | | `/changelog` | `ChangelogPage` | Historique des versions (bilingue FR/EN) | diff --git a/src/App.tsx b/src/App.tsx index 436ae75..60e230c 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -14,6 +14,7 @@ import ReportsHighlightsPage from "./pages/ReportsHighlightsPage"; import ReportsTrendsPage from "./pages/ReportsTrendsPage"; import ReportsComparePage from "./pages/ReportsComparePage"; import ReportsCategoryPage from "./pages/ReportsCategoryPage"; +import ReportsCartesPage from "./pages/ReportsCartesPage"; import SettingsPage from "./pages/SettingsPage"; import DocsPage from "./pages/DocsPage"; import ChangelogPage from "./pages/ChangelogPage"; @@ -109,6 +110,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/components/reports/cards/BudgetAdherenceCard.tsx b/src/components/reports/cards/BudgetAdherenceCard.tsx new file mode 100644 index 0000000..3f9ebeb --- /dev/null +++ b/src/components/reports/cards/BudgetAdherenceCard.tsx @@ -0,0 +1,111 @@ +import { useTranslation } from "react-i18next"; +import { Target } from "lucide-react"; +import type { CartesBudgetAdherence } from "../../../shared/types"; + +export interface BudgetAdherenceCardProps { + adherence: CartesBudgetAdherence; +} + +function formatCurrency(amount: number, language: string): string { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "currency", + currency: "CAD", + maximumFractionDigits: 0, + }).format(amount); +} + +function formatPct(pct: number | null, language: string): string { + if (pct === null) return "—"; + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "percent", + maximumFractionDigits: 0, + signDisplay: "always", + }).format(pct / 100); +} + +export default function BudgetAdherenceCard({ adherence }: BudgetAdherenceCardProps) { + const { t, i18n } = useTranslation(); + const { categoriesInTarget, categoriesTotal, worstOverruns } = adherence; + const score = categoriesTotal === 0 ? null : (categoriesInTarget / categoriesTotal) * 100; + + return ( +
+
+ +

+ {t("reports.cartes.budgetAdherenceTitle")} +

+
+ + {categoriesTotal === 0 ? ( +
+ {t("reports.cartes.budgetAdherenceEmpty")} +
+ ) : ( + <> +
+
+ {categoriesInTarget} + + {" / "} + {categoriesTotal} + +
+
+ {t("reports.cartes.budgetAdherenceSubtitle", { + score: + score !== null + ? new Intl.NumberFormat(i18n.language === "fr" ? "fr-CA" : "en-CA", { + style: "percent", + maximumFractionDigits: 0, + }).format(score / 100) + : "—", + })} +
+
+ + {worstOverruns.length > 0 && ( +
+
+ {t("reports.cartes.budgetAdherenceWorst")} +
+ {worstOverruns.map((r) => { + const progressPct = r.budget > 0 ? Math.min((r.actual / r.budget) * 100, 200) : 0; + return ( +
+
+ + + {r.categoryName} + + + {formatCurrency(r.actual, i18n.language)} + {" / "} + {formatCurrency(r.budget, i18n.language)} + + {formatPct(r.overrunPct, i18n.language)} + + +
+
+
+
+
+ ); + })} +
+ )} + + )} +
+ ); +} diff --git a/src/components/reports/cards/IncomeExpenseOverlayChart.tsx b/src/components/reports/cards/IncomeExpenseOverlayChart.tsx new file mode 100644 index 0000000..774c7db --- /dev/null +++ b/src/components/reports/cards/IncomeExpenseOverlayChart.tsx @@ -0,0 +1,97 @@ +import { useTranslation } from "react-i18next"; +import { + ComposedChart, + Bar, + Line, + XAxis, + YAxis, + Tooltip, + Legend, + CartesianGrid, + ReferenceLine, + ResponsiveContainer, +} from "recharts"; +import type { CartesMonthFlow } from "../../../shared/types"; + +export interface IncomeExpenseOverlayChartProps { + flow: CartesMonthFlow[]; +} + +function formatCurrency(amount: number, language: string): string { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "currency", + currency: "CAD", + maximumFractionDigits: 0, + }).format(amount); +} + +function formatMonthShort(month: string, language: string): string { + const [y, m] = month.split("-").map(Number); + if (!Number.isFinite(y) || !Number.isFinite(m)) return month; + return new Intl.DateTimeFormat(language === "fr" ? "fr-CA" : "en-CA", { + month: "short", + year: "2-digit", + }).format(new Date(y, m - 1, 1)); +} + +export default function IncomeExpenseOverlayChart({ flow }: IncomeExpenseOverlayChartProps) { + const { t, i18n } = useTranslation(); + + if (flow.length === 0) { + return ( +
+ {t("reports.empty.noData")} +
+ ); + } + + const data = flow.map((p) => ({ + ...p, + label: formatMonthShort(p.month, i18n.language), + })); + + return ( +
+
+ {t("reports.cartes.flowChartTitle")} +
+ + + + + formatCurrency(v, i18n.language)} + width={80} + /> + + typeof value === "number" ? formatCurrency(value, i18n.language) : String(value) + } + contentStyle={{ + backgroundColor: "var(--card)", + border: "1px solid var(--border)", + borderRadius: "0.5rem", + }} + /> + + + + + + + +
+ ); +} diff --git a/src/components/reports/cards/KpiCard.tsx b/src/components/reports/cards/KpiCard.tsx new file mode 100644 index 0000000..5de9af5 --- /dev/null +++ b/src/components/reports/cards/KpiCard.tsx @@ -0,0 +1,139 @@ +import { useTranslation } from "react-i18next"; +import KpiSparkline from "./KpiSparkline"; +import type { CartesKpi, CartesKpiId } from "../../../shared/types"; + +export interface KpiCardProps { + id: CartesKpiId; + title: string; + kpi: CartesKpi; + format: "currency" | "percent"; + /** When true, positive deltas are rendered in red (e.g. rising expenses). */ + deltaIsBadWhenUp?: boolean; +} + +function formatCurrency(amount: number, language: string): string { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "currency", + currency: "CAD", + maximumFractionDigits: 0, + }).format(amount); +} + +function formatPercent(value: number, language: string, signed = false): string { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "percent", + maximumFractionDigits: 1, + signDisplay: signed ? "always" : "auto", + }).format(value / 100); +} + +function formatValue(value: number, format: "currency" | "percent", language: string): string { + return format === "currency" ? formatCurrency(value, language) : formatPercent(value, language); +} + +function formatDeltaAbs( + value: number, + format: "currency" | "percent", + language: string, +): string { + if (format === "currency") { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "currency", + currency: "CAD", + maximumFractionDigits: 0, + signDisplay: "always", + }).format(value); + } + // Savings rate delta in percentage points — not a % of % + const formatted = new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + maximumFractionDigits: 1, + signDisplay: "always", + }).format(value); + return `${formatted} pt`; +} + +interface DeltaBadgeProps { + abs: number | null; + pct: number | null; + label: string; + format: "currency" | "percent"; + language: string; + deltaIsBadWhenUp: boolean; +} + +function DeltaBadge({ abs, pct, label, format, language, deltaIsBadWhenUp }: DeltaBadgeProps) { + if (abs === null) { + return ( +
+ + {label} + + +
+ ); + } + const isUp = abs >= 0; + const isBad = deltaIsBadWhenUp ? isUp : !isUp; + // Treat near-zero as neutral + const isNeutral = abs === 0; + const colorClass = isNeutral + ? "text-[var(--muted-foreground)]" + : isBad + ? "text-[var(--negative)]" + : "text-[var(--positive)]"; + const absText = formatDeltaAbs(abs, format, language); + const pctText = pct === null ? "" : ` (${formatPercent(pct, language, true)})`; + return ( +
+ + {label} + + + {absText} + {pctText} + +
+ ); +} + +export default function KpiCard({ + id, + title, + kpi, + format, + deltaIsBadWhenUp = false, +}: KpiCardProps) { + const { t, i18n } = useTranslation(); + const language = i18n.language; + + return ( +
+
{title}
+
+ {formatValue(kpi.current, format, language)} +
+ +
+ + +
+
+ ); +} diff --git a/src/components/reports/cards/KpiSparkline.tsx b/src/components/reports/cards/KpiSparkline.tsx new file mode 100644 index 0000000..665f5c7 --- /dev/null +++ b/src/components/reports/cards/KpiSparkline.tsx @@ -0,0 +1,50 @@ +import { LineChart, Line, ResponsiveContainer, YAxis, ReferenceDot } from "recharts"; +import type { CartesSparklinePoint } from "../../../shared/types"; + +export interface KpiSparklineProps { + data: CartesSparklinePoint[]; + color?: string; + height?: number; +} + +/** + * Compact line chart with the reference month (the last point) highlighted + * by a filled dot. Rendered inside the KPI cards on the Cartes page. + */ +export default function KpiSparkline({ + data, + color = "var(--primary)", + height = 40, +}: KpiSparklineProps) { + if (data.length === 0) { + return
; + } + + const chartData = data.map((p, index) => ({ index, value: p.value, month: p.month })); + const lastIndex = chartData.length - 1; + const lastValue = chartData[lastIndex]?.value ?? 0; + + return ( + + + + + + + + ); +} diff --git a/src/components/reports/cards/SeasonalityCard.tsx b/src/components/reports/cards/SeasonalityCard.tsx new file mode 100644 index 0000000..4909569 --- /dev/null +++ b/src/components/reports/cards/SeasonalityCard.tsx @@ -0,0 +1,106 @@ +import { useTranslation } from "react-i18next"; +import { CalendarClock } from "lucide-react"; +import type { CartesSeasonality } from "../../../shared/types"; + +export interface SeasonalityCardProps { + seasonality: CartesSeasonality; + referenceYear: number; + referenceMonth: number; +} + +function formatCurrency(amount: number, language: string): string { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "currency", + currency: "CAD", + maximumFractionDigits: 0, + }).format(amount); +} + +function formatPct(pct: number, language: string, signed = true): string { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "percent", + maximumFractionDigits: 1, + signDisplay: signed ? "always" : "auto", + }).format(pct / 100); +} + +function formatMonthYear(year: number, month: number, language: string): string { + return new Intl.DateTimeFormat(language === "fr" ? "fr-CA" : "en-CA", { + month: "long", + year: "numeric", + }).format(new Date(year, month - 1, 1)); +} + +export default function SeasonalityCard({ + seasonality, + referenceYear, + referenceMonth, +}: SeasonalityCardProps) { + const { t, i18n } = useTranslation(); + const language = i18n.language; + const { referenceAmount, historicalYears, historicalAverage, deviationPct } = seasonality; + + const refLabel = formatMonthYear(referenceYear, referenceMonth, language); + + return ( +
+
+ +

+ {t("reports.cartes.seasonalityTitle")} +

+
+ + {historicalYears.length === 0 ? ( +
+ {t("reports.cartes.seasonalityEmpty")} +
+ ) : ( +
+
+ {refLabel} + + {formatCurrency(referenceAmount, language)} + +
+ +
+ {historicalYears.map((y) => ( +
+ {y.year} + {formatCurrency(y.amount, language)} +
+ ))} + {historicalAverage !== null && ( +
+ {t("reports.cartes.seasonalityAverage")} + + {formatCurrency(historicalAverage, language)} + +
+ )} +
+ + {deviationPct !== null && ( +
5 + ? "text-[var(--negative)]" + : deviationPct < -5 + ? "text-[var(--positive)]" + : "text-[var(--muted-foreground)]" + }`} + > + {t("reports.cartes.seasonalityDeviation", { + pct: formatPct(deviationPct, language), + })} +
+ )} +
+ )} +
+ ); +} diff --git a/src/components/reports/cards/TopMoversList.tsx b/src/components/reports/cards/TopMoversList.tsx new file mode 100644 index 0000000..285ad40 --- /dev/null +++ b/src/components/reports/cards/TopMoversList.tsx @@ -0,0 +1,86 @@ +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { TrendingUp, TrendingDown } from "lucide-react"; +import type { CartesTopMover } from "../../../shared/types"; + +export interface TopMoversListProps { + movers: CartesTopMover[]; + direction: "up" | "down"; +} + +function formatSignedCurrency(amount: number, language: string): string { + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "currency", + currency: "CAD", + maximumFractionDigits: 0, + signDisplay: "always", + }).format(amount); +} + +function formatPct(pct: number | null, language: string): string { + if (pct === null) return "—"; + return new Intl.NumberFormat(language === "fr" ? "fr-CA" : "en-CA", { + style: "percent", + maximumFractionDigits: 1, + signDisplay: "always", + }).format(pct / 100); +} + +function categoryHref(categoryId: number | null): string { + if (categoryId === null) return "/transactions"; + const params = new URLSearchParams(window.location.search); + params.set("cat", String(categoryId)); + return `/reports/category?${params.toString()}`; +} + +export default function TopMoversList({ movers, direction }: TopMoversListProps) { + const { t, i18n } = useTranslation(); + + const title = + direction === "up" + ? t("reports.cartes.topMoversUp") + : t("reports.cartes.topMoversDown"); + const Icon = direction === "up" ? TrendingUp : TrendingDown; + const accentClass = direction === "up" ? "text-[var(--negative)]" : "text-[var(--positive)]"; + + return ( +
+
+ +

{title}

+
+ {movers.length === 0 ? ( +
+ {t("reports.empty.noData")} +
+ ) : ( +
    + {movers.map((m) => ( +
  • + + + + + {m.categoryName} + + + + {formatSignedCurrency(m.deltaAbs, i18n.language)} + + {formatPct(m.deltaPct, i18n.language)} + + + +
  • + ))} +
+ )} +
+ ); +} diff --git a/src/hooks/useCartes.test.ts b/src/hooks/useCartes.test.ts new file mode 100644 index 0000000..58f74a6 --- /dev/null +++ b/src/hooks/useCartes.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from "vitest"; +import { defaultCartesReferencePeriod } from "./useCartes"; + +describe("defaultCartesReferencePeriod", () => { + it("returns the month before the given date", () => { + expect(defaultCartesReferencePeriod(new Date(2026, 3, 15))).toEqual({ + year: 2026, + month: 3, + }); + }); + + it("wraps around January to December of the previous year", () => { + expect(defaultCartesReferencePeriod(new Date(2026, 0, 10))).toEqual({ + year: 2025, + month: 12, + }); + }); + + it("handles the last day of a month", () => { + expect(defaultCartesReferencePeriod(new Date(2026, 5, 30))).toEqual({ + year: 2026, + month: 5, + }); + }); +}); diff --git a/src/hooks/useCartes.ts b/src/hooks/useCartes.ts new file mode 100644 index 0000000..d42cc15 --- /dev/null +++ b/src/hooks/useCartes.ts @@ -0,0 +1,103 @@ +import { useReducer, useCallback, useEffect, useRef } from "react"; +import type { CartesSnapshot } from "../shared/types"; +import { getCartesSnapshot } from "../services/reportService"; +import { useReportsPeriod } from "./useReportsPeriod"; + +interface State { + year: number; + month: number; + snapshot: CartesSnapshot | null; + isLoading: boolean; + error: string | null; +} + +type Action = + | { type: "SET_REFERENCE_PERIOD"; payload: { year: number; month: number } } + | { type: "SET_LOADING"; payload: boolean } + | { type: "SET_SNAPSHOT"; payload: CartesSnapshot } + | { type: "SET_ERROR"; payload: string }; + +/** + * Default reference period for the Cartes report: the month preceding `today`. + * January wraps around to December of the previous year. Exported for tests. + */ +export function defaultCartesReferencePeriod( + today: Date = new Date(), +): { year: number; month: number } { + const y = today.getFullYear(); + const m = today.getMonth() + 1; + if (m === 1) return { year: y - 1, month: 12 }; + return { year: y, month: m - 1 }; +} + +const defaultRef = defaultCartesReferencePeriod(); +const initialState: State = { + year: defaultRef.year, + month: defaultRef.month, + snapshot: null, + isLoading: false, + error: null, +}; + +function reducer(state: State, action: Action): State { + switch (action.type) { + case "SET_REFERENCE_PERIOD": + return { ...state, year: action.payload.year, month: action.payload.month }; + case "SET_LOADING": + return { ...state, isLoading: action.payload }; + case "SET_SNAPSHOT": + return { ...state, snapshot: action.payload, isLoading: false, error: null }; + case "SET_ERROR": + return { ...state, error: action.payload, isLoading: false }; + default: + return state; + } +} + +export function useCartes() { + const { from, to, period, setPeriod, setCustomDates } = useReportsPeriod(); + const [state, dispatch] = useReducer(reducer, initialState); + const fetchIdRef = useRef(0); + + const fetch = useCallback(async (year: number, month: number) => { + const id = ++fetchIdRef.current; + dispatch({ type: "SET_LOADING", payload: true }); + try { + const snapshot = await getCartesSnapshot(year, month); + if (id !== fetchIdRef.current) return; + dispatch({ type: "SET_SNAPSHOT", payload: snapshot }); + } catch (e) { + if (id !== fetchIdRef.current) return; + dispatch({ type: "SET_ERROR", payload: e instanceof Error ? e.message : String(e) }); + } + }, []); + + useEffect(() => { + fetch(state.year, state.month); + }, [fetch, state.year, state.month]); + + // Keep the reference month in sync with the URL `to` date, so navigating + // via PeriodSelector works as expected. + useEffect(() => { + const [y, m] = to.split("-").map(Number); + if (!Number.isFinite(y) || !Number.isFinite(m)) return; + if (y !== state.year || m !== state.month) { + dispatch({ type: "SET_REFERENCE_PERIOD", payload: { year: y, month: m } }); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [to]); + + const setReferencePeriod = useCallback((year: number, month: number) => { + dispatch({ type: "SET_REFERENCE_PERIOD", payload: { year, month } }); + }, []); + + return { + ...state, + setReferencePeriod, + from, + to, + period, + setPeriod, + setCustomDates, + }; +} diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index cd1174d..d48723a 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -397,7 +397,9 @@ "compare": "Compare", "compareDescription": "Compare a reference month against previous month, previous year, or budget", "categoryZoom": "Category Analysis", - "categoryZoomDescription": "Zoom in on a single category" + "categoryZoomDescription": "Zoom in on a single category", + "cartes": "Cards", + "cartesDescription": "KPI dashboard with sparklines, top movers, budget adherence, and seasonality" }, "trends": { "subviewGlobal": "Global flow", @@ -411,6 +413,26 @@ "subModeAria": "Comparison period", "referenceMonth": "Reference month" }, + "cartes": { + "kpiSectionAria": "Key indicators for the reference month", + "income": "Income", + "expenses": "Expenses", + "net": "Net balance", + "savingsRate": "Savings rate", + "deltaMoMLabel": "vs last month", + "deltaYoYLabel": "vs last year", + "flowChartTitle": "Income vs expenses — last 12 months", + "topMoversUp": "Biggest increases", + "topMoversDown": "Biggest decreases", + "budgetAdherenceTitle": "Budget adherence", + "budgetAdherenceSubtitle": "{{score}} of budgeted categories on target", + "budgetAdherenceEmpty": "No budgeted categories this month", + "budgetAdherenceWorst": "Worst overruns", + "seasonalityTitle": "Seasonality", + "seasonalityEmpty": "Not enough history for this month", + "seasonalityAverage": "Average", + "seasonalityDeviation": "{{pct}} vs average" + }, "category": { "selectCategory": "Select a category", "includeSubcategories": "Include subcategories", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 2a90a66..cf93a73 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -397,7 +397,9 @@ "compare": "Comparables", "compareDescription": "Comparer un mois de référence au précédent, à l'année passée ou au budget", "categoryZoom": "Analyse par catégorie", - "categoryZoomDescription": "Zoom sur une catégorie" + "categoryZoomDescription": "Zoom sur une catégorie", + "cartes": "Cartes", + "cartesDescription": "Tableau de bord KPI, sparklines, top mouvements, budget et saisonnalité" }, "trends": { "subviewGlobal": "Flux global", @@ -411,6 +413,26 @@ "subModeAria": "Période de comparaison", "referenceMonth": "Mois de référence" }, + "cartes": { + "kpiSectionAria": "Indicateurs clés du mois de référence", + "income": "Revenus", + "expenses": "Dépenses", + "net": "Solde net", + "savingsRate": "Taux d'épargne", + "deltaMoMLabel": "vs mois précédent", + "deltaYoYLabel": "vs l'an dernier", + "flowChartTitle": "Revenus vs dépenses — 12 derniers mois", + "topMoversUp": "Catégories en hausse", + "topMoversDown": "Catégories en baisse", + "budgetAdherenceTitle": "Respect du budget", + "budgetAdherenceSubtitle": "{{score}} des catégories avec budget sont dans la cible", + "budgetAdherenceEmpty": "Aucune catégorie avec budget ce mois-ci", + "budgetAdherenceWorst": "Pires dépassements", + "seasonalityTitle": "Saisonnalité", + "seasonalityEmpty": "Pas assez d'historique pour ce mois", + "seasonalityAverage": "Moyenne", + "seasonalityDeviation": "{{pct}} par rapport à la moyenne" + }, "category": { "selectCategory": "Choisir une catégorie", "includeSubcategories": "Inclure les sous-catégories", diff --git a/src/pages/ReportsCartesPage.tsx b/src/pages/ReportsCartesPage.tsx new file mode 100644 index 0000000..d6157ca --- /dev/null +++ b/src/pages/ReportsCartesPage.tsx @@ -0,0 +1,120 @@ +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { ArrowLeft } from "lucide-react"; +import PeriodSelector from "../components/dashboard/PeriodSelector"; +import CompareReferenceMonthPicker from "../components/reports/CompareReferenceMonthPicker"; +import KpiCard from "../components/reports/cards/KpiCard"; +import IncomeExpenseOverlayChart from "../components/reports/cards/IncomeExpenseOverlayChart"; +import TopMoversList from "../components/reports/cards/TopMoversList"; +import BudgetAdherenceCard from "../components/reports/cards/BudgetAdherenceCard"; +import SeasonalityCard from "../components/reports/cards/SeasonalityCard"; +import { useCartes } from "../hooks/useCartes"; + +export default function ReportsCartesPage() { + const { t } = useTranslation(); + const { + year, + month, + snapshot, + isLoading, + error, + setReferencePeriod, + period, + setPeriod, + from, + to, + setCustomDates, + } = useCartes(); + + const preserveSearch = typeof window !== "undefined" ? window.location.search : ""; + + return ( +
+
+ + + +

{t("reports.hub.cartes")}

+
+ +
+ + +
+ + {error && ( +
+ {error} +
+ )} + + {!snapshot ? ( +
+ {t("reports.empty.noData")} +
+ ) : ( +
+
+ + + + +
+ + + +
+ + +
+ +
+ + +
+
+ )} +
+ ); +} diff --git a/src/pages/ReportsPage.tsx b/src/pages/ReportsPage.tsx index 0785c07..66b5f72 100644 --- a/src/pages/ReportsPage.tsx +++ b/src/pages/ReportsPage.tsx @@ -1,5 +1,5 @@ import { useTranslation } from "react-i18next"; -import { Sparkles, TrendingUp, Scale, Search } from "lucide-react"; +import { Sparkles, TrendingUp, Scale, Search, LayoutDashboard } from "lucide-react"; import { PageHelp } from "../components/shared/PageHelp"; import PeriodSelector from "../components/dashboard/PeriodSelector"; import HubHighlightsPanel from "../components/reports/HubHighlightsPanel"; @@ -38,6 +38,12 @@ export default function ReportsPage() { title: t("reports.hub.categoryZoom"), description: t("reports.hub.categoryZoomDescription"), }, + { + to: `/reports/cartes${preserveSearch}`, + icon: , + title: t("reports.hub.cartes"), + description: t("reports.hub.cartesDescription"), + }, ]; return ( @@ -62,7 +68,7 @@ export default function ReportsPage() {

{t("reports.hub.explore")}

-
+
{navCards.map((card) => ( ))} diff --git a/src/services/reportService.cartes.test.ts b/src/services/reportService.cartes.test.ts new file mode 100644 index 0000000..4e459fb --- /dev/null +++ b/src/services/reportService.cartes.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { shiftMonth, getCartesSnapshot } from "./reportService"; + +vi.mock("./db", () => ({ + getDb: vi.fn(), +})); + +import { getDb } from "./db"; + +const mockSelect = vi.fn(); +const mockDb = { select: mockSelect }; + +beforeEach(() => { + vi.mocked(getDb).mockResolvedValue(mockDb as never); + mockSelect.mockReset(); +}); + +describe("shiftMonth", () => { + it("shifts forward within a year", () => { + expect(shiftMonth(2026, 1, 2)).toEqual({ year: 2026, month: 3 }); + }); + + it("shifts backward within a year", () => { + expect(shiftMonth(2026, 6, -3)).toEqual({ year: 2026, month: 3 }); + }); + + it("wraps around January to the previous year", () => { + expect(shiftMonth(2026, 1, -1)).toEqual({ year: 2025, month: 12 }); + }); + + it("wraps past multiple years back", () => { + expect(shiftMonth(2026, 4, -24)).toEqual({ year: 2024, month: 4 }); + }); + + it("wraps past year forward", () => { + expect(shiftMonth(2025, 11, 3)).toEqual({ year: 2026, month: 2 }); + }); +}); + +/** + * Dispatch mock SELECT responses based on the SQL fragment being queried. + * Each entry returns the canned rows for queries whose text contains `match`. + */ +function routeSelect(routes: { match: string; rows: unknown[] }[]): void { + mockSelect.mockImplementation((sql: string) => { + for (const r of routes) { + if (sql.includes(r.match)) return Promise.resolve(r.rows); + } + return Promise.resolve([]); + }); +} + +describe("getCartesSnapshot", () => { + it("returns zero-filled KPIs when there is no data", async () => { + routeSelect([]); + const snapshot = await getCartesSnapshot(2026, 3); + expect(snapshot.referenceYear).toBe(2026); + expect(snapshot.referenceMonth).toBe(3); + expect(snapshot.kpis.income.current).toBe(0); + expect(snapshot.kpis.expenses.current).toBe(0); + expect(snapshot.kpis.net.current).toBe(0); + expect(snapshot.kpis.savingsRate.current).toBe(0); + expect(snapshot.kpis.income.sparkline).toHaveLength(13); + expect(snapshot.flow12Months).toHaveLength(12); + expect(snapshot.topMoversUp).toHaveLength(0); + expect(snapshot.topMoversDown).toHaveLength(0); + expect(snapshot.budgetAdherence.categoriesTotal).toBe(0); + expect(snapshot.seasonality.historicalYears).toHaveLength(0); + expect(snapshot.seasonality.historicalAverage).toBeNull(); + expect(snapshot.seasonality.deviationPct).toBeNull(); + }); + + it("computes MoM and YoY deltas from a monthly flow stream", async () => { + // Reference = 2026-03 + routeSelect([ + { + match: "strftime('%Y-%m', date)", + rows: [ + { month: "2025-03", income: 3000, expenses: 1800 }, // YoY comparison + { month: "2026-02", income: 4000, expenses: 2000 }, // MoM comparison + { month: "2026-03", income: 5000, expenses: 2500 }, // Reference + ], + }, + ]); + + const snapshot = await getCartesSnapshot(2026, 3); + + expect(snapshot.kpis.income.current).toBe(5000); + expect(snapshot.kpis.income.previousMonth).toBe(4000); + expect(snapshot.kpis.income.previousYear).toBe(3000); + expect(snapshot.kpis.income.deltaMoMAbs).toBe(1000); + expect(snapshot.kpis.income.deltaMoMPct).toBe(25); + expect(snapshot.kpis.income.deltaYoYAbs).toBe(2000); + expect(Math.round(snapshot.kpis.income.deltaYoYPct ?? 0)).toBe(67); + + expect(snapshot.kpis.expenses.current).toBe(2500); + expect(snapshot.kpis.net.current).toBe(2500); + expect(snapshot.kpis.savingsRate.current).toBe(50); + }); + + it("January reference month shifts MoM to December of previous year", async () => { + routeSelect([ + { + match: "strftime('%Y-%m', date)", + rows: [ + { month: "2025-12", income: 2000, expenses: 1000 }, + { month: "2026-01", income: 3000, expenses: 1500 }, + ], + }, + ]); + + const snapshot = await getCartesSnapshot(2026, 1); + + expect(snapshot.kpis.income.current).toBe(3000); + expect(snapshot.kpis.income.previousMonth).toBe(2000); + // YoY for January 2026 = January 2025 = no data + expect(snapshot.kpis.income.previousYear).toBeNull(); + expect(snapshot.kpis.income.deltaYoYAbs).toBeNull(); + }); + + it("savings rate stays at 0 when income is zero (no division by zero)", async () => { + routeSelect([ + { + match: "strftime('%Y-%m', date)", + rows: [ + { month: "2026-03", income: 0, expenses: 500 }, + ], + }, + ]); + + const snapshot = await getCartesSnapshot(2026, 3); + expect(snapshot.kpis.savingsRate.current).toBe(0); + expect(snapshot.kpis.income.current).toBe(0); + expect(snapshot.kpis.expenses.current).toBe(500); + expect(snapshot.kpis.net.current).toBe(-500); + }); + + it("handles less than 13 months of history by filling gaps with zero", async () => { + routeSelect([ + { + match: "strftime('%Y-%m', date)", + rows: [ + { month: "2026-03", income: 1000, expenses: 400 }, + ], + }, + ]); + + const snapshot = await getCartesSnapshot(2026, 3); + expect(snapshot.kpis.income.sparkline).toHaveLength(13); + // First 12 points are zero, last one is 1000 + expect(snapshot.kpis.income.sparkline[12].value).toBe(1000); + expect(snapshot.kpis.income.sparkline[0].value).toBe(0); + // MoM comparison with a missing month returns null (no data for 2026-02) + expect(snapshot.kpis.income.previousMonth).toBeNull(); + expect(snapshot.kpis.income.deltaMoMAbs).toBeNull(); + }); + + it("computes seasonality only when historical data exists", async () => { + routeSelect([ + { + match: "strftime('%Y-%m', date)", + rows: [{ month: "2026-03", income: 3000, expenses: 1500 }], + }, + { + match: "CAST(strftime('%Y', date) AS INTEGER) AS year", + rows: [ + { year: 2025, amount: 1200 }, + { year: 2024, amount: 1000 }, + ], + }, + ]); + + const snapshot = await getCartesSnapshot(2026, 3); + expect(snapshot.seasonality.historicalYears).toHaveLength(2); + expect(snapshot.seasonality.historicalAverage).toBe(1100); + expect(snapshot.seasonality.referenceAmount).toBe(1500); + // (1500 - 1100) / 1100 * 100 ≈ 36.36 + expect(Math.round(snapshot.seasonality.deviationPct ?? 0)).toBe(36); + }); + + it("seasonality deviation stays null when there is no historical average", async () => { + routeSelect([ + { + match: "strftime('%Y-%m', date)", + rows: [{ month: "2026-03", income: 2000, expenses: 800 }], + }, + ]); + + const snapshot = await getCartesSnapshot(2026, 3); + expect(snapshot.seasonality.historicalYears).toHaveLength(0); + expect(snapshot.seasonality.historicalAverage).toBeNull(); + expect(snapshot.seasonality.deviationPct).toBeNull(); + }); + + it("splits top movers by sign and caps each list at 5", async () => { + // Seven up-movers, three down-movers — verify we get 5 up and 3 down. + const momRows = [ + { category_id: 1, category_name: "C1", category_color: "#000", current_total: 200, previous_total: 100 }, + { category_id: 2, category_name: "C2", category_color: "#000", current_total: 400, previous_total: 100 }, + { category_id: 3, category_name: "C3", category_color: "#000", current_total: 500, previous_total: 100 }, + { category_id: 4, category_name: "C4", category_color: "#000", current_total: 700, previous_total: 100 }, + { category_id: 5, category_name: "C5", category_color: "#000", current_total: 900, previous_total: 100 }, + { category_id: 6, category_name: "C6", category_color: "#000", current_total: 1100, previous_total: 100 }, + { category_id: 7, category_name: "C7", category_color: "#000", current_total: 1300, previous_total: 100 }, + { category_id: 8, category_name: "D1", category_color: "#000", current_total: 100, previous_total: 500 }, + { category_id: 9, category_name: "D2", category_color: "#000", current_total: 100, previous_total: 700 }, + { category_id: 10, category_name: "D3", category_color: "#000", current_total: 100, previous_total: 900 }, + ]; + routeSelect([ + { + match: "strftime('%Y-%m', date)", + rows: [{ month: "2026-03", income: 1000, expenses: 500 }], + }, + { + // Matches the getCompareMonthOverMonth SQL pattern. + match: "ORDER BY ABS(current_total - previous_total) DESC", + rows: momRows, + }, + ]); + + const snapshot = await getCartesSnapshot(2026, 3); + expect(snapshot.topMoversUp).toHaveLength(5); + expect(snapshot.topMoversDown).toHaveLength(3); + // Top up is the biggest delta (C7: +1200) + expect(snapshot.topMoversUp[0].categoryName).toBe("C7"); + // Top down is the biggest negative delta (D3: -800) + expect(snapshot.topMoversDown[0].categoryName).toBe("D3"); + }); +}); diff --git a/src/services/reportService.ts b/src/services/reportService.ts index 8b85088..efe9632 100644 --- a/src/services/reportService.ts +++ b/src/services/reportService.ts @@ -1,4 +1,5 @@ import { getDb } from "./db"; +import { getBudgetVsActualData } from "./budgetService"; import type { MonthlyTrendItem, CategoryBreakdownItem, @@ -12,6 +13,15 @@ import type { CategoryZoomEvolutionPoint, MonthBalance, RecentTransaction, + CartesSnapshot, + CartesKpi, + CartesSparklinePoint, + CartesTopMover, + CartesMonthFlow, + CartesBudgetAdherence, + CartesBudgetWorstOverrun, + CartesSeasonality, + CartesSeasonalityYear, } from "../shared/types"; export async function getMonthlyTrends( @@ -570,3 +580,304 @@ export async function getCategoryZoom( transactions: txRows, }; } + +// --- Cartes dashboard (Issue #97) --- + +/** + * Signed month shift. Exported for unit tests. + * shiftMonth(2026, 1, -1) -> { year: 2025, month: 12 } + * shiftMonth(2026, 4, -24) -> { year: 2024, month: 4 } + */ +export function shiftMonth( + year: number, + month: number, + offset: number, +): { year: number; month: number } { + const total = year * 12 + (month - 1) + offset; + return { + year: Math.floor(total / 12), + month: (total % 12) + 1, + }; +} + +function monthKey(year: number, month: number): string { + return `${year}-${String(month).padStart(2, "0")}`; +} + +function extractDelta( + current: number, + previous: number | null, +): { abs: number | null; pct: number | null } { + if (previous === null) return { abs: null, pct: null }; + const abs = current - previous; + const pct = previous === 0 ? null : (abs / previous) * 100; + return { abs, pct }; +} + +function buildKpi( + sparkline: CartesSparklinePoint[], + current: number, + previousMonth: number | null, + previousYear: number | null, +): CartesKpi { + const mom = extractDelta(current, previousMonth); + const yoy = extractDelta(current, previousYear); + return { + current, + previousMonth, + previousYear, + deltaMoMAbs: mom.abs, + deltaMoMPct: mom.pct, + deltaYoYAbs: yoy.abs, + deltaYoYPct: yoy.pct, + sparkline, + }; +} + +interface RawMonthFlow { + month: string; + income: number | null; + expenses: number | null; +} + +async function fetchMonthlyFlows( + dateFrom: string, + dateTo: string, +): Promise { + const db = await getDb(); + return db.select( + `SELECT + strftime('%Y-%m', date) AS month, + COALESCE(SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END), 0) AS income, + ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS expenses + FROM transactions + WHERE date >= $1 AND date <= $2 + GROUP BY month + ORDER BY month ASC`, + [dateFrom, dateTo], + ); +} + +interface RawSeasonalityRow { + year: number; + amount: number | null; +} + +async function fetchSeasonality( + month: number, + yearFrom: number, + yearTo: number, +): Promise { + const db = await getDb(); + const mm = String(month).padStart(2, "0"); + return db.select( + `SELECT + CAST(strftime('%Y', date) AS INTEGER) AS year, + ABS(COALESCE(SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END), 0)) AS amount + FROM transactions + WHERE strftime('%m', date) = $1 + AND CAST(strftime('%Y', date) AS INTEGER) >= $2 + AND CAST(strftime('%Y', date) AS INTEGER) <= $3 + GROUP BY year + ORDER BY year DESC`, + [mm, yearFrom, yearTo], + ); +} + +/** + * Cartes dashboard snapshot. Single entry point that returns every widget's + * data for the Cartes report, computed against a reference (year, month). + * + * Layout (all concurrent): + * 1. 25-month expense/income series (covers ref, MoM, YoY, 12-month flow, + * 13-month sparklines without any extra round trips). + * 2. Month-over-month category deltas for top movers (existing service). + * 3. Year-over-year category deltas to seed the savings-rate YoY lookup + * via the monthly series instead of re-querying. + * 4. Budget vs actual for the reference month. + * 5. Seasonality: same calendar month across the two prior years. + */ +export async function getCartesSnapshot( + referenceYear: number, + referenceMonth: number, +): Promise { + // Date window: 25 months back from the reference to cover YoY + a 13-month + // sparkline. Start = 24 months before ref = (ref - 24 months) = month offset -24. + const windowStart = shiftMonth(referenceYear, referenceMonth, -24); + const { start: windowStartIso } = monthBoundaries(windowStart.year, windowStart.month); + const { end: refEnd } = monthBoundaries(referenceYear, referenceMonth); + + // Seasonality range: previous 2 years for the same calendar month. + const [seasonalityRows, flowRows, momRows, budgetRows] = await Promise.all([ + fetchSeasonality(referenceMonth, referenceYear - 2, referenceYear - 1), + fetchMonthlyFlows(windowStartIso, refEnd), + getCompareMonthOverMonth(referenceYear, referenceMonth), + getBudgetVsActualData(referenceYear, referenceMonth), + ]); + + // Index the flow rows by month for O(1) lookup, then fill missing months + // with zeroes so downstream consumers get a contiguous series. + const flowByMonth = new Map(); + for (const r of flowRows) { + flowByMonth.set(r.month, { + income: Number(r.income ?? 0), + expenses: Number(r.expenses ?? 0), + }); + } + + const buildSeries = (count: number): CartesMonthFlow[] => { + const series: CartesMonthFlow[] = []; + for (let i = count - 1; i >= 0; i--) { + const { year: y, month: m } = shiftMonth(referenceYear, referenceMonth, -i); + const key = monthKey(y, m); + const row = flowByMonth.get(key); + const income = row?.income ?? 0; + const expenses = row?.expenses ?? 0; + series.push({ month: key, income, expenses, net: income - expenses }); + } + return series; + }; + + // 13-month sparklines for each KPI (reference month + 12 prior). + const sparkSeries = buildSeries(13); + const incomeSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({ + month: p.month, + value: p.income, + })); + const expensesSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({ + month: p.month, + value: p.expenses, + })); + const netSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({ + month: p.month, + value: p.net, + })); + const savingsSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({ + month: p.month, + value: p.income > 0 ? (p.net / p.income) * 100 : 0, + })); + + // Compute MoM / YoY values directly from `flowByMonth` (which preserves the + // "missing" distinction). The sparkline fills gaps with zero for display, + // but deltas must remain null when the comparison month has no data. + const refKey = monthKey(referenceYear, referenceMonth); + const momMeta = shiftMonth(referenceYear, referenceMonth, -1); + const momKey = monthKey(momMeta.year, momMeta.month); + const yoyMeta = { year: referenceYear - 1, month: referenceMonth }; + const yoyKey = monthKey(yoyMeta.year, yoyMeta.month); + + const refRow = flowByMonth.get(refKey); + const refIncome = refRow?.income ?? 0; + const refExpenses = refRow?.expenses ?? 0; + const refNet = refIncome - refExpenses; + const refSavings = refIncome > 0 ? (refNet / refIncome) * 100 : 0; + + const momRow = flowByMonth.get(momKey); + const momIncome = momRow ? momRow.income : null; + const momExpenses = momRow ? momRow.expenses : null; + const momNet = momRow ? momRow.income - momRow.expenses : null; + const momSavings = + momRow && momRow.income > 0 ? ((momRow.income - momRow.expenses) / momRow.income) * 100 : null; + + const yoyRow = flowByMonth.get(yoyKey); + const yoyIncome = yoyRow ? yoyRow.income : null; + const yoyExpenses = yoyRow ? yoyRow.expenses : null; + const yoyNet = yoyRow ? yoyRow.income - yoyRow.expenses : null; + const yoySavings = + yoyRow && yoyRow.income > 0 ? ((yoyRow.income - yoyRow.expenses) / yoyRow.income) * 100 : null; + + const incomeKpi = buildKpi(incomeSpark, refIncome, momIncome, yoyIncome); + const expensesKpi = buildKpi(expensesSpark, refExpenses, momExpenses, yoyExpenses); + const netKpi = buildKpi(netSpark, refNet, momNet, yoyNet); + const savingsKpi = buildKpi(savingsSpark, refSavings, momSavings, yoySavings); + + // 12-month income vs expenses series for the overlay chart. + const flow12Months = buildSeries(12); + + // Top movers: biggest MoM increases / decreases. `momRows` are sorted by + // absolute delta already; filter out near-zero noise and split by sign. + const significantMovers = momRows.filter( + (r) => r.deltaAbs !== 0 && (r.previousAmount > 0 || r.currentAmount > 0), + ); + const topMoversUp: CartesTopMover[] = significantMovers + .filter((r) => r.deltaAbs > 0) + .sort((a, b) => b.deltaAbs - a.deltaAbs) + .slice(0, 5); + const topMoversDown: CartesTopMover[] = significantMovers + .filter((r) => r.deltaAbs < 0) + .sort((a, b) => a.deltaAbs - b.deltaAbs) + .slice(0, 5); + + // Budget adherence — only expense categories with a non-zero budget count. + // monthActual is signed from transactions; expense categories have + // monthActual <= 0, so we compare on absolute values. + const budgetedExpenseRows = budgetRows.filter( + (r) => r.category_type === "expense" && r.monthBudget > 0 && !r.is_parent, + ); + const budgetsInTarget = budgetedExpenseRows.filter( + (r) => Math.abs(r.monthActual) <= r.monthBudget, + ).length; + + const overruns: CartesBudgetWorstOverrun[] = budgetedExpenseRows + .map((r) => { + const actual = Math.abs(r.monthActual); + const overrunAbs = actual - r.monthBudget; + const overrunPct = r.monthBudget > 0 ? (overrunAbs / r.monthBudget) * 100 : null; + return { + categoryId: r.category_id, + categoryName: r.category_name, + categoryColor: r.category_color, + budget: r.monthBudget, + actual, + overrunAbs, + overrunPct, + }; + }) + .filter((r) => r.overrunAbs > 0) + .sort((a, b) => b.overrunAbs - a.overrunAbs) + .slice(0, 3); + + const budgetAdherence: CartesBudgetAdherence = { + categoriesInTarget: budgetsInTarget, + categoriesTotal: budgetedExpenseRows.length, + worstOverruns: overruns, + }; + + // Seasonality — average of the same calendar month across the previous + // two years. If no data, average stays null. + const historicalYears: CartesSeasonalityYear[] = seasonalityRows.map((r) => ({ + year: Number(r.year), + amount: Number(r.amount ?? 0), + })); + const historicalAverage = historicalYears.length + ? historicalYears.reduce((sum, r) => sum + r.amount, 0) / historicalYears.length + : null; + const referenceAmount = expensesKpi.current; + const deviationPct = + historicalAverage !== null && historicalAverage > 0 + ? ((referenceAmount - historicalAverage) / historicalAverage) * 100 + : null; + + const seasonality: CartesSeasonality = { + referenceAmount, + historicalYears, + historicalAverage, + deviationPct, + }; + + return { + referenceYear, + referenceMonth, + kpis: { + income: incomeKpi, + expenses: expensesKpi, + net: netKpi, + savingsRate: savingsKpi, + }, + flow12Months, + topMoversUp, + topMoversDown, + budgetAdherence, + seasonality, + }; +} diff --git a/src/shared/types/index.ts b/src/shared/types/index.ts index 5ec6a98..f315f43 100644 --- a/src/shared/types/index.ts +++ b/src/shared/types/index.ts @@ -360,6 +360,87 @@ export interface BudgetVsActualRow { ytdVariationPct: number | null; } +// --- Cartes (Issue #97) — dashboard snapshot --- + +export interface CartesSparklinePoint { + month: string; // "YYYY-MM" + value: number; +} + +export interface CartesKpi { + current: number; + previousMonth: number | null; + previousYear: number | null; + deltaMoMAbs: number | null; + deltaMoMPct: number | null; + deltaYoYAbs: number | null; + deltaYoYPct: number | null; + sparkline: CartesSparklinePoint[]; // 13 months ending at reference month +} + +export type CartesKpiId = "income" | "expenses" | "net" | "savingsRate"; + +export interface CartesTopMover { + categoryId: number | null; + categoryName: string; + categoryColor: string; + previousAmount: number; + currentAmount: number; + deltaAbs: number; + deltaPct: number | null; +} + +export interface CartesMonthFlow { + month: string; // "YYYY-MM" + income: number; + expenses: number; + net: number; +} + +export interface CartesBudgetWorstOverrun { + categoryId: number; + categoryName: string; + categoryColor: string; + budget: number; + actual: number; + overrunAbs: number; + overrunPct: number | null; +} + +export interface CartesBudgetAdherence { + categoriesInTarget: number; + categoriesTotal: number; + worstOverruns: CartesBudgetWorstOverrun[]; +} + +export interface CartesSeasonalityYear { + year: number; + amount: number; +} + +export interface CartesSeasonality { + referenceAmount: number; + historicalYears: CartesSeasonalityYear[]; // up to 2 previous years + historicalAverage: number | null; + deviationPct: number | null; +} + +export interface CartesSnapshot { + referenceYear: number; + referenceMonth: number; + kpis: { + income: CartesKpi; + expenses: CartesKpi; + net: CartesKpi; + savingsRate: CartesKpi; // value stored as 0-100 + }; + flow12Months: CartesMonthFlow[]; + topMoversUp: CartesTopMover[]; + topMoversDown: CartesTopMover[]; + budgetAdherence: CartesBudgetAdherence; + seasonality: CartesSeasonality; +} + export type ImportWizardStep = | "source-list" | "source-config"