Simpl-Resultat/src/hooks/useCategoryZoom.ts
le king fu 1a44788f07
All checks were successful
PR Check — Frontend / frontend (pull_request) Successful in 3m16s
fix(reports): open the category zoom on the clicked card category, fill its left box
The category zoom now reads the zoomed category from the `cat` query param
written by the report cards' links, and writes it back (replace) when the
selection changes, so a click on a card opens the zoom on that category and
the selector and the URL always agree. Data read for another category is
never shown.

getCategoryZoom sums each direct child over its whole subtree (bounded
recursive CTE), so the donut of a first-level category shows its
subcategories instead of nothing, and returns the key figures of the
period's transactions (count, average, largest, smallest), oriented like the
total and computed in SQL over every row, a split transaction counting once
for its net in the scope. When the donut has no part to draw (a leaf, the
subcategories left out), the box beside the evolution chart shows those
figures; "No data" only when there is no transaction.

test: reproduces #548 (hook mounted on ?cat=, level-1 parts on real SQLite,
leaf metrics, render of the box)

Fixes #548

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:13:43 -05:00

136 lines
4.5 KiB
TypeScript

import { useReducer, useEffect, useRef, useCallback } from "react";
import { useSearchParams } from "react-router-dom";
import type { CategoryZoomData } from "../shared/types";
import { getCategoryZoom } from "../services/reportService";
import { useReportsPeriod } from "./useReportsPeriod";
/** Query param holding the zoomed category, written by the report cards' links (#548). */
const CATEGORY_PARAM = "cat";
/**
* Pure parser for the `cat` query param: a positive safe integer written in
* plain digits, anything else (`abc`, `0`, `-3`, `1.5`, `1e3`, a blank) is no
* category. Exported for tests.
*/
export function parseCategoryId(raw: string | null): number | null {
if (raw === null || !/^\d+$/.test(raw)) return null;
const id = Number(raw);
return Number.isSafeInteger(id) && id > 0 ? id : null;
}
interface State {
rollupChildren: boolean;
data: CategoryZoomData | null;
/** The category `data` was read for: data of another one is never shown. */
dataCategoryId: number | null;
isLoading: boolean;
error: string | null;
}
type Action =
| { type: "TOGGLE_ROLLUP"; payload: boolean }
| { type: "SET_LOADING"; payload: boolean }
| { type: "SET_DATA"; payload: { categoryId: number; data: CategoryZoomData } }
| { type: "SET_ERROR"; payload: string };
const initialState: State = {
rollupChildren: true,
data: null,
dataCategoryId: null,
isLoading: false,
error: null,
};
function reducer(state: State, action: Action): State {
switch (action.type) {
case "TOGGLE_ROLLUP":
return { ...state, rollupChildren: action.payload };
case "SET_LOADING":
return { ...state, isLoading: action.payload };
case "SET_DATA":
return {
...state,
data: action.payload.data,
dataCategoryId: action.payload.categoryId,
isLoading: false,
error: null,
};
case "SET_ERROR":
return { ...state, error: action.payload, isLoading: false };
default:
return state;
}
}
/**
* The zoom-on-category report. The zoomed category is the `cat` query param,
* read at every render, so a card's link opens the report on the category it
* names and the selector and the URL always agree (#548); `setCategory`
* rewrites it in place (`replace`), every other param (period, sources) kept.
*/
export function useCategoryZoom() {
const { from, to } = useReportsPeriod();
const [searchParams, setSearchParams] = useSearchParams();
const zoomedCategoryId = parseCategoryId(searchParams.get(CATEGORY_PARAM));
const [state, dispatch] = useReducer(reducer, initialState);
const fetchIdRef = useRef(0);
// `dateFrom` / `dateTo` are absent on « Tout »: getCategoryZoom then binds
// them as NULL and reads every date (#479).
const fetch = useCallback(
async (
categoryId: number | null,
includeChildren: boolean,
dateFrom: string | undefined,
dateTo: string | undefined,
) => {
if (categoryId === null) return;
const id = ++fetchIdRef.current;
dispatch({ type: "SET_LOADING", payload: true });
try {
const data = await getCategoryZoom(categoryId, dateFrom, dateTo, includeChildren);
if (id !== fetchIdRef.current) return;
dispatch({ type: "SET_DATA", payload: { categoryId, data } });
} catch (e) {
if (id !== fetchIdRef.current) return;
dispatch({ type: "SET_ERROR", payload: e instanceof Error ? e.message : String(e) });
}
},
[],
);
useEffect(() => {
fetch(zoomedCategoryId, state.rollupChildren, from, to);
}, [fetch, zoomedCategoryId, state.rollupChildren, from, to]);
const setCategory = useCallback(
(id: number | null) => {
setSearchParams(
(prev) => {
const params = new URLSearchParams(prev);
if (id === null) {
params.delete(CATEGORY_PARAM);
} else {
params.set(CATEGORY_PARAM, String(id));
}
return params;
},
{ replace: true },
);
},
[setSearchParams],
);
const setRollupChildren = useCallback((flag: boolean) => {
dispatch({ type: "TOGGLE_ROLLUP", payload: flag });
}, []);
const refetch = useCallback(() => {
fetch(zoomedCategoryId, state.rollupChildren, from, to);
}, [fetch, zoomedCategoryId, state.rollupChildren, from, to]);
const { dataCategoryId, ...rest } = state;
const data = zoomedCategoryId !== null && dataCategoryId === zoomedCategoryId ? state.data : null;
return { ...rest, data, zoomedCategoryId, setCategory, setRollupChildren, refetch, from, to };
}