Compare commits

..

4 commits

Author SHA1 Message Date
le king fu
9f628aa9f4 refactor(categories): unify both category trees' collapse state onto useCollapsibleGroups
Replace the two hand-rolled Set-of-ids collapse state machines in the category
trees with the shared useCollapsibleGroups hook (a strict superset after #288),
keeping each tree's distinct recursive render and CategoryTree's drag-and-drop
untouched.

- CategoryTree (Categories page): storageKey null + defaultExpanded true, so
  every parent opens with no seeding; drops the local Set + collectExpandable.
- CategoryTaxonomyTree + guide page: storageKey null + defaultExpanded false
  (collapsed by default); exports a shared TAXONOMY_COLLAPSE_ACCESSORS.
- Fix the guide's button bug: allExpanded = expanded.size > 0 flipped to
  "Collapse all" after opening a single node; now uses the hook's correct
  allExpanded (every group must be open).
- Also migrate StepDiscover (4th consumer of CategoryTaxonomyTree, same button
  bug) onto the hook for a green build and consistency.

Both trees pass a flattened node list to the bulk ops; behaviour preserved:
Categories opens expanded, the guide/wizard open collapsed.

Resolves #290

Generated autonomously by /autopilot run of 2026-07-15

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 21:30:17 -04:00
le king fu
9c325e274b feat(budget): adopt multi-level collapse on the Budget grid
Reverse #278's deliberate no-collapse decision for the budget grid: it now
folds/unfolds at every category level like the hierarchical reports, opening
fully collapsed with a one-click "Expand all".

- BudgetTable: wire useCollapsibleGroups (defaultExpanded: false), inline
  BUDGET_COLLAPSE_ACCESSORS + BUDGET_EXPANDED_KEY (mirrors ComparePeriodTable /
  BudgetVsActualTable — no budgetTableModel.ts). Chevron + aria-expanded +
  aria-level on every parent row; groups.visible(group) before reorderRows.
- BudgetTable: section subtotal now uses the tested sumLeavesForType on the RAW
  group (drop-in for the hand-rolled loop) so folding stays purely visual.
- BudgetTable: rename STORAGE_KEY to "budget-subtotals-position", decoupling the
  subtotals-position preference from BudgetVsActualTable (they collided).
- useBudget: extract the pure buildBudgetYearRows(); the grid's rows are
  level-order (BFS), not DFS — document the invariant and pin it in a test, since
  the #288 ancestor-walk collapse is order-independent (the v1 plan assumed DFS
  and would have broken here).
- Tests: useBudget.test.ts locks the level-order emission, the DFS-killer, the
  end-to-end multi-level collapse on real builder output, and that subtotals sum
  raw rows regardless of collapse. 828 vitest pass.

Resolves #289

Generated autonomously by /autopilot run of 2026-07-15
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 21:16:01 -04:00
le king fu
48adb3db77 feat(reports): collapse category hierarchy at every level (socle + 3 reports)
All checks were successful
PR Check / rust (pull_request) Successful in 23m0s
PR Check / frontend (pull_request) Successful in 2m30s
Generalize the report category collapse from level-1-only to every hierarchy
level, on the three hierarchical report tables (real-vs-real Compare,
real-vs-budget Compare, Trends by category). Visibility is now decided by an
ancestor walk, not by row adjacency, so it is independent of row order (the
level-ordered budget grid emits a non-DFS order).

- collapsibleRows: rewrite visibleRows as an ancestor walk (a row is hidden iff
  any ancestor is collapsed); add parentKeyOf + injective `p:` keys;
  collapsibleKeys returns all parents (any depth); extract the pure, tested
  isCollapsedFor polarity helper; MAX_TREE_DEPTH cycle guard.
- useCollapsibleGroups: persist in user_preferences (per-profile, destroyed with
  the profile) instead of localStorage; storageKey nullable (no persistence);
  options.defaultExpanded; async hydration (no flash); collapseAll(rows).
- 3 tables: fix BOTH gates (collapsed flag + button) isTopParent -> isParent, add
  parentKeyOf accessors, aria-level on parent rows.
- Delete dead CategoryTable.tsx (0 imports).
- Tests: rewrite collapsibleRows.test.ts (BFS==DFS masking, cycle guard,
  cross-section ancestor, "(direct)" leaf, polarity); extend overTimeTableModel
  fixture to 3 levels with cascade assertions.

Collapse stays purely visual: subtotals and result lines are computed from raw
rows, never from visible rows.

Resolves #288

Generated autonomously by /autopilot run of 2026-07-15

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 20:58:18 -04:00
le king fu
524fe162ea chore: harden release skill (pre-flight and post-CI checks)
Lessons from the v0.13.0 release (session fdda84cb):
- Step 0: revalidate the tip locally before tagging — check.yml never
  runs on main, and ensure .claude/worktrees/ is empty (vitest recurses)
- Step 9: verify the published release — 7 expected artifacts and
  latest.json content (drives auto-update); status=success is not enough
- Rule: tagging publishes externally via the updater JSON — confirm
  with Max before tagging

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 20:32:58 -04:00
19 changed files with 1060 additions and 633 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-01
updated: 2026-07-13
---
# /release — Release Simpl-Resultat
@ -15,6 +15,7 @@ updated: 2026-07-01
## 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 = "..."`)
@ -37,6 +38,9 @@ updated: 2026-07-01
```
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
@ -45,7 +49,9 @@ updated: 2026-07-01
- 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,6 +2,15 @@
## [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,6 +2,15 @@
## [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,9 +1,11 @@
import { useState, useRef, useEffect, Fragment } from "react";
import { useTranslation } from "react-i18next";
import { AlertTriangle, ArrowUpDown } from "lucide-react";
import { AlertTriangle, ArrowUpDown, ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide-react";
import type { BudgetYearRow } from "../../shared/types";
import { reorderRows } from "../../utils/reorderRows";
import { computeBudgetResults, type BudgetTotals } from "./budgetTableResults";
import type { CollapseAccessors } from "../../utils/collapsibleRows";
import { useCollapsibleGroups } from "../../hooks/useCollapsibleGroups";
import { computeBudgetResults, sumLeavesForType, type BudgetTotals } from "./budgetTableResults";
const fmt = new Intl.NumberFormat("en-CA", {
style: "currency",
@ -18,7 +20,22 @@ const MONTH_KEYS = [
"months.sep", "months.oct", "months.nov", "months.dec",
] as const;
const STORAGE_KEY = "subtotals-position";
// 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";
interface BudgetTableProps {
rows: BudgetYearRow[];
@ -43,6 +60,15 @@ 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);
@ -173,24 +199,37 @@ 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
// Parent subtotal row: read-only, bold, distinct background. Collapsible
// at every level (issue #289) — a chevron toggles its subtree.
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`}`}>
<div className="flex items-center gap-2">
<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)]" />
)}
<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>
</div>
</button>
</td>
<td className={`py-2 px-2 text-right text-xs ${isIntermediateParent ? "font-medium" : "font-semibold"} text-[var(--muted-foreground)]`}>
{formatSigned(row.previousYearTotal)}
@ -211,6 +250,7 @@ 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 */}
@ -297,18 +337,11 @@ 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;
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
}
// 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);
return (
<Fragment key={type}>
<tr>
@ -319,14 +352,14 @@ export default function BudgetTable({ rows, onUpdatePlanned, onSplitEvenly }: Bu
{t(typeLabelKeys[type])}
</td>
</tr>
{reorderRows(group, subtotalsOnTop).map((row) => renderRow(row))}
{reorderRows(groups.visible(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(sectionPrevYearTotal)}</td>
<td className="py-2.5 px-2 text-right text-sm font-semibold">{formatSigned(sectionAnnualTotal)}</td>
{sectionMonthTotals.map((total, mIdx) => (
<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 key={mIdx} className="py-2.5 px-2 text-right text-sm font-semibold">
{formatSigned(total)}
</td>
@ -362,9 +395,22 @@ 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 px-3 py-2 border-b border-[var(--border)]">
<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>
)}
<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,22 +1,27 @@
import { useState } from "react";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ArrowRight, ChevronsDownUp, ChevronsUpDown, Search } from "lucide-react";
import { useCategoryTaxonomy } from "../../hooks/useCategoryTaxonomy";
import CategoryTaxonomyTree from "../categories/CategoryTaxonomyTree";
import CategoryTaxonomyTree, {
TAXONOMY_COLLAPSE_ACCESSORS,
} from "../categories/CategoryTaxonomyTree";
import type { TaxonomyNode } from "../../services/categoryTaxonomyService";
import { useCollapsibleGroups } from "../../hooks/useCollapsibleGroups";
interface StepDiscoverProps {
onNext: () => void;
}
function collectAllIds(nodes: TaxonomyNode[]): number[] {
const ids: number[] = [];
// 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[] = [];
const walk = (n: TaxonomyNode) => {
ids.push(n.id);
flat.push(n);
n.children.forEach(walk);
};
nodes.forEach(walk);
return ids;
return flat;
}
function countNodes(nodes: TaxonomyNode[]): {
@ -52,25 +57,23 @@ export default function StepDiscover({ onNext }: StepDiscoverProps) {
const { t } = useTranslation();
const { taxonomy } = useCategoryTaxonomy();
const [search, setSearch] = useState("");
const [expanded, setExpanded] = useState<Set<number>>(() => new Set());
// 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 counts = countNodes(taxonomy.roots);
const total = counts.roots + counts.subcategories + counts.leaves;
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 flatNodes = useMemo(() => flattenNodes(taxonomy.roots), [taxonomy.roots]);
const handleExpandAll = () => {
setExpanded(new Set(collectAllIds(taxonomy.roots)));
};
const handleCollapseAll = () => setExpanded(new Set());
const allExpanded = expanded.size > 0;
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);
return (
<section className="space-y-6">
@ -146,8 +149,8 @@ export default function StepDiscover({ onNext }: StepDiscoverProps) {
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-3">
<CategoryTaxonomyTree
nodes={taxonomy.roots}
expanded={expanded}
onToggle={toggleNode}
isCollapsed={groups.isCollapsed}
onToggle={groups.toggle}
searchQuery={search}
/>
</div>

View file

@ -2,33 +2,49 @@ 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[];
expanded: Set<number>;
onToggle: (id: number) => void;
isCollapsed: (node: TaxonomyNode) => boolean;
onToggle: (node: TaxonomyNode) => void;
searchQuery: string;
}
interface NodeRowProps {
node: TaxonomyNode;
depth: number;
expanded: Set<number>;
onToggle: (id: number) => void;
isCollapsed: (node: TaxonomyNode) => boolean;
onToggle: (node: TaxonomyNode) => void;
visibleIds: Set<number> | null;
}
function NodeRow({
node,
depth,
expanded,
isCollapsed,
onToggle,
visibleIds,
}: NodeRowProps) {
const { t } = useTranslation();
const label = t(node.i18n_key, { defaultValue: node.name });
const hasChildren = node.children.length > 0;
const isExpanded = expanded.has(node.id);
const isExpanded = !isCollapsed(node);
// Filter children by visibility set (search mode) if provided.
const visibleChildren = useMemo(() => {
@ -63,7 +79,7 @@ function NodeRow({
{hasChildren ? (
<button
type="button"
onClick={() => onToggle(node.id)}
onClick={() => onToggle(node)}
aria-label={
isExpanded
? t("categoriesSeed.guidePage.collapseAll")
@ -114,7 +130,7 @@ function NodeRow({
key={child.id}
node={child}
depth={depth + 1}
expanded={expanded}
isCollapsed={isCollapsed}
onToggle={onToggle}
visibleIds={visibleIds}
/>
@ -172,7 +188,7 @@ export function normalize(s: string): string {
export default function CategoryTaxonomyTree({
nodes,
expanded,
isCollapsed,
onToggle,
searchQuery,
}: CategoryTaxonomyTreeProps) {
@ -204,7 +220,7 @@ export default function CategoryTaxonomyTree({
key={root.id}
node={root}
depth={0}
expanded={expanded}
isCollapsed={isCollapsed}
onToggle={onToggle}
visibleIds={visibleIds}
/>

View file

@ -18,6 +18,8 @@ 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;
@ -40,14 +42,28 @@ function getSubtreeDepth(node: CategoryTreeNode): number {
return 1 + Math.max(...node.children.map(getSubtreeDepth));
}
function flattenTree(tree: CategoryTreeNode[], expandedSet: Set<number>): FlatItem[] {
// 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[] {
const items: FlatItem[] = [];
function recurse(nodes: CategoryTreeNode[], depth: number, parentId: number | null) {
for (const node of nodes) {
const hasChildren = node.children.length > 0;
const isExpanded = expandedSet.has(node.id);
items.push({ id: node.id, node, depth, parentId, isExpanded, hasChildren });
if (isExpanded && hasChildren) {
const expanded = hasChildren && isExpanded(node);
items.push({ id: node.id, node, depth, parentId, isExpanded: expanded, hasChildren });
if (expanded) {
recurse(node.children, depth + 1, node.id);
}
}
@ -153,7 +169,7 @@ function SortableTreeRow({
item: FlatItem;
selectedId: number | null;
onSelect: (id: number) => void;
onToggle: (id: number) => void;
onToggle: (node: CategoryTreeNode) => void;
isDragActive: boolean;
}) {
const {
@ -180,7 +196,7 @@ function SortableTreeRow({
selectedId={isDragActive ? null : selectedId}
onSelect={onSelect}
expanded={item.isExpanded}
onToggle={() => onToggle(item.id)}
onToggle={() => onToggle(item.node)}
hasChildren={item.hasChildren}
dragHandleProps={listeners}
isDragging={isDragging}
@ -190,23 +206,20 @@ function SortableTreeRow({
}
export default function CategoryTree({ tree, selectedId, onSelect, onMoveCategory }: Props) {
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;
});
// 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 [activeId, setActiveId] = useState<number | null>(null);
// Update expanded set when tree changes (new parents appear)
const flatItems = useMemo(() => flattenTree(tree, expanded), [tree, expanded]);
const flatItems = useMemo(
() => flattenTree(tree, (node) => !isCollapsed(node)),
[tree, isCollapsed],
);
const activeItem = useMemo(
() => (activeId !== null ? flatItems.find((i) => i.id === activeId) ?? null : null),
@ -219,15 +232,6 @@ 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; depth mirrors the render logic below
// (a missing depth is derived from parent_id) so hidden rows are exactly a
// group's indented descendants.
// Collapse groups keyed by category id; a row is hidden when any ancestor
// (walking parent_id) is collapsed, so every parent level is collapsible.
const BVA_COLLAPSE_ACCESSORS: CollapseAccessors<BudgetVsActualRow> = {
keyOf: (row) => String(row.category_id),
keyOf: (row) => `p:${row.category_id}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
depthOf: (row) => row.depth ?? (row.parent_id !== null && !row.is_parent ? 1 : 0),
isParent: (row) => row.is_parent,
};
@ -116,11 +116,12 @@ 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 = isTopParent && groups.isCollapsed(row);
const collapsed = isParent && 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" : ""
@ -133,7 +134,7 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
? `${paddingClass} bg-[color-mix(in_srgb,var(--muted)_15%,var(--card))]`
: `${paddingClass} bg-[var(--card)]`
}`}>
{isTopParent ? (
{isParent ? (
<button
type="button"
onClick={() => groups.toggle(row)}
@ -255,7 +256,7 @@ export default function BudgetVsActualTable({ data }: BudgetVsActualTableProps)
{hasGroups && (
<button
type="button"
onClick={() => (allExpanded ? groups.collapseAll() : groups.expandAll(data))}
onClick={() => (allExpanded ? groups.collapseAll(data) : 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,12 +93,13 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
const depth = row.depth;
const isTopParent = isParent && depth === 0;
const isIntermediateParent = isParent && depth >= 1;
const collapsed = isTopParent && groups.isCollapsed(row);
const collapsed = isParent && 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"
@ -116,7 +117,7 @@ export default function CategoryOverTimeTable({ data }: CategoryOverTimeTablePro
: `${paddingClass} bg-[var(--card)]`
}`}
>
{isTopParent ? (
{isParent ? (
<button
type="button"
onClick={() => groups.toggle(row)}
@ -211,7 +212,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() : groups.expandAll(data.tree))}
onClick={() => (allExpanded ? groups.collapseAll(data.tree) : 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

@ -1,74 +0,0 @@
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,10 +59,11 @@ function deltaColor(value: number, higherIsBetter: boolean): string {
const STORAGE_KEY = "compare-subtotals-position";
// Collapse groups keyed by category id; depth/parent mirror the render logic
// below so the hidden rows are exactly a group's indented descendants.
// Collapse groups keyed by category id; a row is hidden when any ancestor
// (walking parent_id) is collapsed, so every parent level is collapsible.
const COMPARE_COLLAPSE_ACCESSORS: CollapseAccessors<CategoryDelta> = {
keyOf: (row) => String(row.categoryId),
keyOf: (row) => `p:${row.categoryId}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
depthOf: (row) => row.depth ?? 0,
isParent: (row) => row.is_parent ?? false,
};
@ -154,12 +155,13 @@ export default function ComparePeriodTable({
const depth = row.depth ?? 0;
const isTopParent = isParent && depth === 0;
const isIntermediateParent = isParent && depth >= 1;
const collapsed = isTopParent && groups.isCollapsed(row);
const collapsed = isParent && 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"
@ -177,7 +179,7 @@ export default function ComparePeriodTable({
: `${paddingClass} bg-[var(--card)]`
}`}
>
{isTopParent ? (
{isParent ? (
<button
type="button"
onClick={() => groups.toggle(row)}
@ -349,7 +351,7 @@ export default function ComparePeriodTable({
{hasGroups && (
<button
type="button"
onClick={() => (allExpanded ? groups.collapseAll() : groups.expandAll(rows))}
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} />}

View file

@ -45,23 +45,26 @@ function makeData(months: string[], tree: OverTimeRow[]): CategoryOverTimeData {
const MONTHS = ["2025-01", "2025-02"];
// A realistic parent-first depth-first tree (income → expense → transfer):
// A realistic parent-first depth-first tree, three levels deep on the expense
// side (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)
// Épicerie (leaf, id 21)
// Resto (leaf, id 22)
// Loyer (top-level leaf, id 23)
// Épargne (transfer leaf, id 3)
// Alimentation (INTERMEDIATE parent, id 20)
// É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(21, "Épicerie", [400, 600], "expense", { parent_id: 2, depth: 1 }),
mkRow(22, "Resto", [100, 200], "expense", { parent_id: 2, depth: 1 }),
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(23, "Loyer", [1000, 1000], "expense", { depth: 0 }),
mkRow(3, "Épargne", [200, 200], "transfer", { depth: 0 }),
];
@ -70,6 +73,7 @@ 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", () => {
@ -79,13 +83,18 @@ describe("overTimeTableModel — storage key", () => {
});
describe("overTimeTableModel — collapse accessors", () => {
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);
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);
});
});
@ -101,12 +110,14 @@ 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(income.rows.map((r) => r.categoryName)).toEqual(["Revenus", "Paie", "Bonus"]);
expect(names(income.rows)).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(expense.rows.map((r) => r.categoryName)).toEqual([
expect(names(expense.rows)).toEqual([
"Dépenses",
"Alimentation",
"Épicerie",
"Resto",
"Loyer",
@ -114,7 +125,7 @@ describe("overTimeTableModel.groupOverTimeSections", () => {
expect(transferSection?.rows.map((r) => r.categoryName)).toEqual(["Épargne"]);
});
it("keeps subtotals as the reducer's leaf sums — a parent is never double-counted", () => {
it("keeps subtotals as the reducer's leaf sums — parents (incl. intermediate) are never double-counted", () => {
const data = makeData(MONTHS, buildTree());
const analysis = computeOverTimeResults(data);
const { nonTransferSections } = groupOverTimeSections(analysis, data.tree);
@ -125,7 +136,8 @@ 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 parent excluded).
// Épicerie 1000 + Resto 300 + Loyer 2000 = 3300 (Dépenses AND Alimentation
// parents excluded, even though Alimentation carries a [500,800] series).
expect(expense.total).toBe(3300);
});
@ -148,12 +160,13 @@ 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(visIncome.map((r) => r.categoryName)).toEqual(["Revenus"]);
expect(names(visIncome)).toEqual(["Revenus"]);
const expense = nonTransferSections.find((s) => s.type === "expense")!;
const visExpense = visibleRows(expense.rows, acc, isCollapsed(new Set()));
// Dépenses folds its children; the top-level leaf Loyer always stays.
expect(visExpense.map((r) => r.categoryName)).toEqual(["Dépenses", "Loyer"]);
// Dépenses folds its whole subtree (Alimentation + its leaves); the top-level
// leaf Loyer always stays.
expect(names(visExpense)).toEqual(["Dépenses", "Loyer"]);
});
it("reveals Paie (revenue) under Revenus once its group is expanded", () => {
@ -161,28 +174,55 @@ 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(["1"])));
expect(visible.map((r) => r.categoryName)).toEqual(["Revenus", "Paie", "Bonus"]);
const visible = visibleRows(income.rows, acc, isCollapsed(new Set(["p:1"])));
expect(names(visible)).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(["1"])));
const expanded = visibleRows(income.rows, acc, isCollapsed(new Set(["p:1"])));
expect(collapsed.length).toBeLessThan(expanded.length);
// The subtotal the table shows is identical in both states.
expect(income.total).toBe(6500);
// 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);
});
});

View file

@ -10,13 +10,14 @@ import type { OverTimeAnalysis, OverTimeType } from "./overTimeResults";
*/
/**
* 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
* 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
* `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) => String(row.categoryId),
keyOf: (row) => `p:${row.categoryId}`,
parentKeyOf: (row) => (row.parent_id != null ? `p:${row.parent_id}` : null),
depthOf: (row) => row.depth,
isParent: (row) => row.is_parent,
};

130
src/hooks/useBudget.test.ts Normal file
View file

@ -0,0 +1,130 @@
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 } from "../shared/types";
import type { BudgetYearRow, BudgetTemplate, ImportSource, Category, BudgetEntry } from "../shared/types";
import {
getAllActiveCategories,
getBudgetEntriesForYear,
@ -73,6 +73,304 @@ 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);
@ -93,276 +391,7 @@ export function useBudget() {
if (fetchId !== fetchIdRef.current) return;
// 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);
});
const rows = buildBudgetYearRows(allCategories, entries, prevYearActuals);
dispatch({ type: "SET_DATA", payload: { rows, templates } });
} catch (e) {

View file

@ -1,93 +1,133 @@
import { useCallback, useState } from "react";
import { useCallback, useEffect, 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 top-level parent row is collapsed (its children are hidden). */
/** True when this parent row is collapsed (its subtree is 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 group (back to the default), then persist. */
collapseAll: () => void;
/** Collapse every collapsible group found in `rows`, then persist. */
collapseAll: (rows: T[]) => void;
/** True when `rows` has at least one group and all of them are expanded. */
allExpanded: (rows: T[]) => boolean;
/** Number of collapsible top-level groups in `rows`. */
/** Number of collapsible groups (parents, any depth) in `rows`. */
groupCount: (rows: T[]) => number;
}
/**
* 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.
* Per-report collapse/expand state for the hierarchical tables (issue #254/#265),
* generalised to every hierarchy level (issue #288).
*
* 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`.
* 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).
*/
export function useCollapsibleGroups<T>(
storageKey: string,
storageKey: string | null,
acc: CollapseAccessors<T>,
options?: { defaultExpanded?: boolean },
): CollapsibleGroups<T> {
const [expanded, setExpanded] = useState<Set<string>>(() =>
parseStoredExpanded(
typeof localStorage !== "undefined" ? localStorage.getItem(storageKey) : null,
),
);
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 persist = useCallback(
(next: Set<string>) => {
try {
localStorage.setItem(storageKey, serializeExpanded(next));
} catch {
// Best-effort: a write failure just means the next session falls back
// to the collapsed default.
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.
});
}
setExpanded(next);
},
[storageKey],
);
const isCollapsed = useCallback((row: T) => !expanded.has(acc.keyOf(row)), [expanded, acc]);
const isCollapsed = useCallback(
(row: T) => isCollapsedFor(flipped, acc.keyOf(row), defaultExpanded),
[flipped, acc, defaultExpanded],
);
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(expanded);
const next = new Set(flipped);
if (next.has(key)) next.delete(key);
else next.add(key);
persist(next);
},
[expanded, acc, persist],
[flipped, 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(new Set(collapsibleKeys(rows, acc))),
[acc, persist],
(rows: T[]) => persist(defaultExpanded ? new Set() : new Set(collapsibleKeys(rows, acc))),
[acc, persist, defaultExpanded],
);
const collapseAll = useCallback(() => persist(new Set()), [persist]);
const collapseAll = useCallback(
(rows: T[]) => persist(defaultExpanded ? new Set(collapsibleKeys(rows, acc)) : new Set()),
[acc, persist, defaultExpanded],
);
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) => expanded.has(k));
return keys.length > 0 && keys.every((k) => !isCollapsedFor(flipped, k, defaultExpanded));
},
[expanded, acc],
[flipped, acc, defaultExpanded],
);
return { visible, isCollapsed, toggle, expandAll, collapseAll, allExpanded, groupCount };

View file

@ -3,8 +3,11 @@ 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 from "../components/categories/CategoryTaxonomyTree";
import CategoryTaxonomyTree, {
TAXONOMY_COLLAPSE_ACCESSORS,
} from "../components/categories/CategoryTaxonomyTree";
import type { TaxonomyNode } from "../services/categoryTaxonomyService";
import { useCollapsibleGroups } from "../hooks/useCollapsibleGroups";
function countNodes(nodes: TaxonomyNode[]): {
roots: number;
@ -32,51 +35,47 @@ function countNodes(nodes: TaxonomyNode[]): {
return { roots, subcategories, leaves };
}
function collectAllIds(nodes: TaxonomyNode[]): number[] {
const ids: number[] = [];
// 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[] = [];
const walk = (n: TaxonomyNode) => {
ids.push(n.id);
flat.push(n);
n.children.forEach(walk);
};
nodes.forEach(walk);
return ids;
return flat;
}
export default function CategoriesStandardGuidePage() {
const { t } = useTranslation();
const { taxonomy } = useCategoryTaxonomy();
const [search, setSearch] = useState("");
const [expanded, setExpanded] = useState<Set<number>>(() => {
// Start with roots collapsed (user can expand as needed); counter and search still work.
return new Set<number>();
// 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 counts = useMemo(() => countNodes(taxonomy.roots), [taxonomy.roots]);
const total = counts.roots + counts.subcategories + counts.leaves;
const toggleNode = (id: number) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
// Flattened nodes for the bulk ops (expand/collapse all, allExpanded).
const flatNodes = useMemo(() => flattenNodes(taxonomy.roots), [taxonomy.roots]);
const handleExpandAll = () => {
setExpanded(new Set(collectAllIds(taxonomy.roots)));
};
const handleCollapseAll = () => {
setExpanded(new Set());
};
const handleExpandAll = () => groups.expandAll(flatNodes);
const handleCollapseAll = () => groups.collapseAll(flatNodes);
const handlePrint = () => {
// window.print() opens the browser print dialog; @media print rules strip chrome.
window.print();
};
const allExpanded = expanded.size > 0;
// 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);
return (
<div className="p-6 max-w-4xl mx-auto space-y-6">
@ -177,8 +176,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}
expanded={expanded}
onToggle={toggleNode}
isCollapsed={groups.isCollapsed}
onToggle={groups.toggle}
searchQuery={search}
/>
</section>

View file

@ -1,102 +1,234 @@
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 for the tests: key, depth, is-parent. */
/** Tiny hierarchy row: id, parent id, is-parent flag, indentation depth. */
interface Row {
k: string;
d: number;
p: boolean;
id: number;
parent: number | null;
is_parent: boolean;
depth: number;
}
const acc: CollapseAccessors<Row> = {
keyOf: (r) => r.k,
depthOf: (r) => r.d,
isParent: (r) => r.p,
keyOf: (r) => `p:${r.id}`,
parentKeyOf: (r) => (r.parent === null ? null : `p:${r.parent}`),
isParent: (r) => r.is_parent,
depthOf: (r) => r.depth,
};
const row = (k: string, d: number, p: boolean): Row => ({ k, d, p });
const r = (id: number, parent: number | null, is_parent: boolean, depth: number): Row => ({
id,
parent,
is_parent,
depth,
});
// 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),
// 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
];
// 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);
// 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
];
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"]);
/** 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]);
});
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 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("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("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("shows everything when all groups are expanded", () => {
const visible = visibleRows(tree, acc, isCollapsed(new Set(["housing", "salary"])));
expect(visible).toHaveLength(tree.length);
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("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);
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]);
});
});
describe("collapsibleRows.collapsibleKeys", () => {
it("lists only top-level parent rows, in order", () => {
expect(collapsibleKeys(tree, acc)).toEqual(["housing", "salary"]);
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("returns [] when there is no hierarchy", () => {
const flat = [row("a", 0, false), row("b", 0, false)];
const flat = [r(1, null, false, 0), r(2, null, false, 0)];
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 collapsed default (empty set)", () => {
it("treats absent storage as the default state (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('["housing","salary"]')].sort()).toEqual(["housing", "salary"]);
expect([...parseStoredExpanded('["p:1","p:2"]')].sort()).toEqual(["p:1", "p:2"]);
});
it("falls back to empty on corrupt or non-array JSON", () => {
@ -110,7 +242,7 @@ describe("collapsibleRows.parseStoredExpanded / serializeExpanded", () => {
});
it("round-trips through serialize", () => {
const set = new Set(["a", "b"]);
expect([...parseStoredExpanded(serializeExpanded(set))].sort()).toEqual(["a", "b"]);
const set = new Set(["p:1", "p:12"]);
expect([...parseStoredExpanded(serializeExpanded(set))].sort()).toEqual(["p:1", "p:12"]);
});
});

View file

@ -1,71 +1,104 @@
/**
* Collapse/expand of top-level category groups in the hierarchical comparable
* reports (real-vs-real Compare + Budget-vs-Actual) issue #254.
* 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.
*
* Pure helpers only; the React state + persistence glue lives in the
* `useCollapsibleGroups` hook.
*
* 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.
* 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.
*
* 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.
* 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.
*/
/**
* 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-group key (a category id, stringified). */
/** Stable per-parent key, injective across the section: `p:<categoryId>`. */
keyOf: (row: T) => string;
/** Indentation depth; 0 = top-level. Must match the rendered indentation. */
depthOf: (row: T) => number;
/** Key of this row's parent (`p:<parent_id>`), or null at a root. */
parentKeyOf: (row: T) => string | null;
/** 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 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.
* 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.
*/
export function visibleRows<T>(
rows: T[],
acc: CollapseAccessors<T>,
isCollapsed: (row: T) => boolean,
): T[] {
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);
// 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);
}
}
return out;
return false;
};
return rows.filter((r) => !hiddenByAncestor(r));
}
/** Keys of every collapsible group (top-level parent rows), in encounter order. */
/** Keys of every collapsible group (all parent rows, any depth), in encounter order. */
export function collapsibleKeys<T>(rows: T[], acc: CollapseAccessors<T>): string[] {
const keys: string[] = [];
for (const row of rows) {
if (acc.depthOf(row) === 0 && acc.isParent(row)) keys.push(acc.keyOf(row));
if (acc.isParent(row)) keys.push(acc.keyOf(row));
}
return keys;
}
/**
* 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.
* 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.
*/
export function parseStoredExpanded(raw: string | null): Set<string> {
if (!raw) return new Set();
@ -75,12 +108,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 collapsed default.
// Corrupt value: fall back to the default state.
}
return new Set();
}
/** Serialises the set of expanded group keys for persistence. */
export function serializeExpanded(expanded: Set<string>): string {
return JSON.stringify([...expanded]);
/** Serialises the flipped-key set for persistence. */
export function serializeExpanded(flipped: Set<string>): string {
return JSON.stringify([...flipped]);
}