feat(dashboard): KPI cards follow the selected period, monthly analysis keeps the reference month #553

Merged
maximus merged 2 commits from issue-549-dashboard-period-kpis into main 2026-11-26 02:25:36 +00:00
20 changed files with 1543 additions and 264 deletions

View file

@ -2,6 +2,10 @@
## [Non publié]
### Modifié
- Tableau de bord : les quatre indicateurs clés (revenus, dépenses, solde net, taux d'épargne) et le graphique « Revenus vs dépenses — 12 derniers mois » suivent désormais la période choisie en haut de la page, comme les deux graphiques de dépenses, au lieu du mois de référence. Chaque indicateur se compare à la période précédente de même durée (« vs période précédente ») et aux mêmes dates l'an dernier (« vs même période l'an dernier ») ; « Cette année », « 12 mois » et une période personnalisée d'un an exactement n'affichent que l'écart avec l'an dernier, leur période précédente étant celle de l'an dernier, et « Tout » n'en affiche aucun. Le graphique des 12 mois et les courbes des indicateurs finissent au dernier mois de la période. Le mois de référence ne pilote plus que les trois cartes regroupées sous « Analyse mensuelle » : catégories en hausse, catégories en baisse et respect du budget. L'aide de la page et la section Tableau de bord du guide d'utilisation décrivent désormais la page telle qu'elle est, sans le graphique circulaire ni le tableau Budget vs Réel qu'elle n'a plus (#549).
### Corrigé
- L'ajout d'un mot-clé par le clic droit sur une transaction, la création d'une catégorie et les autres enregistrements en plusieurs étapes, comme une répartition ou une restauration, ne peuvent plus échouer sur « database is locked » (#543).

View file

@ -2,6 +2,10 @@
## [Unreleased]
### Changed
- Dashboard: the four key indicators (income, expenses, net balance, savings rate) and the “Income vs expenses — last 12 months” chart now follow the period chosen at the top of the page, like the two expense charts, instead of the reference month. Each indicator is compared with the previous period of the same length (“vs previous period”) and with the same dates last year (“vs same period last year”); “This year”, “12 months” and a custom period of exactly one year only show the change from last year, since their previous period is last year's, and “All” shows none. The 12-month chart and the indicators' curves end at the last month of the period. The reference month now only drives the three cards gathered under “Monthly analysis”: biggest increases, biggest decreases and budget adherence. The page's help and the Dashboard section of the user guide now describe the page as it is, without the pie chart and the Budget vs Actual table it no longer has (#549).
### Fixed
- Adding a keyword from a transaction's right-click menu, creating a category, and the other saves made in several steps, such as a split or a restore, can no longer fail with “database is locked” (#543).

View file

@ -9,7 +9,7 @@ Application de bureau pour importer, catégoriser et analyser vos transactions f
## Fonctionnalités
- **Import CSV** — Importez vos relevés bancaires depuis plusieurs sources avec auto-détection des colonnes et modèles d'import réutilisables
- **Tableau de bord** — Vue d'ensemble avec KPIs, répartition par catégorie et dernières transactions
- **Tableau de bord** — Vue d'ensemble de la période choisie avec KPIs comparés à la période précédente et à l'an dernier, dépenses par catégorie et analyse d'un mois de référence
- **Transactions** — Parcourez, recherchez et filtrez avec sélection rapide de période
- **Catégorisation automatique** — Attribution automatique par mots-clés, avec ajustement manuel
- **Split de transactions** — Répartissez une transaction sur plusieurs catégories
@ -73,9 +73,9 @@ Documents/
### 4. Consulter le tableau de bord
Le tableau de bord affiche automatiquement :
- Les KPIs du mois (revenus, dépenses, solde)
- La répartition des dépenses par catégorie
- Les dernières transactions
- Les KPIs de la période choisie (revenus, dépenses, solde net, taux d'épargne), comparés à la période précédente et à la même période l'an dernier
- Les dépenses par catégorie et leur évolution dans le temps
- L'analyse d'un mois de référence : catégories en hausse et en baisse, respect du budget
### 5. Parcourir et catégoriser les transactions

View file

@ -213,7 +213,7 @@ Le dossier des bases est celui du plugin : `app_config_dir()`, résolu par `prof
| `adjustmentService.ts` | Gestion des ajustements |
| `budgetService.ts` | Gestion budgétaire |
| `dashboardService.ts` | Agrégation données tableau de bord : `getExpensesByCategory` (barres classées, dépense de chaque catégorie de dépense, `accountIds`), `deriveNetWorthTile` (pur — tuile valeur nette du Bilan, réutilise `deriveLandingState`). `getDashboardSummary`, sans appelant depuis #279, est retiré par #392 |
| `reportService.ts` | Génération de rapports : `getMonthlyTrends` (état de résultat par mois, aussi lu par Cartes et le tableau de bord), `getCategoryOverTime`, `getHighlights`, `getCompareMonthOverMonth`, `getCompareYearOverYear`, `getCategoryZoom` (CTE récursive bornée anti-cycle), `getCartesSnapshot` (snapshot dashboard Cartes, requêtes parallèles). Toutes les sommes de montants suivent la convention de signe de l'[ADR 0026](adr/0026-convention-signe-rapports.md) (#392) : le SQL rend le solde signé de chaque catégorie avec sa section (`SECTION_SQL` sur `CATEGORY_JOIN_SQL`), `src/utils/incomeStatement.ts` (pur) en tire ce que les écrans montrent (`orient`, `incomeStatement`, `savingsRate`, `toCents`) ; `ABS` ne sert qu'au tri |
| `reportService.ts` | Génération de rapports : `getMonthlyTrends` (état de résultat par mois, aussi lu par Cartes et le tableau de bord), `getCategoryOverTime`, `getHighlights`, `getCompareMonthOverMonth`, `getCompareYearOverYear`, `getCategoryZoom` (CTE récursive bornée anti-cycle), `getCartesSnapshot` (snapshot dashboard Cartes, requêtes parallèles ; le tableau de bord n'en lit plus que les top movers et l'adhésion budgétaire), `getIncomeStatement` (état de résultat d'une plage de jours : les mois de `getMonthlyTrends` dans ses bornes exactes, additionnés ; `null` sans transaction, #549), `getPeriodKpis` (cartes KPI et graphique 12 mois du tableau de bord sur sa période, contre la période précédente et la même période l'an dernier de `computeComparisonRanges` (`src/utils/dateRange.ts`, pur), #549). Toutes les sommes de montants suivent la convention de signe de l'[ADR 0026](adr/0026-convention-signe-rapports.md) (#392) : le SQL rend le solde signé de chaque catégorie avec sa section (`SECTION_SQL` sur `CATEGORY_JOIN_SQL`), `src/utils/incomeStatement.ts` (pur) en tire ce que les écrans montrent (`orient`, `incomeStatement`, `savingsRate`, `toCents`) ; `ABS` ne sert qu'au tri |
| `dataExportService.ts` | Export de données (chiffré), lecture du fichier et validations de la frontière d'import. L'enveloppe SREF porte un `format_version` explicite (`SREF_FORMAT_VERSION = 3`), **inclut `import_sources` + `import_config_templates`** depuis #331 et, dans les deux modes qui portent les catégories, **`budget_entries`, `budget_templates` et `adjustments`** depuis #520 ; `collectExportData(mode)` rassemble les tableaux de chaque mode, pour « Exporter » comme pour la sauvegarde d'avant migration ; l'export CSV commence par une colonne `id` (#518). `parseImportedJson` et `parseImportedCsv` refusent, avant que la fenêtre de confirmation ne s'ouvre, une configuration illisible (`validateImportedFormatRows`) et des lignes de répartition qui ne retrouvent pas leur parent (`validateImportedTransactionIds`, #518), et `parseImportedJson` un format plus récent que celui de l'application ou un numéro de format invalide (`validateImportedFormatVersion`, clés `newerFormat` et `invalidFormatVersion`, #520), des catégories, mots-clés ou fournisseurs qui renvoient à une catégorie absente du fichier (`validateImportedCategoryReferences`, clé `danglingCategoryReference`, #521) et, au format 3, un budget que la restauration ne pourrait pas réécrire (`validateImportedBudget`, clé `invalidBudgetRows`, #520), par une `SrefValidationError` qui porte sa clé i18n. La restauration vit dans `dataRestoreService.ts` ([ADR 0025](adr/0025-contenu-restauration-sauvegarde-sref.md)) |
| `dataRestoreService.ts` | Restauration d'une sauvegarde SREF/JSON ou d'un export CSV, sortie de `dataExportService.ts` par #518 : les trois modes passent par `runRestore`, qui efface puis réinsère dans une seule transaction (`withTransaction`, son `BEGIN`, son `COMMIT`, `ROLLBACK` puis relance sur un échec) et ne notifie qu'après le `COMMIT` ([ADR 0022](adr/0022-canal-evenements-donnees.md)) ; modèles restaurés avant les sources avec remap de `template_id` ; transactions réinsérées avec leur `id` exporté, les lignes sans parent avant les lignes de répartition (#518). Les deux restaurations de transactions lisent puis retirent les transferts du Bilan avant `DELETE FROM transactions`, et réinsèrent tels quels ceux dont la transaction revient avec le même identifiant, la même date, le même montant et la même description ([ADR 0010](adr/0010-fk-restrict-balance-transfers.md), amendement #521) ; une transaction dont la catégorie manque au profil revient sans catégorie, drapeau manuel à 0, et une ligne `logWarn` en donne le nombre ; `restoreCategories` insère les catégories sans parent, puis pose les `parent_id` dans un second passage (#521), et écrit leur `i18n_key` (#520). Les deux restaurations qui portent les catégories reçoivent le format du fichier (`formatVersion`), lisent puis retirent les lignes de budget, de modèle et d'ajustement avant `DELETE FROM categories` (`takeBudget`), et les remettent une fois les catégories en place (`restoreBudget`) : au format 3, le budget du fichier (lignes de budget et ajustements remplacés, modèles insérés ou mis à jour par leur nom, un modèle absent du fichier gardant ses lignes dont la catégorie revient) ; en dessous, les lignes du profil dont la catégorie revient ([ADR 0025](adr/0025-contenu-restauration-sauvegarde-sref.md), #520). Les trois restaurations rendent un `RestoreOutcome` (`unlinkedTransfers`, `uncategorizedTransactions` ; zéros pour « Catégories uniquement ») ; `previewUnlinkedTransfers` compte, hors transaction et par la même règle, les transferts qu'une restauration délierait. `importTransactionsOnly` et `importTransactionsWithCategories` rejouent en tête les validations du parse, `importTransactionsWithCategories` et `importCategoriesOnly` celles du format, des références de catégorie et du budget, avant toute suppression. Appelé par `useDataImport` et, pour « Rétablir la sauvegarde », par `readBackup` (lecture, déchiffrement, analyse et compte des transferts, sans écriture) puis `applyBackup` (restauration et préférences, `RestoreResult` avec le `RestoreOutcome`) de `categoryRestoreService.ts` |
| `userPreferenceService.ts` | Stockage préférences utilisateur |
@ -252,7 +252,7 @@ Les 30 fichiers `.ts` de `src/hooks/`, hors tests (`ls src/hooks/*.ts | grep -v
| `useImportHistory` | Historique des imports ; un refus pour transferts du Bilan devient un état structuré (`blocked` : portée, comptes, nombre), puis « Délier et supprimer » (#522) |
| `useAdjustments` | Ajustements |
| `useBudget` | Budget |
| `useDashboard` | Tableau de bord (`/`) — convergé sur le modèle `/reports/cartes` (#279) : KPIs+deltas/top movers/adherence budget via `getCartesSnapshot` sur un mois de référence propre au Dashboard (`referenceYear`/`referenceMonth`, défaut mois précédent), barres classées + tendance par catégorie sur une période flexible propre (`period`/dates custom), filtre compte (`accountIds`) local partagé par les deux axes temporels, tuile valeur nette (Bilan) chargée une fois, indépendante du filtre compte |
| `useDashboard` | Tableau de bord (`/`) — convergé sur le modèle `/reports/cartes` (#279), un chargement par axe temporel depuis #549 : la période propre au Dashboard (`period`/dates custom) alimente les cartes KPI et le graphique 12 mois (`getPeriodKpis`, sur les fenêtres de `computeComparisonRanges`), les barres classées et la tendance par catégorie ; le mois de référence (`referenceYear`/`referenceMonth`, défaut mois précédent) n'alimente que l'« Analyse mensuelle » (top movers et adhérence budget de `getCartesSnapshot`). Chaque chargement a son compteur contre les réponses périmées, son drapeau de chargement (la page reste voilée jusqu'aux deux) et son erreur, effacée par sa seule relance. Filtre compte (`accountIds`) local partagé par les deux axes, tuile valeur nette (Bilan) chargée une fois, indépendante du filtre compte |
| `useOnboardingChecklist` | Parcours de démarrage (#351, #396), appelé une seule fois par `OnboardingProvider` (`src/contexts/OnboardingContext.tsx`, monté dans `AppShell` autour de `<Outlet/>`) ; les pages le lisent par `useOnboarding()`. Reducer exporté (`onboardingChecklistReducer`) : chargements numérotés (la réponse d'un chargement autre que le dernier lancé est ignorée), actions locales (`HIDE`, `SHOW`, `SKIP`, `RESUME`, `ACKNOWLEDGE`) prioritaires sur le snapshot d'un chargement parti avant elles (`ACKNOWLEDGE` garde le verrou de carte, contrairement à `SKIP`), rafraîchissement qui garde `ready` et les compteurs, échec après un premier succès qui garde le dernier état. `createOnboardingLoader` attend la règle D9 au premier chargement, une fois (promesse partagée contre le double montage de StrictMode), et n'écrit au Journal qu'au passage en échec. `createVisitStepsInitializer` lance `initializeVisitSteps(shouldAcknowledgeVisitSteps(checklist))` une fois par fournisseur (promesse partagée), après le premier chargement réussi où `budgetReady` est vrai et le drapeau absent (`needsVisitStepsInitialization`), puis relit (#425). Relecture au montage, à chaque changement de route et 150 ms après une rafale d'événements de données (`followDataChanges`, [ADR 0022](adr/0022-canal-evenements-donnees.md)). `computeChecklist` reçoit `useEntitlement("budget")` (ligne Budget verrouillée hors Base+, exclue du total), les étapes passées et reconnues et `visitStepsInitialized` ; `deriveOnboardingView` (pur) en tire l'étape suivante, le verrou de carte (`latchCardPage`) et le mode (`bannerMode`, `utils/onboardingPath.ts`, la fin attendant `budgetReady && visitStepsInitialized`). Expose `status`, `checklist`, `counters` (le Dashboard lit `transactions` pour l'état vide), `hidden`, `budgetReady`, `visitStepsInitialized`, `nextStep`, `mode`, `cardPage`, `hide()` / `show()` / `skip()` / `resume()` / `acknowledge()` / `refresh()` |
| `useReportsPeriod` | Période de reporting synchronisée via query string (bookmarkable) + filtre compte (`accountIds`, `import_sources.id`) via le paramètre `sources`, même mécanique bookmarkable ; défaut `[]` = aucun filtre (fondation #272). Branché sur les 7 services de rapports (#273) et exposé via `<FilterPanel>` (#274) ; adopté sur Tendances (#275) puis Comparaison et Budget (#276). Le Dashboard (`/`) n'utilise pas ce hook — il porte son propre `accountIds` local (`useDashboard`), câblé au même `<FilterPanel>` (#279) |
| `useHighlights` | Panneau de faits saillants du hub rapports |
@ -624,7 +624,7 @@ Les modules payants sont enveloppés dans des **layout-routes pathless `RequireF
| Route | Page | Description |
|-------|------|-------------|
| `/` | `DashboardPage` | Tableau de bord (KPIs+deltas, top movers, adhérence budget, tuile valeur nette, barres classées, dépenses dans le temps — modèle Cartes, #279) |
| `/` | `DashboardPage` | Tableau de bord (KPIs+deltas et graphique 12 mois sur la période, #549 ; « Analyse mensuelle » : top movers et adhérence budget du mois de référence ; tuile valeur nette, barres classées, dépenses dans le temps — modèle Cartes, #279) |
| `/import` | `ImportPage` | Assistant d'import CSV : source → configuration (détection automatique + score) → sélection des fichiers → **aperçu obligatoire** (récap signé, inversion des signes, panneau de dérive) → doublons → confirmation |
| `/transactions` | `TransactionsPage` | Liste avec filtres |
| `/categories` | `CategoriesPage` | Gestion hiérarchique ; le bouton « Vérifier la hiérarchie » ouvre `HierarchyCheckModal` (#393) |
@ -717,7 +717,7 @@ Garde : `src/__integration__/i18n-mock-guard.test.ts` lit tous les `*.test.ts(x)
`categoryService.test.ts` exécute les requêtes qui vérifient ce que porte un parent (transactions, montants de budget, mots-clés) telles qu'elles sont écrites, sur une base SQLite en mémoire de `node:sqlite`, module intégré à Node (aucun paquet ; expérimental sous Node 22, qui l'annonce par un avertissement à l'exécution). Ses tables y sont créées par leur `CREATE TABLE` de `consolidated_schema.sql`, clés étrangères coupées : la table `categories` reste dans le faux du test. Une condition retirée d'une requête (`amount <> 0`, `is_active = 1`) rougit donc un test, ce qu'un faux qui réimplémente la règle ne ferait pas.
Le harnais partagé `src/test/sqliteHarness.ts` (#392) fait tourner des services entiers, tels qu'ils sont écrits, sur le schéma complet d'un profil neuf (`consolidated_schema.sql`, seed compris), clés étrangères actives comme sous sqlx. Chaque fichier de test remplace `../services/db` par lui (`vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule())`, puis `useDb(openProfileDb())`) : `select` et `execute` lient `$N` par nom, `execute` rend `rowsAffected` et `lastInsertId`, `withTransaction` passe à son rappel le même handle, et `getDb()` comme un `withTransaction` imbriqué échouent pendant une transaction, là où le vrai verrou, non réentrant, bloquerait ; `src/test/sqliteHarness.test.ts` prouve ces règles. Le harnais n'importe aucun service, puisque la fabrique du mock l'importe pendant que `../services/db` se construit. L'app embarque SQLite 3.46.0 (`libsqlite3-sys` 0.30.1), Node 22 une version plus récente : une requête n'utilise rien de postérieur à 3.46. `src/__integration__/report-totals.test.ts` (#392) y lit chaque rapport par son vrai service, sur le jeu de reproduction de #392 et sur ses cas limites (convention de l'[ADR 0026](adr/0026-convention-signe-rapports.md)). `src/__integration__/split-offset-manual-flag.test.ts` (#454) y fait tourner `saveSplitAdjustment`, `updateTransactionCategory` et `autoCategorizeTransactions` (mot-clé `METRO`, catégories 1111 et 1112). `src/__integration__/restore.test.ts` (#518) y fait tourner les restaurations (`importTransactionsOnly`, `importTransactionsWithCategories`, `importCategoriesOnly`, et « Rétablir la sauvegarde » par `readBackup` puis `applyBackup`), avec une seconde base qui tient lieu de profil neuf ; #521 y ajoute les transferts du Bilan, liés par le vrai `linkTransfer`, les catégories absentes, « Réinitialiser » compris, et les catégories rangées sous une plus récente ou en boucle ; #520 le budget, les modèles et les ajustements, écrits par les vrais services des pages Budget et Ajustements, au format 3 comme au format 2, et la migration des catégories elle-même (`createPreMigrationBackup`, `computeMigrationPlan` puis `applyMigration`) avant « Rétablir la sauvegarde ». Les autres tests de services gardent leurs faux.
Le harnais partagé `src/test/sqliteHarness.ts` (#392) fait tourner des services entiers, tels qu'ils sont écrits, sur le schéma complet d'un profil neuf (`consolidated_schema.sql`, seed compris), clés étrangères actives comme sous sqlx. Chaque fichier de test remplace `../services/db` par lui (`vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule())`, puis `useDb(openProfileDb())`) : `select` et `execute` lient `$N` par nom, `execute` rend `rowsAffected` et `lastInsertId`, `withTransaction` passe à son rappel le même handle, et `getDb()` comme un `withTransaction` imbriqué échouent pendant une transaction, là où le vrai verrou, non réentrant, bloquerait ; `src/test/sqliteHarness.test.ts` prouve ces règles. Le harnais n'importe aucun service, puisque la fabrique du mock l'importe pendant que `../services/db` se construit. L'app embarque SQLite 3.46.0 (`libsqlite3-sys` 0.30.1), Node 22 une version plus récente : une requête n'utilise rien de postérieur à 3.46. `src/__integration__/report-totals.test.ts` (#392) y lit chaque rapport par son vrai service, sur le jeu de reproduction de #392 et sur ses cas limites (convention de l'[ADR 0026](adr/0026-convention-signe-rapports.md)), et `src/__integration__/dashboard-period-kpis.test.ts` (#549) les cartes KPI du tableau de bord sur leur période (période coupée au jour près, écarts vs la période précédente et l'an dernier, filtre de comptes). `src/__integration__/split-offset-manual-flag.test.ts` (#454) y fait tourner `saveSplitAdjustment`, `updateTransactionCategory` et `autoCategorizeTransactions` (mot-clé `METRO`, catégories 1111 et 1112). `src/__integration__/restore.test.ts` (#518) y fait tourner les restaurations (`importTransactionsOnly`, `importTransactionsWithCategories`, `importCategoriesOnly`, et « Rétablir la sauvegarde » par `readBackup` puis `applyBackup`), avec une seconde base qui tient lieu de profil neuf ; #521 y ajoute les transferts du Bilan, liés par le vrai `linkTransfer`, les catégories absentes, « Réinitialiser » compris, et les catégories rangées sous une plus récente ou en boucle ; #520 le budget, les modèles et les ajustements, écrits par les vrais services des pages Budget et Ajustements, au format 3 comme au format 2, et la migration des catégories elle-même (`createPreMigrationBackup`, `computeMigrationPlan` puis `applyMigration`) avant « Rétablir la sauvegarde ». Les autres tests de services gardent leurs faux.
### Limites connues (#437)

View file

@ -86,15 +86,16 @@ Gérez plusieurs profils indépendants, chacun avec sa propre base de données.
## 3. Tableau de bord
Le tableau de bord vous donne un aperçu rapide de votre situation financière pour une période sélectionnée.
Le tableau de bord vous donne un aperçu rapide de votre situation financière sur la période choisie, avec l'analyse d'un mois de référence.
### Fonctionnalités
- Cartes résumées du solde, des revenus et des dépenses
- Répartition des dépenses par catégorie (graphique circulaire avec motifs SVG)
- Tableau Budget vs Réel du mois courant (écart en $ et %)
- Histogramme empilé des dépenses par catégorie et par mois
- Sélecteur de période ajustable (par défaut : année à ce jour)
- Filtre de la période (Ce mois, 3 mois, 6 mois, Cette année, 12 mois, Tout ou Personnalisé ; par défaut Cette année) et des sources d'import, en haut de la page
- Quatre indicateurs clés sur la période : revenus, dépenses, solde net et taux d'épargne, chacun avec sa courbe des 13 derniers mois et ses écarts vs la période précédente et vs la même période l'an dernier
- Tuile « Valeur nette actuelle », tirée du Bilan, qui ne suit ni la période ni le filtre des sources
- Graphique « Revenus vs dépenses » des 12 mois qui finissent au dernier mois de la période
- Analyse mensuelle : catégories en hausse, catégories en baisse et respect du budget d'un mois de référence, choisi dans la liste à côté de « Indicateurs clés »
- Dépenses par catégorie (barres classées) et dépenses dans le temps (histogramme empilé par mois), sur la période
- Menu contextuel (clic droit) pour masquer une catégorie ou voir ses transactions
- Carte d'accueil d'un profil sans transaction, avec la liste de démarrage : huit étapes, cochées selon vos données ou par « J'ai compris » pour les visites, et un bouton « Masquer »
@ -103,17 +104,19 @@ Le tableau de bord vous donne un aperçu rapide de votre situation financière p
1. Dans un profil sans transaction, le tableau de bord affiche une carte d'accueil et la liste de démarrage, en huit étapes : « Créer un profil » (déjà cochée), « Choisir un dossier d'import », « Configurer une source d'import », « Importer un premier fichier », « Parcourir les catégories et les mots-clés », « Classer une transaction à la main », « Saisir un premier budget » et « Parcourir les rapports ». Les étapes se cochent selon vos données, sauf les deux étapes de visite (catégories et rapports), cochées par « J'ai compris » sur leur carte ou, pour les rapports, par un clic sur la carte Tendances entourée. Chaque ligne non cochée mène à la page où la faire ; la case Budget est marquée « Base et plus » en édition Gratuite et ne compte pas dans le total
2. Dès que le profil a des transactions, la liste quitte le tableau de bord : le bandeau de démarrage, en haut de chaque page, la remplace jusqu'à la fin du parcours (voir Premiers pas → Le parcours de démarrage)
3. « Masquer » retire la liste de la carte d'accueil, et le bandeau de toutes les pages, pour ce profil seulement ; Paramètres → Utilisateurs les réaffiche
4. Utilisez le sélecteur de période en haut à droite pour choisir une plage de temps (mois, 3 mois, année, etc.)
5. Consultez les cartes résumées pour votre solde, revenus totaux et dépenses totales
6. Vérifiez le graphique circulaire pour voir comment vos dépenses sont réparties par catégorie
7. Consultez le tableau Budget vs Réel pour comparer vos dépenses au budget du mois courant
8. Analysez l'histogramme en bas de page pour voir l'évolution de vos dépenses par catégorie dans le temps
9. Cliquez droit sur une catégorie dans un graphique pour la masquer ou voir le détail de ses transactions
4. Choisissez la période dans le filtre en haut de la page : les quatre indicateurs clés, le graphique « Revenus vs dépenses » et les deux graphiques de dépenses la suivent. Le filtre des sources s'applique à tout, sauf à la tuile « Valeur nette actuelle »
5. Lisez les écarts sous chaque indicateur : « vs période précédente » le compare à la période de même durée qui précède, « vs même période l'an dernier » aux mêmes dates un an plus tôt. « Cette année », « 12 mois » et une période personnalisée d'un an exactement n'ont que l'écart de l'an dernier, leur période précédente étant celle de l'an dernier, et « Tout » n'en a aucun
6. Choisissez le mois de référence dans la liste à côté de « Indicateurs clés » : il pilote les trois cartes de l'« Analyse mensuelle », soit les catégories en hausse et en baisse par rapport au mois précédent, et le respect du budget du mois
7. Cliquez sur une catégorie en hausse ou en baisse pour ouvrir son analyse sur ce mois (Rapports → Analyse par catégorie, édition Base et plus)
8. Cliquez droit sur une catégorie dans un graphique de dépenses pour la masquer ou voir le détail de ses transactions
### Astuces
- La période par défaut est « année à ce jour » pour un aperçu annuel dès l'ouverture
- Le solde net est la somme de toutes les transactions du mois de référence : les revenus moins les dépenses, plus les transactions non classées et les transferts, qu'une note sous la carte détaille quand ils ne sont pas nuls. Le taux d'épargne vaut (revenus − dépenses) ÷ revenus (voir Rapports → Comment les montants sont calculés)
- La période par défaut est « Cette année », du 1er janvier à aujourd'hui, et le mois de référence est le dernier mois complet
- Le solde net est la somme de toutes les transactions de la période : les revenus moins les dépenses, plus les transactions non classées et les transferts, qu'une note sous la carte détaille quand ils ne sont pas nuls. Le taux d'épargne vaut (revenus − dépenses) ÷ revenus (voir Rapports → Comment les montants sont calculés)
- La période précédente de « Ce mois », « 3 mois » et « 6 mois » finit au même jour du mois : un 14 novembre, « Ce mois » (du 1er au 14) se compare au 1er au 14 octobre. Celle d'une période personnalisée compte le même nombre de jours, juste avant
- Le graphique des 12 mois et les courbes des indicateurs comptent des mois entiers : une période personnalisée qui finit un 15 y montre son dernier mois en entier
- Un écart affiché « — » signale une période comparée sans aucune transaction
- Les catégories masquées apparaissent sous forme de pastilles au-dessus du graphique — cliquez sur Tout afficher pour les restaurer
- Les motifs SVG (lignes, points, hachures) aident à distinguer les catégories au-delà des couleurs
- Les cases de la liste de démarrage se cochent sur vos données, pas sur un clic : « Classer une transaction à la main » attend une transaction dont vous avez changé la catégorie vous-même, la catégorisation automatique de l'import ne la coche pas

View file

@ -0,0 +1,269 @@
/**
* The Dashboard's KPI cards over its period, read through their real services
* (#549), on a real SQLite database (`src/test/sqliteHarness.ts`).
*
* The four cards and the 12-month chart follow the period of the selector, no
* longer the reference month: each card holds the figure of the period, to the
* day, its change from the previous period of the same length and from the
* same period last year (`computeComparisonRanges`), and its curve over the 13
* months ending at the period's last month. A comparison period without any
* transaction gives no change (« — »), as in Cartes. Every amount follows the
* sign convention of the reports (ADR 0026): « Solde net » is the sum of every
* amount of the period, its uncategorized and transfer parts in the note.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { DatabaseSync } from "node:sqlite";
vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule());
import { openProfileDb, useDb } from "../test/sqliteHarness";
import { getIncomeStatement, getPeriodKpis } from "../services/reportService";
import { computeComparisonRanges } from "../utils/dateRange";
import type { DashboardPeriod } from "../shared/types";
// Categories of the seed of a new profile.
const PAY = 1011; // « Paie régulière », income
const GROCERIES = 1111; // « Épicerie régulière », expense
const BUTCHER = 1112; // « Boucherie & poissonnerie », expense
const CARD = 1971; // « Paiement carte crédit », transfer
/** Saturday, November 14, 2026, local noon: « Ce mois » is November 1st–14th. */
const NOV_14 = new Date(2026, 10, 14, 12);
let db: DatabaseSync;
beforeEach(() => {
db = useDb(openProfileDb());
});
afterEach(() => {
db.close();
});
/** A transaction as an import writes it. */
function insert(date: string, amount: number, categoryId: number | null, sourceId: number | null = null): void {
db.prepare(
`INSERT INTO transactions (date, description, amount, category_id, source_id, original_description)
VALUES ($date, 'TX', $amount, $category, $source, 'TX')`,
).run({ $date: date, $amount: amount, $category: categoryId, $source: sourceId });
}
/** An import source; its id. */
function source(name: string): number {
const result = db.prepare("INSERT INTO import_sources (name, column_mapping) VALUES ($name, '{}')").run({ $name: name });
return Number(result.lastInsertRowid);
}
/** The cards of `period` on `today`, as the Dashboard asks for them. */
function kpisOf(period: DashboardPeriod, today: Date, from?: string, to?: string, accountIds?: number[]) {
return getPeriodKpis(computeComparisonRanges(period, from, to, today), accountIds);
}
describe("getIncomeStatement — the statement of a range of days (#549)", () => {
it("adds up the months of a range that cuts a month at each end, and only its own days", async () => {
insert("2026-09-14", -7, GROCERIES); // the day before: out
insert("2026-09-15", -10, GROCERIES);
insert("2026-09-20", 1000, PAY);
insert("2026-10-05", 500, PAY);
insert("2026-10-10", -20, GROCERIES);
insert("2026-10-11", -40, GROCERIES); // the day after: out
expect(await getIncomeStatement("2026-09-15", "2026-10-10")).toEqual({
income: 1500,
expenses: 30,
uncategorized: 0,
transfers: 0,
resultBeforeTransfers: 1470,
net: 1470,
});
});
it("is null for a range without any transaction, and reads every date without bounds", async () => {
insert("2024-03-02", 300, PAY);
insert("2026-10-05", -20, GROCERIES);
expect(await getIncomeStatement("2025-01-01", "2025-12-31")).toBeNull();
expect(await getIncomeStatement()).toMatchObject({ income: 300, expenses: 20, net: 280 });
});
});
describe("getPeriodKpis — the four cards follow the period, to the day (#549)", () => {
it("a custom period that cuts two months: the cards hold its days only", async () => {
insert("2026-09-14", -7, GROCERIES);
insert("2026-09-15", -10, GROCERIES);
insert("2026-09-20", 1000, PAY);
insert("2026-10-05", 500, PAY);
insert("2026-10-10", -20, GROCERIES);
insert("2026-10-11", -40, GROCERIES);
const { kpis } = await kpisOf("custom", NOV_14, "2026-09-15", "2026-10-10");
expect([kpis.income.current, kpis.expenses.current, kpis.net.current]).toEqual([1500, 30, 1470]);
expect(kpis.savingsRate.current).toBeCloseTo(98, 6);
});
it("« Solde net » holds the uncategorized line and the transfers, the savings rate leaves them out", async () => {
// The edge cases of #392: income 1000, expenses 30 (a refund alone in
// Butcher), +40 without a category, a card payment with one leg only.
insert("2026-11-02", 1000, PAY);
insert("2026-11-03", -80, GROCERIES);
insert("2026-11-04", 50, BUTCHER);
insert("2026-11-06", 40, null);
insert("2026-11-07", -300, CARD);
const { kpis, netBreakdown } = await kpisOf("month", NOV_14);
expect([kpis.income.current, kpis.expenses.current, kpis.net.current, kpis.savingsRate.current]).toEqual([
1000, 30, 710, 97,
]);
expect(netBreakdown).toEqual({ uncategorized: 40, transfers: -300 });
});
it("a period without any transaction shows zero, its savings rate null, and still reads its comparisons", async () => {
insert("2026-10-05", 500, PAY); // the previous period, October 1st–14th
const { kpis, netBreakdown } = await kpisOf("month", NOV_14);
expect(kpis.income).toMatchObject({ current: 0, previousMonth: 500, deltaMoMAbs: -500, deltaMoMPct: -100 });
expect(kpis.net.current).toBe(0);
expect(kpis.savingsRate.current).toBeNull();
expect(kpis.savingsRate.deltaMoMAbs).toBeNull();
expect(netBreakdown).toEqual({ uncategorized: 0, transfers: 0 });
});
});
describe("getPeriodKpis — the changes from the previous period and from last year (#549)", () => {
beforeEach(() => {
// November 1st–14th, 2026.
insert("2026-11-02", 1000, PAY);
insert("2026-11-05", -100, GROCERIES);
});
it("an empty previous period gives no change, while last year's data gives its own", async () => {
// October 20 is out of the previous period, October 1st–14th.
insert("2026-10-20", -60, GROCERIES);
// November 1st–14th, 2025.
insert("2025-11-03", 800, PAY);
insert("2025-11-04", -50, GROCERIES);
const { kpis } = await kpisOf("month", NOV_14);
expect(kpis.income).toMatchObject({
current: 1000,
previousMonth: null,
deltaMoMAbs: null,
deltaMoMPct: null,
previousYear: 800,
deltaYoYAbs: 200,
deltaYoYPct: 25,
});
expect(kpis.expenses).toMatchObject({ previousYear: 50, deltaYoYAbs: 50, deltaYoYPct: 100 });
expect(kpis.net).toMatchObject({ previousYear: 750, deltaYoYAbs: 150, deltaYoYPct: 20 });
// 90 % against 93.75 %: −3.75 points, −4 % of last year's rate.
expect(kpis.savingsRate.deltaYoYAbs).toBeCloseTo(-3.75, 6);
expect(kpis.savingsRate.deltaYoYPct).toBeCloseTo(-4, 6);
});
it("a previous period with data gives its change; a zero there gives no percentage", async () => {
// October 1st–14th: groceries only, no income.
insert("2026-10-08", -40, GROCERIES);
const { kpis } = await kpisOf("month", NOV_14);
expect(kpis.expenses).toMatchObject({ current: 100, previousMonth: 40, deltaMoMAbs: 60, deltaMoMPct: 150 });
expect(kpis.income).toMatchObject({ previousMonth: 0, deltaMoMAbs: 1000, deltaMoMPct: null });
// No income in October: no savings rate there, no change.
expect(kpis.savingsRate).toMatchObject({ current: 90, previousMonth: null, deltaMoMAbs: null });
// Nothing last year.
expect(kpis.income).toMatchObject({ previousYear: null, deltaYoYAbs: null });
});
it("« Cette année » reads no previous period of its own, only last year's, January 1st to the same day", async () => {
insert("2025-11-10", 800, PAY); // in January 1st – November 14, 2025
insert("2025-11-20", 5000, PAY); // after November 14, 2025: out
const { kpis, ranges } = await kpisOf("year", NOV_14);
expect(ranges.previous).toBeNull();
expect(kpis.income).toMatchObject({
current: 1000,
previousMonth: null,
deltaMoMAbs: null,
previousYear: 800,
deltaYoYAbs: 200,
});
});
it("« Tout » reads every date and compares with nothing", async () => {
insert("2024-03-02", 300, PAY);
const { kpis, ranges } = await kpisOf("all", NOV_14);
expect([ranges.previous, ranges.previousYear]).toEqual([null, null]);
expect(kpis.income).toMatchObject({
current: 1300,
previousMonth: null,
previousYear: null,
deltaMoMAbs: null,
deltaYoYAbs: null,
});
});
});
describe("getPeriodKpis — the 12-month chart and the curves end at the period's last month (#549)", () => {
it("a custom period ending in June: twelve whole months to June, zero for a month without data", async () => {
insert("2026-02-10", 400, PAY);
insert("2026-06-15", 1000, PAY); // the period's last day
insert("2026-06-20", 250, PAY); // after the period, in its last month
insert("2026-07-03", 9999, PAY); // after its last month
const { kpis, flow12Months } = await kpisOf("custom", NOV_14, "2026-01-01", "2026-06-15");
expect(flow12Months.map((m) => m.month)).toEqual([
"2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12",
"2026-01", "2026-02", "2026-03", "2026-04", "2026-05", "2026-06",
]);
// The chart reads whole months, the card the period's own days.
expect(flow12Months[11]).toMatchObject({ income: 1250, net: 1250 });
expect(flow12Months[10]).toMatchObject({ income: 0, expenses: 0, net: 0 });
expect(kpis.income.current).toBe(1400);
const spark = kpis.income.sparkline;
expect(spark).toHaveLength(13);
expect(spark[0]).toEqual({ month: "2025-06", value: 0 });
expect(spark[12]).toEqual({ month: "2026-06", value: 1250 });
expect(spark.find((p) => p.month === "2026-02")).toEqual({ month: "2026-02", value: 400 });
});
it("a preset ends them this month", async () => {
insert("2026-11-02", 1000, PAY);
const { flow12Months, kpis } = await kpisOf("3months", NOV_14);
expect(flow12Months[11]).toMatchObject({ month: "2026-11", income: 1000 });
expect(kpis.net.sparkline[12]).toEqual({ month: "2026-11", value: 1000 });
});
});
describe("getPeriodKpis — the account filter reaches the period, both comparisons and the chart (#549)", () => {
let chosen: number;
let other: number;
beforeEach(() => {
chosen = source("Compte courant");
other = source("Carte");
insert("2026-11-02", 1000, PAY, chosen); // the period
insert("2026-10-05", -100, GROCERIES, chosen); // the previous period
insert("2025-11-03", 800, PAY, chosen); // last year
for (const date of ["2026-11-03", "2026-10-06", "2025-11-04"]) insert(date, 200, PAY, other);
});
it("filtered on the chosen source, every figure leaves the other one out", async () => {
const { kpis, flow12Months } = await kpisOf("month", NOV_14, undefined, undefined, [chosen]);
expect(kpis.income).toMatchObject({ current: 1000, previousMonth: 0, previousYear: 800 });
expect(kpis.expenses.previousMonth).toBe(100);
expect(flow12Months[11]).toMatchObject({ month: "2026-11", income: 1000 });
});
it("without a filter, the other source counts too", async () => {
const { kpis, flow12Months } = await kpisOf("month", NOV_14);
expect(kpis.income).toMatchObject({ current: 1200, previousMonth: 200, previousYear: 1000 });
expect(flow12Months[11]).toMatchObject({ month: "2026-11", income: 1200 });
});
});

View file

@ -32,7 +32,9 @@ import {
getCompareYearOverYear,
getHighlights,
getMonthlyTrends,
getPeriodKpis,
} from "../services/reportService";
import { computeComparisonRanges } from "../utils/dateRange";
import { getExpensesByCategory } from "../services/dashboardService";
import { getActualTotalsForYear, getBudgetVsActualData } from "../services/budgetService";
import { computeResults as compareResults } from "../components/reports/compareResults";
@ -179,7 +181,18 @@ describe("the reproduction of #392: every report reads income 1000, expenses 80,
expect(await getMonthlyTrends(FROM, TO)).toEqual([{ month: "2026-10", ...REPRODUCTION }]);
});
it("Dashboard and Cartes: the four indicators, their note, seasonality, movers and budget adherence", async () => {
it("Dashboard, on « Ce mois »: the four indicators and their note (#549)", async () => {
const { kpis, netBreakdown, flow12Months } = await getPeriodKpis(
computeComparisonRanges("month", undefined, undefined, TODAY),
);
expect([kpis.income.current, kpis.expenses.current, kpis.net.current, kpis.savingsRate.current]).toEqual([
1000, 80, 920, 92,
]);
expect(netBreakdown).toEqual({ uncategorized: 0, transfers: 0 });
expect(flow12Months[flow12Months.length - 1]).toEqual({ month: "2026-10", ...REPRODUCTION });
});
it("Cartes, and the Dashboard's monthly analysis: the four indicators, their note, seasonality, movers and budget adherence", async () => {
const snapshot = await getCartesSnapshot(2026, 10, "month");
expect(snapshot.kpis.income.current).toBe(1000);
expect(snapshot.kpis.expenses.current).toBe(80);
@ -292,7 +305,17 @@ describe("the edge cases of #392: every report reads the same net, 710", () => {
expect(await getMonthlyTrends(FROM, TO)).toEqual([{ month: "2026-10", ...EDGE_CASES }]);
});
it("Dashboard and Cartes: a refund lowers the expenses, the savings rate leaves transfers out", async () => {
it("Dashboard, on « Ce mois »: a refund lowers the expenses, the savings rate leaves transfers out (#549)", async () => {
const { kpis, netBreakdown } = await getPeriodKpis(computeComparisonRanges("month", undefined, undefined, TODAY));
expect([kpis.income.current, kpis.expenses.current, kpis.net.current, kpis.savingsRate.current]).toEqual([
1000, 30, 710, 97,
]);
expect(netBreakdown).toEqual({ uncategorized: 40, transfers: -300 });
const spark = kpis.savingsRate.sparkline;
expect(spark[spark.length - 1]).toEqual({ month: "2026-10", value: 97 });
});
it("Cartes, and the Dashboard's monthly analysis: a refund lowers the expenses, the savings rate leaves transfers out", async () => {
const snapshot = await getCartesSnapshot(2026, 10, "month");
expect(snapshot.kpis.income.current).toBe(1000);
expect(snapshot.kpis.expenses.current).toBe(30);
@ -466,6 +489,10 @@ describe("the account filter (#273, #279) keeps every report on the chosen sourc
]);
expect(snapshot.seasonality.referenceAmount).toBe(80);
expect(snapshot.seasonality.historicalYears).toEqual([{ year: 2025, amount: 40 }]);
const period = await getPeriodKpis(computeComparisonRanges("month", undefined, undefined, TODAY), ids);
expect([period.kpis.income.current, period.kpis.expenses.current, period.kpis.net.current]).toEqual([
1000, 80, 920,
]);
expect(compareResults(await getCompareMonthOverMonth(2026, 10, ids)).expense.monthCurrent).toBe(80);
expect(compareResults(await getCompareYearOverYear(2026, 10, ids)).expense.monthCurrent).toBe(80);
const actuals = await getActualTotalsForYear(2026, ids);

View file

@ -14,6 +14,13 @@ export interface KpiCardProps {
tooltip?: string;
/** Optional line under the value, e.g. what « Solde net » holds beyond income − expenses (#392). */
note?: string;
/**
* Labels of the two changes under the value, Cartes' by default (« vs mois
* précédent », « vs l'an dernier »). A null label hides its change, and the
* row goes when both are: on the Dashboard, « Cette année » and « 12 mois »
* have no previous period of their own, « Tout » no comparison at all (#549).
*/
deltaLabels?: { previous: string | null; lastYear: string | null };
}
function formatCurrency(amount: number, language: string): string {
@ -109,9 +116,14 @@ export default function KpiCard({
deltaIsBadWhenUp = false,
tooltip,
note,
deltaLabels,
}: KpiCardProps) {
const { t, i18n } = useTranslation();
const language = i18n.language;
const labels = deltaLabels ?? {
previous: t("reports.cartes.deltaMoMLabel"),
lastYear: t("reports.cartes.deltaYoYLabel"),
};
return (
<div
@ -135,24 +147,30 @@ export default function KpiCard({
</div>
{note && <div className="-mt-2 text-xs text-[var(--muted-foreground)]">{note}</div>}
<KpiSparkline data={kpi.sparkline} />
<div className="flex items-start justify-between gap-2 pt-1 border-t border-[var(--border)]">
<DeltaBadge
abs={kpi.deltaMoMAbs}
pct={kpi.deltaMoMPct}
label={t("reports.cartes.deltaMoMLabel")}
format={format}
language={language}
deltaIsBadWhenUp={deltaIsBadWhenUp}
/>
<DeltaBadge
abs={kpi.deltaYoYAbs}
pct={kpi.deltaYoYPct}
label={t("reports.cartes.deltaYoYLabel")}
format={format}
language={language}
deltaIsBadWhenUp={deltaIsBadWhenUp}
/>
</div>
{(labels.previous !== null || labels.lastYear !== null) && (
<div className="flex items-start justify-between gap-2 pt-1 border-t border-[var(--border)]">
{labels.previous !== null && (
<DeltaBadge
abs={kpi.deltaMoMAbs}
pct={kpi.deltaMoMPct}
label={labels.previous}
format={format}
language={language}
deltaIsBadWhenUp={deltaIsBadWhenUp}
/>
)}
{labels.lastYear !== null && (
<DeltaBadge
abs={kpi.deltaYoYAbs}
pct={kpi.deltaYoYPct}
label={labels.lastYear}
format={format}
language={language}
deltaIsBadWhenUp={deltaIsBadWhenUp}
/>
)}
</div>
)}
</div>
);
}

View file

@ -91,3 +91,60 @@ describe("KpiCard", () => {
expect(divs(render())).toBe(divs(render("Dont 40 $ non classés")) - 1);
});
});
describe("KpiCard — the labels of its two changes (#549)", () => {
// A change from the previous period, none from last year (no data there).
const kpi: CartesKpi = {
current: 1000,
previousMonth: 800,
previousYear: null,
deltaMoMAbs: 200,
deltaMoMPct: 25,
deltaYoYAbs: null,
deltaYoYPct: null,
sparkline: [],
};
const render = (deltaLabels?: { previous: string | null; lastYear: string | null }) =>
renderToStaticMarkup(
<KpiCard id="income" title="Revenus" kpi={kpi} format="currency" deltaLabels={deltaLabels} />,
);
const ROW = 'border-t border-[var(--border)]">';
/** Each change under the value: its label and what it shows, in order. */
function changesOf(html: string): Array<[string, string]> {
const row = html.split(ROW)[1];
if (row === undefined) return [];
return [...row.matchAll(/<span class="text-\[10px\][^"]*">(.*?)<\/span><span[^>]*>(.*?)<\/span>/g)].map(
(m): [string, string] => [m[1], m[2].replace(/<!-- -->/g, "")],
);
}
it("without labels, shows Cartes' two changes", () => {
expect(changesOf(render())).toEqual([
["t(reports.cartes.deltaMoMLabel)", expect.stringContaining("+200")],
["t(reports.cartes.deltaYoYLabel)", "—"],
]);
});
it("shows the labels it is given, a change without data as « — »", () => {
expect(changesOf(render({ previous: "Previous", lastYear: "Last year" }))).toEqual([
["Previous", expect.stringContaining("+200")],
["Last year", "—"],
]);
});
it("a null label hides its change, data or not", () => {
expect(changesOf(render({ previous: null, lastYear: "Last year" }))).toEqual([["Last year", "—"]]);
expect(changesOf(render({ previous: "Previous", lastYear: null }))).toEqual([
["Previous", expect.stringContaining("+200")],
]);
});
it("with both labels null, has no row of changes at all", () => {
const html = render({ previous: null, lastYear: null });
expect(html).not.toContain(ROW);
expect(html).not.toContain("+200");
// The value stays: 1 000 $, whatever space fr-CA groups it with.
expect(html).toMatch(/>1\D?000\D*\$</);
});
});

View file

@ -1,17 +1,29 @@
// useDashboard — scoped useReducer hook backing DashboardPage (the `/` home page).
//
// Converged onto the `/reports/cartes` model (Issue #279, epic #260): the KPI
// row, top movers and budget adherence are the exact Cartes widgets, sourced
// from `getCartesSnapshot` against a (year, month) reference period. The
// row, top movers and budget adherence are the exact Cartes widgets. The
// Dashboard keeps its OWN two temporal axes, neither of which is
// `useReportsPeriod` (M1/I4 deliberately left the Dashboard untouched):
// `useReportsPeriod` (M1/I4 deliberately left the Dashboard untouched), and
// since #549 each one has a fetch of its own:
// - `period` / `customDateFrom` / `customDateTo` — a flexible date range,
// feeding the two range-based transactional widgets (top-expenses bar
// chart, category-over-time trend).
// feeding the four KPI cards (`getPeriodKpis`: the figure of the period,
// its changes from the previous period of the same length and from the
// same period last year, `computeComparisonRanges`), the income-vs-expenses
// chart of the 12 months ending at the period's last month, and the two
// range-based transactional widgets (top-expenses bar chart,
// category-over-time trend).
// - `referenceYear` / `referenceMonth` — a single reference month, feeding
// the Cartes snapshot (KPIs + deltas, top movers, budget adherence, the
// income-vs-expenses overlay chart). Defaults to the previous complete
// month, like Cartes/Compare (`defaultReferencePeriod`).
// the « Analyse mensuelle »: the top movers and budget adherence of the
// Cartes snapshot (`getCartesSnapshot`, whose KPIs the page no longer
// reads). Defaults to the previous complete month, like Cartes/Compare
// (`defaultReferencePeriod`).
// A change of one axis re-runs its own fetch only. Each fetch drops a response
// that a later run of the same fetch superseded (its own fetch id), has its
// own loading flag — the page stays veiled until both have landed — and its
// own error, cleared only by its own next run: a month that loads never hides
// a period that failed. The import sources load once, at mount, so their error
// stays until the page mounts again. The page shows the period's error first,
// then the month's, then the sources'.
//
// The account (import-source) filter (`accountIds`) is Dashboard-local state
// (not routed through `useReportsPeriod`), but applies to every transactional
@ -30,25 +42,32 @@ import type {
CategoryOverTimeData,
CartesSnapshot,
ImportSource,
PeriodKpis,
} from "../shared/types";
import {
getExpensesByCategory,
deriveNetWorthTile,
type NetWorthTileData,
} from "../services/dashboardService";
import { getCategoryOverTime, getCartesSnapshot } from "../services/reportService";
import { getCategoryOverTime, getCartesSnapshot, getPeriodKpis } from "../services/reportService";
import { getAllImportSources } from "../services/transactionService";
import {
getSnapshotTotalsByDate,
listSnapshots,
listBalanceAccounts,
} from "../services/balance.service";
import { computeDateRange } from "../utils/dateRange";
import { computeComparisonRanges } from "../utils/dateRange";
import { defaultReferencePeriod } from "../utils/referencePeriod";
/** The Dashboard's two fetches, one per temporal axis (#549). */
type DashboardFetch = "period" | "month";
interface DashboardState {
categoryBreakdown: CategoryBreakdownItem[];
categoryOverTime: CategoryOverTimeData;
/** The KPI cards and the 12-month chart, over the period (#549). */
periodKpis: PeriodKpis | null;
/** The reference month's snapshot, read for its top movers and budget adherence only. */
cartesSnapshot: CartesSnapshot | null;
period: DashboardPeriod;
customDateFrom: string;
@ -58,21 +77,22 @@ interface DashboardState {
accountIds: number[];
accounts: ImportSource[];
netWorth: NetWorthTileData;
isLoading: boolean;
error: string | null;
loading: Record<DashboardFetch, boolean>;
errors: Record<DashboardFetch | "accounts", string | null>;
}
type DashboardAction =
| { type: "SET_LOADING"; payload: boolean }
| { type: "SET_ERROR"; payload: string | null }
| { type: "FETCH_START"; payload: DashboardFetch }
| { type: "FETCH_ERROR"; payload: { source: DashboardFetch | "accounts"; message: string } }
| {
type: "SET_DATA";
type: "SET_PERIOD_DATA";
payload: {
categoryBreakdown: CategoryBreakdownItem[];
categoryOverTime: CategoryOverTimeData;
cartesSnapshot: CartesSnapshot;
periodKpis: PeriodKpis;
};
}
| { type: "SET_MONTH_DATA"; payload: CartesSnapshot }
| { type: "SET_PERIOD"; payload: DashboardPeriod }
| { type: "SET_CUSTOM_DATES"; payload: { dateFrom: string; dateTo: string } }
| { type: "SET_REFERENCE_PERIOD"; payload: { year: number; month: number } }
@ -99,6 +119,7 @@ const EMPTY_NET_WORTH: NetWorthTileData = { visible: false, total: null, asOfDat
const initialState: DashboardState = {
categoryBreakdown: [],
categoryOverTime: EMPTY_CATEGORY_OVER_TIME,
periodKpis: null,
cartesSnapshot: null,
period: "year",
customDateFrom: yearStartStr,
@ -108,24 +129,30 @@ const initialState: DashboardState = {
accountIds: [],
accounts: [],
netWorth: EMPTY_NET_WORTH,
isLoading: false,
error: null,
loading: { period: false, month: false },
errors: { period: null, month: null, accounts: null },
};
function reducer(state: DashboardState, action: DashboardAction): DashboardState {
switch (action.type) {
case "SET_LOADING":
return { ...state, isLoading: action.payload };
case "SET_ERROR":
return { ...state, error: action.payload, isLoading: false };
case "SET_DATA":
case "FETCH_START":
return {
...state,
categoryBreakdown: action.payload.categoryBreakdown,
categoryOverTime: action.payload.categoryOverTime,
cartesSnapshot: action.payload.cartesSnapshot,
isLoading: false,
loading: { ...state.loading, [action.payload]: true },
errors: { ...state.errors, [action.payload]: null },
};
case "FETCH_ERROR": {
const { source, message } = action.payload;
return {
...state,
errors: { ...state.errors, [source]: message },
loading: source === "accounts" ? state.loading : { ...state.loading, [source]: false },
};
}
case "SET_PERIOD_DATA":
return { ...state, ...action.payload, loading: { ...state.loading, period: false } };
case "SET_MONTH_DATA":
return { ...state, cartesSnapshot: action.payload, loading: { ...state.loading, month: false } };
case "SET_PERIOD":
return { ...state, period: action.payload };
case "SET_CUSTOM_DATES":
@ -148,62 +175,65 @@ function reducer(state: DashboardState, action: DashboardAction): DashboardState
}
}
const messageOf = (e: unknown) => (e instanceof Error ? e.message : String(e));
export function useDashboard() {
const [state, dispatch] = useReducer(reducer, initialState);
const fetchIdRef = useRef(0);
// One counter per fetch: a run supersedes the earlier runs of its own fetch only.
const periodFetchIdRef = useRef(0);
const monthFetchIdRef = useRef(0);
const fetchData = useCallback(async (
const fetchPeriod = useCallback(async (
period: DashboardPeriod,
customFrom: string | undefined,
customTo: string | undefined,
refYear: number,
refMonth: number,
accountIds: number[],
) => {
const fetchId = ++fetchIdRef.current;
dispatch({ type: "SET_LOADING", payload: true });
dispatch({ type: "SET_ERROR", payload: null });
const fetchId = ++periodFetchIdRef.current;
dispatch({ type: "FETCH_START", payload: "period" });
try {
const { dateFrom, dateTo } = computeDateRange(period, customFrom, customTo);
const [categoryBreakdown, categoryOverTime, cartesSnapshot] = await Promise.all([
const ranges = computeComparisonRanges(period, customFrom, customTo);
const { dateFrom, dateTo } = ranges.current;
const [categoryBreakdown, categoryOverTime, periodKpis] = await Promise.all([
getExpensesByCategory(dateFrom, dateTo, accountIds),
// typeFilter "expense" (Issue #279): this chart is titled "expenses
// over time" but previously aggregated every category type — a
// revenue category could silently show up in an "expenses" trend.
getCategoryOverTime(dateFrom, dateTo, undefined, accountIds, "expense"),
getCartesSnapshot(refYear, refMonth, "month", accountIds),
getPeriodKpis(ranges, accountIds),
]);
if (fetchId !== fetchIdRef.current) return;
dispatch({ type: "SET_DATA", payload: { categoryBreakdown, categoryOverTime, cartesSnapshot } });
if (fetchId !== periodFetchIdRef.current) return;
dispatch({ type: "SET_PERIOD_DATA", payload: { categoryBreakdown, categoryOverTime, periodKpis } });
} catch (e) {
if (fetchId !== fetchIdRef.current) return;
dispatch({
type: "SET_ERROR",
payload: e instanceof Error ? e.message : String(e),
});
if (fetchId !== periodFetchIdRef.current) return;
dispatch({ type: "FETCH_ERROR", payload: { source: "period", message: messageOf(e) } });
}
}, []);
const fetchMonth = useCallback(async (refYear: number, refMonth: number, accountIds: number[]) => {
const fetchId = ++monthFetchIdRef.current;
dispatch({ type: "FETCH_START", payload: "month" });
try {
const cartesSnapshot = await getCartesSnapshot(refYear, refMonth, "month", accountIds);
if (fetchId !== monthFetchIdRef.current) return;
dispatch({ type: "SET_MONTH_DATA", payload: cartesSnapshot });
} catch (e) {
if (fetchId !== monthFetchIdRef.current) return;
dispatch({ type: "FETCH_ERROR", payload: { source: "month", message: messageOf(e) } });
}
}, []);
useEffect(() => {
fetchData(
state.period,
state.customDateFrom,
state.customDateTo,
state.referenceYear,
state.referenceMonth,
state.accountIds,
);
}, [
state.period,
state.customDateFrom,
state.customDateTo,
state.referenceYear,
state.referenceMonth,
state.accountIds,
fetchData,
]);
fetchPeriod(state.period, state.customDateFrom, state.customDateTo, state.accountIds);
}, [state.period, state.customDateFrom, state.customDateTo, state.accountIds, fetchPeriod]);
useEffect(() => {
fetchMonth(state.referenceYear, state.referenceMonth, state.accountIds);
}, [state.referenceYear, state.referenceMonth, state.accountIds, fetchMonth]);
// One-time: import sources for the FilterPanel's account checkboxes (same
// query as Trends/Compare/Budget — see useTrends.ts).
@ -213,7 +243,7 @@ export function useDashboard() {
const accounts = await getAllImportSources();
dispatch({ type: "SET_ACCOUNTS", payload: accounts });
} catch (e) {
dispatch({ type: "SET_ERROR", payload: e instanceof Error ? e.message : String(e) });
dispatch({ type: "FETCH_ERROR", payload: { source: "accounts", message: messageOf(e) } });
}
})();
}, []);
@ -257,5 +287,15 @@ export function useDashboard() {
dispatch({ type: "SET_ACCOUNT_IDS", payload: accountIds });
}, []);
return { state, setPeriod, setCustomDates, setReferencePeriod, setAccountIds };
return {
state,
/** True until both fetches have landed. */
isLoading: state.loading.period || state.loading.month,
/** The period's error first, then the month's, then the import sources'. */
error: state.errors.period ?? state.errors.month ?? state.errors.accounts,
setPeriod,
setCustomDates,
setReferencePeriod,
setAccountIds,
};
}

View file

@ -0,0 +1,283 @@
// useDashboard — one fetch per temporal axis (#549). The period feeds the KPI
// cards, the 12-month chart and the two expense charts; the reference month
// feeds the « Analyse mensuelle » alone. A change of one axis re-runs its own
// fetch only, each fetch keeps its own guard against superseded responses,
// its own loading flag and its own error.
//
// React's hooks come from the shared harness (src/test/hookHarness.ts, #409):
// the hook runs as a plain function, its reducer is applied, and `commit()`
// runs its effects. The services are mocked and never settle unless a test
// settles them, so no late dispatch lands in the next test's mount. The clock
// is fixed in `vi.hoisted`, before the hook's module reads it for its default
// dates: November 14, 2026, local noon; only `Date` is faked, so promises and
// timers still run.
import { describe, it, expect, vi, beforeEach, afterAll } from "vitest";
import type { CartesSnapshot, CategoryOverTimeData, PeriodKpis } from "../shared/types";
vi.hoisted(() => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date(2026, 10, 14, 12));
});
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
const services = vi.hoisted(() => ({
getExpensesByCategory: vi.fn(),
deriveNetWorthTile: vi.fn(),
getCategoryOverTime: vi.fn(),
getCartesSnapshot: vi.fn(),
getPeriodKpis: vi.fn(),
getAllImportSources: vi.fn(),
listBalanceAccounts: vi.fn(),
listSnapshots: vi.fn(),
getSnapshotTotalsByDate: vi.fn(),
}));
vi.mock("../services/dashboardService", () => ({
getExpensesByCategory: services.getExpensesByCategory,
deriveNetWorthTile: services.deriveNetWorthTile,
}));
vi.mock("../services/reportService", () => ({
getCategoryOverTime: services.getCategoryOverTime,
getCartesSnapshot: services.getCartesSnapshot,
getPeriodKpis: services.getPeriodKpis,
}));
vi.mock("../services/transactionService", () => ({ getAllImportSources: services.getAllImportSources }));
vi.mock("../services/balance.service", () => ({
listBalanceAccounts: services.listBalanceAccounts,
listSnapshots: services.listSnapshots,
getSnapshotTotalsByDate: services.getSnapshotTotalsByDate,
}));
import { hookHarness } from "../test/hookHarness";
import { computeComparisonRanges } from "../utils/dateRange";
import { useDashboard } from "./useDashboard";
const harness = hookHarness();
const EMPTY_OVER_TIME: CategoryOverTimeData = {
categories: [],
data: [],
colors: {},
categoryIds: {},
types: {},
tree: [],
};
/** The figures the hook stores as they come: only their identity is read. */
const kpisNamed = (name: string) => ({ name }) as unknown as PeriodKpis;
const snapshotNamed = (name: string) => ({ name }) as unknown as CartesSnapshot;
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
/** The next period fetch, settled by the test: its two charts answer at once, its cards on the deferred. */
function nextPeriodFetch() {
const cards = deferred<PeriodKpis>();
services.getExpensesByCategory.mockResolvedValueOnce([]);
services.getCategoryOverTime.mockResolvedValueOnce(EMPTY_OVER_TIME);
services.getPeriodKpis.mockReturnValueOnce(cards.promise);
return cards;
}
/** The next month fetch, settled by the test. */
function nextMonthFetch() {
const snapshot = deferred<CartesSnapshot>();
services.getCartesSnapshot.mockReturnValueOnce(snapshot.promise);
return snapshot;
}
/** One render of the mounted hook, its effects run. */
function renderAndCommit() {
const value = harness.render(useDashboard);
harness.commit();
return value;
}
/** Lets the settled promises and the dispatches that follow them run. */
const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
const DATA_SERVICES = [
services.getExpensesByCategory,
services.getCategoryOverTime,
services.getPeriodKpis,
services.getCartesSnapshot,
] as const;
beforeEach(() => {
harness.clear();
for (const fn of Object.values(services)) fn.mockReset().mockReturnValue(new Promise(() => {}));
});
afterAll(() => {
vi.useRealTimers();
});
describe("useDashboard — at mount, each axis has its fetch (#549)", () => {
it("the period's ranges reach the cards and both charts, the reference month the snapshot, with the account filter", () => {
renderAndCommit();
// « Cette année » on November 14, 2026, the hook's default.
const ranges = computeComparisonRanges("year", "2026-01-01", "2026-11-14");
expect(ranges.current).toEqual({ dateFrom: "2026-01-01", dateTo: "2026-11-14" });
expect(services.getPeriodKpis.mock.calls).toEqual([[ranges, []]]);
expect(services.getExpensesByCategory.mock.calls).toEqual([["2026-01-01", "2026-11-14", []]]);
expect(services.getCategoryOverTime.mock.calls).toEqual([["2026-01-01", "2026-11-14", undefined, [], "expense"]]);
// The previous complete month.
expect(services.getCartesSnapshot.mock.calls).toEqual([[2026, 10, "month", []]]);
expect(harness.render(useDashboard).isLoading).toBe(true);
});
});
describe("useDashboard — a change of one axis re-runs its own fetch only (#549)", () => {
beforeEach(() => {
renderAndCommit();
for (const fn of DATA_SERVICES) fn.mockClear();
});
it("a new reference month asks for its snapshot, and nothing of the period", () => {
harness.render(useDashboard).setReferencePeriod(2026, 7);
renderAndCommit();
expect(services.getCartesSnapshot.mock.calls).toEqual([[2026, 7, "month", []]]);
expect(services.getPeriodKpis).not.toHaveBeenCalled();
expect(services.getExpensesByCategory).not.toHaveBeenCalled();
expect(services.getCategoryOverTime).not.toHaveBeenCalled();
});
it("a new period asks for its cards and charts, and nothing of the month", () => {
harness.render(useDashboard).setPeriod("month");
renderAndCommit();
expect(services.getPeriodKpis.mock.calls).toEqual([[computeComparisonRanges("month"), []]]);
expect(services.getExpensesByCategory.mock.calls).toEqual([["2026-11-01", "2026-11-14", []]]);
expect(services.getCartesSnapshot).not.toHaveBeenCalled();
});
it("custom dates reach the cards and both charts as they are", () => {
harness.render(useDashboard).setCustomDates("2026-03-10", "2026-03-20");
renderAndCommit();
const ranges = computeComparisonRanges("custom", "2026-03-10", "2026-03-20");
expect(ranges.previous).toEqual({ dateFrom: "2026-02-27", dateTo: "2026-03-09" });
expect(services.getPeriodKpis.mock.calls).toEqual([[ranges, []]]);
expect(services.getExpensesByCategory.mock.calls).toEqual([["2026-03-10", "2026-03-20", []]]);
expect(services.getCategoryOverTime.mock.calls).toEqual([["2026-03-10", "2026-03-20", undefined, [], "expense"]]);
expect(services.getCartesSnapshot).not.toHaveBeenCalled();
});
it("a new account filter re-runs both fetches with it, never the net-worth tile nor the sources", () => {
services.listBalanceAccounts.mockClear();
services.listSnapshots.mockClear();
services.getSnapshotTotalsByDate.mockClear();
services.getAllImportSources.mockClear();
harness.render(useDashboard).setAccountIds([3]);
renderAndCommit();
expect(services.getPeriodKpis.mock.calls).toEqual([[computeComparisonRanges("year", "2026-01-01", "2026-11-14"), [3]]]);
expect(services.getExpensesByCategory.mock.calls).toEqual([["2026-01-01", "2026-11-14", [3]]]);
expect(services.getCategoryOverTime.mock.calls).toEqual([["2026-01-01", "2026-11-14", undefined, [3], "expense"]]);
expect(services.getCartesSnapshot.mock.calls).toEqual([[2026, 10, "month", [3]]]);
expect(services.listBalanceAccounts).not.toHaveBeenCalled();
expect(services.listSnapshots).not.toHaveBeenCalled();
expect(services.getSnapshotTotalsByDate).not.toHaveBeenCalled();
expect(services.getAllImportSources).not.toHaveBeenCalled();
});
});
describe("useDashboard — each fetch has its own guard, loading flag and error (#549)", () => {
it("a period answer that lands after a month change is still shown; a superseded month answer is dropped", async () => {
const period = nextPeriodFetch();
const october = nextMonthFetch();
renderAndCommit();
const august = nextMonthFetch();
harness.render(useDashboard).setReferencePeriod(2026, 8);
renderAndCommit();
period.resolve(kpisNamed("year"));
await flush();
expect(harness.render(useDashboard).state.periodKpis).toEqual(kpisNamed("year"));
october.resolve(snapshotNamed("october"));
await flush();
expect(harness.render(useDashboard).state.cartesSnapshot).toBeNull();
august.resolve(snapshotNamed("august"));
await flush();
expect(harness.render(useDashboard).state.cartesSnapshot).toEqual(snapshotNamed("august"));
});
it("a superseded period answer is dropped too", async () => {
const year = nextPeriodFetch();
renderAndCommit();
const month = nextPeriodFetch();
harness.render(useDashboard).setPeriod("month");
renderAndCommit();
month.resolve(kpisNamed("month"));
year.resolve(kpisNamed("year"));
await flush();
expect(harness.render(useDashboard).state.periodKpis).toEqual(kpisNamed("month"));
});
it("the page stays veiled until both fetches have landed", async () => {
const period = nextPeriodFetch();
const month = nextMonthFetch();
renderAndCommit();
period.resolve(kpisNamed("year"));
await flush();
expect(harness.render(useDashboard).state.loading).toEqual({ period: false, month: true });
expect(harness.render(useDashboard).isLoading).toBe(true);
month.resolve(snapshotNamed("october"));
await flush();
expect(harness.render(useDashboard).isLoading).toBe(false);
});
it("a period that failed stays shown while the month loads and lands; its own next run clears it", async () => {
const period = nextPeriodFetch();
const october = nextMonthFetch();
renderAndCommit();
period.reject(new Error("period failed"));
october.resolve(snapshotNamed("october"));
await flush();
expect(harness.render(useDashboard)).toMatchObject({ error: "period failed", isLoading: false });
const july = nextMonthFetch();
harness.render(useDashboard).setReferencePeriod(2026, 7);
renderAndCommit();
expect(harness.render(useDashboard).error).toBe("period failed");
july.resolve(snapshotNamed("july"));
await flush();
expect(harness.render(useDashboard).error).toBe("period failed");
nextPeriodFetch();
harness.render(useDashboard).setPeriod("month");
renderAndCommit();
expect(harness.render(useDashboard).error).toBeNull();
});
it("a month that failed stays shown while the period loads and lands", async () => {
const year = nextPeriodFetch();
const october = nextMonthFetch();
renderAndCommit();
october.reject(new Error("month failed"));
year.resolve(kpisNamed("year"));
await flush();
expect(harness.render(useDashboard).error).toBe("month failed");
const month = nextPeriodFetch();
harness.render(useDashboard).setPeriod("month");
renderAndCommit();
month.resolve(kpisNamed("month"));
await flush();
expect(harness.render(useDashboard)).toMatchObject({ error: "month failed", isLoading: false });
});
});

View file

@ -26,6 +26,9 @@
"dashboard": {
"title": "Dashboard",
"kpiSectionTitle": "Key indicators",
"monthlyAnalysisTitle": "Monthly analysis",
"deltaPreviousPeriod": "vs previous period",
"deltaSamePeriodLastYear": "vs same period last year",
"income": "Income",
"expenses": "Expenses",
"net": "Net",
@ -56,15 +59,15 @@
"title": "How to use the Dashboard",
"tips": [
"The filter bar at the top picks the date range and which import sources to include",
"The key indicators (income, expenses, net, savings rate) cover the chosen reference month, with their change vs the previous month and vs last year",
"The key indicators (income, expenses, net balance, savings rate) and the \"Income vs expenses\" chart follow the period of the filter; each indicator is compared with the previous period of the same length and with the same period last year, except under \"All\"",
"The \"Current net worth\" tile comes from the Balance sheet — it is not filtered by import source",
"Rising/falling categories and budget adherence summarize the reference month's changes",
"The \"Monthly analysis\" (biggest increases and decreases, budget adherence) covers the month chosen in the list next to \"Key indicators\"",
"The bar chart ranks your expenses by category; the chart below tracks their trend over time"
]
},
"empty": {
"title": "Welcome to Simpl'Résultat",
"description": "After your first import, this page will show your income, expenses, savings rate and top categories for the selected month.",
"description": "After your first import, this page will show your income, expenses, savings rate and top categories for the selected period.",
"cta": "Choose an import folder"
}
},
@ -1060,13 +1063,14 @@
},
"dashboard": {
"title": "Dashboard",
"overview": "The Dashboard gives you an at-a-glance summary of your financial situation for a selected time period.",
"overview": "The Dashboard gives you an at-a-glance summary of your financial situation over the selected period, with the analysis of a reference month.",
"features": [
"Balance, income, and expense summary cards",
"Expense breakdown by category (pie chart with SVG patterns)",
"Budget vs Actual table for the current month (variance in $ and %)",
"Stacked bar chart of expenses by category and month",
"Adjustable time period selector (default: year to date)",
"Period filter (This month, 3 months, 6 months, This year, 12 months, All or Custom; default: This year) and import-source filter, at the top of the page",
"Four key indicators over the period: income, expenses, net balance and savings rate, each with its 13-month curve and its changes vs the previous period and vs the same period last year",
"\"Current net worth\" tile, from the Balance sheet, which follows neither the period nor the source filter",
"\"Income vs expenses\" chart of the 12 months ending at the period's last month",
"Monthly analysis: biggest increases, biggest decreases and budget adherence of a reference month, chosen in the list next to \"Key indicators\"",
"Expenses by category (ranked bars) and expenses over time (stacked bars by month), over the period",
"Context menu (right-click) to hide a category or view its transactions",
"Welcome card for a profile without transactions, with the getting-started checklist: eight steps, checked from your data or with \"Got it\" for the visit steps, and a \"Hide\" button"
],
@ -1074,16 +1078,18 @@
"In a profile without transactions, the dashboard shows a welcome card and the getting-started checklist, in eight steps: \"Create a profile\" (already ticked), \"Choose an import folder\", \"Set up an import source\", \"Import a first file\", \"Browse categories and keywords\", \"Categorize a transaction by hand\", \"Enter a first budget\" and \"Browse the reports\". The steps are ticked from your data, except the two visit steps (categories and reports), ticked with \"Got it\" on their card or, for the reports, by a click on the outlined Trends card. Each unticked row leads to the page where it is done; the Budget box is marked \"Base and up\" in the Free edition and does not count towards the total",
"Once the profile has transactions, the checklist leaves the dashboard: the getting-started banner, at the top of every page, takes over until the end of the path (see Getting Started → The getting-started path)",
"\"Hide\" removes the checklist from the welcome card, and the banner from every page, for this profile only; Settings → Users shows them again",
"Use the period selector in the top-right to choose a time range (month, 3 months, year, etc.)",
"Review the summary cards for your balance, total income, and total expenses",
"Check the pie chart to see how your spending is distributed across categories",
"Review the Budget vs Actual table to compare your spending against your plan for the current month",
"Analyze the stacked bar chart at the bottom to see expense trends by category over time",
"Right-click a category in a chart to hide it or view its transaction details"
"Choose the period in the filter at the top of the page: the four key indicators, the \"Income vs expenses\" chart and both expense charts follow it. The source filter applies to everything except the \"Current net worth\" tile",
"Read the changes under each indicator: \"vs previous period\" compares it with the period of the same length just before, \"vs same period last year\" with the same dates a year earlier. \"This year\", \"12 months\" and a custom period of exactly one year only have last year's change, since their previous period is last year's, and \"All\" has none",
"Choose the reference month in the list next to \"Key indicators\": it drives the three cards of the \"Monthly analysis\", that is the biggest increases and decreases against the month before, and the month's budget adherence",
"Click a category among the increases or decreases to open its analysis for that month (Reports → Category Analysis, Base edition and up)",
"Right-click a category in an expense chart to hide it or view its transaction details"
],
"tips": [
"The default period is year to date for an annual overview when you open the app",
"The net balance is the sum of every transaction of the reference month: income minus expenses, plus uncategorized transactions and transfers, which a note under the card details when they are not zero. The savings rate is (income − expenses) ÷ income",
"The default period is \"This year\", from January 1st to today, and the reference month is the last complete month",
"The net balance is the sum of every transaction of the period: income minus expenses, plus uncategorized transactions and transfers, which a note under the card details when they are not zero. The savings rate is (income − expenses) ÷ income",
"The previous period of \"This month\", \"3 months\" and \"6 months\" ends on the same day of the month: on November 14, \"This month\" (the 1st to the 14th) is compared with October 1st to 14th. A custom period's covers the same number of days, just before",
"The 12-month chart and the indicators' curves count whole months: a custom period that ends on the 15th shows its last month in full there",
"A change shown as \"—\" means the compared period has no transaction",
"Hidden categories appear as dismissible chips above the chart — click Show All to restore them",
"SVG patterns (lines, dots, crosshatch) help distinguish categories beyond just color",
"The checklist boxes tick on your data, not on a click: \"Categorize a transaction by hand\" expects a transaction whose category you changed yourself; the automatic categorization of the import does not tick it"

View file

@ -26,6 +26,9 @@
"dashboard": {
"title": "Tableau de bord",
"kpiSectionTitle": "Indicateurs clés",
"monthlyAnalysisTitle": "Analyse mensuelle",
"deltaPreviousPeriod": "vs période précédente",
"deltaSamePeriodLastYear": "vs même période l'an dernier",
"income": "Revenus",
"expenses": "Dépenses",
"net": "Net",
@ -56,15 +59,15 @@
"title": "Comment utiliser le tableau de bord",
"tips": [
"Le filtre en haut choisit la plage de dates et les sources d'import à inclure",
"Les indicateurs clés (revenus, dépenses, net, taux d'épargne) portent sur le mois de référence choisi, avec leur variation vs le mois précédent et vs l'an dernier",
"Les indicateurs clés (revenus, dépenses, solde net, taux d'épargne) et le graphique « Revenus vs dépenses » suivent la période du filtre ; chaque indicateur se compare à la période précédente de même durée et à la même période l'an dernier, sauf sous « Tout »",
"La tuile « Valeur nette actuelle » vient du Bilan — elle n'est pas filtrée par source d'import",
"Les catégories en hausse/en baisse et le respect du budget résument les changements du mois de référence",
"L'« Analyse mensuelle » (catégories en hausse et en baisse, respect du budget) porte sur le mois choisi dans la liste à côté de « Indicateurs clés »",
"Le graphique en barres classe vos dépenses par catégorie ; le graphique du bas en suit l'évolution dans le temps"
]
},
"empty": {
"title": "Bienvenue dans Simpl'Résultat",
"description": "Après votre premier import, cette page montrera vos revenus, vos dépenses, votre taux d'épargne et vos principales catégories pour le mois choisi.",
"description": "Après votre premier import, cette page montrera vos revenus, vos dépenses, votre taux d'épargne et vos principales catégories pour la période choisie.",
"cta": "Choisir un dossier d'import"
}
},
@ -1060,13 +1063,14 @@
},
"dashboard": {
"title": "Tableau de bord",
"overview": "Le tableau de bord vous donne un aperçu rapide de votre situation financière pour une période sélectionnée.",
"overview": "Le tableau de bord vous donne un aperçu rapide de votre situation financière sur la période choisie, avec l'analyse d'un mois de référence.",
"features": [
"Cartes résumées du solde, des revenus et des dépenses",
"Répartition des dépenses par catégorie (graphique circulaire avec motifs SVG)",
"Tableau Budget vs Réel du mois courant (écart en $ et %)",
"Histogramme empilé des dépenses par catégorie et par mois",
"Sélecteur de période ajustable (par défaut : année à ce jour)",
"Filtre de la période (Ce mois, 3 mois, 6 mois, Cette année, 12 mois, Tout ou Personnalisé ; par défaut Cette année) et des sources d'import, en haut de la page",
"Quatre indicateurs clés sur la période : revenus, dépenses, solde net et taux d'épargne, chacun avec sa courbe des 13 derniers mois et ses écarts vs la période précédente et vs la même période l'an dernier",
"Tuile « Valeur nette actuelle », tirée du Bilan, qui ne suit ni la période ni le filtre des sources",
"Graphique « Revenus vs dépenses » des 12 mois qui finissent au dernier mois de la période",
"Analyse mensuelle : catégories en hausse, catégories en baisse et respect du budget d'un mois de référence, choisi dans la liste à côté de « Indicateurs clés »",
"Dépenses par catégorie (barres classées) et dépenses dans le temps (histogramme empilé par mois), sur la période",
"Menu contextuel (clic droit) pour masquer une catégorie ou voir ses transactions",
"Carte d'accueil d'un profil sans transaction, avec la liste de démarrage : huit étapes, cochées selon vos données ou par « J'ai compris » pour les visites, et un bouton « Masquer »"
],
@ -1074,16 +1078,18 @@
"Dans un profil sans transaction, le tableau de bord affiche une carte d'accueil et la liste de démarrage, en huit étapes : « Créer un profil » (déjà cochée), « Choisir un dossier d'import », « Configurer une source d'import », « Importer un premier fichier », « Parcourir les catégories et les mots-clés », « Classer une transaction à la main », « Saisir un premier budget » et « Parcourir les rapports ». Les étapes se cochent selon vos données, sauf les deux étapes de visite (catégories et rapports), cochées par « J'ai compris » sur leur carte ou, pour les rapports, par un clic sur la carte Tendances entourée. Chaque ligne non cochée mène à la page où la faire ; la case Budget est marquée « Base et plus » en édition Gratuite et ne compte pas dans le total",
"Dès que le profil a des transactions, la liste quitte le tableau de bord : le bandeau de démarrage, en haut de chaque page, la remplace jusqu'à la fin du parcours (voir Premiers pas → Le parcours de démarrage)",
"« Masquer » retire la liste de la carte d'accueil, et le bandeau de toutes les pages, pour ce profil seulement ; Paramètres → Utilisateurs les réaffiche",
"Utilisez le sélecteur de période en haut à droite pour choisir une plage de temps (mois, 3 mois, année, etc.)",
"Consultez les cartes résumées pour votre solde, revenus totaux et dépenses totales",
"Vérifiez le graphique circulaire pour voir comment vos dépenses sont réparties par catégorie",
"Consultez le tableau Budget vs Réel pour comparer vos dépenses au budget du mois courant",
"Analysez l'histogramme en bas de page pour voir l'évolution de vos dépenses par catégorie dans le temps",
"Cliquez droit sur une catégorie dans un graphique pour la masquer ou voir le détail de ses transactions"
"Choisissez la période dans le filtre en haut de la page : les quatre indicateurs clés, le graphique « Revenus vs dépenses » et les deux graphiques de dépenses la suivent. Le filtre des sources s'applique à tout, sauf à la tuile « Valeur nette actuelle »",
"Lisez les écarts sous chaque indicateur : « vs période précédente » le compare à la période de même durée qui précède, « vs même période l'an dernier » aux mêmes dates un an plus tôt. « Cette année », « 12 mois » et une période personnalisée d'un an exactement n'ont que l'écart de l'an dernier, leur période précédente étant celle de l'an dernier, et « Tout » n'en a aucun",
"Choisissez le mois de référence dans la liste à côté de « Indicateurs clés » : il pilote les trois cartes de l'« Analyse mensuelle », soit les catégories en hausse et en baisse par rapport au mois précédent, et le respect du budget du mois",
"Cliquez sur une catégorie en hausse ou en baisse pour ouvrir son analyse sur ce mois (Rapports → Analyse par catégorie, édition Base et plus)",
"Cliquez droit sur une catégorie dans un graphique de dépenses pour la masquer ou voir le détail de ses transactions"
],
"tips": [
"La période par défaut est « année à ce jour » pour un aperçu annuel dès l'ouverture",
"Le solde net est la somme de toutes les transactions du mois de référence : les revenus moins les dépenses, plus les transactions non classées et les transferts, qu'une note sous la carte détaille quand ils ne sont pas nuls. Le taux d'épargne vaut (revenus − dépenses) ÷ revenus",
"La période par défaut est « Cette année », du 1er janvier à aujourd'hui, et le mois de référence est le dernier mois complet",
"Le solde net est la somme de toutes les transactions de la période : les revenus moins les dépenses, plus les transactions non classées et les transferts, qu'une note sous la carte détaille quand ils ne sont pas nuls. Le taux d'épargne vaut (revenus − dépenses) ÷ revenus",
"La période précédente de « Ce mois », « 3 mois » et « 6 mois » finit au même jour du mois : un 14 novembre, « Ce mois » (du 1er au 14) se compare au 1er au 14 octobre. Celle d'une période personnalisée compte le même nombre de jours, juste avant",
"Le graphique des 12 mois et les courbes des indicateurs comptent des mois entiers : une période personnalisée qui finit un 15 y montre son dernier mois en entier",
"Un écart affiché « — » signale une période comparée sans aucune transaction",
"Les catégories masquées apparaissent sous forme de pastilles au-dessus du graphique — cliquez sur Tout afficher pour les restaurer",
"Les motifs SVG (lignes, points, hachures) aident à distinguer les catégories au-delà des couleurs",
"Les cases de la liste de démarrage se cochent sur vos données, pas sur un clic : « Classer une transaction à la main » attend une transaction dont vous avez changé la catégorie vous-même, la catégorisation automatique de l'import ne la coche pas"

View file

@ -4,27 +4,37 @@
// to markers: what is pinned is the page's branching on the path. Since #397
// the page has no list of its own once transactions exist: the banner of
// AppShell replaced the compact bar (D7). The fake KpiCard records its props:
// the page hands « Solde net » the note of the snapshot (#392, D5).
// the page hands « Solde net » the note of the period (#392, D5), and each card
// the labels of the changes its period has (#549).
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router-dom";
import type { OnboardingValue } from "../hooks/useOnboardingChecklist";
import type { CartesKpi, CartesSnapshot } from "../shared/types";
import type {
CartesKpi,
CartesSnapshot,
DashboardPeriod,
PeriodComparisonRanges,
PeriodKpis,
} from "../shared/types";
vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock());
let onboarding: OnboardingValue;
vi.mock("../contexts/OnboardingContext", () => ({ useOnboarding: () => onboarding }));
let periodKpis: PeriodKpis | null = null;
let cartesSnapshot: CartesSnapshot | null = null;
let selectedPeriod: DashboardPeriod = "year";
vi.mock("../hooks/useDashboard", () => ({
useDashboard: () => ({
state: {
categoryBreakdown: [],
categoryOverTime: { categories: [], data: [] },
periodKpis,
cartesSnapshot,
period: "year",
period: selectedPeriod,
customDateFrom: "2026-01-01",
customDateTo: "2026-10-08",
referenceYear: 2026,
@ -32,9 +42,11 @@ vi.mock("../hooks/useDashboard", () => ({
accountIds: [],
accounts: [],
netWorth: null,
isLoading: false,
error: null,
loading: { period: false, month: false },
errors: { period: null, month: null, accounts: null },
},
isLoading: false,
error: null,
setPeriod: vi.fn(),
setCustomDates: vi.fn(),
setReferencePeriod: vi.fn(),
@ -43,11 +55,12 @@ vi.mock("../hooks/useDashboard", () => ({
}));
// Hoisted with the mocks below, which run before the imports.
const { marker, emptyStateProps, kpiProps, moversProps } = vi.hoisted(() => ({
const { marker, emptyStateProps, kpiProps, moversProps, overlayProps } = vi.hoisted(() => ({
marker: (name: string) => ({ default: () => <i data-marker={name} /> }),
emptyStateProps: { current: null as Record<string, unknown> | null },
kpiProps: new Map<string, Record<string, unknown>>(),
moversProps: [] as Record<string, unknown>[],
overlayProps: { current: null as Record<string, unknown> | null },
}));
vi.mock("../components/shared/PageHelp", () => ({ PageHelp: () => null }));
vi.mock("../components/dashboard/CategoriesV1DiscoveryBanner", () => marker("discovery"));
@ -71,7 +84,12 @@ vi.mock("../components/reports/cards/KpiCard", () => ({
return <i data-marker="kpi" />;
},
}));
vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => marker("overlay"));
vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => ({
default: (props: Record<string, unknown>) => {
overlayProps.current = props;
return <i data-marker="overlay" />;
},
}));
vi.mock("../components/reports/cards/TopMoversList", () => ({
default: (props: Record<string, unknown>) => {
moversProps.push(props);
@ -123,6 +141,49 @@ function path(overrides: Partial<OnboardingValue> & { transactions?: number } =
};
}
const kpi = (current: number): CartesKpi => ({
current,
previousMonth: null,
previousYear: null,
deltaMoMAbs: null,
deltaMoMPct: null,
deltaYoYAbs: null,
deltaYoYPct: null,
sparkline: [],
});
/** The reference month's snapshot: September's movers and budget, and KPIs the page must not read. */
const snapshotOf = (overrides: Partial<CartesSnapshot> = {}): CartesSnapshot => ({
referenceYear: 2026,
referenceMonth: 9,
kpis: { income: kpi(1), expenses: kpi(2), net: kpi(3), savingsRate: kpi(4) },
netBreakdown: { uncategorized: 1, transfers: 2 },
flow12Months: [],
topMoversUp: [],
topMoversDown: [],
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
...overrides,
});
/** « Ce mois » on October 8, 2026: both comparisons. */
const MONTH_RANGES: PeriodComparisonRanges = {
current: { dateFrom: "2026-10-01", dateTo: "2026-10-08" },
previous: { dateFrom: "2026-09-01", dateTo: "2026-09-08" },
previousYear: { dateFrom: "2025-10-01", dateTo: "2025-10-08" },
lastMonth: { year: 2026, month: 10 },
};
const periodOf = (ranges: PeriodComparisonRanges = MONTH_RANGES, overrides: Partial<PeriodKpis> = {}): PeriodKpis => ({
ranges,
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(710), savingsRate: kpi(97) },
netBreakdown: { uncategorized: 0, transfers: 0 },
flow12Months: [],
...overrides,
});
const KPI_IDS = ["income", "expenses", "net", "savingsRate"];
const render = () =>
renderToStaticMarkup(
<MemoryRouter>
@ -133,9 +194,12 @@ const render = () =>
beforeEach(() => {
onboarding = path();
emptyStateProps.current = null;
periodKpis = null;
cartesSnapshot = null;
selectedPeriod = "year";
kpiProps.clear();
moversProps.length = 0;
overlayProps.current = null;
});
describe("DashboardPage on the shared path (#352, #396, #397)", () => {
@ -191,65 +255,102 @@ describe("DashboardPage — texts that go through t (#437)", () => {
});
});
describe("DashboardPage — the note under « Solde net » (#392, D5)", () => {
const kpi = (current: number): CartesKpi => ({
current,
previousMonth: null,
previousYear: null,
deltaMoMAbs: null,
deltaMoMPct: null,
deltaYoYAbs: null,
deltaYoYPct: null,
sparkline: [],
describe("DashboardPage — the KPI cards and the 12-month chart follow the period (#549)", () => {
it("the cards read the period's figures, not the reference month's snapshot", () => {
periodKpis = periodOf();
cartesSnapshot = snapshotOf();
render();
expect([...kpiProps.keys()]).toEqual(KPI_IDS);
expect(kpiProps.get("income")!.kpi).toBe(periodKpis.kpis.income);
expect(kpiProps.get("expenses")!.kpi).toBe(periodKpis.kpis.expenses);
expect(kpiProps.get("net")!.kpi).toBe(periodKpis.kpis.net);
expect(kpiProps.get("savingsRate")!.kpi).toBe(periodKpis.kpis.savingsRate);
});
it("hands the net card the note of the snapshot's breakdown, and no other card a note", () => {
const netBreakdown = { uncategorized: 40, transfers: -300 };
cartesSnapshot = {
referenceYear: 2026,
referenceMonth: 10,
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(710), savingsRate: kpi(97) },
netBreakdown,
flow12Months: [],
topMoversUp: [],
topMoversDown: [],
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
};
it("the cards show without the snapshot, and the snapshot alone brings none", () => {
periodKpis = periodOf();
render();
expect([...kpiProps.keys()]).toEqual(KPI_IDS);
kpiProps.clear();
periodKpis = null;
cartesSnapshot = snapshotOf();
render();
expect(kpiProps.size).toBe(0);
});
it("hands the net card the note of the period's breakdown, and no other card a note", () => {
const netBreakdown = { uncategorized: 40, transfers: -300 };
periodKpis = periodOf(MONTH_RANGES, { netBreakdown });
cartesSnapshot = snapshotOf();
render();
expect([...kpiProps.keys()]).toEqual(["income", "expenses", "net", "savingsRate"]);
expect(kpiProps.get("net")!.note).toContain("t(reports.cartes.netNote.both[");
expect(kpiProps.get("net")!.note).toBe(netNote(markedT, "fr", netBreakdown));
for (const id of ["income", "expenses", "savingsRate"]) expect(kpiProps.get(id)!.note).toBeUndefined();
});
it("hands the 12-month chart the period's months, not the snapshot's", () => {
const flow12Months = [
{ month: "2026-10", income: 1000, expenses: 30, uncategorized: 0, transfers: 0, resultBeforeTransfers: 970, net: 970 },
];
periodKpis = periodOf(MONTH_RANGES, { flow12Months });
cartesSnapshot = snapshotOf();
expect(render()).toContain('data-marker="overlay"');
expect(overlayProps.current!.flow).toBe(flow12Months);
});
it.each([
[
"both comparisons",
MONTH_RANGES,
{ previous: "t(dashboard.deltaPreviousPeriod)", lastYear: "t(dashboard.deltaSamePeriodLastYear)" },
],
[
"last year's alone (« Cette année », « 12 mois »)",
{ ...MONTH_RANGES, previous: null },
{ previous: null, lastYear: "t(dashboard.deltaSamePeriodLastYear)" },
],
["none (« Tout »)", { ...MONTH_RANGES, current: {}, previous: null, previousYear: null }, { previous: null, lastYear: null }],
])("labels every card's changes for a period with %s", (_, ranges, labels) => {
periodKpis = periodOf(ranges);
render();
for (const id of KPI_IDS) expect(kpiProps.get(id)!.deltaLabels, id).toEqual(labels);
});
it("labels the changes of the figures on screen, not of the selector, while the next period loads", () => {
// The selector is on « Tout »; the figures of « Ce mois » are still on screen.
selectedPeriod = "all";
periodKpis = periodOf(MONTH_RANGES);
render();
expect(kpiProps.get("income")!.deltaLabels).toEqual({
previous: "t(dashboard.deltaPreviousPeriod)",
lastYear: "t(dashboard.deltaSamePeriodLastYear)",
});
});
});
describe("DashboardPage — « Analyse mensuelle », the three cards of the reference month (#549)", () => {
it("heads the movers and the budget adherence, after the 12-month chart", () => {
periodKpis = periodOf();
cartesSnapshot = snapshotOf();
const html = render();
const title = html.indexOf(">t(dashboard.monthlyAnalysisTitle)<");
expect(title).toBeGreaterThan(html.indexOf('data-marker="overlay"'));
expect(title).toBeLessThan(html.indexOf('data-marker="movers"'));
expect(title).toBeLessThan(html.indexOf('data-marker="adherence"'));
});
it("is absent without the reference month's snapshot", () => {
periodKpis = periodOf();
expect(render()).not.toContain("t(dashboard.monthlyAnalysisTitle)");
});
});
describe("DashboardPage — the movers link to the month of their snapshot (#548)", () => {
const kpi = (current: number): CartesKpi => ({
current,
previousMonth: null,
previousYear: null,
deltaMoMAbs: null,
deltaMoMPct: null,
deltaYoYAbs: null,
deltaYoYPct: null,
sparkline: [],
});
it("hands both lists the snapshot's month, not the picker's, while the next snapshot loads", () => {
// The picker is on September (the state's month); October's snapshot is
// still on screen until September's arrives.
cartesSnapshot = {
referenceYear: 2026,
referenceMonth: 10,
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(970), savingsRate: kpi(97) },
netBreakdown: { uncategorized: 0, transfers: 0 },
flow12Months: [],
topMoversUp: [],
topMoversDown: [],
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
};
cartesSnapshot = snapshotOf({ referenceMonth: 10 });
render();
expect(moversProps.map((p) => [p.direction, p.year, p.month])).toEqual([
["up", 2026, 10],

View file

@ -2,11 +2,17 @@
//
// Converged onto the `/reports/cartes` model (Issue #279, epic #260): the KPI
// row, top movers and budget adherence are the exact Cartes presentational
// components, sourced from the same `getCartesSnapshot` reference-month
// snapshot. Two Dashboard-specific widgets remain: the top-expense-categories
// ranked bar chart (replacing the former expense-only pie) and the net-worth
// tile (from the Bilan — a different metric from every transactional widget
// here, see NetWorthTile's own header comment).
// components. Since #549 the KPI row and the 12-month chart follow the period
// of the filter (`getPeriodKpis`), like the two expense charts below; the
// reference month, picked next to the KPI title, only drives the three cards
// under « Analyse mensuelle » (top movers, budget adherence), read from the
// `getCartesSnapshot` reference-month snapshot. Each card shows the changes
// its period has (`ranges` of the figures on screen, not of the selector, so
// they match while the next period loads). Two Dashboard-specific widgets
// remain: the top-expense-categories ranked bar chart (replacing the former
// expense-only pie) and the net-worth tile (from the Bilan — a different
// metric from every transactional widget here, see NetWorthTile's own header
// comment).
//
// Onboarding (#352): the page branches on the getting-started checklist
// `status`, never on a bare counter. While it loads, only the title and the
@ -45,12 +51,14 @@ export default function DashboardPage() {
const { t, i18n } = useTranslation();
const {
state,
isLoading,
error,
setPeriod,
setCustomDates,
setReferencePeriod,
setAccountIds,
} = useDashboard();
const { categoryBreakdown, categoryOverTime, cartesSnapshot, period, isLoading } = state;
const { categoryBreakdown, categoryOverTime, periodKpis, cartesSnapshot, period } = state;
const onboarding = useOnboarding();
const [hiddenCategories, setHiddenCategories] = useState<Set<string>>(new Set());
@ -75,6 +83,15 @@ export default function DashboardPage() {
const { dateFrom, dateTo } = computeDateRange(period, state.customDateFrom, state.customDateTo);
// The changes the period has (#549): none for « Tout », last year's alone
// when the previous period is last year's range (« Cette année », « 12 mois »).
const deltaLabels = periodKpis
? {
previous: periodKpis.ranges.previous ? t("dashboard.deltaPreviousPeriod") : null,
lastYear: periodKpis.ranges.previousYear ? t("dashboard.deltaSamePeriodLastYear") : null,
}
: undefined;
const header = (
<>
<CategoriesV1DiscoveryBanner />
@ -112,9 +129,9 @@ export default function DashboardPage() {
<div className={isLoading ? "opacity-50 pointer-events-none" : ""}>
{header}
{state.error && (
{error && (
<div className="bg-[var(--negative)]/10 text-[var(--negative)] rounded-xl p-4 mb-6">
{state.error}
{error}
</div>
)}
@ -153,55 +170,62 @@ export default function DashboardPage() {
<div className="flex flex-wrap gap-3 mb-6">
<NetWorthTile data={state.netWorth} />
{cartesSnapshot && (
{periodKpis && (
<>
<div className="flex-1 min-w-[180px]">
<KpiCard
id="income"
title={t("reports.cartes.income")}
kpi={cartesSnapshot.kpis.income}
kpi={periodKpis.kpis.income}
format="currency"
deltaIsBadWhenUp={false}
deltaLabels={deltaLabels}
/>
</div>
<div className="flex-1 min-w-[180px]">
<KpiCard
id="expenses"
title={t("reports.cartes.expenses")}
kpi={cartesSnapshot.kpis.expenses}
kpi={periodKpis.kpis.expenses}
format="currency"
deltaIsBadWhenUp={true}
deltaLabels={deltaLabels}
/>
</div>
<div className="flex-1 min-w-[180px]">
<KpiCard
id="net"
title={t("reports.cartes.net")}
kpi={cartesSnapshot.kpis.net}
kpi={periodKpis.kpis.net}
format="currency"
deltaIsBadWhenUp={false}
note={netNote(t, i18n.language, cartesSnapshot.netBreakdown)}
note={netNote(t, i18n.language, periodKpis.netBreakdown)}
deltaLabels={deltaLabels}
/>
</div>
<div className="flex-1 min-w-[180px]">
<KpiCard
id="savingsRate"
title={t("reports.cartes.savingsRate")}
kpi={cartesSnapshot.kpis.savingsRate}
kpi={periodKpis.kpis.savingsRate}
format="percent"
deltaIsBadWhenUp={false}
deltaLabels={deltaLabels}
/>
</div>
</>
)}
</div>
{periodKpis && (
<div className="mb-6">
<IncomeExpenseOverlayChart flow={periodKpis.flow12Months} />
</div>
)}
{cartesSnapshot && (
<>
<div className="mb-6">
<IncomeExpenseOverlayChart flow={cartesSnapshot.flow12Months} />
</div>
<h2 className="text-lg font-semibold mb-3">{t("dashboard.monthlyAnalysisTitle")}</h2>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-3 mb-6">
<TopMoversList
movers={cartesSnapshot.topMoversUp}

View file

@ -96,6 +96,26 @@ describe("ReportsCartesPage — the note under « Solde net » (#392, D5)", () =
for (const id of ["income", "expenses", "savingsRate"]) expect(kpiProps.get(id)!.note).toBeUndefined();
});
it("keeps Cartes' labels for the changes: no card is handed the Dashboard's (#549)", () => {
snapshot = {
referenceYear: 2026,
referenceMonth: 10,
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(970), savingsRate: kpi(97) },
netBreakdown: { uncategorized: 0, transfers: 0 },
flow12Months: [],
topMoversUp: [],
topMoversDown: [],
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
};
render();
expect([...kpiProps.keys()]).toEqual(["income", "expenses", "net", "savingsRate"]);
for (const [id, props] of kpiProps) {
expect(props.kpi, id).toBe(snapshot.kpis[id as keyof CartesSnapshot["kpis"]]);
expect(props.deltaLabels, id).toBeUndefined();
}
});
it("renders no card without a snapshot", () => {
expect(render()).toContain("t(reports.empty.noData)");
expect(kpiProps.size).toBe(0);

View file

@ -39,6 +39,8 @@ import type {
CartesKpiPeriodMode,
BudgetVsActualRow,
IncomeStatementFigures,
PeriodComparisonRanges,
PeriodKpis,
ReportSection,
} from "../shared/types";
@ -1299,6 +1301,75 @@ function buildKpi(
};
}
/** The statements of a `getMonthlyTrends` result by month ("YYYY-MM"), for O(1) lookup. */
function statementsByMonth(rows: MonthlyTrendItem[]): Map<string, IncomeStatementFigures> {
const byMonth = new Map<string, IncomeStatementFigures>();
for (const { month, ...figures } of rows) byMonth.set(month, figures);
return byMonth;
}
/**
* The `count` months ending at (year, month), oldest first. A month without
* any transaction is filled with zeroes, so consumers get a contiguous series.
*/
function monthSeries(
byMonth: Map<string, IncomeStatementFigures>,
year: number,
month: number,
count: number,
): CartesMonthFlow[] {
const series: CartesMonthFlow[] = [];
for (let i = count - 1; i >= 0; i--) {
const { year: y, month: m } = shiftMonth(year, month, -i);
const key = monthKey(y, m);
series.push({ month: key, ...(byMonth.get(key) ?? EMPTY_STATEMENT) });
}
return series;
}
type KpiSparklines = Record<"income" | "expenses" | "net" | "savings", CartesSparklinePoint[]>;
/** The curve of each KPI card over a series of months. */
function kpiSparklines(series: CartesMonthFlow[]): KpiSparklines {
return {
income: series.map((p) => ({ month: p.month, value: p.income })),
expenses: series.map((p) => ({ month: p.month, value: p.expenses })),
net: series.map((p) => ({ month: p.month, value: p.net })),
savings: series.map((p) => ({ month: p.month, value: savingsRate(p.income, p.expenses) ?? 0 })),
};
}
type KpiFigures = Record<"income" | "expenses" | "net" | "savings", number | null>;
/**
* The four KPI figures of a period, or null for a period without data.
* « Solde net » is the net result (D5); the savings rate is undefined when
* income is not positive — null rather than a misleading "0 %" in the UI (D6).
*/
function kpiFigures(s: IncomeStatementFigures | null | undefined): KpiFigures {
return {
income: s ? s.income : null,
expenses: s ? s.expenses : null,
net: s ? s.net : null,
savings: s ? savingsRate(s.income, s.expenses) : null,
};
}
/** The four KPI cards: the figures of a period against those of its two comparisons. */
function buildKpis(
spark: KpiSparklines,
current: KpiFigures,
previous: KpiFigures,
previousYear: KpiFigures,
): CartesSnapshot["kpis"] {
return {
income: buildKpi(spark.income, current.income, previous.income, previousYear.income),
expenses: buildKpi(spark.expenses, current.expenses, previous.expenses, previousYear.expenses),
net: buildKpi(spark.net, current.net, previous.net, previousYear.net),
savingsRate: buildKpi(spark.savings, current.savings, previous.savings, previousYear.savings),
};
}
interface RawSeasonalityRow {
year: number;
/** Signed balance of the expense categories in that year's month. */
@ -1383,39 +1454,12 @@ export async function getCartesSnapshot(
getBudgetVsActualData(referenceYear, referenceMonth, accountIds),
]);
// Index the monthly statements by month for O(1) lookup, then fill missing
// months with zeroes so downstream consumers get a contiguous series.
const flowByMonth = new Map<string, IncomeStatementFigures>();
for (const { month, ...figures } of flowRows) flowByMonth.set(month, figures);
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);
series.push({ month: key, ...(flowByMonth.get(key) ?? EMPTY_STATEMENT) });
}
return series;
};
// Index the monthly statements by month; `monthSeries` fills missing months
// with zeroes so downstream consumers get a contiguous series.
const flowByMonth = statementsByMonth(flowRows);
// 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: savingsRate(p.income, p.expenses) ?? 0,
}));
const spark = kpiSparklines(monthSeries(flowByMonth, referenceYear, referenceMonth, 13));
// Compute MoM / YoY values directly from `flowByMonth` (which preserves the
// "missing" distinction). The sparkline fills gaps with zero for display,
@ -1426,16 +1470,6 @@ export async function getCartesSnapshot(
const yoyMeta = { year: referenceYear - 1, month: referenceMonth };
const yoyKey = monthKey(yoyMeta.year, yoyMeta.month);
// The four KPI figures of a period, or null for a period without data.
// « Solde net » is the net result (D5); the savings rate is undefined when
// income is not positive — null rather than a misleading "0 %" in the UI (D6).
const kpiFigures = (s: IncomeStatementFigures | undefined) => ({
income: s ? s.income : null,
expenses: s ? s.expenses : null,
net: s ? s.net : null,
savings: s ? savingsRate(s.income, s.expenses) : null,
});
// YTD aggregates — sum the monthly statements from January of a given year
// up to (and including) `upToMonth`. Reuses the already-fetched
// `flowByMonth` map, so no additional SQL round trip is required. Missing
@ -1472,11 +1506,6 @@ export async function getCartesSnapshot(
);
const yoy = kpiFigures(isYtd ? sumYtd(referenceYear - 1, referenceMonth) : flowByMonth.get(yoyKey));
const incomeKpi = buildKpi(incomeSpark, ref.income, mom.income, yoy.income);
const expensesKpi = buildKpi(expensesSpark, ref.expenses, mom.expenses, yoy.expenses);
const netKpi = buildKpi(netSpark, ref.net, mom.net, yoy.net);
const savingsKpi = buildKpi(savingsSpark, ref.savings, mom.savings, yoy.savings);
// What « Solde net » holds beyond income − expenses, for the note under its card (D5).
const netBreakdown = {
uncategorized: refStatement.uncategorized,
@ -1484,7 +1513,7 @@ export async function getCartesSnapshot(
};
// 12-month income vs expenses series for the overlay chart.
const flow12Months = buildSeries(12);
const flow12Months = monthSeries(flowByMonth, referenceYear, referenceMonth, 12);
// Top movers: biggest MoM increases / decreases. `momRows` now carries the
// compare hierarchy (Issue #247) — skip the subtotal (`is_parent`) rows so a
@ -1591,12 +1620,7 @@ export async function getCartesSnapshot(
return {
referenceYear,
referenceMonth,
kpis: {
income: incomeKpi,
expenses: expensesKpi,
net: netKpi,
savingsRate: savingsKpi,
},
kpis: buildKpis(spark, ref, mom, yoy),
netBreakdown,
flow12Months,
topMoversUp,
@ -1605,3 +1629,67 @@ export async function getCartesSnapshot(
seasonality,
};
}
// --- Dashboard period KPIs (Issue #549) ---
/**
* The income statement of a range of days (#549): the statements that
* `getMonthlyTrends` gives for the months of the range, within its exact
* bounds, added up. A period that cuts a month counts its own days only, and
* every screen keeps reading the one monthly query (ADR 0026). Null when the
* range holds no transaction, so that a comparison with an empty period stays
* « — » rather than a change against zero. An absent bound is no bound
* (« Tout »).
*/
export async function getIncomeStatement(
dateFrom?: string,
dateTo?: string,
accountIds?: number[],
): Promise<IncomeStatementFigures | null> {
const months = await getMonthlyTrends(dateFrom, dateTo, accountIds);
if (months.length === 0) return null;
return months.reduce<IncomeStatementFigures>((sum, month) => addStatements(sum, month), EMPTY_STATEMENT);
}
/**
* The KPI cards and the 12-month chart of the Dashboard over its period
* (#549), against the comparisons of `ranges` (`computeComparisonRanges`).
*
* Each card holds the figure of the period, to the day, and its changes from
* the previous period and from the same period last year: null when that
* period holds no transaction, or when the period has no such comparison
* (`ranges.previous` or `ranges.previousYear` null). A period without any
* transaction shows zero, its savings rate null (D6). The cards' curves cover
* the 13 months ending at `ranges.lastMonth`, the chart the last 12 of them,
* in whole months. « Solde net » is the net result, its uncategorized and
* transfer parts in `netBreakdown` (D5). `accountIds` reaches every query.
*/
export async function getPeriodKpis(
ranges: PeriodComparisonRanges,
accountIds?: number[],
): Promise<PeriodKpis> {
const { current, previous, previousYear, lastMonth } = ranges;
const windowStart = shiftMonth(lastMonth.year, lastMonth.month, -12);
const { start: windowStartIso } = monthBoundaries(windowStart.year, windowStart.month);
const { end: windowEndIso } = monthBoundaries(lastMonth.year, lastMonth.month);
const [statement, previousStatement, previousYearStatement, flowRows] = await Promise.all([
getIncomeStatement(current.dateFrom, current.dateTo, accountIds),
previous ? getIncomeStatement(previous.dateFrom, previous.dateTo, accountIds) : null,
previousYear ? getIncomeStatement(previousYear.dateFrom, previousYear.dateTo, accountIds) : null,
getMonthlyTrends(windowStartIso, windowEndIso, accountIds),
]);
const flowByMonth = statementsByMonth(flowRows);
const spark = kpiSparklines(monthSeries(flowByMonth, lastMonth.year, lastMonth.month, 13));
// The period itself always has figures, zero without any transaction: only
// a comparison can be missing.
const figures = statement ?? EMPTY_STATEMENT;
return {
ranges,
kpis: buildKpis(spark, kpiFigures(figures), kpiFigures(previousStatement), kpiFigures(previousYearStatement)),
netBreakdown: { uncategorized: figures.uncategorized, transfers: figures.transfers },
flow12Months: monthSeries(flowByMonth, lastMonth.year, lastMonth.month, 12),
};
}

View file

@ -336,6 +336,30 @@ export interface ImportReport {
export type DashboardPeriod = "month" | "3months" | "6months" | "year" | "12months" | "all" | "custom";
/** A range of ISO dates (YYYY-MM-DD), both bounds included. */
export interface DateRange {
dateFrom: string;
dateTo: string;
}
/**
* The Dashboard's period and the two periods its KPI cards compare it with
* (#549), from `computeComparisonRanges`. `current` has no bounds for « Tout ».
*/
export interface PeriodComparisonRanges {
current: { dateFrom?: string; dateTo?: string };
/**
* The period of the same length just before, or null when the period has
* none of its own: « Tout », and a period whose previous one is last year's
* very range (« Cette année », « 12 mois »).
*/
previous: DateRange | null;
/** The same dates one year earlier (February 29 on the 28th), or null for « Tout ». */
previousYear: DateRange | null;
/** The month of the period's last day, where the 12-month chart and the cards' curves end. */
lastMonth: { year: number; month: number };
}
export interface CategoryBreakdownItem {
category_id: number | null;
category_name: string;
@ -561,13 +585,18 @@ export interface CartesKpi {
// `current` is nullable for ratio-style KPIs (e.g. savings rate) when the
// denominator is zero and the value is genuinely undefined rather than 0.
current: number | null;
// On the Dashboard's cards (#549), `previousMonth` and `deltaMoM*` hold the
// previous period of the same length, `previousYear` and `deltaYoY*` the
// same period last year.
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
// 13 months ending at the reference month (Cartes) or at the period's last
// month (the Dashboard, #549).
sparkline: CartesSparklinePoint[];
}
export type CartesKpiId = "income" | "expenses" | "net" | "savingsRate";
@ -645,6 +674,20 @@ export interface CartesSnapshot {
seasonality: CartesSeasonality;
}
/**
* The KPI cards and the 12-month chart of the Dashboard over its period
* (#549), from `getPeriodKpis`. The cards keep the shape of Cartes' (see
* `CartesKpi`), with `ranges` telling which comparisons the period has.
*/
export interface PeriodKpis {
ranges: PeriodComparisonRanges;
kpis: CartesSnapshot["kpis"];
/** What « Solde net » holds beyond income − expenses over the period: the note under its card (D5). */
netBreakdown: CartesSnapshot["netBreakdown"];
/** The 12 months ending at `ranges.lastMonth`. */
flow12Months: CartesMonthFlow[];
}
export type ImportWizardStep =
| "source-list"
| "source-config"

View file

@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { computeDateRange, buildMonthOptions } from "./dateRange";
import { computeDateRange, computeComparisonRanges, buildMonthOptions } from "./dateRange";
import type { DashboardPeriod } from "../shared/types";
describe("computeDateRange", () => {
beforeEach(() => {
@ -86,6 +87,179 @@ describe("computeDateRange", () => {
});
});
describe("computeComparisonRanges — the Dashboard's period and its two comparisons (#549)", () => {
// Local noon, so the day is the same in every time zone. November 14, 2026
// is the day of the issue's example.
const NOV_14 = new Date(2026, 10, 14, 12);
const at = (period: DashboardPeriod, today: Date, from?: string, to?: string) =>
computeComparisonRanges(period, from, to, today);
const range = (dateFrom: string, dateTo: string) => ({ dateFrom, dateTo });
it("« Ce mois », November 1st–14th, is compared with October 1st–14th and November 1st–14th of last year", () => {
expect(at("month", NOV_14)).toEqual({
current: range("2026-11-01", "2026-11-14"),
previous: range("2026-10-01", "2026-10-14"),
previousYear: range("2025-11-01", "2025-11-14"),
lastMonth: { year: 2026, month: 11 },
});
});
it.each([
["3months", "2026-09-01", range("2026-06-01", "2026-08-14"), range("2025-09-01", "2025-11-14")],
["6months", "2026-06-01", range("2025-12-01", "2026-05-14"), range("2025-06-01", "2025-11-14")],
] as const)("« %s » moves back by its own number of months, to the same day", (period, from, previous, previousYear) => {
expect(at(period, NOV_14)).toEqual({
current: range(from, "2026-11-14"),
previous,
previousYear,
lastMonth: { year: 2026, month: 11 },
});
});
it("« Cette année » has no previous period of its own: its previous one is last year's range, kept once", () => {
expect(at("year", NOV_14)).toEqual({
current: range("2026-01-01", "2026-11-14"),
previous: null,
previousYear: range("2025-01-01", "2025-11-14"),
lastMonth: { year: 2026, month: 11 },
});
});
it("« 12 mois » moved back 12 months is last year's range: only last year's is kept", () => {
expect(at("12months", NOV_14)).toEqual({
current: range("2025-12-01", "2026-11-14"),
previous: null,
previousYear: range("2024-12-01", "2025-11-14"),
lastMonth: { year: 2026, month: 11 },
});
});
it("« Tout » has no bound and nothing to compare with; its chart ends this month", () => {
expect(at("all", NOV_14)).toEqual({
current: {},
previous: null,
previousYear: null,
lastMonth: { year: 2026, month: 11 },
});
});
it("a custom period is compared with the same number of days just before, and its own dates last year", () => {
// March 10–20: 11 days; the 11 days before are February 27 – March 9.
expect(at("custom", NOV_14, "2026-03-10", "2026-03-20")).toEqual({
current: range("2026-03-10", "2026-03-20"),
previous: range("2026-02-27", "2026-03-09"),
previousYear: range("2025-03-10", "2025-03-20"),
lastMonth: { year: 2026, month: 3 },
});
});
it("a custom period counts its days across a year boundary and a leap day", () => {
// December 20 – January 10: 22 days.
expect(at("custom", NOV_14, "2025-12-20", "2026-01-10")).toMatchObject({
previous: range("2025-11-28", "2025-12-19"),
previousYear: range("2024-12-20", "2025-01-10"),
lastMonth: { year: 2026, month: 1 },
});
// February 20 – March 5, 2024: 15 days, February 29 included.
expect(at("custom", NOV_14, "2024-02-20", "2024-03-05")).toMatchObject({
previous: range("2024-02-05", "2024-02-19"),
previousYear: range("2023-02-20", "2023-03-05"),
});
// One day: the day before.
expect(at("custom", NOV_14, "2026-03-01", "2026-03-01").previous).toEqual(range("2026-02-28", "2026-02-28"));
});
it("a custom year: its previous days are last year's range, kept once", () => {
// March 1st, 2025 – February 28, 2026: 365 days, the 365 before are last year's dates.
expect(at("custom", NOV_14, "2025-03-01", "2026-02-28")).toMatchObject({
previous: null,
previousYear: range("2024-03-01", "2025-02-28"),
});
});
it("a custom calendar year is compared with last year alone, a leap year next to it or not (review 35029)", () => {
// 2025: the 365 days before are January 2nd – December 31, 2024, one day
// off last year's dates because of February 29, 2024.
expect(at("custom", NOV_14, "2025-01-01", "2025-12-31")).toMatchObject({
previous: null,
previousYear: range("2024-01-01", "2024-12-31"),
});
// 2024, itself a leap year: its 366 days before start on December 31, 2022.
expect(at("custom", NOV_14, "2024-01-01", "2024-12-31")).toMatchObject({
previous: null,
previousYear: range("2023-01-01", "2023-12-31"),
});
expect(at("custom", NOV_14, "2026-01-01", "2026-12-31").previous).toBeNull();
// Any range of exactly one year, wherever it starts.
expect(at("custom", NOV_14, "2023-03-15", "2024-03-14").previous).toBeNull();
});
it("a custom period one day short of a year keeps its previous period", () => {
expect(at("custom", NOV_14, "2025-01-01", "2025-12-30")).toMatchObject({
previous: range("2024-01-03", "2024-12-31"),
previousYear: range("2024-01-01", "2024-12-30"),
});
});
it("a custom period ends its chart at its own last month, not today's", () => {
expect(at("custom", NOV_14, "2026-01-01", "2026-06-15").lastMonth).toEqual({ year: 2026, month: 6 });
});
it("a custom period without its two dates is « Ce mois », as computeDateRange reads it", () => {
expect(at("custom", NOV_14)).toEqual(at("month", NOV_14));
expect(at("custom", NOV_14, "2026-03-10")).toEqual(at("month", NOV_14));
});
it("on the last day of a month, the previous period ends on the last day of a shorter month", () => {
// « Ce mois » on March 31: February 1st–28th, 29th in a leap year.
expect(at("month", new Date(2026, 2, 31, 12)).previous).toEqual(range("2026-02-01", "2026-02-28"));
expect(at("month", new Date(2028, 2, 31, 12)).previous).toEqual(range("2028-02-01", "2028-02-29"));
// « 3 mois » on May 31: March 1st – May 31, compared with December 1st – February 28.
expect(at("3months", new Date(2026, 4, 31, 12))).toMatchObject({
current: range("2026-03-01", "2026-05-31"),
previous: range("2025-12-01", "2026-02-28"),
});
// « 6 mois » on August 31: March 1st – August 31, compared with September 1st – February 28.
expect(at("6months", new Date(2026, 7, 31, 12))).toMatchObject({
current: range("2026-03-01", "2026-08-31"),
previous: range("2025-09-01", "2026-02-28"),
});
});
it("January rolls back into the previous year", () => {
const jan20 = new Date(2027, 0, 20, 12);
expect(at("month", jan20).previous).toEqual(range("2026-12-01", "2026-12-20"));
expect(at("3months", jan20)).toMatchObject({
current: range("2026-11-01", "2027-01-20"),
previous: range("2026-08-01", "2026-10-20"),
previousYear: range("2025-11-01", "2026-01-20"),
});
});
it("on February 29, last year's range ends on February 28", () => {
const feb29 = new Date(2028, 1, 29, 12);
expect(at("month", feb29)).toEqual({
current: range("2028-02-01", "2028-02-29"),
previous: range("2028-01-01", "2028-01-29"),
previousYear: range("2027-02-01", "2027-02-28"),
lastMonth: { year: 2028, month: 2 },
});
// « 12 mois »: both comparisons end on February 28, 2027, so one is kept.
expect(at("12months", feb29)).toMatchObject({
current: range("2027-03-01", "2028-02-29"),
previous: null,
previousYear: range("2026-03-01", "2027-02-28"),
});
});
it.each(["month", "3months", "6months", "year", "12months", "all"] as const)(
"« %s »: the current range is computeDateRange's, the one of the widgets that follow the period",
(period) => {
expect(at(period, NOV_14).current).toEqual(computeDateRange(period, undefined, undefined, NOV_14));
},
);
});
describe("buildMonthOptions", () => {
beforeEach(() => {
vi.useFakeTimers();

View file

@ -1,4 +1,4 @@
import type { DashboardPeriod } from "../shared/types";
import type { DashboardPeriod, DateRange, PeriodComparisonRanges } from "../shared/types";
/**
* Compute a date range (dateFrom / dateTo) based on the selected period.
@ -52,6 +52,118 @@ export function computeDateRange(
return { dateFrom, dateTo };
}
/** How many months back the previous period of a rolling preset lies (#549). */
const PRESET_MONTHS: Partial<Record<DashboardPeriod, number>> = {
month: 1,
"3months": 3,
"6months": 6,
"12months": 12,
};
function parseIso(iso: string): { year: number; monthIndex: number; day: number } {
const [year, month, day] = iso.split("-").map(Number);
return { year, monthIndex: month - 1, day };
}
/** A date as YYYY-MM-DD; `monthIndex` and `day` past their range carry over, as `Date.UTC` does. */
function isoOf(year: number, monthIndex: number, day: number): string {
const d = new Date(Date.UTC(year, monthIndex, day));
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;
}
/**
* The same day `months` months away, or the last day of the target month when
* it is shorter: March 31 one month back is February 28 (29 in a leap year),
* and February 29 twelve months back is February 28.
*/
function shiftMonths(iso: string, months: number): string {
const { year, monthIndex, day } = parseIso(iso);
const lastDay = new Date(Date.UTC(year, monthIndex + months + 1, 0)).getUTCDate();
return isoOf(year, monthIndex + months, Math.min(day, lastDay));
}
function shiftDays(iso: string, days: number): string {
const { year, monthIndex, day } = parseIso(iso);
return isoOf(year, monthIndex, day + days);
}
/** Days from `dateFrom` to `dateTo`, both included. */
function dayCount(dateFrom: string, dateTo: string): number {
const a = parseIso(dateFrom);
const b = parseIso(dateTo);
const ms = Date.UTC(b.year, b.monthIndex, b.day) - Date.UTC(a.year, a.monthIndex, a.day);
return Math.round(ms / 86_400_000) + 1;
}
/**
* The Dashboard's period and the two periods its KPI cards compare it with
* (#549). `current` is `computeDateRange`'s range, the one of every widget
* that follows the period.
*
* - `previous`, the period of the same length just before: a rolling preset
* (« Ce mois », « 3 mois », « 6 mois », « 12 mois ») moved back by its own
* number of months, its end on the same day of the month or on the last day
* of a shorter month (« Ce mois » on November 14 is compared with October
* 1–14); a custom period, the same number of days just before its first day;
* « Cette année », January 1st to today, last year's range.
* - `previousYear`, the same dates one year earlier, February 29 on the 28th.
*
* When `previous` is the very range of `previousYear` (« Cette année »,
* « 12 mois »), or the period lasts one year exactly (its next day twelve
* months after its first, a calendar year for instance, whose previous days
* miss last year's dates by the February 29 that one of them holds), it is
* null: the cards show the change from last year alone rather than the same
* figure, or nearly, twice. « Tout » has neither.
* `lastMonth` is the month of the period's last day, today's month for
* « Tout »: the 12-month chart and the cards' curves end there.
*/
export function computeComparisonRanges(
period: DashboardPeriod,
customDateFrom?: string,
customDateTo?: string,
today: Date = new Date(),
): PeriodComparisonRanges {
const current = computeDateRange(period, customDateFrom, customDateTo, today);
const { dateFrom, dateTo } = current;
if (dateFrom === undefined || dateTo === undefined) {
// « Tout », the only period without bounds.
return {
current,
previous: null,
previousYear: null,
lastMonth: { year: today.getFullYear(), month: today.getMonth() + 1 },
};
}
const previousYear: DateRange = { dateFrom: shiftMonths(dateFrom, -12), dateTo: shiftMonths(dateTo, -12) };
let previous: DateRange;
if (period === "custom" && customDateFrom && customDateTo) {
const days = dayCount(dateFrom, dateTo);
previous = { dateFrom: shiftDays(dateFrom, -days), dateTo: shiftDays(dateFrom, -1) };
} else if (period === "year") {
previous = previousYear;
} else {
// A rolling preset, or a custom period without its two dates, which
// `computeDateRange` reads as « Ce mois ».
const months = PRESET_MONTHS[period] ?? 1;
previous = { dateFrom: shiftMonths(dateFrom, -months), dateTo: shiftMonths(dateTo, -months) };
}
// 2025 against the 365 days before it is January 2nd – December 31, 2024,
// against last year's dates January 1st – December 31: one year either way.
const lastsOneYear = shiftMonths(dateFrom, 12) === shiftDays(dateTo, 1);
const sameAsLastYear =
lastsOneYear ||
(previous.dateFrom === previousYear.dateFrom && previous.dateTo === previousYear.dateTo);
const end = parseIso(dateTo);
return {
current,
previous: sameAsLastYear ? null : previous,
previousYear,
lastMonth: { year: end.year, month: end.monthIndex + 1 },
};
}
/**
* Build an array of month options for the budget month dropdown.
* Returns the last 24 months with localized labels.