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>
This commit is contained in:
parent
48adb3db77
commit
9c325e274b
5 changed files with 501 additions and 294 deletions
|
|
@ -5,6 +5,7 @@
|
|||
### 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).
|
||||
|
||||
## [0.13.0] - 2026-07-12
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
### 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).
|
||||
|
||||
## [0.13.0] - 2026-07-12
|
||||
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
130
src/hooks/useBudget.test.ts
Normal file
130
src/hooks/useBudget.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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,26 +73,30 @@ 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 };
|
||||
|
||||
export function useBudget() {
|
||||
const { accountIds } = useReportsPeriod();
|
||||
const [state, dispatch] = useReducer(reducer, undefined, initialState);
|
||||
const fetchIdRef = useRef(0);
|
||||
|
||||
const refreshData = useCallback(async (year: number, ids: number[]) => {
|
||||
const fetchId = ++fetchIdRef.current;
|
||||
dispatch({ type: "SET_LOADING", payload: true });
|
||||
dispatch({ type: "SET_ERROR", payload: null });
|
||||
|
||||
try {
|
||||
const [allCategories, entries, prevYearActuals, templates] = await Promise.all([
|
||||
getAllActiveCategories(),
|
||||
getBudgetEntriesForYear(year),
|
||||
getActualTotalsForYear(year - 1, ids),
|
||||
getAllTemplates(),
|
||||
]);
|
||||
|
||||
if (fetchId !== fetchIdRef.current) return;
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
|
|
@ -364,6 +368,31 @@ export function useBudget() {
|
|||
return a.category_name.localeCompare(b.category_name);
|
||||
});
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function useBudget() {
|
||||
const { accountIds } = useReportsPeriod();
|
||||
const [state, dispatch] = useReducer(reducer, undefined, initialState);
|
||||
const fetchIdRef = useRef(0);
|
||||
|
||||
const refreshData = useCallback(async (year: number, ids: number[]) => {
|
||||
const fetchId = ++fetchIdRef.current;
|
||||
dispatch({ type: "SET_LOADING", payload: true });
|
||||
dispatch({ type: "SET_ERROR", payload: null });
|
||||
|
||||
try {
|
||||
const [allCategories, entries, prevYearActuals, templates] = await Promise.all([
|
||||
getAllActiveCategories(),
|
||||
getBudgetEntriesForYear(year),
|
||||
getActualTotalsForYear(year - 1, ids),
|
||||
getAllTemplates(),
|
||||
]);
|
||||
|
||||
if (fetchId !== fetchIdRef.current) return;
|
||||
|
||||
const rows = buildBudgetYearRows(allCategories, entries, prevYearActuals);
|
||||
|
||||
dispatch({ type: "SET_DATA", payload: { rows, templates } });
|
||||
} catch (e) {
|
||||
if (fetchId !== fetchIdRef.current) return;
|
||||
|
|
|
|||
Loading…
Reference in a new issue