feat: open the Reports on « Cette année » and let « Tout » reach every date (#479) #517

Merged
maximus merged 5 commits from issue-479-reports-period-filters into main 2026-10-30 00:39:11 +00:00
20 changed files with 481 additions and 78 deletions

View file

@ -14,6 +14,7 @@
- Textes d'aide : l'aide de la page Rapports nomme désormais les rapports par leurs cartes, « Tendances » et « Analyse par catégorie », au lieu de « Tendances mensuelles » et « Catégories dans le temps », des onglets qui n'existent plus. La section Tableau de bord du guide d'utilisation nomme désormais les huit étapes de démarrage et dit comment elles se cochent : selon vos données, ou par « J'ai compris » (ou, pour les rapports, un clic sur la carte Tendances entourée) pour les visites (#446).
- Guide d'utilisation : la procédure BMO de « Exporter un CSV depuis votre banque » est désormais confirmée sur un compte réel (2026-10-22). Le bouton s'appelle « Télécharger » sur le site français, sans l'ancien « ou Exporter », et les trois points qui n'ont pas pu être vérifiés (l'historique de la Mastercard, les prêts qui ne s'exportent pas, les colonnes des comptes de dépôt) sont marqués comme non vérifiés. La note dit désormais que la détection générique lit les exports BMO, des comptes de dépôt comme de la Mastercard, en retenant pour la Mastercard la date de la transaction plutôt que celle de l'inscription au relevé, et qu'un fichier dont les vingt premières lignes comptent plus d'entrées que de sorties sort inversé à l'aperçu jusqu'à « Inverser les signes » (#371).
- L'écran de déverrouillage qui s'ouvre dans une fenêtre en édition Gratuite, depuis un profil verrouillé du sélecteur de profil ou depuis le bouton Répartition de la page Transactions, se ferme désormais avec Échap. Les lecteurs d'écran reconnaissent désormais la fenêtre du sélecteur de profil comme une boîte de dialogue, nommée d'après l'édition requise (par exemple « Fonctionnalité Base »), avec un bouton « Fermer », comme celle du bouton Répartition. Ces fenêtres, et la fenêtre « Gérer les profils », s'ouvrent désormais avec le focus sur leur bouton « Fermer », gardent Tab et Maj+Tab à l'intérieur et rendent le focus quand elles se ferment : au bouton du sélecteur de profil pour les fenêtres ouvertes depuis son menu, sinon au bouton qui les a ouvertes. La fenêtre « Gérer les profils » se ferme aussi avec Échap, sauf pendant l'enregistrement d'un profil ; les lecteurs d'écran la reconnaissent comme une boîte de dialogue nommée d'après son titre, avec un bouton « Fermer », et le bouton du sélecteur de profil dit désormais si sa liste est ouverte. Dans « Gérer les profils », le focus revient sur « Créer un profil » après « Annuler » ou après l'enregistrement des modifications d'un profil (#451, #494).
- Rapports : les rapports s'ouvrent désormais sur « Cette année », du 1er janvier à aujourd'hui, avec son bouton allumé, au lieu de « Personnalisé » sur toute l'année civile, mois à venir compris ; le tableau de bord ne change pas. L'aide de la page Rapports dit désormais que Tendances montre vos revenus et dépenses mois par mois sur la période choisie, et sa carte Tendances affiche « Où vous allez, mois par mois », au lieu de « sur 12 mois » : Tendances suit le sélecteur de période. Sur les Comparables, dont le mois de référence suit la fin de la période, « Ce mois », « 3 mois », « 6 mois » et « 12 mois » finissent aujourd'hui comme « Cette année » : choisis juste après l'ouverture, ils ne déplacent plus le mois de référence vers le mois en cours ; la liste « Mois de référence » le fait toujours (#479).
### Corrigé
@ -26,6 +27,7 @@
- Journaux (Paramètres → Système) : une ligne des journaux ne porte plus votre dossier personnel ni le dossier qui contient les bases des profils, nommés tous deux d'après votre compte d'utilisateur, quoi qu'il y ait autour, comme un nom de dossier qui contient une virgule (`Smith, Jean`) ou un chemin collé à un `;` : le dossier personnel devient `~` et celui des bases `<profile folder>`. Cela vaut pour toutes les lignes, ce que copie « Copier » compris, et les lignes écrites au démarrage avant que ces dossiers soient connus les perdent dès qu'ils le sont. Une ligne d'erreur sur l'ouverture ou la fermeture d'un profil ne nomme toujours que le fichier. Ces lignes peuvent partir avec une rétroaction quand vous y incluez les derniers logs d'erreur (#497).
- Transactions : changer la catégorie d'une transaction répartie déplace désormais toute sa part non répartie vers la nouvelle catégorie. Les rapports gardaient, dans l'ancienne catégorie, le montant envoyé vers les autres catégories avec le signe inverse, sans transaction correspondante, et comptaient la transaction entière dans la nouvelle : une transaction de −120 dont −50 sont répartis vers B, déplacée de A vers C, laissait +50 dans A et −120 dans C, au lieu de −70 dans C. Cela vaut pour la catégorie choisie dans la liste des transactions comme pour les transactions recatégorisées par un nouveau mot-clé. Une répartition déjà touchée se répare au prochain changement de catégorie de sa transaction, et sa fenêtre de répartition ne montre plus ce montant comme l'une de ses lignes. La prévisualisation d'un mot-clé ne liste plus les parts d'une répartition, qu'elle pouvait recatégoriser sans leur transaction (#454).
- Transactions : enregistrer ou supprimer une répartition ne laisse plus de répartition à moitié écrite après une erreur (#513).
- Rapports : « Tout » montre désormais toutes les dates sur Tendances, dans ses deux vues, et sur l'Analyse par catégorie ; il montrait l'année civile en cours. Sur les Comparables, « Tout » ne déplace plus le mois de référence vers décembre de l'année en cours : le mois affiché reste le même jusqu'au choix d'une période datée, qui le place à la fin de cette période (#479).
### Sécurité

View file

@ -14,6 +14,7 @@
- Help texts: the help of the Reports page now names the reports by their cards, “Trends” and “Category Analysis”, instead of “Monthly Trends” and “Category Over Time”, tabs that no longer exist. The Dashboard section of the user guide now names the eight getting-started steps and says how they get checked: from your data, or with “Got it” (or, for the reports, a click on the outlined Trends card) for the visit steps (#446).
- User guide: the BMO procedure of “Export a CSV from your bank” is now confirmed on a real account (2026-10-22). The button is named “Télécharger” on the French site, without the former “or Export”, and the three points that could not be checked (the Mastercard history, loans that cannot be exported, the columns of deposit accounts) are marked as not verified. The note now says that generic detection reads BMO exports, deposit accounts and Mastercard alike, keeping the transaction date rather than the posting date for the Mastercard, and that a file whose first twenty rows hold more inflows than outflows comes out reversed in the preview until “Flip the signs” (#371).
- The unlock screen that opens in a window on the Free edition, from a locked profile of the profile switcher or from the Split button of the Transactions page, now closes with Escape. Screen readers now identify the profile switcher's window as a dialog, named after the edition it needs (such as “Base feature”), with a “Close” button, like the Split button's. These windows, and the “Manage Profiles” window, now open with the focus on their “Close” button, keep Tab and Shift+Tab inside them, and give the focus back when they close: to the profile switcher's button for the windows opened from its menu, otherwise to the button that opened them. The “Manage Profiles” window also closes with Escape, except while a profile is being saved; screen readers identify it as a dialog named after its title, with a “Close” button, and the profile switcher's button now tells whether its list is open. In “Manage Profiles”, the focus goes back to “Create Profile” after “Cancel” or after saving a profile's changes (#451, #494).
- Reports: the reports now open on “This year”, from January 1st to today, with its button lit, instead of “Custom” over the whole calendar year, months to come included; the Dashboard does not change. The help of the Reports page now says that Trends shows your income and expenses month by month over the selected period, and its Trends card reads “Where you're heading, month by month”, instead of “over 12 months”: Trends follows the period selector. On Compare, whose reference month follows the end of the period, “This month”, “3 months”, “6 months” and “12 months” end today like “This year”: chosen right after opening, they no longer move the reference month to the current month; the “Reference month” list still does (#479).
### Fixed
@ -26,6 +27,7 @@
- Logs (Settings → System): a line of the logs no longer carries your home folder or the folder that holds the profile databases, both named after your user account, whatever surrounds them, such as a folder name that holds a comma (`Smith, Jean`) or a path glued to a `;`: the home folder becomes `~` and the databases' folder `<profile folder>`. This holds for every line, what “Copy” copies included, and the lines written at startup before these folders are known lose them as soon as they are. An error line about opening or closing a profile still names the file only. These lines can go with a feedback report when you include the recent error logs (#497).
- Transactions: changing the category of a split transaction now moves all of its unsplit part to the new category. The reports used to keep, in the former category, the amount sent to the other categories with the opposite sign, matching no transaction, and to count the whole transaction in the new one: a transaction of −120 with −50 split to B, moved from A to C, left +50 in A and −120 in C, instead of −70 in C. This holds for the category chosen in the Transactions list and for the transactions recategorized by a new keyword. A split already affected is repaired the next time its transaction changes category, and its split window no longer shows that amount as one of its rows. The keyword preview no longer lists the parts of a split, which it could recategorize without their transaction (#454).
- Transactions: saving or deleting a split no longer leaves a half-written split after an error (#513).
- Reports: “All” now shows every date on Trends, in both views, and on Category Analysis; it showed the current calendar year. On Compare, “All” no longer moves the reference month to December of the current year: the month shown stays as it is until you choose a dated period, which moves it to the end of that period (#479).
### Security

View file

@ -205,6 +205,7 @@ Côté site, la demande « merger et déployer après la publication » pour l'
- Focus des fenêtres d'incitation (#494, PR #511), en édition Gratuite sauf mention, en FR et en EN, thèmes clair et sombre, sous Linux et sous Windows : Transactions → bouton Répartition verrouillé (à la souris, puis par Tab et Entrée), et sélecteur de profil → profil verrouillé : anneau de focus visible sur le X à l'ouverture, Tab et Maj+Tab font le tour de la fenêtre sans passer derrière le voile, X et Échap rendent le focus au bouton Répartition de la ligne, ou au bouton du sélecteur pour la fenêtre ouverte depuis son menu, comme « J'ai déjà une clé » depuis le sélecteur (depuis Transactions, la page change et le focus n'est nulle part, comme après toute navigation) ; « Gérer les profils » : focus sur le X à l'ouverture, Tab qui boucle dans chaque mode, « Créer un profil » verrouillé → focus sur le X, « Annuler » → focus sur « Créer un profil », en Base « Créer un profil » et « Modifier » → champ Nom, « Annuler » ou « Enregistrer » d'une modification → « Créer un profil », Échap qui ferme la fenêtre (depuis le champ Nom aussi) sauf pendant un enregistrement, X et Échap qui rendent le focus au bouton du sélecteur ; la même fenêtre ouverte depuis l'écran de choix du profil (aucun profil actif, hors routeur), le focus rendu à sa tuile « Créer un profil » ; lecteur d'écran (Orca, Narrateur) : chaque fenêtre annoncée à l'ouverture comme une boîte de dialogue avec son nom, le X lu « Fermer », le bouton du sélecteur annoncé déplié ou replié ; en Base, le sélecteur change toujours de profil et Répartition ouvre la fenêtre de répartition. Après la suppression d'un profil, la fenêtre se ferme le temps du rechargement des profils, comme avant : le focus ne va pas sur « Créer un profil » (attendu, PR #511).
- Journal sans dossier (#497, PR #512), sous Linux puis sous Windows, sur un profil secondaire de test : l'app fermée, lire le nom de sa base (`db_filename`, `profile_<hex>.db`) dans `profiles.json` (`~/.local/share/com.simpl.resultat/` sous Linux, `%APPDATA%\com.simpl.resultat\` sous Windows), renommer cette base et créer à sa place un dossier vide du même nom, dans le dossier des bases (`~/.config/com.simpl.resultat/` sous Linux, `$XDG_CONFIG_HOME/com.simpl.resultat/` s'il est défini ; `%APPDATA%\com.simpl.resultat\` sous Windows), une base en lecture seule s'ouvrant sans erreur ; ouvrir l'app sur un autre profil et basculer vers celui-ci (l'ouverture échoue), puis lire dans Paramètres → Système → Journaux les lignes « Migration repair failed » et « database preparation failed » : elles nomment `profile_<hex>.db` et ne contiennent aucun segment du dossier personnel ; si la page d'erreur s'affiche à la place, remettre la base puis « Actualiser » (le Journal de la session garde les lignes) ; « Copier », puis une rétroaction de test avec « Inclure les derniers logs d'erreur » : aucun dossier ; supprimer le dossier et remettre la base ensuite.
- Compensation d'une répartition (#454, PR #515), en édition Base, en FR et en EN : une transaction répartie reclassée par la liste puis par un mot-clé, l'ancienne catégorie se vide et la fenêtre de répartition ne montre que les vraies lignes ; procédure dans le corps de la PR. Même fenêtre, même profil (#513, PR #516) : une répartition modifiée puis supprimée, depuis Transactions et depuis Ajustements, sans « database is locked », la transaction revient entière dans sa catégorie.
- Période des Rapports (#479, PR #517), en édition Base, en FR et en EN : ouverture sans paramètre sur « Cette année » allumé (1er janvier à aujourd'hui) ; « Tout » sur Tendances (deux vues), Analyse par catégorie et Comparables (mois de référence inchangé, recalé par une période datée ensuite) ; aide et carte Tendances ; procédure dans le corps de la PR.
- **Le paiement est live : « aucun tag avant le go-live » n'a plus de raison d'être, et la release desktop qu'attendait le go-live est publiée (v0.16.0, 2026-10-03).** Bascule live le 2026-09-29 (Product et Price live à 19 $ CAD, webhook, variables Stripe de production, redeploy `3673d09` de maximus-api, URL `cs_live_` vérifiée), puis achat réel de contrôle le 2026-09-30 : clé sur `/merci` et par courriel, activation dans l'app, remboursement complet et licence révoquée par `charge.refunded`. **Volet serveur clos le 2026-10-03** (derniers commentaires relus le 2026-10-04) : maximus-api#62 fermée, tous critères cochés (maximus-api 0.4.2 en prod, secrets en runtime seul), avec la milestone `spec-paiements` de maximus-api (12/12) ; la-compagnie-maximus#150 (Link dans les textes légaux) livrée et fermée le 2026-10-01. **Go-live clos : la-compagnie-maximus#141** fermée le 2026-10-10 sur décision de Max, l'updater vérifié (Free refuse et invite à acheter, Base accepte ; confirmé le même jour). Restent pour mémoire, sans issue : le Dashboard Stripe (logo, paramètres Checkout, reçus automatiques, alertes d'échec de webhook) et les relevés du commentaire de fermeture. la-compagnie-maximus#184 (politique de confidentialité : données d'activation, contrôle au démarrage) est en `status:review` ; sa PR reste en brouillon jusqu'au déploiement de maximus-api#85 (commentaire du 2026-10-03). Les deux textes des suites de licence (contrôle à la saisie, retrait de la clé) y sont postés depuis le 2026-10-05 (commentaire 19724). **Vérifications manuelles sur la release publiée, toutes faites** : #365 le 2026-10-03, #346 et #350 le 2026-10-04 (voir Décisions). L'étape 10 sous Windows est faite (Michel, confirmée le 2026-10-10).
- Backlog ouvert : **vague `planned-2026-09-24-paiements` close 3/3** (milestone fermée le 2026-09-30) : #270 (PR #359) et #346 (PR #362) mergées le 2026-09-27, #347 (PR #364, ferme aussi #360) mergée le 2026-09-30 ; volet site **clos** (maximus/la-compagnie-maximus#153, redirection de `/simpl-resultat` en prod). **#365 fermée le 2026-10-03** après sa vérification manuelle. **Milestone `planned-2026-10-03-suites-licence` fermée 3/3 le 2026-10-05** (#373, #370, #367 mergées, voir Décisions ; suivi #389 en `status:triage`). Hors milestone : **#369** (réserver le fractionnement de transactions à l'édition Base) **fermée le 2026-10-17** (PR #452, voir Décisions) ; **#372** (la liste complète des versions repousse le Journal en bas de Paramètres → Systèmes) reste en `status:ready`. **#350 fermée le 2026-10-04** (étape 3 vérifiée en production, voir Décisions) ; #363 fermée le 2026-10-10 sur décision de Max (ses tests, absorbés par #347, sont livrés dans la v0.16.0) ; réglés côté serveur et site : maximus-api#63 (clés de 100 ans) et maximus-api#70 (réactivation d'une machine désactivée), fermées et contenues dans `3673d09`, le commit déployé à la bascule du 2026-09-29, et la-compagnie-maximus#157, fermée, dont les CGV sont publiées en tronc commun plus annexe Simpl-Résultat (annexe relue en production le 2026-09-30, plus aucune durée de 10 ans) ; côté serveur, `/v1/prices` ne vérifie pas qu'une machine est encore active (une machine désactivée garde les cours jusqu'à l'expiration de son jeton), issue maximus-api à ouvrir ; suites de #350 ouvertes le 2026-10-01 : maximus-api#82 (`status:triage` : identifiants machine bruts déjà stockés, lignes désactivées comprises ; à rehacher avant l'expiration des premiers jetons bruts, sinon une réactivation crée une seconde ligne) et la-compagnie-maximus#184 (`status:review`, voir ci-dessus) ; go-live clos (la-compagnie-maximus#141 fermée le 2026-10-10, maximus-api#62 le 2026-10-03) ; `spec-paiements` fermée ici 5/5 ; onboarding phase 2 (parcours guidé) **mergée** : milestone `planned-2026-10-06-onboarding-parcours-guide` fermée 6/6 le 2026-10-08 (#396 à #401, `ee17f31`), suivis **#408** et **#409** (`status:triage`) ; onboarding phase 1 **livrée** : milestone `planned-2026-10-03-onboarding-phase1` fermée 7/7 le 2026-10-04 (#351 à #357, mergées en avance rapide, `667e058`) ; suivis ouverts : **#384** (`status:ready`, suivis non bloquants des revues) ; **#371** fermée le 2026-10-23 (PR #489, bloc BMO confirmé sur compte réel), la signature d'import BMO suit en **#488** (`status:blocked` : lignes aux valeurs fictives, préambule éventuel et en-tête d'un compte de dépôt à fournir par Max) ; analyse d'origine dans `docs/analyse-onboarding-2026-09.md`, plan détaillé dans les `spec-*-onboarding-phase1.md` locaux, ignorés par git ; #271 absorbé par #301, livré ; `spec-ci-build-optimization` **fermée 4/4** le 2026-10-05 (#232 livrée le 2026-07-27 ; #234 close le 2026-10-05 avec ses quatre preuves : dispatch run 464, PR #386 run 480, run planifié 488, `actcache` à 999 Mo) ; **#376** fermée le 2026-10-12 (Node 24, PR #414). Le suivi « glob `src-tauri/**` non prouvé » ouvert avec #232 est **levé** : la PR #344 est le cas test isolé attendu (`Cargo.lock` + 2 `.md` seulement) — `check-rust` a bien tourné, `check-frontend` a bien été sauté par sa denylist.
- Suivis des advisories : **#312, #313 et #315 fermées le 2026-08-15** (PRs #321/#322 mergées). **#314 fermée le 2026-08-15, prémisse infirmée** — elle affirmait « zéro run `schedule` », or `audit.yml` tire tous les jours à 06:00 UTC (**19 runs `schedule` verts** du 07-28 au 08-15, sans trou) ; elle a été écrite le 07-27 vers 23:56Z, ~6 h avant le premier tir programmé possible, et décrivait donc une fenêtre trop courte, pas un scheduler en panne. Ces 19 runs confirment au passage que `.cargo/audit.toml` est bien lu en conteneur **sur `main`** — l'ADR 0018 ne l'avait vérifié que par un `workflow_dispatch` sur une branche. **#343 fermée le 2026-09-04** (PR #344) — RUSTSEC-2026-0258 sur `h2`, la seule vulnérabilité qui rougissait l'audit depuis le 08-19 ; l'audit est de nouveau vert sur `main`, prouvé par `workflow_dispatch` (run 393) et non déduit du run de PR. **#348 fermée le 2026-09-21** (PR #349) — RUSTSEC-2026-0285 sur `rustls`, seule vulnérabilité rougissant l'audit depuis le 09-15 (7 runs, 405→411) ; vert reprouvé par `workflow_dispatch` sur `main` (run 414 : 666 paquets, zéro vulnérabilité, 12 warnings autorisés). Deux advisories en cinq semaines sur le même chemin, celui de la mise à jour automatique. **#447 fermée le 2026-10-16** (PR #448, run 556 vert), quatre avis `rustls` sur ce même chemin ; le Défenseur n'audite pas le Rust (agent-defenseurs#186), `audit.yml` reste le seul canal pour les avis RustSec. **#455 fermée le 2026-10-18** (PR #459, run 564 vert), trois avis `zip` sur ce même chemin, retirés avec la feature `zip` de l'updater plutôt que supprimés. **#317** fermée le 2026-10-12 par la PR #417 (#358). Reste **#319** (déclencheur de retrait pour `rsa`, désormais **seule** entrée de `.cargo/audit.toml` — le garde-fou est passé à 2 vérifications). **#345** fermée le 2026-10-12 (PR #415) : garde `Verify windows-sys pinning` dans `check-rust.yml` et ADR 0023, qui portent la mesure, le coût (3 contre 5 versions compilées pour Windows) et la condition de sortie. Côté npm, **#358** fermée le 2026-10-12 (PR #417) : lock régénéré par `npm@11.21.0` dans les bornes de `package.json`, `npm audit` 8 → 0 au 2026-10-10.

View file

@ -4,6 +4,8 @@
- Date: 2026-04-14
- Milestone: `spec-refonte-rapports`
> **Amendment of 2026-10-27 (#479)** — the default reporting period changes; the shared, bookmarkable query-string period and the rest of this decision are unchanged. Without any period in the URL, the Reports now open on « Cette année » (`period=year`: January 1st to today, the year to date, as on the Dashboard) instead of the whole current civil year under « Personnalisé » (`custom`), and a `custom` period without two valid dates falls back to it too. `period=all` (« Tout ») now reaches every date: `resolveReportsPeriod` leaves `from` and `to` absent instead of substituting the civil year, so no bounds are sent to the services (`getCategoryZoom` binds the missing bounds as NULL and skips them).
## Context
The original `/reports` page exposed five tabs (`trends`, `byCategory`, `overTime`, `budgetVsActual`, `dynamic`) as independent analytic views backed by a single monolithic `useReports` hook. Three problems built up over time:
@ -26,7 +28,7 @@ Refactor `/reports` into a **hub + four dedicated sub-routes**, wired to a share
/reports/category → single-category zoom with rollup
```
All pages share the reporting period through the URL query string (`?from=YYYY-MM-DD&to=YYYY-MM-DD&period=...`), resolved by a pure `resolveReportsPeriod()` helper. Default: current civil year. The query string approach is deliberately **not** a React context — it keeps the URL bookmarkable and stays consistent with the rest of the project, which does not use global React contexts for UI state.
All pages share the reporting period through the URL query string (`?from=YYYY-MM-DD&to=YYYY-MM-DD&period=...`), resolved by a pure `resolveReportsPeriod()` helper. Default: current civil year *(until #479; see the amendment at the top)*. The query string approach is deliberately **not** a React context — it keeps the URL bookmarkable and stays consistent with the rest of the project, which does not use global React contexts for UI state.
### Per-domain hooks

View file

@ -358,13 +358,13 @@ Planifiez votre budget mensuel pour chaque catégorie et suivez le prévu par ra
## 9. Rapports
`/reports` est un **hub** qui répond à quatre questions : *qu'est-ce qui a bougé ce mois ?*, *où je vais sur 12 mois ?*, *comment je me situe vs période précédente ou vs budget ?*, *que se passe-t-il dans cette catégorie ?*
`/reports` est un **hub** qui répond à quatre questions : *qu'est-ce qui a bougé ce mois ?*, *où je vais, mois par mois ?*, *comment je me situe vs période précédente ou vs budget ?*, *que se passe-t-il dans cette catégorie ?*
### Le hub
En haut, un **panneau de faits saillants** condensé : solde net du mois courant + solde cumul annuel (YTD) avec sparkline 12 mois, top mouvements vs mois précédent et top 5 des plus grosses transactions récentes. En bas, cinq cartes mènent aux cinq sous-rapports dédiés.
Le sélecteur de période en haut à droite est **partagé** entre toutes les pages via l'URL : `?from=YYYY-MM-DD&to=YYYY-MM-DD`. Copiez l'URL pour revenir plus tard au même état ou la partager.
Le sélecteur de période en haut à droite est **partagé** entre toutes les pages via l'URL : `?period=…` pour un bouton prédéfini, par exemple `?period=year` pour « Cette année » (du 1er janvier à aujourd'hui) ou `?period=all` pour « Tout » (toutes les dates), et `?period=custom&from=YYYY-MM-DD&to=YYYY-MM-DD` pour une période personnalisée. Ouverts sans paramètre, les Rapports montrent « Cette année ». Copiez l'URL pour revenir plus tard au même état ou la partager.
### Rapport Faits saillants (`/reports/highlights`)

View file

@ -48,8 +48,15 @@ export function useCategoryZoom() {
const [state, dispatch] = useReducer(reducer, initialState);
const fetchIdRef = useRef(0);
// `dateFrom` / `dateTo` are absent on « Tout »: getCategoryZoom then binds
// them as NULL and reads every date (#479).
const fetch = useCallback(
async (categoryId: number | null, includeChildren: boolean, dateFrom: string, dateTo: string) => {
async (
categoryId: number | null,
includeChildren: boolean,
dateFrom: string | undefined,
dateTo: string | undefined,
) => {
if (categoryId === null) return;
const id = ++fetchIdRef.current;
dispatch({ type: "SET_LOADING", payload: true });

View file

@ -0,0 +1,59 @@
// useCategoryZoom — the period's bounds reach the service as they are, so
// « Tout » asks for every date (#479).
//
// 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 service and the reports period are mocked: on
// « Tout », `from` and `to` are absent (resolveReportsPeriod). What is pinned:
// the zoom hands those absent bounds to `getCategoryZoom`, which binds them as
// NULL and skips them (reportService.test.ts), instead of a range of its own.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
const period = vi.hoisted(() => ({
from: undefined as string | undefined,
to: undefined as string | undefined,
}));
vi.mock("./useReportsPeriod", () => ({
useReportsPeriod: () => ({ from: period.from, to: period.to }),
}));
const services = vi.hoisted(() => ({ getCategoryZoom: vi.fn() }));
vi.mock("../services/reportService", () => services);
import { hookHarness } from "../test/hookHarness";
import { useCategoryZoom } from "./useCategoryZoom";
const harness = hookHarness();
/** Mounts the hook, picks a category, and runs the effects of that render. */
function zoomOn(categoryId: number) {
harness.render(useCategoryZoom);
harness.commit(); // no category yet: nothing is asked
harness.render(useCategoryZoom).setCategory(categoryId);
harness.render(useCategoryZoom);
harness.commit();
}
beforeEach(() => {
harness.clear();
period.from = undefined;
period.to = undefined;
// Never settles: only the arguments are read, and a late dispatch would
// land in the next test's mount.
services.getCategoryZoom.mockReset().mockReturnValue(new Promise(() => {}));
});
describe("useCategoryZoom — the period's bounds reach the service (#479)", () => {
it("« Tout »: the zoom asks for no date bound", () => {
zoomOn(42);
expect(services.getCategoryZoom).toHaveBeenCalledTimes(1);
expect(services.getCategoryZoom).toHaveBeenCalledWith(42, undefined, undefined, true);
});
it("a dated period passes its bounds as they are", () => {
period.from = "2026-01-01";
period.to = "2026-04-14";
zoomOn(42);
expect(services.getCategoryZoom).toHaveBeenCalledWith(42, "2026-01-01", "2026-04-14", true);
});
});

View file

@ -84,5 +84,30 @@ describe("useCompare helpers", () => {
expect(r.next).toBeNull();
expect(r.lastSyncedTo).toBe("garbage");
});
// « Tout » (#479) has no upper bound: `to` is absent. The reference month
// shown does not move; only a later switch to a dated period syncs it.
it("keeps the reference month when `to` goes absent (« Tout »)", () => {
const r = syncReferenceOnPeriodChange("2026-04-14", undefined, 2026, 9);
expect(r.next).toBeNull();
expect(r.lastSyncedTo).toBeUndefined();
});
it("mounted on « Tout », then « Cette année »: syncs to the end of that period", () => {
const mount = syncReferenceOnPeriodChange(undefined, undefined, 2026, 9);
expect(mount.next).toBeNull();
const year = syncReferenceOnPeriodChange(mount.lastSyncedTo, "2026-04-14", 2026, 9);
expect(year.next).toEqual({ year: 2026, month: 4 });
expect(year.lastSyncedTo).toBe("2026-04-14");
});
it("« Cette année » → « Tout » → « Cette année »: unchanged on « Tout », synced on the way back", () => {
const mount = syncReferenceOnPeriodChange("2026-04-14", "2026-04-14", 2026, 9);
const all = syncReferenceOnPeriodChange(mount.lastSyncedTo, undefined, 2026, 9);
const back = syncReferenceOnPeriodChange(all.lastSyncedTo, "2026-04-14", 2026, 9);
expect(mount.next).toBeNull();
expect(all.next).toBeNull();
expect(back.next).toEqual({ year: 2026, month: 4 });
});
});
});

View file

@ -69,20 +69,26 @@ export function comparisonMeta(
* Gates on a *change* of `to` (the period's upper bound) rather than a
* fire-once flag: seeded with the initial `to`, the mount is a no-op, so the
* previous-month default from initialState survives instead of snapping to the
* civil-year December that useReportsPeriod yields by default (Issue #253).
* Because it keys off a value change, it is idempotent under React StrictMode's
* dev double-invoke of effects — called twice with the same `to` it dispatches
* nothing the second time (a fire-once boolean would wrongly sync on run #2).
* month that ends useReportsPeriod's default period, « Cette année », which
* ends today (Issues #253, #479). Because it keys off a value change, it is
* idempotent under React StrictMode's dev double-invoke of effects — called
* twice with the same `to` it dispatches nothing the second time (a fire-once
* boolean would wrongly sync on run #2).
*
* `to` is absent on « Tout » (`all`, no upper bound): the reference month shown
* stays as it is, and the absent `to` is remembered, so a later switch to a
* dated period syncs it to the end of that period (#479).
*
* Returns the `to` to remember plus an optional reference period to dispatch.
*/
export function syncReferenceOnPeriodChange(
lastSyncedTo: string,
to: string,
lastSyncedTo: string | undefined,
to: string | undefined,
currentYear: number,
currentMonth: number,
): { lastSyncedTo: string; next: { year: number; month: number } | null } {
): { lastSyncedTo: string | undefined; next: { year: number; month: number } | null } {
if (to === lastSyncedTo) return { lastSyncedTo, next: null };
if (to === undefined) return { lastSyncedTo: to, next: null };
const [y, m] = to.split("-").map(Number);
if (!Number.isFinite(y) || !Number.isFinite(m)) return { lastSyncedTo: to, next: null };
if (y === currentYear && m === currentMonth) return { lastSyncedTo: to, next: null };
@ -174,8 +180,9 @@ export function useCompare() {
// via PeriodSelector — but not on mount. The ref is seeded with the initial
// `to`, so syncReferenceOnPeriodChange only fires on an actual change of `to`,
// leaving the previous-month default from initialState intact (Issue #253) and
// staying idempotent under StrictMode's dev double-invoke.
const lastSyncedToRef = useRef(to);
// staying idempotent under StrictMode's dev double-invoke. `to` is undefined
// on « Tout », a direct opening on `?period=all` included (#479).
const lastSyncedToRef = useRef<string | undefined>(to);
useEffect(() => {
const { lastSyncedTo, next } = syncReferenceOnPeriodChange(
lastSyncedToRef.current,

View file

@ -0,0 +1,99 @@
// useCompare — the reference month follows the URL period, never at mount
// (#253), and « Tout » leaves it where it is (#479).
//
// 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 and the reports period are mocked; a test
// changes `period.to` between renders, as the period selector does through
// the URL. What is pinned: the ref the sync effect compares against is seeded
// with the first `to`, a mount on « Tout » (`to` absent, `?period=all`) neither
// throws nor moves the month, and a switch to a dated period afterwards syncs
// it to the end of that period.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
const period = vi.hoisted(() => ({
to: undefined as string | undefined,
// One array for every render: a new one would read as a changed filter.
accountIds: [] as number[],
}));
vi.mock("./useReportsPeriod", () => ({
useReportsPeriod: () => ({ from: undefined, to: period.to, accountIds: period.accountIds }),
}));
// Never settle: the rows and the accounts are not what is tested here, and a
// late dispatch would land in the next test's mount.
vi.mock("../services/reportService", () => ({
getCompareMonthOverMonth: vi.fn(() => new Promise(() => {})),
getCompareYearOverYear: vi.fn(() => new Promise(() => {})),
}));
vi.mock("../services/transactionService", () => ({
getAllImportSources: vi.fn(() => new Promise(() => {})),
}));
import { hookHarness } from "../test/hookHarness";
import { useCompare, defaultReferencePeriod } from "./useCompare";
const harness = hookHarness();
/** The end of « Cette année » on 2026-04-14: a month gone by, never the default (the month before today). */
const YEAR_TO = "2026-04-14";
/** Renders the mounted hook with the given `to`, runs its effects, and renders again to read the state. */
function step(to: string | undefined) {
period.to = to;
harness.render(useCompare);
harness.commit();
return harness.render(useCompare);
}
/** The reference month a render shows. */
const shown = (result: { year: number; month: number }) => ({ year: result.year, month: result.month });
/** The reference periods the sync effect dispatched, in order. */
const synced = () =>
harness.dispatch.mock.calls
.map(([action]) => action as { type: string; payload?: unknown })
.filter((action) => action.type === "SET_REFERENCE_PERIOD")
.map((action) => action.payload);
beforeEach(() => {
harness.clear();
});
describe("useCompare — the reference month and the URL period (#253, #479)", () => {
it("a mount on « Cette année » keeps the previous month (#253)", () => {
const result = step(YEAR_TO);
expect(synced()).toEqual([]);
expect(shown(result)).toEqual(defaultReferencePeriod());
});
it("a mount on « Tout » neither throws nor moves the reference month", () => {
const result = step(undefined);
expect(synced()).toEqual([]);
expect(shown(result)).toEqual(defaultReferencePeriod());
});
it("mounted on « Tout », a switch to « Cette année » syncs to the end of that period", () => {
step(undefined);
const result = step(YEAR_TO);
expect(synced()).toEqual([{ year: 2026, month: 4 }]);
expect(shown(result)).toEqual({ year: 2026, month: 4 });
});
it("« Cette année » → « Tout » → « Cette année »: unchanged on « Tout », synced on the way back", () => {
step(YEAR_TO);
const onAll = step(undefined);
expect(synced()).toEqual([]);
expect(shown(onAll)).toEqual(defaultReferencePeriod());
const back = step(YEAR_TO);
expect(synced()).toEqual([{ year: 2026, month: 4 }]);
expect(shown(back)).toEqual({ year: 2026, month: 4 });
});
it("« Tout » keeps a reference month the user picked", () => {
step(YEAR_TO).setReferencePeriod(2025, 12);
const onAll = step(undefined);
expect(shown(onAll)).toEqual({ year: 2025, month: 12 });
});
});

View file

@ -2,13 +2,15 @@ import { describe, it, expect } from "vitest";
import { resolveReportsPeriod, parseAccountIds, serializeAccountIds } from "./useReportsPeriod";
describe("resolveReportsPeriod", () => {
const fixedToday = new Date("2026-04-14T12:00:00Z");
// A day far from the clock: a range computed from `new Date()` instead of
// the given day ends elsewhere, and these tests go red. Local noon, so it is
// April 14 in every time zone (noon UTC is already April 15 in UTC+12).
const fixedToday = new Date(2026, 3, 14, 12);
/** « Cette année » on that day: January 1st to that day (#479). */
const YEAR_TO_DATE = { from: "2026-01-01", to: "2026-04-14", period: "year" };
it("defaults to current civil year when no URL params are set", () => {
const result = resolveReportsPeriod(null, null, null, fixedToday);
expect(result.from).toBe("2026-01-01");
expect(result.to).toBe("2026-12-31");
expect(result.period).toBe("custom");
it("defaults to « Cette année », the year to date, when no URL params are set (#479)", () => {
expect(resolveReportsPeriod(null, null, null, fixedToday)).toEqual(YEAR_TO_DATE);
});
it("restores state from bookmarked from/to params", () => {
@ -18,37 +20,50 @@ describe("resolveReportsPeriod", () => {
expect(result.period).toBe("custom");
});
it("keeps a ?period=custom&from=…&to=… bookmark as it is (#479)", () => {
expect(resolveReportsPeriod("2025-03-01", "2025-06-30", "custom", fixedToday)).toEqual({
from: "2025-03-01",
to: "2025-06-30",
period: "custom",
});
});
it("keeps period=yearly alongside explicit from/to", () => {
const result = resolveReportsPeriod("2024-01-01", "2024-12-31", "year", fixedToday);
expect(result.period).toBe("year");
});
it("ignores malformed dates and falls back to the civil year", () => {
const result = resolveReportsPeriod("not-a-date", "also-not", null, fixedToday);
expect(result.from).toBe("2026-01-01");
expect(result.to).toBe("2026-12-31");
expect(result.period).toBe("custom");
it("ignores malformed dates and falls back to the year to date (#479)", () => {
expect(resolveReportsPeriod("not-a-date", "also-not", null, fixedToday)).toEqual(YEAR_TO_DATE);
});
it("resolves preset period values without from/to", () => {
const result = resolveReportsPeriod(null, null, "6months", fixedToday);
expect(result.period).toBe("6months");
expect(result.from).toBeTruthy();
expect(result.to).toBeTruthy();
it("falls back to the year to date for `custom` without two valid dates (#479)", () => {
expect(resolveReportsPeriod(null, null, "custom", fixedToday)).toEqual(YEAR_TO_DATE);
// One valid bound is not a range.
expect(resolveReportsPeriod("2025-03-01", null, "custom", fixedToday)).toEqual(YEAR_TO_DATE);
});
it("rejects an invalid period string and falls back to civil year custom", () => {
const result = resolveReportsPeriod(null, null, "bogus", fixedToday);
expect(result.period).toBe("custom");
expect(result.from).toBe("2026-01-01");
it("resolves preset period values without from/to, from the given day (#479)", () => {
expect(resolveReportsPeriod(null, null, "6months", fixedToday)).toEqual({
from: "2025-11-01",
to: "2026-04-14",
period: "6months",
});
});
it("treats `all` as a preset with empty range (service handles the clauses)", () => {
it("resolves `year` to the year to date (#479)", () => {
expect(resolveReportsPeriod(null, null, "year", fixedToday)).toEqual(YEAR_TO_DATE);
});
it("rejects an invalid period string and falls back to the year to date (#479)", () => {
expect(resolveReportsPeriod(null, null, "bogus", fixedToday)).toEqual(YEAR_TO_DATE);
});
it("leaves the range absent for `all`: the services get no date bound (#479)", () => {
const result = resolveReportsPeriod(null, null, "all", fixedToday);
expect(result.period).toBe("all");
// Fallback civil year when computeDateRange returns empty
expect(result.from).toBe("2026-01-01");
expect(result.to).toBe("2026-12-31");
expect(result.from).toBeUndefined();
expect(result.to).toBeUndefined();
});
});

View file

@ -21,11 +21,6 @@ function isValidIsoDate(s: string | null): s is string {
return !!s && /^\d{4}-\d{2}-\d{2}$/.test(s);
}
function currentYearRange(today: Date = new Date()): { from: string; to: string } {
const year = today.getFullYear();
return { from: `${year}-01-01`, to: `${year}-12-31` };
}
// Matches a bare (optionally negative) integer token, e.g. "3" or "-3", but
// not "3.5", "abc", "" or "1e3" — deliberately stricter than `Number(...)` so
// that hex/exponential-notation strings from a hand-edited URL don't sneak
@ -66,33 +61,37 @@ export function serializeAccountIds(accountIds: number[]): string | null {
/**
* Pure resolver used by the hook and unit tests. Exposed to keep the core
* logic hookless and testable without rendering a router.
*
* - Two valid dates (a bookmark): kept as they are.
* - A valid preset other than `custom`: its range, computed for `today`;
* `all` has none, so `from` and `to` are absent and the services add no
* date clause (#479).
* - Anything else (no parameter, an invalid period, `custom` without two
* valid dates): « Cette année », the year to date (#479).
*/
export function resolveReportsPeriod(
rawFrom: string | null,
rawTo: string | null,
rawPeriod: string | null,
today: Date = new Date(),
): { from: string; to: string; period: DashboardPeriod } {
): { from?: string; to?: string; period: DashboardPeriod } {
if (isValidIsoDate(rawFrom) && isValidIsoDate(rawTo)) {
const p = isValidPeriod(rawPeriod) ? rawPeriod : "custom";
return { from: rawFrom, to: rawTo, period: p };
}
if (isValidPeriod(rawPeriod) && rawPeriod !== "custom") {
const range = computeDateRange(rawPeriod);
const { from: defaultFrom, to: defaultTo } = currentYearRange(today);
return {
from: range.dateFrom ?? defaultFrom,
to: range.dateTo ?? defaultTo,
period: rawPeriod,
};
const { dateFrom, dateTo } = computeDateRange(rawPeriod, undefined, undefined, today);
return { from: dateFrom, to: dateTo, period: rawPeriod };
}
const { from, to } = currentYearRange(today);
return { from, to, period: "custom" };
const { dateFrom, dateTo } = computeDateRange("year", undefined, undefined, today);
return { from: dateFrom, to: dateTo, period: "year" };
}
export interface UseReportsPeriodResult {
from: string;
to: string;
/** First day of the period (ISO date); absent for « Tout » (`all`). */
from?: string;
/** Last day of the period (ISO date); absent for « Tout » (`all`). */
to?: string;
period: DashboardPeriod;
accountIds: number[];
setPeriod: (period: DashboardPeriod) => void;
@ -105,8 +104,9 @@ export interface UseReportsPeriodResult {
* (import source) filter — via the URL query string so both are bookmarkable
* and shared across the report sub-routes.
*
* Defaults to the current civil year (Jan 1 → Dec 31) with no account filter
* (`accountIds: []`, meaning all accounts).
* Defaults to « Cette année » (`year`: Jan 1 → today, the year to date, as on
* the Dashboard) with no account filter (`accountIds: []`, meaning all
* accounts). « Tout » (`all`) leaves `from` and `to` undefined (#479).
*/
export function useReportsPeriod(): UseReportsPeriodResult {
const [searchParams, setSearchParams] = useSearchParams();

View file

@ -56,8 +56,15 @@ export function useTrends() {
const [state, dispatch] = useReducer(reducer, initialState);
const fetchIdRef = useRef(0);
// `dateFrom` / `dateTo` are absent on « Tout »: the services then add no
// date clause (#479).
const fetch = useCallback(
async (subView: TrendsSubView, dateFrom: string, dateTo: string, ids: number[]) => {
async (
subView: TrendsSubView,
dateFrom: string | undefined,
dateTo: string | undefined,
ids: number[],
) => {
const id = ++fetchIdRef.current;
dispatch({ type: "SET_LOADING", payload: true });
try {

View file

@ -0,0 +1,76 @@
// useTrends — the period's bounds reach both services as they are, so
// « Tout » asks for every date (#479).
//
// 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 and the reports period are mocked: on
// « Tout », `from` and `to` are absent (resolveReportsPeriod). What is pinned:
// the by-category view and the global flow hand those absent bounds to their
// service, which then adds no date clause, instead of a range of their own.
import { describe, it, expect, vi, beforeEach } from "vitest";
vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig()));
const period = vi.hoisted(() => ({
from: undefined as string | undefined,
to: undefined as string | undefined,
// One array for every render: a new one would read as a changed filter.
accountIds: [] as number[],
}));
vi.mock("./useReportsPeriod", () => ({
useReportsPeriod: () => ({ from: period.from, to: period.to, accountIds: period.accountIds }),
}));
const services = vi.hoisted(() => ({
getMonthlyTrends: vi.fn(),
getCategoryOverTime: vi.fn(),
}));
vi.mock("../services/reportService", () => services);
// Never settles: the accounts of the filter are not what is tested here.
vi.mock("../services/transactionService", () => ({
getAllImportSources: vi.fn(() => new Promise(() => {})),
}));
import { hookHarness } from "../test/hookHarness";
import { useTrends } from "./useTrends";
const harness = hookHarness();
beforeEach(() => {
harness.clear();
period.from = undefined;
period.to = undefined;
// Never settle: only the arguments are read, and a late dispatch would land
// in the next test's mount.
services.getMonthlyTrends.mockReset().mockReturnValue(new Promise(() => {}));
services.getCategoryOverTime.mockReset().mockReturnValue(new Promise(() => {}));
});
describe("useTrends — the period's bounds reach the services (#479)", () => {
it("« Tout »: the by-category view asks for no date bound", () => {
harness.render(useTrends);
harness.commit();
expect(services.getCategoryOverTime).toHaveBeenCalledTimes(1);
expect(services.getCategoryOverTime).toHaveBeenCalledWith(undefined, undefined, undefined, period.accountIds);
});
it("« Tout »: the global flow asks for no date bound", () => {
harness.render(useTrends).setSubView("global");
harness.render(useTrends);
harness.commit();
expect(services.getMonthlyTrends).toHaveBeenCalledTimes(1);
expect(services.getMonthlyTrends).toHaveBeenCalledWith(undefined, undefined, period.accountIds);
expect(services.getCategoryOverTime).not.toHaveBeenCalled();
});
it("a dated period passes its bounds as they are", () => {
period.from = "2026-01-01";
period.to = "2026-04-14";
harness.render(useTrends);
harness.commit();
expect(services.getCategoryOverTime).toHaveBeenCalledWith(
"2026-01-01",
"2026-04-14",
undefined,
period.accountIds,
);
});
});

View file

@ -606,7 +606,7 @@
"highlights": "Highlights",
"highlightsDescription": "What moved this month",
"trends": "Trends",
"trendsDescription": "Where you're heading over 12 months",
"trendsDescription": "Where you're heading, month by month",
"compare": "Compare",
"compareDescription": "Compare a reference month against previous month, previous year, or budget",
"categoryZoom": "Category Analysis",
@ -709,7 +709,7 @@
"tips": [
"The cards at the bottom of the page open the five reports: Highlights, Trends, Compare, Category Analysis and Cards",
"Use the period selector to adjust the time range for all charts",
"Trends shows your income and expenses month by month over 12 months",
"Trends shows your income and expenses month by month over the selected period",
"Category Analysis tracks how a single category evolves over time"
]
}

View file

@ -606,7 +606,7 @@
"highlights": "Faits saillants",
"highlightsDescription": "Ce qui a bougé ce mois-ci",
"trends": "Tendances",
"trendsDescription": "Où vous allez sur 12 mois",
"trendsDescription": "Où vous allez, mois par mois",
"compare": "Comparables",
"compareDescription": "Comparer un mois de référence au précédent, à l'année passée ou au budget",
"categoryZoom": "Analyse par catégorie",
@ -709,7 +709,7 @@
"tips": [
"Les cartes du bas de la page ouvrent les cinq rapports : Faits saillants, Tendances, Comparables, Analyse par catégorie et Cartes",
"Utilisez le sélecteur de période pour ajuster la plage de dates de tous les graphiques",
"Tendances montre vos revenus et dépenses mois par mois sur 12 mois",
"Tendances montre vos revenus et dépenses mois par mois sur la période choisie",
"Analyse par catégorie suit l'évolution d'une catégorie dans le temps"
]
}

View file

@ -880,6 +880,79 @@ describe("getCategoryZoom", () => {
expect(txSql).not.toContain("cat_tree");
expect(txSql).toContain("t.category_id = $1");
});
// « Tout » (#479): no bound at all. Each bound is skipped when bound to
// NULL, with the same three parameters in the same order: spelled out here
// rather than imported, so a typo in the service goes red.
const BOUNDS = "($2 IS NULL OR t.date >= $2) AND ($3 IS NULL OR t.date <= $3)";
/** A date condition left outside the NULL-skipping form. */
const BARE_BOUND = /t\.date\s*[<>]=/;
const answerFourQueries = () =>
mockSelect
.mockResolvedValueOnce([]) // transactions
.mockResolvedValueOnce([{ rollup: 0 }]) // rollup
.mockResolvedValueOnce([]) // byChild
.mockResolvedValueOnce([]); // evolution
it("sends no date bound for « Tout »: [id, null, null], skipped by every query (#479)", async () => {
answerFourQueries();
await getCategoryZoom(42, undefined, undefined, true);
expect(mockSelect).toHaveBeenCalledTimes(4);
for (const [sql, params] of mockSelect.mock.calls) {
expect(params).toEqual([42, null, null]);
expect(sql).toContain(BOUNDS);
expect((sql as string).split(BOUNDS).join("")).not.toMatch(BARE_BOUND);
}
});
it("passes the bounds of a dated period to every query, in number and order (#479)", async () => {
answerFourQueries();
await getCategoryZoom(42, "2026-01-01", "2026-04-14", true);
expect(mockSelect).toHaveBeenCalledTimes(4);
for (const [sql, params] of mockSelect.mock.calls) {
expect(params).toEqual([42, "2026-01-01", "2026-04-14"]);
expect(sql).toContain(BOUNDS);
}
});
it("keeps the per-child bounds in the LEFT JOIN's ON, never in the WHERE (#479)", async () => {
// In the WHERE, the join would turn inner: a subcategory without any
// transaction in the period would lose its row instead of showing 0.
answerFourQueries();
await getCategoryZoom(42, undefined, undefined, true);
const childSql = mockSelect.mock.calls
.map(([sql]) => sql as string)
.find((sql) => sql.includes("FROM categories child"));
expect(childSql).toBeDefined();
const [join, rest] = childSql!.split(/\bWHERE\b/);
expect(join.replace(/\s+/g, " ")).toContain(
`LEFT JOIN transactions t ON t.category_id = child.id AND ${BOUNDS}`,
);
expect(rest).not.toContain("t.date");
});
it("direct only: its three queries skip a NULL bound too (#479)", async () => {
mockSelect
.mockResolvedValueOnce([]) // transactions
.mockResolvedValueOnce([{ rollup: 0 }]) // rollup
.mockResolvedValueOnce([]); // evolution
await getCategoryZoom(7, undefined, undefined, false);
expect(mockSelect).toHaveBeenCalledTimes(3);
for (const [sql, params] of mockSelect.mock.calls) {
expect(params).toEqual([7, null, null]);
expect(sql).toContain(BOUNDS);
expect((sql as string).split(BOUNDS).join("")).not.toMatch(BARE_BOUND);
}
});
});
describe("buildCompareTree — hierarchical real-vs-real (Issue #247)", () => {

View file

@ -1020,32 +1020,44 @@ const CATEGORY_TREE_CTE = `
)
`;
/**
* Date bounds of the zoom queries: `$2` (first day) and `$3` (last day), each
* skipped when bound to NULL, so « Tout » (`all`, no bound) reads every date
* while the parameters keep their number and order (#479). In the per-child
* query it stays in the LEFT JOIN's ON: in the WHERE, the join would turn
* inner and a subcategory without any transaction in the period would lose
* its row instead of showing 0.
*/
const ZOOM_DATE_BOUNDS = "($2 IS NULL OR t.date >= $2) AND ($3 IS NULL OR t.date <= $3)";
/**
* Returns the zoom-on-category report for the given category id.
*
* When `includeSubcategories` is true the recursive CTE walks down the
* category tree (capped at 5 levels) and aggregates matching rows. When
* false, only direct transactions on `categoryId` are considered. Every
* query is parameterised; the category id is never interpolated.
* query is parameterised; the category id is never interpolated. An absent
* `dateFrom` or `dateTo` is no bound on that side (« Tout »).
*/
export async function getCategoryZoom(
categoryId: number,
dateFrom: string,
dateTo: string,
dateFrom?: string,
dateTo?: string,
includeSubcategories: boolean = true,
): Promise<CategoryZoomData> {
const db = await getDb();
const params = [categoryId, dateFrom ?? null, dateTo ?? null];
const categoryFilter = includeSubcategories
? `${CATEGORY_TREE_CTE}
SELECT t.id, t.date, t.description, t.amount, t.category_id
FROM transactions t
WHERE t.category_id IN (SELECT id FROM cat_tree)
AND t.date >= $2 AND t.date <= $3`
AND ${ZOOM_DATE_BOUNDS}`
: `SELECT t.id, t.date, t.description, t.amount, t.category_id
FROM transactions t
WHERE t.category_id = $1
AND t.date >= $2 AND t.date <= $3`;
AND ${ZOOM_DATE_BOUNDS}`;
// 1. Transactions (with join for display)
const txRows = await db.select<RecentTransaction[]>(
@ -1056,16 +1068,16 @@ export async function getCategoryZoom(
WHERE ${includeSubcategories
? "t.category_id IN (SELECT id FROM cat_tree)"
: "t.category_id = $1"}
AND t.date >= $2 AND t.date <= $3
AND ${ZOOM_DATE_BOUNDS}
ORDER BY ABS(t.amount) DESC
LIMIT 500`,
[categoryId, dateFrom, dateTo],
params,
);
// 2. Rollup total (sum of absolute amounts of matching rows)
const totalRows = await db.select<Array<{ rollup: number | null }>>(
`${categoryFilter.replace("SELECT t.id, t.date, t.description, t.amount, t.category_id", "SELECT COALESCE(SUM(ABS(t.amount)), 0) AS rollup")}`,
[categoryId, dateFrom, dateTo],
params,
);
const rollupTotal = Number(totalRows[0]?.rollup ?? 0);
@ -1081,11 +1093,11 @@ export async function getCategoryZoom(
COALESCE(SUM(ABS(t.amount)), 0) AS total
FROM categories child
LEFT JOIN transactions t ON t.category_id = child.id
AND t.date >= $2 AND t.date <= $3
AND ${ZOOM_DATE_BOUNDS}
WHERE child.parent_id = $1
GROUP BY child.id, child.name, child.color
ORDER BY total DESC`,
[categoryId, dateFrom, dateTo],
params,
);
for (const r of childRows) {
byChild.push({
@ -1106,10 +1118,10 @@ export async function getCategoryZoom(
WHERE ${includeSubcategories
? "t.category_id IN (SELECT id FROM cat_tree)"
: "t.category_id = $1"}
AND t.date >= $2 AND t.date <= $3
AND ${ZOOM_DATE_BOUNDS}
GROUP BY month
ORDER BY month ASC`,
[categoryId, dateFrom, dateTo],
params,
);
const monthlyEvolution: CategoryZoomEvolutionPoint[] = evolutionRows.map((r) => ({
month: r.month,

View file

@ -55,6 +55,18 @@ describe("computeDateRange", () => {
expect(result).toEqual({ dateFrom: "2024-08-01", dateTo: "2025-07-15" });
});
// `today` is injectable (#479): the Reports resolve their default, the year
// to date, from a fixed day in tests, whatever the clock says.
it('computes "year" from the given today, not the clock (#479)', () => {
const result = computeDateRange("year", undefined, undefined, new Date(2026, 3, 14));
expect(result).toEqual({ dateFrom: "2026-01-01", dateTo: "2026-04-14" });
});
it("computes a rolling preset from the given today too (#479)", () => {
const result = computeDateRange("6months", undefined, undefined, new Date(2026, 0, 20));
expect(result).toEqual({ dateFrom: "2025-08-01", dateTo: "2026-01-20" });
});
it("handles January rollover for 3months period", () => {
vi.setSystemTime(new Date(2025, 1, 10)); // Feb 10, 2025
const result = computeDateRange("3months");

View file

@ -2,22 +2,26 @@ import type { DashboardPeriod } from "../shared/types";
/**
* Compute a date range (dateFrom / dateTo) based on the selected period.
* Shared between useDashboard, useReports, DashboardPage and ReportsPage.
* Shared between useDashboard, DashboardPage and useReportsPeriod (the
* Reports). "all" has no range: both bounds are absent.
*
* `today` is the day the presets end on, the current day by default; the
* Reports pass theirs so a test can fix it (#479).
*/
export function computeDateRange(
period: DashboardPeriod,
customDateFrom?: string,
customDateTo?: string,
today: Date = new Date(),
): { dateFrom?: string; dateTo?: string } {
if (period === "all") return {};
if (period === "custom" && customDateFrom && customDateTo) {
return { dateFrom: customDateFrom, dateTo: customDateTo };
}
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
const day = now.getDate();
const year = today.getFullYear();
const month = today.getMonth();
const day = today.getDate();
const dateTo = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;