Compare commits

..

No commits in common. "issue-291-collapse-docs" and "main" have entirely different histories.

24 changed files with 641 additions and 1177 deletions

View file

@ -2,7 +2,7 @@
name: release
description: Release a new version of Simpl-Resultat (bump, changelog, tag, push)
user-invocable: true
updated: 2026-07-13
updated: 2026-07-01
---
# /release — Release Simpl-Resultat
@ -15,7 +15,6 @@ updated: 2026-07-13
## Workflow
0. **Pré-vol — revalider le tip localement.** `check.yml` ne tourne pas sur `main` : le tip mergé n'a jamais été vu par le CI (le dernier run vert portait sur la branche d'issue avant merge), et le tag grave ce tip exact dans des binaires distribués. Lancer `npm run build && npm test` (vitest) + `cd src-tauri && cargo check && cargo test`. Vérifier aussi que `.claude/worktrees/` est vide (worktrees leftover → vitest récurse et gonfle le compteur). Ne tagger que sur un tip vert.
1. Determiner la nouvelle version (argument utilisateur ou demander)
2. Bump version dans les 5 fichiers :
- `src-tauri/Cargo.toml` (ligne `version = "..."`)
@ -38,9 +37,6 @@ updated: 2026-07-13
```
7. Push : `git push origin main && git push origin vX.Y.Z`
8. Forgejo CI build automatique (Windows + Linux) via `release.yml` sur `on: push: tags: v*`
9. **Post-CI — vérifier la release publiée.** Surveiller `release.yml` (outil `Monitor` sur le run), puis vérifier la release réellement attachée — `status=success` du workflow ne suffit pas :
- Les **7 artefacts** attendus : `.exe` NSIS, `.deb`, `.rpm`, leurs 3 signatures `.sig`, et `latest.json`.
- Le contenu de `latest.json` (il pilote l'auto-update des installations existantes) : champ `version` correct, signatures non vides pour les deux plateformes, URLs pointant vers les bons binaires, notes extraites du CHANGELOG.
## Regles
@ -49,9 +45,7 @@ updated: 2026-07-13
- Format Keep a Changelog : `## [X.Y.Z] - YYYY-MM-DD`
- Les changelogs sont bundles dans `public/` pour l'affichage in-app
- Tag **annote** (`-a`), pas lightweight : les artefacts CI reference le tag pour les release notes
- **Tagger publie vers l'extérieur** : `release.yml` pousse le JSON d'updater, donc les utilisateurs installés reçoivent la mise à jour automatiquement. Confirmer avec Max avant de tagger.
## Changelog
- 2026-04-19 — Added Cargo.lock + package-lock.json to bump list, `npm install --package-lock-only` fallback when lockfile stale, explicit `[Unreleased]` migration pattern, annotated tags (#102/#112 release cycle)
- 2026-07-01 — Documenter que le header FR est `## [Non publié]` (≠ `[Unreleased]`), pour éviter le faux diagnostic « changelog FR vide » lors de la migration. Source : session 5466da98.
- 2026-07-13 — Étape 0 (pré-vol) : revalider le tip localement avant de tagger — `check.yml` ne tourne pas sur `main`, le tip mergé n'a jamais été vu par le CI ; vérifier `.claude/worktrees/` vide (vitest récurse sinon). Étape 9 (post-CI) : vérifier la release publiée — 7 artefacts attendus + contenu de `latest.json` (pilote l'auto-update) ; `status=success` ne suffit pas. Règle : tagger publie vers l'extérieur (updater automatique) → confirmer avec Max avant de tagger. Source : session fdda84cb (release v0.13.0).

View file

@ -2,15 +2,6 @@
## [Non publié]
### Modifié
- Rapports : les trois tableaux de rapport hiérarchiques (Comparaison réel-vs-réel, réel-vs-budget, et Tendances par catégorie) permettent désormais de **replier ou déplier chaque niveau de la hiérarchie de catégories**, plus seulement le premier. Chaque catégorie parente — y compris les intermédiaires — porte son propre chevron ; en déplier une révèle ses enfants directs (eux-mêmes repliés), pour descendre un niveau à la fois. Les tableaux s'ouvrent entièrement repliés (seules les catégories de premier niveau visibles), « Tout déplier » ouvre tous les niveaux d'un coup, et vos choix de repli sont désormais enregistrés **par profil** — dans la base de données du profil, donc détruits avec lui — au lieu du navigateur. Les sous-totaux et les lignes de résultat restent rigoureusement inchangés quel que soit ce que vous repliez (#288).
- Budget : la grille budget se **replie et se déplie elle aussi à chaque niveau de catégorie**, à l'image des rapports. Chaque catégorie parente porte un chevron, la grille **s'ouvre entièrement repliée** (seules les catégories de premier niveau visibles) pour un aperçu compact, et « Tout déplier » ouvre tous les niveaux en un clic. Replier une catégorie est purement visuel — les totaux de section et les lignes de résultat sont inchangés, et aucune valeur de budget que vous avez saisie n'est jamais perdue. Vos choix de repli sont enregistrés par profil (#289).
### Corrigé
- Arbre des catégories standard (le guide autonome comme l'étape d'aperçu de l'assistant de migration des catégories) : le bouton « Tout déplier / Tout replier » reflète désormais l'état réel de l'arbre — il reste sur « Tout déplier » tant que tous les groupes ne sont pas ouverts, au lieu de basculer sur « Tout replier » dès qu'une seule catégorie était dépliée (#290).
## [0.13.0] - 2026-07-12
### Ajouté

View file

@ -2,15 +2,6 @@
## [Unreleased]
### Changed
- Reports: the three hierarchical report tables (real-vs-real Compare, real-vs-budget Compare, and Trends by category) now let you **collapse or expand every level of the category hierarchy**, not just the top level. Every parent category — including the intermediate ones — carries its own chevron; expanding one reveals its direct children (themselves collapsed), so you drill down one level at a time. The tables open fully collapsed (only the top-level categories visible), "Expand all" opens every level at once, and your collapse choices are now saved **per profile** — in the profile's own database, so they are destroyed with the profile — instead of in the browser. Subtotals and result lines stay exactly the same whatever you fold away (#288).
- Budget: the budget grid now **collapses and expands at every category level** too, matching the reports. Each parent category carries a chevron, the grid **opens fully collapsed** (only the top-level categories visible) for a compact overview, and "Expand all" opens every level in one click. Folding a category is purely visual — section totals and the result lines are unchanged, and no budget figure you have typed is ever lost. Your collapse choices are saved per profile (#289).
### Fixed
- Standard categories tree (both the standalone guide and the category-migration wizard's overview step): the "Expand all / Collapse all" button now reflects the tree's real state — it stays on "Expand all" until every group is open, instead of flipping to "Collapse all" as soon as a single category was expanded (#290).
## [0.13.0] - 2026-07-12
### Added

View file

@ -1,87 +0,0 @@
# ADR 0016 — Persistance de l'état UI par profil : le repli des catégories vit dans `user_preferences`
- Status: **Accepted**
- Date: 2026-07-15
- Issues: #288 (socle multi-niveaux + 3 rapports + bascule vers `user_preferences`), #289 (grille budget), #290 (unification des deux arbres de catégories), #291 (cet ADR + doc)
- Spec: [`spec-decisions-collapse-multi-niveaux.md`](../../spec-decisions-collapse-multi-niveaux.md), [`spec-plan-collapse-multi-niveaux.md`](../../spec-plan-collapse-multi-niveaux.md) (plan v2)
- S'appuie sur [ADR 0005](0005-multi-profile-db.md) (bases SQLite séparées par profil) et [ADR 0002](0002-useReducer-vs-redux.md) (état local, pas de store global)
## Contexte
Le repli/dépli des catégories a d'abord été introduit sur les deux rapports comparables (issue #254/#265) : un `Set` d'ID de catégories par rapport, persisté en **`localStorage`**, replié par défaut. La généralisation (issues #288/#289/#290) a étendu ce mécanisme à **tous les niveaux** de la hiérarchie et à **six surfaces** : les trois tableaux de rapports hiérarchiques (comparable réel-vs-réel `ComparePeriodTable`, réel-vs-budget `BudgetVsActualTable`, tendance par catégorie `CategoryOverTimeTable`), la **grille budgétaire** (`BudgetTable`), et les **deux arbres de gestion des catégories** (`CategoryTree` de la page Catégories + `CategoryTaxonomyTree` du guide standard et de l'assistant de migration).
Cette généralisation a forcé une question qui n'était pas tranchée en #254 : **où vit l'état de repli ?** Deux propriétés du produit rendent le choix structurant, pas cosmétique.
1. **L'app est multi-profils à bases séparées** ([ADR 0005](0005-multi-profile-db.md)) : chaque profil a sa **propre base SQLite**, ses propres catégories, ses propres ID de catégories. Un profil peut être **protégé par un NIP** (Argon2). Supprimer un profil = **supprimer son fichier `.db`** (`deleteProfileDb` → commande Rust `delete_profile_db`) + retirer son entrée de `profiles.json`. Rien d'autre n'est nettoyé — `deleteProfile` (`ProfileContext`) ne touche **jamais** `localStorage`.
2. **`localStorage` est machine-global**, partagé par tous les profils du poste. La clé de repli est un ensemble d'**ID de catégories** (`p:<categoryId>`), et ces ID n'ont de sens que **dans la base d'un profil donné** : le même ID numérique désigne des catégories différentes selon le profil. Une clé de repli en `localStorage` serait donc soit **en collision entre profils** (mêmes ID, catégories différentes), soit suffixée par `profileId` — et dans ce dernier cas, elle **survivrait à la suppression du profil**, devenant un **résidu**.
Ce résidu n'est pas anodin : l'ensemble des catégories qu'un profil a **dépliées** révèle quelles postes de dépense l'utilisateur a explorés. Le laisser traîner en `localStorage` après la suppression d'un profil (potentiellement NIP-protégé) trahit une part de son comportement financier. C'est **incompatible avec le principe privacy-first** (non négociable) du projet.
## Décision
**L'état UI *spécifique à un profil* est persisté dans la table `user_preferences` de la base du profil ; l'état UI *machine-global* reste dans `localStorage`.** Le repli des catégories relève du premier cas.
### 1. Frontière `user_preferences` vs `localStorage`
| Nature de l'état | Support | Pourquoi | Exemples |
|---|---|---|---|
| **Spécifique au profil** (dépend des données du profil, ou révèle son usage) | `user_preferences` (base SQLite du profil) | Scoping par-profil **gratuit** (la clé vit dans la base du profil) ; **détruit avec le profil** (drop du `.db`) ⇒ zéro résidu | **Repli des catégories** des rapports + grille budget (clés `reports-compare-expanded`, `reports-bva-expanded`, `reports-trends-expanded`, `budget-grid-expanded`) ; `import_folder`, `balance_show_returns`, `balance_starter_proposed` (préexistants) |
| **Machine-globale** (scalaire agnostique du profil, ne révèle rien de sensible) | `localStorage` | On *veut* la même valeur quel que soit le profil ouvert ; aucune fuite si elle survit à une suppression | Thème clair/sombre (`theme`), position des sous-totaux (`*-subtotals-position`), mode de période Cartes (`reports-cartes-period-mode`), bascule graphique/tableau par rapport |
Le critère : une préférence est **machine-globale** quand sa valeur est un scalaire agnostique du profil (`"top"`/`"bottom"`, `"dark"`, `"chart"`) qu'on souhaite partager entre tous les profils du poste. Elle est **spécifique au profil** dès qu'elle est indexée par des identifiants propres à la base du profil (les ID de catégories du repli) **ou** qu'elle expose l'usage d'un profil donné.
### 2. Mécanisme — `useCollapsibleGroups(storageKey: string | null)`
Le hook `useCollapsibleGroups` porte cette décision via un unique paramètre `storageKey` :
- **`storageKey` non nul** ⇒ persistance dans `user_preferences` via `userPreferenceService` (`getPreference`/`setPreference`, UPSERT sur `key`). Utilisé par les **quatre surfaces persistées** (3 rapports + budget). La valeur sérialisée est le `Set` des clés dont l'état **diffère du défaut** — ce qui permet un défaut « tout replié » sans graine (Set vide = tout replié pour `defaultExpanded: false`).
- **`storageKey === null`** ⇒ **aucune persistance**, état purement en mémoire, réinitialisé au défaut à chaque montage. Utilisé par les **deux arbres de catégories** (page Catégories, guide standard, assistant de migration) : leur repli est un confort de navigation éphémère, sans intérêt à conserver ni à révéler.
Le hook reste **sans contexte** — il n'appelle jamais `useProfile()` : la clé `user_preferences` est **déjà** par-profil, puisqu'elle vit dans la base du profil actif. Aucun `profileId` à faufiler.
### 3. Rationale privacy — le résidu qui survit à la suppression
C'est l'argument central. `deleteProfile` détruit la base (`.db`) mais **ne purge aucun `localStorage`**. Une clé de repli par-profil en `localStorage` (ex. `reports-compare-expanded:<profileId>`) survivrait donc à la suppression du profil, laissant deviner **quelles catégories** un profil désormais supprimé — et peut-être NIP-protégé — avait explorées. En logeant l'état dans `user_preferences`, il **disparaît avec le fichier `.db`** : la suppression du profil emporte automatiquement son état UI, sans code de nettoyage dédié et sans surface de fuite. La propriété « supprimer un profil = supprimer un fichier » ([ADR 0005](0005-multi-profile-db.md)) est préservée telle quelle.
## Alternatives considérées
### A. `localStorage` suffixé par `profileId` — **rejeté**
Garder le repli en `localStorage` avec une clé `…:<profileId>` par profil. Rejeté : c'est précisément le **résidu** décrit ci-dessus (survit à `deleteProfile`, fuite privacy), et il faudrait ajouter un balayage de nettoyage dans `deleteProfile` — du code fragile qui doit connaître toutes les clés UI par-profil de l'app, à maintenir à chaque nouvelle surface repliable.
### B. Table SQLite dédiée (`ui_collapse_state`) — rejeté
Créer une table par-profil rien que pour le repli. Rejeté : sur-dimensionné. `user_preferences` est déjà une table clé-valeur par-profil faite pour ça (`import_folder`, `balance_show_returns`…) ; une clé par surface suffit, sans migration.
### C. Tout en mémoire (aucune persistance) — rejeté pour les rapports/budget
Simple, zéro résidu. Rejeté pour les **quatre** surfaces persistées : sur des tableaux profonds, re-replier à chaque visite est une friction réelle (finding remonté en #254). **Retenu en revanche pour les deux arbres de catégories** (`storageKey: null`) — d'où le paramètre nullable plutôt qu'un choix uniforme.
## Consequences
### Positives
- **Zéro résidu, zéro fuite** : l'état de repli est détruit avec le `.db` du profil ; aucune trace machine-globale de l'usage d'un profil supprimé. Conforme privacy-first.
- **Scoping par-profil gratuit** : la clé vit dans la base du profil ⇒ isolation automatique, hook sans contexte, pas de `profileId` à propager.
- **Réutilise l'existant** : `user_preferences` + `userPreferenceService` déjà en place ⇒ **aucune migration, aucune table, aucun changement de schéma**.
- **Frontière tracée** : la règle « profil-spécifique → `user_preferences` ; machine-globale → `localStorage` » est explicite (§1) ⇒ le prochain état UI par-profil ne repartira pas en `localStorage` par défaut (caveat de review levé).
### Négatives / risques actés
- **Hydratation asynchrone** : `getPreference`/`setPreference` sont `async` (passent par `getDb()`). L'état initial rendu est le **défaut** (tout replié pour les rapports/budget), puis un `useEffect` hydrate depuis `user_preferences`. **Pas de flash visible** : le défaut EST ce qui s'affiche en premier, et l'hydratation ne peut que **révéler** ce que l'utilisateur avait déplié (jamais masquer ce qui était visible). Acceptable — c'est la contrepartie assumée du choix.
- **Best-effort** : une lecture/écriture en échec retombe silencieusement sur l'état par défaut (jamais de crash). Une écriture perdue = la session suivante rouvre au défaut.
- **Frontière à faire respecter dans la durée** : rien dans le type ne force un futur état par-profil à choisir `user_preferences`. La règle est documentaire (cet ADR + `docs/architecture.md`) — d'où l'importance de l'avoir tracée.
### Neutre
- Les préférences machine-globales existantes (`theme`, `*-subtotals-position`, `reports-cartes-period-mode`, bascule graphique/tableau) **restent en `localStorage`** : elles sont volontairement partagées entre profils et ne révèlent rien de sensible en cas de suppression. Aucune migration de ces clés n'est entreprise.
## Liens
- [ADR 0005](0005-multi-profile-db.md) — bases SQLite séparées par profil ; « supprimer un profil = supprimer un fichier `.db` » (fondement de l'argument résidu)
- [ADR 0002](0002-useReducer-vs-redux.md) — état local par domaine, pas de store global (le repli reste un état UI local persisté à la marge)
- `src/hooks/useCollapsibleGroups.ts` — implémentation (`storageKey: string | null`, `defaultExpanded`, hydratation async)
- `src/utils/collapsibleRows.ts` — helpers purs (marche des ancêtres, polarité du `Set`)
- `src/services/userPreferenceService.ts``getPreference`/`setPreference` (UPSERT sur `user_preferences`)
- Issues #254/#265 (repli d'origine, localStorage) → #288/#289/#290 (généralisation + bascule `user_preferences`) → #291 (cette doc)

View file

@ -89,7 +89,7 @@ simpl-resultat/
| `budget_templates` | Modèles de budget réutilisables |
| `budget_template_entries` | Catégories et montants dans les modèles |
| `import_config_templates` | Modèles prédéfinis de config d'import |
| `user_preferences` | Préférences applicatives (clé-valeur) `import_folder`, `balance_show_returns`, `balance_starter_proposed`**et l'état de repli des catégories** (clés `reports-compare-expanded`, `reports-bva-expanded`, `reports-trends-expanded`, `budget-grid-expanded`) : persisté ici **par profil** plutôt qu'en `localStorage`, pour être détruit avec le profil (pas de résidu machine-global survivant à la suppression) — voir [ADR 0016](adr/0016-persistance-etat-ui-par-profil.md) |
| `user_preferences` | Préférences applicatives (clé-valeur) |
| `balance_categories` | Taxonomie des **classes d'actif** (Liquidités, Fonds/FNB, Actions, Crypto, Autres) — `kind ∈ {simple, priced}` (défaut suggéré pour les nouveaux comptes), `custom_label` pour le renommage bilingue-safe (v12). Les ex-types véhicules (TFSA/RRSP) ont migré vers `balance_accounts.vehicle_type` (Étape 1, v12/v13, [ADR 0014](adr/0014-balance-vehicule-attribut.md)) |
| `balance_accounts` | Comptes de bilan (rattachés à une catégorie). `currency` hardcodée à `CAD` au MVP via CHECK. `archived_at` pour soft-delete. `vehicle_type` (enveloppe fiscale nullable, v12, [ADR 0014](adr/0014-balance-vehicule-attribut.md)). `kind ∈ {simple, detailed}` + `detailed_since` (pivot faisant autorité, v15, [ADR 0015](adr/0015-balance-detail-par-titre.md)) — porte désormais l'axe simple/détaillé (auparavant dérivé de `category.kind`). **Issue #179** : 4 comptes de départ seedés (`consolidated_schema.sql`) + proposés aux profils existants via `StarterAccountsModal` |
| `balance_snapshots` | Snapshots datés (`snapshot_date` UNIQUE) — éditer = mettre à jour les lignes, pas dupliquer |
@ -221,13 +221,6 @@ Chaque hook encapsule la logique d'état via `useReducer` :
| `useLicense` | État de la licence et entitlements |
| `useAuth` | Authentification Compte Maximus (OAuth2 PKCE, subscription status) |
### Hook transverse — `useCollapsibleGroups`
`useCollapsibleGroups<T>(storageKey: string | null, accessors, { defaultExpanded })` est un hook **utilitaire d'état UI** (basé `useState`, hors convention `useReducer` par domaine) partagé par toutes les surfaces à hiérarchie repliable : les 3 tableaux de rapports (`ComparePeriodTable`, `BudgetVsActualTable`, `CategoryOverTimeTable`), la grille budget (`BudgetTable`) et les 2 arbres de catégories (`CategoryTree`, `CategoryTaxonomyTree`). Les helpers purs (marche des ancêtres pour la visibilité, polarité du `Set` selon `defaultExpanded`) vivent dans `src/utils/collapsibleRows.ts`.
- `storageKey` **non nul** → l'état de repli est **persisté par profil** dans `user_preferences` (via `userPreferenceService`), donc détruit avec le profil, sans résidu `localStorage` ([ADR 0016](adr/0016-persistance-etat-ui-par-profil.md)). Quatre surfaces persistées (les 3 rapports + budget). Hydratation **asynchrone** : le défaut (« tout replié » pour rapports/budget) est rendu d'abord, un `useEffect` hydrate ensuite → pas de flash visible.
- `storageKey === null` → état **purement en mémoire**, réinitialisé à chaque montage (les 2 arbres de catégories : navigation éphémère, rien à conserver ni à révéler).
## Commandes Tauri (36)
### `fs_commands.rs` — Système de fichiers (6)
@ -436,4 +429,3 @@ Les ADRs documentent les décisions techniques structurantes. Ils vivent dans `d
| [0013](adr/0013-stocks-provider-evaluation.md) | Évaluation provider stocks : Alpha Vantage retenu comme cible | 2026-05-09 | Accepted |
| [0014](adr/0014-balance-vehicule-attribut.md) | Bilan : le véhicule fiscal est un attribut du compte (Étape 1) | 2026-06-01 | Accepted |
| [0015](adr/0015-balance-detail-par-titre.md) | Bilan : détail par titre (holdings par snapshot, Étape 2) | 2026-06-06 | Accepted |
| [0016](adr/0016-persistance-etat-ui-par-profil.md) | Persistance de l'état UI par profil : repli des catégories dans `user_preferences` | 2026-07-15 | Accepted |

View file

@ -226,7 +226,6 @@ Planifiez votre budget mensuel pour chaque catégorie et suivez le prévu par ra
- Répartition égale du montant annuel sur 12 mois
- Modèles de budget pour sauvegarder et appliquer des configurations
- Sous-totaux par catégorie parente
- Repli / dépli de la hiérarchie à **chaque niveau** : chaque catégorie parente a son chevron, la grille s'ouvre **entièrement repliée** (seules les catégories de premier niveau visibles), et un bouton **« Tout déplier / Tout replier »** ouvre ou ferme tous les niveaux d'un coup — votre choix est mémorisé **par profil**
- En-têtes de colonnes fixes au défilement vertical
### Comment faire
@ -242,7 +241,6 @@ Planifiez votre budget mensuel pour chaque catégorie et suivez le prévu par ra
- La colonne Annuel additionne automatiquement les 12 mois — un avertissement apparaît si les totaux mensuels ne correspondent pas
- Les modèles peuvent être appliqués à des mois spécifiques ou aux 12 mois d'un coup
- Les catégories parentes affichent les sous-totaux agrégés de leurs enfants
- Replier une catégorie est **purement visuel** : les sous-totaux et les totaux annuels sont toujours calculés sur toutes les lignes, jamais seulement sur les lignes visibles — aucun montant saisi n'est perdu quand vous repliez
---
@ -321,7 +319,7 @@ Toujours mensuelle, indépendamment du toggle.
### Rapport Tendances (`/reports/trends`)
- **Flux global** : revenus vs dépenses vs solde net sur la période, en graphique d'aires ou tableau
- **Par catégorie** : évolution de chaque catégorie, en lignes ou tableau. En mode tableau, la hiérarchie se **replie / déplie à chaque niveau** (voir ci-dessous)
- **Par catégorie** : évolution de chaque catégorie, en lignes ou tableau pivot
### Rapport Comparables (`/reports/compare`)
@ -331,10 +329,6 @@ Trois modes accessibles via un tab bar :
- **Année vs année précédente** — même logique sur 12 mois vs 12 mois
- **Réel vs budget** — reprend la vue Budget vs Réel avec ses totaux mensuels et cumul annuel
#### Repli de la hiérarchie
Les trois modes ci-dessus, comme le tableau **Par catégorie** des Tendances, présentent les catégories en arbre repliable **à chaque niveau**. Chaque catégorie parente — y compris les niveaux intermédiaires — porte son propre chevron : le déplier révèle ses enfants directs (eux-mêmes repliés), de sorte que vous descendez d'un niveau à la fois. Le tableau s'ouvre **entièrement replié** (seules les catégories de premier niveau visibles) ; le bouton **« Tout déplier / Tout replier »** ouvre ou ferme tous les niveaux d'un coup. Replier une catégorie est **purement visuel** — les sous-totaux, totaux et lignes de résultat restent calculés sur l'ensemble des lignes, jamais sur les seules lignes visibles. Vos choix de repli sont **mémorisés par profil** (dans la base du profil, ils disparaissent donc avec lui).
### Rapport Zoom catégorie (`/reports/category`)
Choisissez une catégorie dans la combobox en haut. Par défaut le rapport inclut automatiquement les sous-catégories (toggle *Directe seulement* pour les exclure). Vous voyez :

View file

@ -1,11 +1,9 @@
import { useState, useRef, useEffect, Fragment } from "react";
import { useTranslation } from "react-i18next";
import { AlertTriangle, ArrowUpDown, ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide-react";
import { AlertTriangle, ArrowUpDown } from "lucide-react";
import type { BudgetYearRow } from "../../shared/types";
import { reorderRows } from "../../utils/reorderRows";
import type { CollapseAccessors } from "../../utils/collapsibleRows";
import { useCollapsibleGroups } from "../../hooks/useCollapsibleGroups";
import { computeBudgetResults, sumLeavesForType, type BudgetTotals } from "./budgetTableResults";
import { computeBudgetResults, type BudgetTotals } from "./budgetTableResults";
const fmt = new Intl.NumberFormat("en-CA", {
style: "currency",
@ -20,22 +18,7 @@ const MONTH_KEYS = [
"months.sep", "months.oct", "months.nov", "months.dec",
] as const;
// Prefixed so the "subtotals on top/bottom" preference is INDEPENDENT of the
// real-vs-budget report's (BudgetVsActualTable still uses "subtotals-position") —
// they collided before (issue #289).
const STORAGE_KEY = "budget-subtotals-position";
// Collapse groups keyed by category id; a row is hidden when any ancestor
// (walking parent_id) is collapsed, so every parent level is collapsible.
// Declared inline, mirroring ComparePeriodTable / BudgetVsActualTable (issue #289).
const BUDGET_COLLAPSE_ACCESSORS: CollapseAccessors<BudgetYearRow> = {
keyOf: (row) => `p:${row.category_id}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
depthOf: (row) => row.depth ?? 0,
isParent: (row) => row.is_parent,
};
const BUDGET_EXPANDED_KEY = "budget-grid-expanded";
const STORAGE_KEY = "subtotals-position";
interface BudgetTableProps {
rows: BudgetYearRow[];
@ -60,15 +43,6 @@ export default function BudgetTable({ rows, onUpdatePlanned, onSplitEvenly }: Bu
return next;
});
};
// Collapse/expand at every hierarchy level — collapsed by default (issue #289),
// matching the hierarchical reports. Persisted per profile in user_preferences.
const groups = useCollapsibleGroups<BudgetYearRow>(
BUDGET_EXPANDED_KEY,
BUDGET_COLLAPSE_ACCESSORS,
{ defaultExpanded: false },
);
const inputRef = useRef<HTMLInputElement>(null);
const annualInputRef = useRef<HTMLInputElement>(null);
@ -199,37 +173,24 @@ export default function BudgetTable({ rows, onUpdatePlanned, onSplitEvenly }: Bu
const rowKey = row.is_parent ? `parent-${row.category_id}` : `leaf-${row.category_id}-${row.category_name}`;
if (row.is_parent) {
// Parent subtotal row: read-only, bold, distinct background. Collapsible
// at every level (issue #289) — a chevron toggles its subtree.
// Parent subtotal row: read-only, bold, distinct background
const parentDepth = row.depth ?? 0;
const isTopParent = parentDepth === 0;
const isIntermediateParent = parentDepth >= 1;
const collapsed = groups.isCollapsed(row);
const parentPaddingClass = parentDepth >= 3 ? "pl-20 pr-3" : parentDepth === 2 ? "pl-14 pr-3" : parentDepth === 1 ? "pl-8 pr-3" : "px-3";
return (
<tr
key={rowKey}
aria-level={parentDepth + 1}
className={`border-b border-[var(--border)] ${isTopParent ? "bg-[var(--muted)]/30" : "bg-[var(--muted)]/15"}`}
>
<td className={`py-2 sticky left-0 z-10 ${isTopParent ? "px-3 bg-[var(--muted)]/30" : `${parentPaddingClass} bg-[var(--muted)]/15`}`}>
<button
type="button"
onClick={() => groups.toggle(row)}
aria-expanded={!collapsed}
className="flex items-center gap-2 w-full text-left hover:opacity-80 transition-opacity"
>
{collapsed ? (
<ChevronRight size={14} className="shrink-0 text-[var(--muted-foreground)]" />
) : (
<ChevronDown size={14} className="shrink-0 text-[var(--muted-foreground)]" />
)}
<div className="flex items-center gap-2">
<span
className="w-2.5 h-2.5 rounded-full shrink-0"
style={{ backgroundColor: row.category_color }}
/>
<span className={`truncate text-xs ${isIntermediateParent ? "font-medium" : "font-semibold"}`}>{row.category_name}</span>
</button>
</div>
</td>
<td className={`py-2 px-2 text-right text-xs ${isIntermediateParent ? "font-medium" : "font-semibold"} text-[var(--muted-foreground)]`}>
{formatSigned(row.previousYearTotal)}
@ -250,7 +211,6 @@ export default function BudgetTable({ rows, onUpdatePlanned, onSplitEvenly }: Bu
return (
<tr
key={rowKey}
aria-level={depth + 1}
className="border-b border-[var(--border)] last:border-b-0 hover:bg-[var(--muted)]/50 transition-colors"
>
{/* Category name - sticky */}
@ -337,11 +297,18 @@ export default function BudgetTable({ rows, onUpdatePlanned, onSplitEvenly }: Bu
const renderTypeSection = (type: (typeof typeOrder)[number]) => {
const group = grouped[type];
if (!group || group.length === 0) return null;
// Section subtotal is summed from the RAW group via the tested
// `sumLeavesForType` (leaves only, sign applied to budgeted figures), never
// from the collapse-filtered rows — folding a parent stays purely visual and
// never moves a total (issue #289).
const sectionTotals = sumLeavesForType(group, type);
const sign = signFor(type);
const leaves = group.filter((r) => !r.is_parent);
const sectionMonthTotals: number[] = Array(12).fill(0);
let sectionAnnualTotal = 0;
let sectionPrevYearTotal = 0;
for (const row of leaves) {
for (let m = 0; m < 12; m++) {
sectionMonthTotals[m] += row.months[m] * sign;
}
sectionAnnualTotal += row.annual * sign;
sectionPrevYearTotal += row.previousYearTotal; // actuals are already signed in the DB
}
return (
<Fragment key={type}>
<tr>
@ -352,14 +319,14 @@ export default function BudgetTable({ rows, onUpdatePlanned, onSplitEvenly }: Bu
{t(typeLabelKeys[type])}
</td>
</tr>
{reorderRows(groups.visible(group), subtotalsOnTop).map((row) => renderRow(row))}
{reorderRows(group, subtotalsOnTop).map((row) => renderRow(row))}
<tr className="bg-[var(--muted)]/40 border-b border-[var(--border)]">
<td className="py-2.5 px-3 sticky left-0 bg-[var(--muted)]/40 z-10 text-sm font-semibold">
{t(typeTotalKeys[type])}
</td>
<td className="py-2.5 px-2 text-right text-sm font-semibold text-[var(--muted-foreground)]">{formatSigned(sectionTotals.previousYearTotal)}</td>
<td className="py-2.5 px-2 text-right text-sm font-semibold">{formatSigned(sectionTotals.annual)}</td>
{sectionTotals.months.map((total, mIdx) => (
<td className="py-2.5 px-2 text-right text-sm font-semibold text-[var(--muted-foreground)]">{formatSigned(sectionPrevYearTotal)}</td>
<td className="py-2.5 px-2 text-right text-sm font-semibold">{formatSigned(sectionAnnualTotal)}</td>
{sectionMonthTotals.map((total, mIdx) => (
<td key={mIdx} className="py-2.5 px-2 text-right text-sm font-semibold">
{formatSigned(total)}
</td>
@ -395,22 +362,9 @@ export default function BudgetTable({ rows, onUpdatePlanned, onSplitEvenly }: Bu
);
};
const hasGroups = groups.groupCount(rows) > 0;
const allExpanded = groups.allExpanded(rows);
return (
<div className="bg-[var(--card)] rounded-xl border border-[var(--border)] overflow-hidden">
<div className="flex justify-end items-center gap-1 px-3 py-2 border-b border-[var(--border)]">
{hasGroups && (
<button
type="button"
onClick={() => (allExpanded ? groups.collapseAll(rows) : groups.expandAll(rows))}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)] transition-colors"
>
{allExpanded ? <ChevronsDownUp size={13} /> : <ChevronsUpDown size={13} />}
{allExpanded ? t("reports.collapse.collapseAll") : t("reports.collapse.expandAll")}
</button>
)}
<div className="flex justify-end px-3 py-2 border-b border-[var(--border)]">
<button
onClick={toggleSubtotals}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)] transition-colors"

View file

@ -1,27 +1,22 @@
import { useMemo, useState } from "react";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { ArrowRight, ChevronsDownUp, ChevronsUpDown, Search } from "lucide-react";
import { useCategoryTaxonomy } from "../../hooks/useCategoryTaxonomy";
import CategoryTaxonomyTree, {
TAXONOMY_COLLAPSE_ACCESSORS,
} from "../categories/CategoryTaxonomyTree";
import CategoryTaxonomyTree from "../categories/CategoryTaxonomyTree";
import type { TaxonomyNode } from "../../services/categoryTaxonomyService";
import { useCollapsibleGroups } from "../../hooks/useCollapsibleGroups";
interface StepDiscoverProps {
onNext: () => void;
}
// Flattens the taxonomy so the hook's bulk ops (expand/collapse all, allExpanded)
// can walk every parent at any depth.
function flattenNodes(nodes: TaxonomyNode[]): TaxonomyNode[] {
const flat: TaxonomyNode[] = [];
function collectAllIds(nodes: TaxonomyNode[]): number[] {
const ids: number[] = [];
const walk = (n: TaxonomyNode) => {
flat.push(n);
ids.push(n.id);
n.children.forEach(walk);
};
nodes.forEach(walk);
return flat;
return ids;
}
function countNodes(nodes: TaxonomyNode[]): {
@ -57,23 +52,25 @@ export default function StepDiscover({ onNext }: StepDiscoverProps) {
const { t } = useTranslation();
const { taxonomy } = useCategoryTaxonomy();
const [search, setSearch] = useState("");
// State machine only (issue #290): in-memory (storageKey null), collapsed by
// default — same as the standalone guide page it shares CategoryTaxonomyTree with.
const groups = useCollapsibleGroups<TaxonomyNode>(null, TAXONOMY_COLLAPSE_ACCESSORS, {
defaultExpanded: false,
});
const [expanded, setExpanded] = useState<Set<number>>(() => new Set());
const counts = countNodes(taxonomy.roots);
const total = counts.roots + counts.subcategories + counts.leaves;
const flatNodes = useMemo(() => flattenNodes(taxonomy.roots), [taxonomy.roots]);
const toggleNode = (id: number) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const handleExpandAll = () => groups.expandAll(flatNodes);
const handleCollapseAll = () => groups.collapseAll(flatNodes);
// Correct "all expanded" test (issue #290): every group must be open, fixing the
// old expanded.size > 0 bug that flipped the button after a single expand.
const allExpanded = groups.allExpanded(flatNodes);
const handleExpandAll = () => {
setExpanded(new Set(collectAllIds(taxonomy.roots)));
};
const handleCollapseAll = () => setExpanded(new Set());
const allExpanded = expanded.size > 0;
return (
<section className="space-y-6">
@ -149,8 +146,8 @@ export default function StepDiscover({ onNext }: StepDiscoverProps) {
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-3">
<CategoryTaxonomyTree
nodes={taxonomy.roots}
isCollapsed={groups.isCollapsed}
onToggle={groups.toggle}
expanded={expanded}
onToggle={toggleNode}
searchQuery={search}
/>
</div>

View file

@ -2,49 +2,33 @@ import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { ChevronRight, ChevronDown } from "lucide-react";
import type { TaxonomyNode } from "../../services/categoryTaxonomyService";
import type { CollapseAccessors } from "../../utils/collapsibleRows";
/**
* Collapse-state accessors for the taxonomy tree, shared by every consumer that
* drives it through `useCollapsibleGroups` (the guide page and the migration
* wizard's Discover step) issue #290. Only keyOf/isParent are consulted: the
* tree renders recursively and gates each node on `isCollapsed(node)`, so it never
* calls `visibleRows`; parentKeyOf/depthOf are unused stubs (TaxonomyNode carries
* no parent_id).
*/
export const TAXONOMY_COLLAPSE_ACCESSORS: CollapseAccessors<TaxonomyNode> = {
keyOf: (node) => `p:${node.id}`,
parentKeyOf: () => null,
isParent: (node) => node.children.length > 0,
depthOf: () => 0,
};
interface CategoryTaxonomyTreeProps {
nodes: TaxonomyNode[];
isCollapsed: (node: TaxonomyNode) => boolean;
onToggle: (node: TaxonomyNode) => void;
expanded: Set<number>;
onToggle: (id: number) => void;
searchQuery: string;
}
interface NodeRowProps {
node: TaxonomyNode;
depth: number;
isCollapsed: (node: TaxonomyNode) => boolean;
onToggle: (node: TaxonomyNode) => void;
expanded: Set<number>;
onToggle: (id: number) => void;
visibleIds: Set<number> | null;
}
function NodeRow({
node,
depth,
isCollapsed,
expanded,
onToggle,
visibleIds,
}: NodeRowProps) {
const { t } = useTranslation();
const label = t(node.i18n_key, { defaultValue: node.name });
const hasChildren = node.children.length > 0;
const isExpanded = !isCollapsed(node);
const isExpanded = expanded.has(node.id);
// Filter children by visibility set (search mode) if provided.
const visibleChildren = useMemo(() => {
@ -79,7 +63,7 @@ function NodeRow({
{hasChildren ? (
<button
type="button"
onClick={() => onToggle(node)}
onClick={() => onToggle(node.id)}
aria-label={
isExpanded
? t("categoriesSeed.guidePage.collapseAll")
@ -130,7 +114,7 @@ function NodeRow({
key={child.id}
node={child}
depth={depth + 1}
isCollapsed={isCollapsed}
expanded={expanded}
onToggle={onToggle}
visibleIds={visibleIds}
/>
@ -188,7 +172,7 @@ export function normalize(s: string): string {
export default function CategoryTaxonomyTree({
nodes,
isCollapsed,
expanded,
onToggle,
searchQuery,
}: CategoryTaxonomyTreeProps) {
@ -220,7 +204,7 @@ export default function CategoryTaxonomyTree({
key={root.id}
node={root}
depth={0}
isCollapsed={isCollapsed}
expanded={expanded}
onToggle={onToggle}
visibleIds={visibleIds}
/>

View file

@ -18,8 +18,6 @@ import {
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { CategoryTreeNode } from "../../shared/types";
import type { CollapseAccessors } from "../../utils/collapsibleRows";
import { useCollapsibleGroups } from "../../hooks/useCollapsibleGroups";
interface FlatItem {
id: number;
@ -42,28 +40,14 @@ function getSubtreeDepth(node: CategoryTreeNode): number {
return 1 + Math.max(...node.children.map(getSubtreeDepth));
}
// State machine shared with useCollapsibleGroups (issue #290). Only keyOf/isParent
// are consulted here: this tree renders recursively and gates each node on
// isCollapsed(node), so it never calls visibleRows — parentKeyOf/depthOf exist to
// satisfy the accessor contract but are not read (depth is computed in flattenTree).
const CATEGORY_TREE_ACCESSORS: CollapseAccessors<CategoryTreeNode> = {
keyOf: (node) => `p:${node.id}`,
parentKeyOf: (node) => (node.parent_id != null ? `p:${node.parent_id}` : null),
isParent: (node) => node.children.length > 0,
depthOf: () => 0,
};
function flattenTree(
tree: CategoryTreeNode[],
isExpanded: (node: CategoryTreeNode) => boolean,
): FlatItem[] {
function flattenTree(tree: CategoryTreeNode[], expandedSet: Set<number>): FlatItem[] {
const items: FlatItem[] = [];
function recurse(nodes: CategoryTreeNode[], depth: number, parentId: number | null) {
for (const node of nodes) {
const hasChildren = node.children.length > 0;
const expanded = hasChildren && isExpanded(node);
items.push({ id: node.id, node, depth, parentId, isExpanded: expanded, hasChildren });
if (expanded) {
const isExpanded = expandedSet.has(node.id);
items.push({ id: node.id, node, depth, parentId, isExpanded, hasChildren });
if (isExpanded && hasChildren) {
recurse(node.children, depth + 1, node.id);
}
}
@ -169,7 +153,7 @@ function SortableTreeRow({
item: FlatItem;
selectedId: number | null;
onSelect: (id: number) => void;
onToggle: (node: CategoryTreeNode) => void;
onToggle: (id: number) => void;
isDragActive: boolean;
}) {
const {
@ -196,7 +180,7 @@ function SortableTreeRow({
selectedId={isDragActive ? null : selectedId}
onSelect={onSelect}
expanded={item.isExpanded}
onToggle={() => onToggle(item.node)}
onToggle={() => onToggle(item.id)}
hasChildren={item.hasChildren}
dragHandleProps={listeners}
isDragging={isDragging}
@ -206,20 +190,23 @@ function SortableTreeRow({
}
export default function CategoryTree({ tree, selectedId, onSelect, onMoveCategory }: Props) {
// State machine only (issue #290): in-memory (storageKey null), expanded by
// default (defaultExpanded true) so every parent opens with no seeding — the
// previous collectExpandable + local Set behaviour. Render + DnD stay untouched.
const { isCollapsed, toggle } = useCollapsibleGroups<CategoryTreeNode>(
null,
CATEGORY_TREE_ACCESSORS,
{ defaultExpanded: true },
);
const [expanded, setExpanded] = useState<Set<number>>(() => {
const ids = new Set<number>();
function collectExpandable(nodes: CategoryTreeNode[]) {
for (const node of nodes) {
if (node.children.length > 0) {
ids.add(node.id);
collectExpandable(node.children);
}
}
}
collectExpandable(tree);
return ids;
});
const [activeId, setActiveId] = useState<number | null>(null);
const flatItems = useMemo(
() => flattenTree(tree, (node) => !isCollapsed(node)),
[tree, isCollapsed],
);
// Update expanded set when tree changes (new parents appear)
const flatItems = useMemo(() => flattenTree(tree, expanded), [tree, expanded]);
const activeItem = useMemo(
() => (activeId !== null ? flatItems.find((i) => i.id === activeId) ?? null : null),
@ -232,6 +219,15 @@ export default function CategoryTree({ tree, selectedId, onSelect, onMoveCategor
})
);
const toggle = useCallback((id: number) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}, []);
const handleDragStart = useCallback((event: DragStartEvent) => {
setActiveId(event.active.id as number);
}, []);

View file

@ -29,11 +29,11 @@ interface BudgetVsActualTableProps {
const STORAGE_KEY = "subtotals-position";
// Collapse groups keyed by category id; a row is hidden when any ancestor
// (walking parent_id) is collapsed, so every parent level is collapsible.
// Collapse groups keyed by category id; depth mirrors the render logic below
// (a missing depth is derived from parent_id) so hidden rows are exactly a
// group's indented descendants.
const BVA_COLLAPSE_ACCESSORS: CollapseAccessors<BudgetVsActualRow> = {
keyOf: (row) => `p:${row.category_id}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
keyOf: (row) => String(row.category_id),
depthOf: (row) => row.depth ?? (row.parent_id !== null && !row.is_parent ? 1 : 0),
isParent: (row) => row.is_parent,
};
@ -116,12 +116,11 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
const depth = row.depth ?? (row.parent_id !== null && !row.is_parent ? 1 : 0);
const isTopParent = isParent && depth === 0;
const isIntermediateParent = isParent && depth >= 1;
const collapsed = isParent && groups.isCollapsed(row);
const collapsed = isTopParent && groups.isCollapsed(row);
const paddingClass = depth >= 3 ? "pl-20" : depth === 2 ? "pl-14" : depth === 1 ? "pl-8" : "px-3";
return (
<tr
key={`${row.category_id}-${row.is_parent}-${depth}`}
aria-level={isParent ? depth + 1 : undefined}
className={`border-b border-[var(--border)]/50 ${
isTopParent ? "bg-[color-mix(in_srgb,var(--muted)_30%,var(--card))] font-semibold" :
isIntermediateParent ? "bg-[color-mix(in_srgb,var(--muted)_15%,var(--card))] font-medium" : ""
@ -134,7 +133,7 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
? `${paddingClass} bg-[color-mix(in_srgb,var(--muted)_15%,var(--card))]`
: `${paddingClass} bg-[var(--card)]`
}`}>
{isParent ? (
{isTopParent ? (
<button
type="button"
onClick={() => groups.toggle(row)}
@ -256,7 +255,7 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
{hasGroups && (
<button
type="button"
onClick={() => (allExpanded ? groups.collapseAll(data) : groups.expandAll(data))}
onClick={() => (allExpanded ? groups.collapseAll() : groups.expandAll(data))}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)] transition-colors"
>
{allExpanded ? <ChevronsDownUp size={13} /> : <ChevronsUpDown size={13} />}

View file

@ -93,13 +93,12 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
const depth = row.depth;
const isTopParent = isParent && depth === 0;
const isIntermediateParent = isParent && depth >= 1;
const collapsed = isParent && groups.isCollapsed(row);
const collapsed = isTopParent && groups.isCollapsed(row);
const paddingClass =
depth >= 3 ? "pl-20" : depth === 2 ? "pl-14" : depth === 1 ? "pl-8" : "px-3";
return (
<tr
key={`${row.categoryId ?? "uncat"}-${isParent}-${depth}-${row.categoryName}`}
aria-level={isParent ? depth + 1 : undefined}
className={`border-b border-[var(--border)]/50 ${
isTopParent
? "bg-[color-mix(in_srgb,var(--muted)_30%,var(--card))] font-semibold"
@ -117,7 +116,7 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
: `${paddingClass} bg-[var(--card)]`
}`}
>
{isParent ? (
{isTopParent ? (
<button
type="button"
onClick={() => groups.toggle(row)}
@ -212,7 +211,7 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
<div className="flex justify-end items-center gap-1 px-3 py-2 border-b border-[var(--border)]">
<button
type="button"
onClick={() => (allExpanded ? groups.collapseAll(data.tree) : groups.expandAll(data.tree))}
onClick={() => (allExpanded ? groups.collapseAll() : groups.expandAll(data.tree))}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)] transition-colors"
>
{allExpanded ? <ChevronsDownUp size={13} /> : <ChevronsUpDown size={13} />}

View file

@ -0,0 +1,74 @@
import { useTranslation } from "react-i18next";
import type { CategoryBreakdownItem } from "../../shared/types";
const cadFormatter = (value: number) =>
new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(value);
interface CategoryTableProps {
data: CategoryBreakdownItem[];
hiddenCategories?: Set<string>;
}
export default function CategoryTable({ data, hiddenCategories }: CategoryTableProps) {
const { t } = useTranslation();
const visibleData = hiddenCategories?.size
? data.filter((d) => !hiddenCategories.has(d.category_name))
: data;
if (visibleData.length === 0) {
return (
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-8 text-center text-[var(--muted-foreground)]">
{t("dashboard.noData")}
</div>
);
}
const grandTotal = visibleData.reduce((sum, row) => sum + row.total, 0);
return (
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl overflow-hidden">
<div className="overflow-x-auto overflow-y-auto" style={{ maxHeight: "calc(100vh - 220px)" }}>
<table className="w-full text-sm">
<thead className="sticky top-0 z-20">
<tr className="border-b border-[var(--border)] bg-[var(--card)]">
<th className="text-left px-3 py-2 font-medium text-[var(--muted-foreground)] bg-[var(--card)]">
{t("budget.category")}
</th>
<th className="text-right px-3 py-2 font-medium text-[var(--muted-foreground)] bg-[var(--card)]">
{t("common.total")}
</th>
<th className="text-right px-3 py-2 font-medium text-[var(--muted-foreground)] bg-[var(--card)]">
%
</th>
</tr>
</thead>
<tbody>
{visibleData.map((row) => (
<tr key={row.category_id ?? "uncategorized"} className="border-b border-[var(--border)]/50">
<td className="px-3 py-1.5">
<span className="flex items-center gap-2">
<span
className="w-2.5 h-2.5 rounded-full shrink-0"
style={{ backgroundColor: row.category_color }}
/>
{row.category_name}
</span>
</td>
<td className="text-right px-3 py-1.5">{cadFormatter(row.total)}</td>
<td className="text-right px-3 py-1.5 text-[var(--muted-foreground)]">
{grandTotal !== 0 ? `${((row.total / grandTotal) * 100).toFixed(1)}%` : "—"}
</td>
</tr>
))}
<tr className="border-t-2 border-[var(--border)] font-bold text-sm bg-[var(--muted)]/20">
<td className="px-3 py-3">{t("common.total")}</td>
<td className="text-right px-3 py-3">{cadFormatter(grandTotal)}</td>
<td className="text-right px-3 py-3 text-[var(--muted-foreground)]">100%</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}

View file

@ -59,11 +59,10 @@ function deltaColor(value: number, higherIsBetter: boolean): string {
const STORAGE_KEY = "compare-subtotals-position";
// Collapse groups keyed by category id; a row is hidden when any ancestor
// (walking parent_id) is collapsed, so every parent level is collapsible.
// Collapse groups keyed by category id; depth/parent mirror the render logic
// below so the hidden rows are exactly a group's indented descendants.
const COMPARE_COLLAPSE_ACCESSORS: CollapseAccessors<CategoryDelta> = {
keyOf: (row) => `p:${row.categoryId}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
keyOf: (row) => String(row.categoryId),
depthOf: (row) => row.depth ?? 0,
isParent: (row) => row.is_parent ?? false,
};
@ -155,13 +154,12 @@ export default function ComparePeriodTable({
const depth = row.depth ?? 0;
const isTopParent = isParent && depth === 0;
const isIntermediateParent = isParent && depth >= 1;
const collapsed = isParent && groups.isCollapsed(row);
const collapsed = isTopParent && groups.isCollapsed(row);
const paddingClass =
depth >= 3 ? "pl-20" : depth === 2 ? "pl-14" : depth === 1 ? "pl-8" : "px-3";
return (
<tr
key={`${row.categoryId ?? "uncat"}-${isParent}-${depth}-${row.categoryName}`}
aria-level={isParent ? depth + 1 : undefined}
className={`border-b border-[var(--border)]/50 ${
isTopParent
? "bg-[color-mix(in_srgb,var(--muted)_30%,var(--card))] font-semibold"
@ -179,7 +177,7 @@ export default function ComparePeriodTable({
: `${paddingClass} bg-[var(--card)]`
}`}
>
{isParent ? (
{isTopParent ? (
<button
type="button"
onClick={() => groups.toggle(row)}
@ -351,7 +349,7 @@ export default function ComparePeriodTable({
{hasGroups && (
<button
type="button"
onClick={() => (allExpanded ? groups.collapseAll(rows) : groups.expandAll(rows))}
onClick={() => (allExpanded ? groups.collapseAll() : groups.expandAll(rows))}
className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)] transition-colors"
>
{allExpanded ? <ChevronsDownUp size={13} /> : <ChevronsUpDown size={13} />}

View file

@ -45,26 +45,23 @@ function makeData(months: string[], tree: OverTimeRow[]): CategoryOverTimeData {
const MONTHS = ["2025-01", "2025-02"];
// A realistic parent-first depth-first tree, three levels deep on the expense
// side (income → expense → transfer):
// A realistic parent-first depth-first tree (income → expense → transfer):
// Revenus (parent, id 1)
// Paie (leaf, id 11)
// Bonus (leaf, id 12)
// Paie (leaf, id 11)
// Bonus (leaf, id 12)
// Dépenses (parent, id 2)
// Alimentation (INTERMEDIATE parent, id 20)
// Épicerie (leaf, id 21)
// Resto (leaf, id 22)
// Loyer (top-level leaf, id 23)
// Épargne (transfer leaf, id 3)
// Épicerie (leaf, id 21)
// Resto (leaf, id 22)
// Loyer (top-level leaf, id 23)
// Épargne (transfer leaf, id 3)
function buildTree(): OverTimeRow[] {
return [
mkRow(1, "Revenus", [3000, 3500], "income", { is_parent: true, depth: 0 }),
mkRow(11, "Paie", [3000, 3000], "income", { parent_id: 1, depth: 1 }),
mkRow(12, "Bonus", [0, 500], "income", { parent_id: 1, depth: 1 }),
mkRow(2, "Dépenses", [500, 800], "expense", { is_parent: true, depth: 0 }),
mkRow(20, "Alimentation", [500, 800], "expense", { is_parent: true, parent_id: 2, depth: 1 }),
mkRow(21, "Épicerie", [400, 600], "expense", { parent_id: 20, depth: 2 }),
mkRow(22, "Resto", [100, 200], "expense", { parent_id: 20, depth: 2 }),
mkRow(21, "Épicerie", [400, 600], "expense", { parent_id: 2, depth: 1 }),
mkRow(22, "Resto", [100, 200], "expense", { parent_id: 2, depth: 1 }),
mkRow(23, "Loyer", [1000, 1000], "expense", { depth: 0 }),
mkRow(3, "Épargne", [200, 200], "transfer", { depth: 0 }),
];
@ -73,7 +70,6 @@ function buildTree(): OverTimeRow[] {
const acc = OVERTIME_COLLAPSE_ACCESSORS;
/** Mirrors the hook: a group is collapsed unless its key is in the expanded set. */
const isCollapsed = (expanded: Set<string>) => (row: OverTimeRow) => !expanded.has(acc.keyOf(row));
const names = (rows: OverTimeRow[]) => rows.map((r) => r.categoryName);
describe("overTimeTableModel — storage key", () => {
it("uses a trends-specific key, distinct from the comparable tables", () => {
@ -83,18 +79,13 @@ describe("overTimeTableModel — storage key", () => {
});
describe("overTimeTableModel — collapse accessors", () => {
it("keys parents/leaves injectively (p:<id>) and climbs parent_id", () => {
const revenus = buildTree()[0]; // parent
const paie = buildTree()[1]; // leaf under Revenus
const alimentation = buildTree()[4]; // intermediate parent
expect(acc.keyOf(revenus)).toBe("p:1");
expect(acc.parentKeyOf(revenus)).toBeNull(); // root
expect(acc.parentKeyOf(paie)).toBe("p:1"); // climbs to Revenus
expect(acc.parentKeyOf(alimentation)).toBe("p:2"); // climbs to Dépenses
expect(acc.depthOf(paie)).toBe(1);
expect(acc.isParent(revenus)).toBe(true);
expect(acc.isParent(paie)).toBe(false);
expect(acc.isParent(alimentation)).toBe(true);
it("keys by category id and reads the snake_case hierarchy block", () => {
const parent = buildTree()[0];
const leaf = buildTree()[1];
expect(acc.keyOf(parent)).toBe("1");
expect(acc.depthOf(leaf)).toBe(1);
expect(acc.isParent(parent)).toBe(true);
expect(acc.isParent(leaf)).toBe(false);
});
});
@ -110,14 +101,12 @@ describe("overTimeTableModel.groupOverTimeSections", () => {
// Full hierarchy: the parent row is present (unlike the leaves-only reducer sections).
const income = nonTransferSections.find((s) => s.type === "income")!;
expect(names(income.rows)).toEqual(["Revenus", "Paie", "Bonus"]);
expect(income.rows.map((r) => r.categoryName)).toEqual(["Revenus", "Paie", "Bonus"]);
expect(income.rows[0].is_parent).toBe(true);
// Expense carries the intermediate parent (Alimentation) too, parent-first.
const expense = nonTransferSections.find((s) => s.type === "expense")!;
expect(names(expense.rows)).toEqual([
expect(expense.rows.map((r) => r.categoryName)).toEqual([
"Dépenses",
"Alimentation",
"Épicerie",
"Resto",
"Loyer",
@ -125,7 +114,7 @@ describe("overTimeTableModel.groupOverTimeSections", () => {
expect(transferSection?.rows.map((r) => r.categoryName)).toEqual(["Épargne"]);
});
it("keeps subtotals as the reducer's leaf sums — parents (incl. intermediate) are never double-counted", () => {
it("keeps subtotals as the reducer's leaf sums — a parent is never double-counted", () => {
const data = makeData(MONTHS, buildTree());
const analysis = computeOverTimeResults(data);
const { nonTransferSections } = groupOverTimeSections(analysis, data.tree);
@ -136,8 +125,7 @@ describe("overTimeTableModel.groupOverTimeSections", () => {
expect(income.monthly).toEqual({ "2025-01": 3000, "2025-02": 3500 });
const expense = nonTransferSections.find((s) => s.type === "expense")!;
// Épicerie 1000 + Resto 300 + Loyer 2000 = 3300 (Dépenses AND Alimentation
// parents excluded, even though Alimentation carries a [500,800] series).
// Épicerie 1000 + Resto 300 + Loyer 2000 = 3300 (Dépenses parent excluded).
expect(expense.total).toBe(3300);
});
@ -160,13 +148,12 @@ describe("overTimeTableModel — collapse behaviour (via visibleRows)", () => {
const income = nonTransferSections.find((s) => s.type === "income")!;
const visIncome = visibleRows(income.rows, acc, isCollapsed(new Set()));
// Revenus stays (its own subtotal row); Paie/Bonus are folded away.
expect(names(visIncome)).toEqual(["Revenus"]);
expect(visIncome.map((r) => r.categoryName)).toEqual(["Revenus"]);
const expense = nonTransferSections.find((s) => s.type === "expense")!;
const visExpense = visibleRows(expense.rows, acc, isCollapsed(new Set()));
// Dépenses folds its whole subtree (Alimentation + its leaves); the top-level
// leaf Loyer always stays.
expect(names(visExpense)).toEqual(["Dépenses", "Loyer"]);
// Dépenses folds its children; the top-level leaf Loyer always stays.
expect(visExpense.map((r) => r.categoryName)).toEqual(["Dépenses", "Loyer"]);
});
it("reveals Paie (revenue) under Revenus once its group is expanded", () => {
@ -174,55 +161,28 @@ describe("overTimeTableModel — collapse behaviour (via visibleRows)", () => {
const { nonTransferSections } = groupOverTimeSections(computeOverTimeResults(data), data.tree);
const income = nonTransferSections.find((s) => s.type === "income")!;
const visible = visibleRows(income.rows, acc, isCollapsed(new Set(["p:1"])));
expect(names(visible)).toEqual(["Revenus", "Paie", "Bonus"]);
const visible = visibleRows(income.rows, acc, isCollapsed(new Set(["1"])));
expect(visible.map((r) => r.categoryName)).toEqual(["Revenus", "Paie", "Bonus"]);
expect(visible.some((r) => r.categoryName === "Paie")).toBe(true);
});
it("cascades across three levels: a root reveals only its direct child parent, not the leaves", () => {
const data = makeData(MONTHS, buildTree());
const { nonTransferSections } = groupOverTimeSections(computeOverTimeResults(data), data.tree);
const expense = nonTransferSections.find((s) => s.type === "expense")!;
// Expand Dépenses only: Alimentation (direct child) shows, Loyer stays, but
// Épicerie/Resto (grandchildren under the still-collapsed Alimentation) do NOT.
const rootOnly = visibleRows(expense.rows, acc, isCollapsed(new Set(["p:2"])));
expect(names(rootOnly)).toEqual(["Dépenses", "Alimentation", "Loyer"]);
// Expand Dépenses AND Alimentation: the leaves finally appear.
const bothOpen = visibleRows(expense.rows, acc, isCollapsed(new Set(["p:2", "p:20"])));
expect(names(bothOpen)).toEqual(["Dépenses", "Alimentation", "Épicerie", "Resto", "Loyer"]);
// Expand the intermediate but NOT the root: a collapsed ancestor wins, nothing
// under Dépenses is revealed.
const intermediateOnly = visibleRows(expense.rows, acc, isCollapsed(new Set(["p:20"])));
expect(names(intermediateOnly)).toEqual(["Dépenses", "Loyer"]);
});
it("collapse is purely visual: subtotals, before-transfers and net are unchanged", () => {
const data = makeData(MONTHS, buildTree());
const analysis = computeOverTimeResults(data);
const { nonTransferSections } = groupOverTimeSections(analysis, data.tree);
const income = nonTransferSections.find((s) => s.type === "income")!;
const expense = nonTransferSections.find((s) => s.type === "expense")!;
// Figures come from the raw tree (never the visible rows), so they hold in
// every collapse state.
expect(analysis.beforeTransfers.total).toBe(3200); // 6500 income 3300 expense
expect(analysis.net.total).toBe(3600); // 3200 + 400 transfer
expect(income.total).toBe(6500);
expect(expense.total).toBe(3300);
// Folding vs expanding a group only changes how many rows are visible.
const collapsed = visibleRows(income.rows, acc, isCollapsed(new Set()));
const expanded = visibleRows(income.rows, acc, isCollapsed(new Set(["p:1"])));
const expanded = visibleRows(income.rows, acc, isCollapsed(new Set(["1"])));
expect(collapsed.length).toBeLessThan(expanded.length);
// Expanding the intermediate expense level does not move the section subtotal.
const expenseAllOpen = visibleRows(expense.rows, acc, isCollapsed(new Set(["p:2", "p:20"])));
expect(expenseAllOpen.length).toBeGreaterThan(
visibleRows(expense.rows, acc, isCollapsed(new Set())).length,
);
expect(expense.total).toBe(3300);
// The subtotal the table shows is identical in both states.
expect(income.total).toBe(6500);
});
});

View file

@ -10,14 +10,13 @@ import type { OverTimeAnalysis, OverTimeType } from "./overTimeResults";
*/
/**
* Collapse groups keyed by category id; a row is hidden when any ancestor
* (walking parent_id) is collapsed, so every parent level is collapsible. The
* Collapse groups keyed by category id; depth/parent mirror the tree the render
* indents by, so a collapsed group hides exactly its indented descendants. The
* `OverTimeRow` hierarchy block is snake_case (mirrors `CategoryDelta`), so these
* accessors compose with `collapsibleRows` / `useCollapsibleGroups` unchanged.
*/
export const OVERTIME_COLLAPSE_ACCESSORS: CollapseAccessors<OverTimeRow> = {
keyOf: (row) => `p:${row.categoryId}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
keyOf: (row) => String(row.categoryId),
depthOf: (row) => row.depth,
isParent: (row) => row.is_parent,
};

View file

@ -1,130 +0,0 @@
import { describe, it, expect } from "vitest";
import type { BudgetYearRow, Category, BudgetEntry } from "../shared/types";
import { buildBudgetYearRows } from "./useBudget";
import { sumLeavesForType } from "../components/budget/budgetTableResults";
import {
type CollapseAccessors,
visibleRows,
isCollapsedFor,
} from "../utils/collapsibleRows";
// The Budget grid's rows are built by `useBudget` (the "3rd builder" the
// abandoned v1 collapse plan ignored). Its final sort is LEVEL-ORDER (depth
// ascending / BFS), not depth-first. These tests pin that invariant: the
// shipped ancestor-walk collapse (issue #288) is order-INDEPENDENT, but the v1
// depth-cursor algorithm assumed DFS and would have broken exactly here.
function cat(
id: number,
name: string,
type: Category["type"],
opts: { parent_id?: number; is_inputable?: boolean; sort_order?: number } = {},
): Category {
return {
id,
name,
type,
parent_id: opts.parent_id,
color: "#000",
is_active: true,
is_inputable: opts.is_inputable ?? true,
sort_order: opts.sort_order ?? 0,
created_at: "",
};
}
// income leaf + a 3-level expense group:
// Housing (root, non-inputable)
// ├─ Rent (depth-1 leaf)
// └─ Utilities (depth-1 intermediate parent)
// ├─ Hydro (depth-2 leaf)
// └─ Internet (depth-2 leaf)
const CATEGORIES: Category[] = [
cat(10, "Salary", "income", { sort_order: 0 }),
cat(1, "Housing", "expense", { is_inputable: false, sort_order: 1 }),
cat(2, "Rent", "expense", { parent_id: 1, sort_order: 0 }),
cat(3, "Utilities", "expense", { parent_id: 1, is_inputable: false, sort_order: 1 }),
cat(4, "Hydro", "expense", { parent_id: 3, sort_order: 0 }),
cat(5, "Internet", "expense", { parent_id: 3, sort_order: 1 }),
];
function entry(category_id: number, amount: number, month = 1): BudgetEntry {
return { id: 0, category_id, year: 2026, month, amount, created_at: "", updated_at: "" };
}
// Same accessors BudgetTable declares inline — duplicated here (they are 4 trivial
// lambdas the issue mandates stay inline; a .tsx import into a node-env test would
// pull in JSX/lucide/react-i18next needlessly).
const ACCESSORS: CollapseAccessors<BudgetYearRow> = {
keyOf: (row) => `p:${row.category_id}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
depthOf: (row) => row.depth ?? 0,
isParent: (row) => row.is_parent,
};
describe("buildBudgetYearRows — level-order emission (issue #289 invariant)", () => {
const rows = buildBudgetYearRows(CATEGORIES, [], []);
it("emits income before expense, then each group in LEVEL order (BFS), not DFS", () => {
// Salary (income) first; then the Housing expense group depth-ascending:
// root subtotal, then the depth-1 rows (parent Utilities before leaf Rent),
// then the depth-2 grandchildren.
expect(rows.map((r) => r.category_id)).toEqual([10, 1, 3, 2, 4, 5]);
});
it("keeps depth non-decreasing within a top group — the property that would have killed the v1 (DFS-assuming) collapse algorithm", () => {
const expenseGroup = rows.filter((r) => r.category_type === "expense");
const depths = expenseGroup.map((r) => r.depth ?? 0);
for (let i = 1; i < depths.length; i++) {
expect(depths[i]).toBeGreaterThanOrEqual(depths[i - 1]);
}
// Explicit DFS-killer: the depth-2 grandchildren (Hydro/Internet) come AFTER
// the depth-1 leaf sibling (Rent). A depth-first emission would interleave
// them directly under Utilities, i.e. BEFORE Rent.
const leafIdx = (id: number) => rows.findIndex((r) => r.category_id === id && !r.is_parent);
expect(leafIdx(4)).toBeGreaterThan(leafIdx(2)); // Hydro after Rent
expect(leafIdx(5)).toBeGreaterThan(leafIdx(2)); // Internet after Rent
});
});
describe("buildBudgetYearRows + multi-level collapse (issue #289 end-to-end)", () => {
const rows = buildBudgetYearRows(CATEGORIES, [], []);
it("collapsed-by-default (empty set) shows only the roots", () => {
const isCollapsed = (r: BudgetYearRow) => isCollapsedFor(new Set<string>(), ACCESSORS.keyOf(r), false);
const visible = visibleRows(rows, ACCESSORS, isCollapsed);
// Salary (root leaf) + Housing (root subtotal); nothing beneath Housing.
expect(visible.map((r) => r.category_id)).toEqual([10, 1]);
});
it("expanding a root reveals its DIRECT children only — grandchildren stay folded under the still-collapsed intermediate", () => {
const flipped = new Set<string>(["p:1"]); // Housing expanded
const isCollapsed = (r: BudgetYearRow) => isCollapsedFor(flipped, ACCESSORS.keyOf(r), false);
const visible = visibleRows(rows, ACCESSORS, isCollapsed);
// Housing's direct children: Utilities subtotal + Rent leaf. Hydro/Internet
// remain hidden under the collapsed Utilities.
expect(visible.map((r) => r.category_id)).toEqual([10, 1, 3, 2]);
});
});
describe("BudgetTable section subtotals stay on RAW rows (collapse is purely visual, issue #289)", () => {
const ENTRIES = [entry(2, 1000), entry(4, 100), entry(5, 50)];
const rows = buildBudgetYearRows(CATEGORIES, ENTRIES, []);
it("sums every expense LEAF regardless of collapse — folding a parent never moves a total", () => {
const rawExpense = sumLeavesForType(rows, "expense");
expect(rawExpense.annual).toBe(-1150); // -(Rent 1000 + Hydro 100 + Internet 50)
// If the grid mistakenly summed the collapse-visible rows, a fully-collapsed
// grid (only roots visible, and the expense root is a parent → excluded)
// would report 0. The grid feeds the RAW group to `sumLeavesForType`, so the
// section total is invariant under collapse; this asserts the two differ,
// which is exactly why raw rows must be used.
const isCollapsed = (r: BudgetYearRow) => isCollapsedFor(new Set<string>(), ACCESSORS.keyOf(r), false);
const collapsedVisible = visibleRows(rows, ACCESSORS, isCollapsed);
const visibleExpense = sumLeavesForType(collapsedVisible, "expense");
expect(visibleExpense.annual).toBe(0);
expect(rawExpense.annual).not.toBe(visibleExpense.annual);
});
});

View file

@ -1,5 +1,5 @@
import { useReducer, useCallback, useEffect, useRef } from "react";
import type { BudgetYearRow, BudgetTemplate, ImportSource, Category, BudgetEntry } from "../shared/types";
import type { BudgetYearRow, BudgetTemplate, ImportSource } from "../shared/types";
import {
getAllActiveCategories,
getBudgetEntriesForYear,
@ -73,304 +73,6 @@ function reducer(state: BudgetState, action: BudgetAction): BudgetState {
// (`COMPARE_TYPE_ORDER` / `OVER_TIME_TYPE_ORDER`, income-first since #253).
const TYPE_ORDER: Record<string, number> = { income: 0, expense: 1, transfer: 2 };
/**
* Assembles the flat, hierarchical `BudgetYearRow[]` the grid renders from the
* raw category tree, this year's budget entries, and last year's actual totals.
*
* ORDERING INVARIANT (issue #289 the multi-level-collapse consumer). The
* final `rows.sort` below orders each top category group by DEPTH ASCENDING
* (level-order / BFS), NOT depth-first: within a group every depth-0 row
* precedes every depth-1 row, which precedes every depth-2 row. The abandoned
* v1 collapse algorithm wrongly assumed a depth-first emission order and broke
* exactly here; the shipped algorithm (ancestor walk see `collapsibleRows.ts`)
* is order-INDEPENDENT, so this sort needs NO change. The level-order property
* is pinned by `useBudget.test.ts` so a refactor can't silently reintroduce the
* v1 assumption do not reorder into DFS without revisiting the collapse
* consumer (`BudgetTable`).
*
* Pure (no DB, no React) so the invariant is unit-testable without a renderer
* the repo has no jsdom, so hook logic that must be tested is extracted here,
* the same way `useCompare.ts` exposes its pure helpers.
*/
export function buildBudgetYearRows(
allCategories: Category[],
entries: BudgetEntry[],
prevYearActuals: Array<{ category_id: number | null; actual: number }>,
): BudgetYearRow[] {
// Build a map: categoryId -> month(1-12) -> amount
const entryMap = new Map<number, Map<number, number>>();
for (const e of entries) {
if (!entryMap.has(e.category_id)) entryMap.set(e.category_id, new Map());
entryMap.get(e.category_id)!.set(e.month, e.amount);
}
// Build a map for previous year actuals: categoryId -> annual actual total
// Amounts are already signed (expenses negative, income positive) — stored as-is.
const prevYearTotalMap = new Map<number, number>();
for (const a of prevYearActuals) {
if (a.category_id != null) prevYearTotalMap.set(a.category_id, a.actual);
}
// Helper: build months array from entryMap
const buildMonths = (catId: number) => {
const monthMap = entryMap.get(catId);
const months: number[] = [];
let annual = 0;
for (let m = 1; m <= 12; m++) {
const val = monthMap?.get(m) ?? 0;
months.push(val);
annual += val;
}
const previousYearTotal = prevYearTotalMap.get(catId) ?? 0;
return { months, annual, previousYearTotal };
};
// Index categories by id and group children by parent_id
const catById = new Map(allCategories.map((c) => [c.id, c]));
const childrenByParent = new Map<number, typeof allCategories>();
for (const cat of allCategories) {
if (cat.parent_id) {
if (!childrenByParent.has(cat.parent_id)) childrenByParent.set(cat.parent_id, []);
childrenByParent.get(cat.parent_id)!.push(cat);
}
}
const rows: BudgetYearRow[] = [];
// Build rows for an intermediate parent (level 1 or 2 with children)
function buildLevel2Group(cat: typeof allCategories[0], grandparentId: number): BudgetYearRow[] {
const grandchildren = (childrenByParent.get(cat.id) || []).filter((c) => c.is_inputable);
if (grandchildren.length === 0 && cat.is_inputable) {
// Leaf at depth 2
const { months, annual, previousYearTotal } = buildMonths(cat.id);
return [{
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: grandparentId,
is_parent: false,
depth: 2,
months,
annual,
previousYearTotal,
}];
}
if (grandchildren.length === 0 && !cat.is_inputable) {
// Also check if it has non-inputable intermediate children with their own children
// This shouldn't happen at depth 3 (max 3 levels), but handle gracefully
return [];
}
const gcRows: BudgetYearRow[] = [];
if (cat.is_inputable) {
const { months, annual, previousYearTotal } = buildMonths(cat.id);
gcRows.push({
category_id: cat.id,
category_name: `${cat.name} (direct)`,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: cat.id,
is_parent: false,
depth: 2,
months,
annual,
previousYearTotal,
});
}
for (const gc of grandchildren) {
const { months, annual, previousYearTotal } = buildMonths(gc.id);
gcRows.push({
category_id: gc.id,
category_name: gc.name,
category_color: gc.color || cat.color || "#9ca3af",
category_type: gc.type,
parent_id: cat.id,
is_parent: false,
depth: 2,
months,
annual,
previousYearTotal,
});
}
if (gcRows.length === 0) return [];
// Build intermediate subtotal
const subMonths = Array(12).fill(0) as number[];
let subAnnual = 0;
let subPrevYear = 0;
for (const cr of gcRows) {
for (let m = 0; m < 12; m++) subMonths[m] += cr.months[m];
subAnnual += cr.annual;
subPrevYear += cr.previousYearTotal;
}
const subtotal: BudgetYearRow = {
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: grandparentId,
is_parent: true,
depth: 1,
months: subMonths,
annual: subAnnual,
previousYearTotal: subPrevYear,
};
gcRows.sort((a, b) => {
if (a.category_id === cat.id) return -1;
if (b.category_id === cat.id) return 1;
return a.category_name.localeCompare(b.category_name);
});
return [subtotal, ...gcRows];
}
// Identify top-level parents and standalone leaves
const topLevel = allCategories.filter((c) => !c.parent_id);
for (const cat of topLevel) {
const children = childrenByParent.get(cat.id) || [];
const inputableChildren = children.filter((c) => c.is_inputable);
const intermediateParents = children.filter((c) => !c.is_inputable && (childrenByParent.get(c.id) || []).length > 0);
if (inputableChildren.length === 0 && intermediateParents.length === 0 && cat.is_inputable) {
// Standalone leaf (no children) — regular editable row
const { months, annual, previousYearTotal } = buildMonths(cat.id);
rows.push({
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: null,
is_parent: false,
depth: 0,
months,
annual,
previousYearTotal,
});
} else if (inputableChildren.length > 0 || intermediateParents.length > 0) {
const allChildRows: BudgetYearRow[] = [];
// If parent is also inputable, create a "(direct)" fake-child row
if (cat.is_inputable) {
const { months, annual, previousYearTotal } = buildMonths(cat.id);
allChildRows.push({
category_id: cat.id,
category_name: `${cat.name} (direct)`,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: cat.id,
is_parent: false,
depth: 1,
months,
annual,
previousYearTotal,
});
}
for (const child of inputableChildren) {
const grandchildren = childrenByParent.get(child.id) || [];
if (grandchildren.length === 0) {
// Simple leaf at depth 1
const { months, annual, previousYearTotal } = buildMonths(child.id);
allChildRows.push({
category_id: child.id,
category_name: child.name,
category_color: child.color || cat.color || "#9ca3af",
category_type: child.type,
parent_id: cat.id,
is_parent: false,
depth: 1,
months,
annual,
previousYearTotal,
});
} else {
// Intermediate parent at depth 1 with grandchildren
allChildRows.push(...buildLevel2Group(child, cat.id));
}
}
// Non-inputable intermediate parents
for (const ip of intermediateParents) {
allChildRows.push(...buildLevel2Group(ip, cat.id));
}
if (allChildRows.length === 0) continue;
// Parent subtotal row: sum of leaf rows only (avoid double-counting)
const leafRows = allChildRows.filter((r) => !r.is_parent);
const parentMonths = Array(12).fill(0) as number[];
let parentAnnual = 0;
let parentPrevYear = 0;
for (const cr of leafRows) {
for (let m = 0; m < 12; m++) parentMonths[m] += cr.months[m];
parentAnnual += cr.annual;
parentPrevYear += cr.previousYearTotal;
}
rows.push({
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: null,
is_parent: true,
depth: 0,
months: parentMonths,
annual: parentAnnual,
previousYearTotal: parentPrevYear,
});
// Sort children alphabetically, but keep "(direct)" first
allChildRows.sort((a, b) => {
if (a.category_id === cat.id && !a.is_parent) return -1;
if (b.category_id === cat.id && !b.is_parent) return 1;
return a.category_name.localeCompare(b.category_name);
});
rows.push(...allChildRows);
}
// else: non-inputable parent with no inputable children — skip
}
// Sort by type, then within each type: keep hierarchy groups together
function getTopGroupId(r: BudgetYearRow): number {
if ((r.depth ?? 0) === 0) return r.category_id;
if (r.is_parent && r.parent_id === null) return r.category_id;
let pid = r.parent_id;
while (pid !== null) {
const pCat = catById.get(pid);
if (!pCat || !pCat.parent_id) return pid;
pid = pCat.parent_id;
}
return r.category_id;
}
rows.sort((a, b) => {
const typeA = TYPE_ORDER[a.category_type] ?? 9;
const typeB = TYPE_ORDER[b.category_type] ?? 9;
if (typeA !== typeB) return typeA - typeB;
const groupA = getTopGroupId(a);
const groupB = getTopGroupId(b);
if (groupA !== groupB) {
const catA = catById.get(groupA);
const catB = catById.get(groupB);
const orderA = catA?.sort_order ?? 999;
const orderB = catB?.sort_order ?? 999;
if (orderA !== orderB) return orderA - orderB;
return (catA?.name ?? "").localeCompare(catB?.name ?? "");
}
// Same group: sort by depth, then parent before children at same depth
if (a.is_parent !== b.is_parent && (a.depth ?? 0) === (b.depth ?? 0)) return a.is_parent ? -1 : 1;
if ((a.depth ?? 0) !== (b.depth ?? 0)) return (a.depth ?? 0) - (b.depth ?? 0);
if (a.parent_id && a.category_id === a.parent_id) return -1;
if (b.parent_id && b.category_id === b.parent_id) return 1;
return a.category_name.localeCompare(b.category_name);
});
return rows;
}
export function useBudget() {
const { accountIds } = useReportsPeriod();
const [state, dispatch] = useReducer(reducer, undefined, initialState);
@ -391,7 +93,276 @@ export function useBudget() {
if (fetchId !== fetchIdRef.current) return;
const rows = buildBudgetYearRows(allCategories, entries, prevYearActuals);
// Build a map: categoryId -> month(1-12) -> amount
const entryMap = new Map<number, Map<number, number>>();
for (const e of entries) {
if (!entryMap.has(e.category_id)) entryMap.set(e.category_id, new Map());
entryMap.get(e.category_id)!.set(e.month, e.amount);
}
// Build a map for previous year actuals: categoryId -> annual actual total
// Amounts are already signed (expenses negative, income positive) — stored as-is.
const prevYearTotalMap = new Map<number, number>();
for (const a of prevYearActuals) {
if (a.category_id != null) prevYearTotalMap.set(a.category_id, a.actual);
}
// Helper: build months array from entryMap
const buildMonths = (catId: number) => {
const monthMap = entryMap.get(catId);
const months: number[] = [];
let annual = 0;
for (let m = 1; m <= 12; m++) {
const val = monthMap?.get(m) ?? 0;
months.push(val);
annual += val;
}
const previousYearTotal = prevYearTotalMap.get(catId) ?? 0;
return { months, annual, previousYearTotal };
};
// Index categories by id and group children by parent_id
const catById = new Map(allCategories.map((c) => [c.id, c]));
const childrenByParent = new Map<number, typeof allCategories>();
for (const cat of allCategories) {
if (cat.parent_id) {
if (!childrenByParent.has(cat.parent_id)) childrenByParent.set(cat.parent_id, []);
childrenByParent.get(cat.parent_id)!.push(cat);
}
}
const rows: BudgetYearRow[] = [];
// Build rows for an intermediate parent (level 1 or 2 with children)
function buildLevel2Group(cat: typeof allCategories[0], grandparentId: number): BudgetYearRow[] {
const grandchildren = (childrenByParent.get(cat.id) || []).filter((c) => c.is_inputable);
if (grandchildren.length === 0 && cat.is_inputable) {
// Leaf at depth 2
const { months, annual, previousYearTotal } = buildMonths(cat.id);
return [{
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: grandparentId,
is_parent: false,
depth: 2,
months,
annual,
previousYearTotal,
}];
}
if (grandchildren.length === 0 && !cat.is_inputable) {
// Also check if it has non-inputable intermediate children with their own children
// This shouldn't happen at depth 3 (max 3 levels), but handle gracefully
return [];
}
const gcRows: BudgetYearRow[] = [];
if (cat.is_inputable) {
const { months, annual, previousYearTotal } = buildMonths(cat.id);
gcRows.push({
category_id: cat.id,
category_name: `${cat.name} (direct)`,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: cat.id,
is_parent: false,
depth: 2,
months,
annual,
previousYearTotal,
});
}
for (const gc of grandchildren) {
const { months, annual, previousYearTotal } = buildMonths(gc.id);
gcRows.push({
category_id: gc.id,
category_name: gc.name,
category_color: gc.color || cat.color || "#9ca3af",
category_type: gc.type,
parent_id: cat.id,
is_parent: false,
depth: 2,
months,
annual,
previousYearTotal,
});
}
if (gcRows.length === 0) return [];
// Build intermediate subtotal
const subMonths = Array(12).fill(0) as number[];
let subAnnual = 0;
let subPrevYear = 0;
for (const cr of gcRows) {
for (let m = 0; m < 12; m++) subMonths[m] += cr.months[m];
subAnnual += cr.annual;
subPrevYear += cr.previousYearTotal;
}
const subtotal: BudgetYearRow = {
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: grandparentId,
is_parent: true,
depth: 1,
months: subMonths,
annual: subAnnual,
previousYearTotal: subPrevYear,
};
gcRows.sort((a, b) => {
if (a.category_id === cat.id) return -1;
if (b.category_id === cat.id) return 1;
return a.category_name.localeCompare(b.category_name);
});
return [subtotal, ...gcRows];
}
// Identify top-level parents and standalone leaves
const topLevel = allCategories.filter((c) => !c.parent_id);
for (const cat of topLevel) {
const children = childrenByParent.get(cat.id) || [];
const inputableChildren = children.filter((c) => c.is_inputable);
const intermediateParents = children.filter((c) => !c.is_inputable && (childrenByParent.get(c.id) || []).length > 0);
if (inputableChildren.length === 0 && intermediateParents.length === 0 && cat.is_inputable) {
// Standalone leaf (no children) — regular editable row
const { months, annual, previousYearTotal } = buildMonths(cat.id);
rows.push({
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: null,
is_parent: false,
depth: 0,
months,
annual,
previousYearTotal,
});
} else if (inputableChildren.length > 0 || intermediateParents.length > 0) {
const allChildRows: BudgetYearRow[] = [];
// If parent is also inputable, create a "(direct)" fake-child row
if (cat.is_inputable) {
const { months, annual, previousYearTotal } = buildMonths(cat.id);
allChildRows.push({
category_id: cat.id,
category_name: `${cat.name} (direct)`,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: cat.id,
is_parent: false,
depth: 1,
months,
annual,
previousYearTotal,
});
}
for (const child of inputableChildren) {
const grandchildren = childrenByParent.get(child.id) || [];
if (grandchildren.length === 0) {
// Simple leaf at depth 1
const { months, annual, previousYearTotal } = buildMonths(child.id);
allChildRows.push({
category_id: child.id,
category_name: child.name,
category_color: child.color || cat.color || "#9ca3af",
category_type: child.type,
parent_id: cat.id,
is_parent: false,
depth: 1,
months,
annual,
previousYearTotal,
});
} else {
// Intermediate parent at depth 1 with grandchildren
allChildRows.push(...buildLevel2Group(child, cat.id));
}
}
// Non-inputable intermediate parents
for (const ip of intermediateParents) {
allChildRows.push(...buildLevel2Group(ip, cat.id));
}
if (allChildRows.length === 0) continue;
// Parent subtotal row: sum of leaf rows only (avoid double-counting)
const leafRows = allChildRows.filter((r) => !r.is_parent);
const parentMonths = Array(12).fill(0) as number[];
let parentAnnual = 0;
let parentPrevYear = 0;
for (const cr of leafRows) {
for (let m = 0; m < 12; m++) parentMonths[m] += cr.months[m];
parentAnnual += cr.annual;
parentPrevYear += cr.previousYearTotal;
}
rows.push({
category_id: cat.id,
category_name: cat.name,
category_color: cat.color || "#9ca3af",
category_type: cat.type,
parent_id: null,
is_parent: true,
depth: 0,
months: parentMonths,
annual: parentAnnual,
previousYearTotal: parentPrevYear,
});
// Sort children alphabetically, but keep "(direct)" first
allChildRows.sort((a, b) => {
if (a.category_id === cat.id && !a.is_parent) return -1;
if (b.category_id === cat.id && !b.is_parent) return 1;
return a.category_name.localeCompare(b.category_name);
});
rows.push(...allChildRows);
}
// else: non-inputable parent with no inputable children — skip
}
// Sort by type, then within each type: keep hierarchy groups together
function getTopGroupId(r: BudgetYearRow): number {
if ((r.depth ?? 0) === 0) return r.category_id;
if (r.is_parent && r.parent_id === null) return r.category_id;
let pid = r.parent_id;
while (pid !== null) {
const pCat = catById.get(pid);
if (!pCat || !pCat.parent_id) return pid;
pid = pCat.parent_id;
}
return r.category_id;
}
rows.sort((a, b) => {
const typeA = TYPE_ORDER[a.category_type] ?? 9;
const typeB = TYPE_ORDER[b.category_type] ?? 9;
if (typeA !== typeB) return typeA - typeB;
const groupA = getTopGroupId(a);
const groupB = getTopGroupId(b);
if (groupA !== groupB) {
const catA = catById.get(groupA);
const catB = catById.get(groupB);
const orderA = catA?.sort_order ?? 999;
const orderB = catB?.sort_order ?? 999;
if (orderA !== orderB) return orderA - orderB;
return (catA?.name ?? "").localeCompare(catB?.name ?? "");
}
// Same group: sort by depth, then parent before children at same depth
if (a.is_parent !== b.is_parent && (a.depth ?? 0) === (b.depth ?? 0)) return a.is_parent ? -1 : 1;
if ((a.depth ?? 0) !== (b.depth ?? 0)) return (a.depth ?? 0) - (b.depth ?? 0);
if (a.parent_id && a.category_id === a.parent_id) return -1;
if (b.parent_id && b.category_id === b.parent_id) return 1;
return a.category_name.localeCompare(b.category_name);
});
dispatch({ type: "SET_DATA", payload: { rows, templates } });
} catch (e) {

View file

@ -1,133 +1,93 @@
import { useCallback, useEffect, useState } from "react";
import { useCallback, useState } from "react";
import {
type CollapseAccessors,
collapsibleKeys,
isCollapsedFor,
parseStoredExpanded,
serializeExpanded,
visibleRows,
} from "../utils/collapsibleRows";
import { getPreference, setPreference } from "../services/userPreferenceService";
export interface CollapsibleGroups<T> {
/** Filters a section's rows down to the ones visible under the current state. */
visible: (rows: T[]) => T[];
/** True when this parent row is collapsed (its subtree is hidden). */
/** True when this top-level parent row is collapsed (its children are hidden). */
isCollapsed: (row: T) => boolean;
/** Flip one group between collapsed and expanded, then persist. */
toggle: (row: T) => void;
/** Expand every collapsible group found in `rows`, then persist. */
expandAll: (rows: T[]) => void;
/** Collapse every collapsible group found in `rows`, then persist. */
collapseAll: (rows: T[]) => void;
/** Collapse every group (back to the default), then persist. */
collapseAll: () => void;
/** True when `rows` has at least one group and all of them are expanded. */
allExpanded: (rows: T[]) => boolean;
/** Number of collapsible groups (parents, any depth) in `rows`. */
/** Number of collapsible top-level groups in `rows`. */
groupCount: (rows: T[]) => number;
}
/**
* Per-report collapse/expand state for the hierarchical tables (issue #254/#265),
* generalised to every hierarchy level (issue #288).
* Per-report collapse/expand state for the hierarchical comparable tables
* (issue #254). Groups are collapsed by default (issue #260): the persisted
* value is the set of *expanded* group keys, so a first-ever visit (empty set)
* shows every group collapsed with only its subtotal, while any group the user
* expands is remembered.
*
* The persisted value is the set of keys whose state DIFFERS from the default
* (see `isCollapsedFor`), so `defaultExpanded: false` + an empty set = everything
* collapsed the reports' established behaviour while `defaultExpanded: true`
* + an empty set = everything expanded.
*
* Persistence lives in `user_preferences`, the profile's own SQLite table, so the
* state is scoped per profile for free and is destroyed with the profile (no
* localStorage residue surviving `deleteProfile` a privacy-first requirement).
* Reads/writes are async; hydration runs in an effect. There is no visible flash
* because the default state IS what renders first, and hydration can only reveal
* what the user had opened. `storageKey: null` disables persistence entirely
* (pure in-memory state, for the category trees).
*
* The hook stays context-free it never calls `useProfile()` because the
* `user_preferences` key is already per-profile (it lives in the profile's DB).
* Persistence uses localStorage, the same synchronous store the sibling
* "subtotals on top/bottom" toggle already uses in these tables. State is kept
* per report via a distinct `storageKey`.
*/
export function useCollapsibleGroups<T>(
storageKey: string | null,
storageKey: string,
acc: CollapseAccessors<T>,
options?: { defaultExpanded?: boolean },
): CollapsibleGroups<T> {
const defaultExpanded = options?.defaultExpanded ?? false;
// Keys whose state differs from the default. Initial = default (empty), then an
// effect hydrates from user_preferences when a storageKey is set.
const [flipped, setFlipped] = useState<Set<string>>(() => new Set());
useEffect(() => {
if (storageKey === null) {
// No persistence: reset to the default state on (re)mount / key change.
setFlipped(new Set());
return;
}
let cancelled = false;
void getPreference(storageKey)
.then((raw) => {
if (!cancelled) setFlipped(parseStoredExpanded(raw));
})
.catch(() => {
// Best-effort: a read failure just keeps the default state.
});
return () => {
cancelled = true;
};
}, [storageKey]);
const [expanded, setExpanded] = useState<Set<string>>(() =>
parseStoredExpanded(
typeof localStorage !== "undefined" ? localStorage.getItem(storageKey) : null,
),
);
const persist = useCallback(
(next: Set<string>) => {
setFlipped(next);
if (storageKey !== null) {
void setPreference(storageKey, serializeExpanded(next)).catch(() => {
// Best-effort: a write failure just means the next session falls back
// to the default state.
});
try {
localStorage.setItem(storageKey, serializeExpanded(next));
} catch {
// Best-effort: a write failure just means the next session falls back
// to the collapsed default.
}
setExpanded(next);
},
[storageKey],
);
const isCollapsed = useCallback(
(row: T) => isCollapsedFor(flipped, acc.keyOf(row), defaultExpanded),
[flipped, acc, defaultExpanded],
);
const isCollapsed = useCallback((row: T) => !expanded.has(acc.keyOf(row)), [expanded, acc]);
const visible = useCallback((rows: T[]) => visibleRows(rows, acc, isCollapsed), [acc, isCollapsed]);
const toggle = useCallback(
(row: T) => {
const key = acc.keyOf(row);
const next = new Set(flipped);
const next = new Set(expanded);
if (next.has(key)) next.delete(key);
else next.add(key);
persist(next);
},
[flipped, acc, persist],
[expanded, acc, persist],
);
// In `defaultExpanded` polarity the flipped set holds the *collapsed* keys, so
// expanding everything means clearing it; collapsing everything means filling
// it. The polarity is inverted when the default is collapsed.
const expandAll = useCallback(
(rows: T[]) => persist(defaultExpanded ? new Set() : new Set(collapsibleKeys(rows, acc))),
[acc, persist, defaultExpanded],
(rows: T[]) => persist(new Set(collapsibleKeys(rows, acc))),
[acc, persist],
);
const collapseAll = useCallback(
(rows: T[]) => persist(defaultExpanded ? new Set(collapsibleKeys(rows, acc)) : new Set()),
[acc, persist, defaultExpanded],
);
const collapseAll = useCallback(() => persist(new Set()), [persist]);
const groupCount = useCallback((rows: T[]) => collapsibleKeys(rows, acc).length, [acc]);
const allExpanded = useCallback(
(rows: T[]) => {
const keys = collapsibleKeys(rows, acc);
return keys.length > 0 && keys.every((k) => !isCollapsedFor(flipped, k, defaultExpanded));
return keys.length > 0 && keys.every((k) => expanded.has(k));
},
[flipped, acc, defaultExpanded],
[expanded, acc],
);
return { visible, isCollapsed, toggle, expandAll, collapseAll, allExpanded, groupCount };

View file

@ -914,7 +914,6 @@
"Split annual amount evenly across 12 months",
"Budget templates to save and apply configurations",
"Parent category subtotals",
"Collapse/expand the hierarchy at every level: each parent category has its own chevron, the grid opens fully collapsed, and an \"Expand all / Collapse all\" button opens or closes every level at once — remembered per profile",
"Column headers stay fixed when scrolling vertically"
],
"steps": [
@ -927,8 +926,7 @@
"tips": [
"The Annual column auto-sums all 12 months — a warning appears if monthly totals don't match",
"Templates can be applied to specific months or all 12 at once",
"Parent categories show subtotals aggregated from their children",
"Collapsing a category is purely visual: subtotals and annual totals are always computed over all rows, never just the visible ones — no amount you typed is ever lost"
"Parent categories show subtotals aggregated from their children"
]
},
"reports": {
@ -943,8 +941,7 @@
"Category Zoom: single-category drill-down with donut, monthly evolution, and filterable transaction table; auto-rollup of subcategories",
"Contextual keyword editing: right-click a transaction row to add its description as a keyword with a live preview of the matches",
"SVG patterns (lines, dots, crosshatch) to distinguish categories",
"View mode preference (chart vs. table) persisted per report section",
"Collapse the category hierarchy at every level on the Compare reports and the by-category Trends table: a chevron per parent category, opens fully collapsed, an \"Expand all / Collapse all\" button; purely visual (subtotals and results unchanged), remembered per profile"
"View mode preference (chart vs. table) persisted per report section"
],
"steps": [
"Open /reports to see the highlights panel and four navigation cards",
@ -960,8 +957,7 @@
"Keywords must be 264 characters long",
"The Category Zoom is protected against malformed category trees: a parent_id cycle cannot freeze the app",
"On /reports/cartes in YTD mode, the MoM delta for January is always \"—\" (no prior YTD window inside the same year), and the savings rate stays \"—\" when YTD income is zero",
"Seasonality, top movers, and budget adherence stay monthly even when the toggle is set to YTD — only the 4 KPI numbers change",
"Your category collapse choices (Compare, Trends, Budget) are remembered per profile: stored in the profile's own database, they are destroyed with it"
"Seasonality, top movers, and budget adherence stay monthly even when the toggle is set to YTD — only the 4 KPI numbers change"
]
},
"balance": {

View file

@ -914,7 +914,6 @@
"Répartition égale du montant annuel sur 12 mois",
"Modèles de budget pour sauvegarder et appliquer des configurations",
"Sous-totaux par catégorie parente",
"Repli / dépli de la hiérarchie à chaque niveau : chaque catégorie parente a son chevron, la grille s'ouvre entièrement repliée, et un bouton « Tout déplier / Tout replier » ouvre ou ferme tous les niveaux d'un coup — mémorisé par profil",
"En-têtes de colonnes fixes au défilement vertical"
],
"steps": [
@ -927,8 +926,7 @@
"tips": [
"La colonne Annuel additionne automatiquement les 12 mois — un avertissement apparaît si les totaux mensuels ne correspondent pas",
"Les modèles peuvent être appliqués à des mois spécifiques ou aux 12 mois d'un coup",
"Les catégories parentes affichent les sous-totaux agrégés de leurs enfants",
"Replier une catégorie est purement visuel : les sous-totaux et les totaux annuels sont toujours calculés sur toutes les lignes, jamais sur les seules lignes visibles — aucun montant saisi n'est perdu"
"Les catégories parentes affichent les sous-totaux agrégés de leurs enfants"
]
},
"reports": {
@ -943,8 +941,7 @@
"Zoom catégorie : analyse d'une seule catégorie avec donut, évolution mensuelle et tableau de transactions filtrable ; rollup automatique des sous-catégories",
"Édition contextuelle des mots-clés : clic droit sur une ligne de transaction pour ajouter sa description comme mot-clé avec prévisualisation en direct des matches",
"Motifs SVG (lignes, points, hachures) pour distinguer les catégories",
"Préférence chart/table mémorisée par section de rapport",
"Repli de la hiérarchie à chaque niveau sur les Comparables et la tendance Par catégorie : chevron par catégorie parente, ouverture entièrement repliée, bouton « Tout déplier / Tout replier » ; purement visuel (sous-totaux et résultats inchangés), mémorisé par profil"
"Préférence chart/table mémorisée par section de rapport"
],
"steps": [
"Ouvrez /reports pour voir le panneau de faits saillants et les quatre cartes de navigation",
@ -960,8 +957,7 @@
"Les mots-clés doivent faire entre 2 et 64 caractères",
"Le Zoom catégorie est protégé contre les arborescences malformées : un cycle parent_id ne peut pas figer l'app",
"Sur /reports/cartes en mode YTD, le delta MoM du mois de janvier est toujours « — » (pas de fenêtre YTD antérieure dans la même année), et le taux d'épargne reste « — » quand les revenus YTD sont à zéro",
"La saisonnalité, les top mouvements et l'adhésion budgétaire restent mensuels même quand le toggle est sur YTD — seuls les 4 chiffres KPI changent",
"Vos choix de repli des catégories (Comparables, Tendances, Budget) sont mémorisés par profil : stockés dans la base du profil, ils disparaissent avec lui"
"La saisonnalité, les top mouvements et l'adhésion budgétaire restent mensuels même quand le toggle est sur YTD — seuls les 4 chiffres KPI changent"
]
},
"balance": {

View file

@ -3,11 +3,8 @@ import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import { ArrowLeft, Search, Printer, ChevronsDownUp, ChevronsUpDown } from "lucide-react";
import { useCategoryTaxonomy } from "../hooks/useCategoryTaxonomy";
import CategoryTaxonomyTree, {
TAXONOMY_COLLAPSE_ACCESSORS,
} from "../components/categories/CategoryTaxonomyTree";
import CategoryTaxonomyTree from "../components/categories/CategoryTaxonomyTree";
import type { TaxonomyNode } from "../services/categoryTaxonomyService";
import { useCollapsibleGroups } from "../hooks/useCollapsibleGroups";
function countNodes(nodes: TaxonomyNode[]): {
roots: number;
@ -35,47 +32,51 @@ function countNodes(nodes: TaxonomyNode[]): {
return { roots, subcategories, leaves };
}
// Flattens the taxonomy to a single array so the hook's bulk ops
// (expandAll/collapseAll/allExpanded/groupCount) can walk every parent at any depth.
function flattenNodes(nodes: TaxonomyNode[]): TaxonomyNode[] {
const flat: TaxonomyNode[] = [];
function collectAllIds(nodes: TaxonomyNode[]): number[] {
const ids: number[] = [];
const walk = (n: TaxonomyNode) => {
flat.push(n);
ids.push(n.id);
n.children.forEach(walk);
};
nodes.forEach(walk);
return flat;
return ids;
}
export default function CategoriesStandardGuidePage() {
const { t } = useTranslation();
const { taxonomy } = useCategoryTaxonomy();
const [search, setSearch] = useState("");
// State machine only (issue #290): in-memory (storageKey null), collapsed by
// default so the guide opens on roots — the previous local Set behaviour.
const groups = useCollapsibleGroups<TaxonomyNode>(null, TAXONOMY_COLLAPSE_ACCESSORS, {
defaultExpanded: false,
const [expanded, setExpanded] = useState<Set<number>>(() => {
// Start with roots collapsed (user can expand as needed); counter and search still work.
return new Set<number>();
});
const counts = useMemo(() => countNodes(taxonomy.roots), [taxonomy.roots]);
const total = counts.roots + counts.subcategories + counts.leaves;
// Flattened nodes for the bulk ops (expand/collapse all, allExpanded).
const flatNodes = useMemo(() => flattenNodes(taxonomy.roots), [taxonomy.roots]);
const toggleNode = (id: number) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const handleExpandAll = () => groups.expandAll(flatNodes);
const handleCollapseAll = () => groups.collapseAll(flatNodes);
const handleExpandAll = () => {
setExpanded(new Set(collectAllIds(taxonomy.roots)));
};
const handleCollapseAll = () => {
setExpanded(new Set());
};
const handlePrint = () => {
// window.print() opens the browser print dialog; @media print rules strip chrome.
window.print();
};
// Correct "all expanded" test (issue #290): every collapsible group must be open,
// not merely "at least one node open" (the old expanded.size > 0 bug, which
// flipped the button to "Collapse all" after a single node was expanded).
const allExpanded = groups.allExpanded(flatNodes);
const allExpanded = expanded.size > 0;
return (
<div className="p-6 max-w-4xl mx-auto space-y-6">
@ -176,8 +177,8 @@ export default function CategoriesStandardGuidePage() {
<section className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-3 taxonomy-tree-print">
<CategoryTaxonomyTree
nodes={taxonomy.roots}
isCollapsed={groups.isCollapsed}
onToggle={groups.toggle}
expanded={expanded}
onToggle={toggleNode}
searchQuery={search}
/>
</section>

View file

@ -1,234 +1,102 @@
import { describe, it, expect } from "vitest";
import {
type CollapseAccessors,
MAX_TREE_DEPTH,
collapsibleKeys,
isCollapsedFor,
parseStoredExpanded,
serializeExpanded,
visibleRows,
} from "./collapsibleRows";
import { reorderRows } from "./reorderRows";
/** Tiny hierarchy row: id, parent id, is-parent flag, indentation depth. */
/** Tiny hierarchy row for the tests: key, depth, is-parent. */
interface Row {
id: number;
parent: number | null;
is_parent: boolean;
depth: number;
k: string;
d: number;
p: boolean;
}
const acc: CollapseAccessors<Row> = {
keyOf: (r) => `p:${r.id}`,
parentKeyOf: (r) => (r.parent === null ? null : `p:${r.parent}`),
isParent: (r) => r.is_parent,
depthOf: (r) => r.depth,
keyOf: (r) => r.k,
depthOf: (r) => r.d,
isParent: (r) => r.p,
};
const r = (id: number, parent: number | null, is_parent: boolean, depth: number): Row => ({
id,
parent,
is_parent,
depth,
});
const row = (k: string, d: number, p: boolean): Row => ({ k, d, p });
// A three-level tree (income → expense → transfer shape is irrelevant here; the
// point is the depth):
// Housing (parent, id 1)
// Rent (leaf, id 11)
// Utilities (INTERMEDIATE parent, id 12)
// Power (leaf, id 121)
// Water (leaf, id 122)
// Salary (parent, id 2)
// Paycheck (leaf, id 21)
// Misc (top-level leaf, id 3)
const dfsTree: Row[] = [
r(1, null, true, 0), // Housing
r(11, 1, false, 1), // Rent
r(12, 1, true, 1), // Utilities (intermediate)
r(121, 12, false, 2), // Power
r(122, 12, false, 2), // Water
r(2, null, true, 0), // Salary
r(21, 2, false, 1), // Paycheck
r(3, null, false, 0), // Misc
// A two-group tree with one nested sub-group:
// Housing (parent, d0)
// Rent (leaf, d1)
// Utilities (parent, d1) <- intermediate parent
// Power (leaf, d2)
// Salary (parent, d0)
// Paycheck (leaf, d1)
// Misc (leaf, d0) <- top-level leaf, not a group
const tree: Row[] = [
row("housing", 0, true),
row("rent", 1, false),
row("utilities", 1, true),
row("power", 2, false),
row("salary", 0, true),
row("paycheck", 1, false),
row("misc", 0, false),
];
// The EXACT same tree, emitted level-order (BFS) — the order the budget grid
// produces. The ancestor-walk must mask identically to the DFS order.
const bfsTree: Row[] = [
r(1, null, true, 0), // Housing
r(2, null, true, 0), // Salary
r(3, null, false, 0), // Misc
r(11, 1, false, 1), // Rent
r(12, 1, true, 1), // Utilities
r(21, 2, false, 1), // Paycheck
r(121, 12, false, 2), // Power
r(122, 12, false, 2), // Water
];
// Default = collapsed: a group is collapsed unless its key is in the expanded set.
const isCollapsed = (expanded: Set<string>) => (r: Row) => !expanded.has(r.k);
/** Report polarity: a group is collapsed unless its key is in the expanded set. */
const isCollapsed = (expanded: Set<string>) => (row: Row) => !expanded.has(acc.keyOf(row));
const ids = (rows: Row[]) => rows.map((row) => row.id);
const idSet = (rows: Row[]) => new Set(ids(rows));
describe("collapsibleRows.visibleRows — ancestor-walk visibility", () => {
it("collapses every level by default (empty set) ⇒ only roots survive", () => {
const visible = visibleRows(dfsTree, acc, isCollapsed(new Set()));
// Housing + Salary (root parents) + Misc (root leaf); everything deeper folds.
expect(ids(visible)).toEqual([1, 2, 3]);
describe("collapsibleRows.visibleRows", () => {
it("collapses every group by default (empty expanded set)", () => {
const visible = visibleRows(tree, acc, isCollapsed(new Set()));
// Only depth-0 rows survive: the two group headers + the top-level leaf.
expect(visible.map((r) => r.k)).toEqual(["housing", "salary", "misc"]);
});
it("expanding a root reveals ONLY its direct children, not its grandchildren", () => {
const visible = visibleRows(dfsTree, acc, isCollapsed(new Set(["p:1"])));
// Rent + Utilities appear; Power/Water (grandchildren) stay folded because the
// intermediate Utilities is still collapsed.
expect(ids(visible)).toEqual([1, 11, 12, 2, 3]);
expect(visible.some((row) => row.id === 121)).toBe(false);
expect(visible.some((row) => row.id === 122)).toBe(false);
it("reveals a group's full subtree (incl. nested sub-groups) when expanded", () => {
const visible = visibleRows(tree, acc, isCollapsed(new Set(["housing"])));
expect(visible.map((r) => r.k)).toEqual([
"housing",
"rent",
"utilities",
"power",
"salary",
"misc",
]);
});
it("expanding a root AND its intermediate reveals the leaves", () => {
const visible = visibleRows(dfsTree, acc, isCollapsed(new Set(["p:1", "p:12"])));
expect(ids(visible)).toEqual([1, 11, 12, 121, 122, 2, 3]);
it("keeps groups independent — expanding one leaves the others collapsed", () => {
const visible = visibleRows(tree, acc, isCollapsed(new Set(["salary"])));
expect(visible.map((r) => r.k)).toEqual(["housing", "salary", "paycheck", "misc"]);
});
it("a collapsed ancestor always wins: expanding an intermediate whose root is collapsed reveals nothing", () => {
const visible = visibleRows(dfsTree, acc, isCollapsed(new Set(["p:12"])));
// Housing is collapsed, so Utilities (and thus Power/Water) stay hidden even
// though Utilities itself is expanded.
expect(ids(visible)).toEqual([1, 2, 3]);
it("shows everything when all groups are expanded", () => {
const visible = visibleRows(tree, acc, isCollapsed(new Set(["housing", "salary"])));
expect(visible).toHaveLength(tree.length);
});
it("keeps groups independent — expanding Salary leaves Housing folded", () => {
const visible = visibleRows(dfsTree, acc, isCollapsed(new Set(["p:2"])));
expect(ids(visible)).toEqual([1, 2, 21, 3]);
});
it("shows every row once all parents are expanded", () => {
const visible = visibleRows(dfsTree, acc, isCollapsed(new Set(["p:1", "p:12", "p:2"])));
expect(visible).toHaveLength(dfsTree.length);
});
it("BFS (level-order) rows mask IDENTICALLY to DFS rows — the test that would have killed v1", () => {
const states: Set<string>[] = [
new Set(),
new Set(["p:1"]),
new Set(["p:1", "p:12"]),
new Set(["p:12"]),
new Set(["p:2"]),
new Set(["p:1", "p:12", "p:2"]),
];
for (const expanded of states) {
const dfs = idSet(visibleRows(dfsTree, acc, isCollapsed(expanded)));
const bfs = idSet(visibleRows(bfsTree, acc, isCollapsed(expanded)));
expect(bfs).toEqual(dfs);
}
});
it("masking is unchanged when subtotals are moved to the bottom (reorderRows)", () => {
const expanded = new Set(["p:1", "p:12"]);
const normal = idSet(visibleRows(dfsTree, acc, isCollapsed(expanded)));
// Order-independent: run reorder FIRST (subtotals below their children), then
// filter. v1's depth-cursor algorithm broke exactly here.
const bottomFirst = reorderRows(dfsTree, false);
const afterReorder = idSet(visibleRows(bottomFirst, acc, isCollapsed(expanded)));
expect(afterReorder).toEqual(normal);
});
it("always keeps a top-level leaf that has no parent", () => {
const visible = visibleRows(dfsTree, acc, isCollapsed(new Set()));
expect(visible.some((row) => row.id === 3)).toBe(true);
});
});
describe('collapsibleRows.visibleRows — "(direct)" leaf', () => {
// A parent that also holds direct transactions: its "(direct)" leaf shares the
// parent's category id but is a leaf, and points back at the parent subtotal.
const withDirect: Row[] = [
r(1, null, true, 0), // Housing subtotal -> key p:1
r(1, 1, false, 1), // Housing (direct) -> key p:1, parentKey p:1
r(11, 1, false, 1), // Rent
];
it("hides the (direct) leaf when its parent is collapsed", () => {
const visible = visibleRows(withDirect, acc, isCollapsed(new Set()));
// Only the Housing subtotal (a root) survives.
expect(visible).toHaveLength(1);
expect(visible[0].is_parent).toBe(true);
});
it("shows the (direct) leaf when its parent is expanded", () => {
const visible = visibleRows(withDirect, acc, isCollapsed(new Set(["p:1"])));
expect(visible).toHaveLength(3);
});
it("never treats the (direct) leaf as a collapsible group", () => {
// Both the subtotal and the (direct) leaf carry key p:1, but only the parent
// subtotal is collapsible — the leaf is not a parent.
expect(collapsibleKeys(withDirect, acc)).toEqual(["p:1"]);
});
});
describe("collapsibleRows.visibleRows — corrupt / cross-section chains", () => {
it("guards a cyclic parent_id with MAX_TREE_DEPTH (no infinite loop)", () => {
// A <-> B cycle, with a leaf hanging under A. Neither A nor B is collapsed, so
// the walk keeps climbing until the hop guard trips.
const cyclic: Row[] = [
r(100, 101, true, 0), // A, parent B
r(101, 100, true, 1), // B, parent A
r(1001, 100, false, 2), // leaf under A
];
const visible = visibleRows(cyclic, acc, isCollapsed(new Set(["p:100", "p:101"])));
// Terminates and keeps the leaf visible (no collapsed ancestor was found).
expect(visible.some((row) => row.id === 1001)).toBe(true);
// Sanity: the guard is a finite, positive cap.
expect(MAX_TREE_DEPTH).toBeGreaterThan(3);
});
it("keeps a row whose ancestor is absent from the section (child of another type)", () => {
// Orphan points at id 999, which is not in these rows.
const orphaned: Row[] = [r(55, 999, false, 1)];
const visible = visibleRows(orphaned, acc, isCollapsed(new Set()));
// Missing ancestor ⇒ visible (better an orphan shown than a row hidden by a
// parent that lives in another section).
expect(ids(visible)).toEqual([55]);
it("always keeps a top-level leaf that has no group", () => {
const visible = visibleRows(tree, acc, isCollapsed(new Set()));
expect(visible.some((r) => r.k === "misc")).toBe(true);
});
});
describe("collapsibleRows.collapsibleKeys", () => {
it("lists EVERY parent, intermediates included, in encounter order", () => {
// Housing (p:1), Utilities (p:12, intermediate), Salary (p:2) — NOT Misc/leaves.
expect(collapsibleKeys(dfsTree, acc)).toEqual(["p:1", "p:12", "p:2"]);
it("lists only top-level parent rows, in order", () => {
expect(collapsibleKeys(tree, acc)).toEqual(["housing", "salary"]);
});
it("returns [] when there is no hierarchy", () => {
const flat = [r(1, null, false, 0), r(2, null, false, 0)];
const flat = [row("a", 0, false), row("b", 0, false)];
expect(collapsibleKeys(flat, acc)).toEqual([]);
});
});
describe("collapsibleRows.isCollapsedFor — polarity", () => {
it("defaultExpanded=false: empty set ⇒ collapsed, a flipped key ⇒ expanded", () => {
expect(isCollapsedFor(new Set(), "p:1", false)).toBe(true);
expect(isCollapsedFor(new Set(["p:1"]), "p:1", false)).toBe(false);
expect(isCollapsedFor(new Set(["p:2"]), "p:1", false)).toBe(true);
});
it("defaultExpanded=true: empty set ⇒ expanded, a flipped key ⇒ collapsed", () => {
expect(isCollapsedFor(new Set(), "p:1", true)).toBe(false);
expect(isCollapsedFor(new Set(["p:1"]), "p:1", true)).toBe(true);
expect(isCollapsedFor(new Set(["p:2"]), "p:1", true)).toBe(false);
});
});
describe("collapsibleRows.parseStoredExpanded / serializeExpanded", () => {
it("treats absent storage as the default state (empty set)", () => {
it("treats absent storage as the collapsed default (empty set)", () => {
expect(parseStoredExpanded(null).size).toBe(0);
expect(parseStoredExpanded("").size).toBe(0);
});
it("parses a JSON string array back into a set", () => {
expect([...parseStoredExpanded('["p:1","p:2"]')].sort()).toEqual(["p:1", "p:2"]);
expect([...parseStoredExpanded('["housing","salary"]')].sort()).toEqual(["housing", "salary"]);
});
it("falls back to empty on corrupt or non-array JSON", () => {
@ -242,7 +110,7 @@ describe("collapsibleRows.parseStoredExpanded / serializeExpanded", () => {
});
it("round-trips through serialize", () => {
const set = new Set(["p:1", "p:12"]);
expect([...parseStoredExpanded(serializeExpanded(set))].sort()).toEqual(["p:1", "p:12"]);
const set = new Set(["a", "b"]);
expect([...parseStoredExpanded(serializeExpanded(set))].sort()).toEqual(["a", "b"]);
});
});

View file

@ -1,104 +1,71 @@
/**
* Collapse/expand of category groups in the hierarchical reports (real-vs-real
* Compare, Budget-vs-Actual, trends over time) issue #254/#265, generalised to
* every hierarchy level in issue #288.
* Collapse/expand of top-level category groups in the hierarchical comparable
* reports (real-vs-real Compare + Budget-vs-Actual) issue #254.
*
* Pure helpers only; the React state + persistence glue lives in the
* `useCollapsibleGroups` hook.
*
* Visibility is decided by an ANCESTOR WALK, not by row adjacency: a row is
* hidden iff *any* of its ancestors is collapsed. We climb `parentKeyOf` from a
* row until we reach a root (null), an ancestor outside this section ( visible),
* or a collapsed ancestor ( hidden). This is independent of the order rows
* arrive in the fix for the v1 adjacency algorithm, which assumed a
* depth-first order the budget grid (level-ordered) does not emit.
* A "group" is a top-level parent row (depth 0, is_parent). Collapsing it keeps
* its own subtotal row visible but hides its entire subtree (every following
* depth 1 row until the next depth-0 row). Rows must arrive in depth-first
* order the order the compare/budget services already emit them in, and the
* same order `reorderRows` relies on.
*
* The accessors are supplied by each consumer so every table can key + climb the
* exact hierarchy it renders. Keys are prefixed `p:` so they are injective: a
* parent subtotal row and its own "(direct)" leaf share a category id but the
* leaf is never a parent, so only the subtotal is indexed the leaf simply
* carries the parent's key via `parentKeyOf` and is hidden with it.
* The accessors are passed in rather than read off fixed field names so each
* table can supply the *exact* depth expression it renders with (CategoryDelta
* uses `depth ?? 0`; BudgetVsActualRow derives a missing depth from
* `parent_id`). Keeping the collapse depth and the indentation depth identical
* guarantees the hidden rows are exactly the indented descendants.
*/
/**
* Cycle guard for the ancestor walk. The standard taxonomy is three levels deep;
* this generous finite cap only exists so a corrupt cyclic `parent_id` (DB
* corruption) can never loop forever. Any real chain terminates in a few hops.
*/
export const MAX_TREE_DEPTH = 64;
/** How the collapse logic reads hierarchy position + identity off a row. */
export interface CollapseAccessors<T> {
/** Stable per-parent key, injective across the section: `p:<categoryId>`. */
/** Stable per-group key (a category id, stringified). */
keyOf: (row: T) => string;
/** Key of this row's parent (`p:<parent_id>`), or null at a root. */
parentKeyOf: (row: T) => string | null;
/** Indentation depth; 0 = top-level. Must match the rendered indentation. */
depthOf: (row: T) => number;
/** True when the row is a group header / subtotal (has children). */
isParent: (row: T) => boolean;
/** Indentation depth; 0 = top-level. Drives indentation + aria-level ONLY. */
depthOf: (row: T) => number;
}
/**
* Keeps every row that is currently visible given which groups are collapsed. A
* row is dropped iff any ancestor (walking `parentKeyOf`) is collapsed; a missing
* ancestor (parent lives in another section) leaves the row visible.
* Keeps every row that is currently visible given which top-level groups are
* collapsed. `isCollapsed` is consulted only for top-level parent rows; a
* collapsed one keeps its own (subtotal) row and drops its whole subtree.
*/
export function visibleRows<T>(
rows: T[],
acc: CollapseAccessors<T>,
isCollapsed: (row: T) => boolean,
): T[] {
// Index ONLY parents: a "(direct)" leaf shares its parent's category id but is
// never a parent itself, so it never clobbers the subtotal it points at.
const parents = new Map<string, T>();
for (const r of rows) if (acc.isParent(r)) parents.set(acc.keyOf(r), r);
const hiddenByAncestor = (row: T): boolean => {
let key = acc.parentKeyOf(row);
let hops = 0;
while (key !== null && hops++ < MAX_TREE_DEPTH) {
const parent = parents.get(key);
if (parent === undefined) return false; // ancestor outside this section → visible
if (isCollapsed(parent)) return true;
key = acc.parentKeyOf(parent);
const out: T[] = [];
// While true we are inside a collapsed top-level parent's subtree and drop
// every deeper row until the next depth-0 row re-opens the flow.
let hidingSubtree = false;
for (const row of rows) {
if (acc.depthOf(row) === 0) {
out.push(row);
hidingSubtree = acc.isParent(row) && isCollapsed(row);
} else if (!hidingSubtree) {
out.push(row);
}
return false;
};
return rows.filter((r) => !hiddenByAncestor(r));
}
return out;
}
/** Keys of every collapsible group (all parent rows, any depth), in encounter order. */
/** Keys of every collapsible group (top-level parent rows), in encounter order. */
export function collapsibleKeys<T>(rows: T[], acc: CollapseAccessors<T>): string[] {
const keys: string[] = [];
for (const row of rows) {
if (acc.isParent(row)) keys.push(acc.keyOf(row));
if (acc.depthOf(row) === 0 && acc.isParent(row)) keys.push(acc.keyOf(row));
}
return keys;
}
/**
* Polarity of the collapse state. The persisted Set holds the keys whose state
* DIFFERS from the default, which lets one hook serve both polarities without a
* seed:
* - `defaultExpanded: false` (reports, budget) Set = the *expanded* keys, so
* an empty Set means everything collapsed (the reports' current behaviour).
* - `defaultExpanded: true` (category trees) Set = the *collapsed* keys, so an
* empty Set means everything expanded.
*/
export function isCollapsedFor(
flipped: Set<string>,
key: string,
defaultExpanded: boolean,
): boolean {
const isFlipped = flipped.has(key);
return defaultExpanded ? isFlipped : !isFlipped;
}
/**
* Parses the persisted value into the flipped-key set (see `isCollapsedFor`). An
* absent or corrupt value yields an empty set i.e. the default collapse state.
* Parses the persisted value into the set of *expanded* group keys. The report
* default is "everything collapsed" (issue #254/#260), so an absent or corrupt
* value yields an empty set i.e. all groups collapsed on a first-ever visit.
*/
export function parseStoredExpanded(raw: string | null): Set<string> {
if (!raw) return new Set();
@ -108,12 +75,12 @@ export function parseStoredExpanded(raw: string | null): Set<string> {
return new Set(parsed.filter((k): k is string => typeof k === "string"));
}
} catch {
// Corrupt value: fall back to the default state.
// Corrupt value: fall back to the collapsed default.
}
return new Set();
}
/** Serialises the flipped-key set for persistence. */
export function serializeExpanded(flipped: Set<string>): string {
return JSON.stringify([...flipped]);
/** Serialises the set of expanded group keys for persistence. */
export function serializeExpanded(expanded: Set<string>): string {
return JSON.stringify([...expanded]);
}