diff --git a/CHANGELOG.fr.md b/CHANGELOG.fr.md index 9306f39..1601a22 100644 --- a/CHANGELOG.fr.md +++ b/CHANGELOG.fr.md @@ -5,6 +5,7 @@ ### Corrigé - L'ajout d'un mot-clé par le clic droit sur une transaction, la création d'une catégorie et les autres enregistrements en plusieurs étapes, comme une répartition ou une restauration, ne peuvent plus échouer sur « database is locked » (#543). +- Rapports → Analyse par catégorie : un clic sur une catégorie des hausses ou des baisses d'une carte ouvre désormais l'analyse sur cette catégorie, sur la même période, au lieu d'un sélecteur vide ; la catégorie choisie reste dans l'adresse et survit donc à un rechargement. Le donut d'une catégorie de premier niveau montre désormais chaque sous-catégorie avec le total de ses propres sous-catégories, là où il ne montrait rien. Pour une catégorie sans sous-catégorie, ou quand les sous-catégories sont exclues, l'encadré à côté d'« Évolution » montre désormais ses métriques clés sur la période au lieu de « Aucune donnée » : total, nombre de transactions, moyenne, plus grande et plus petite transaction, un remboursement comptant comme un montant négatif et une transaction répartie une seule fois, pour sa part dans la catégorie (#548). ### Sécurité diff --git a/CHANGELOG.md b/CHANGELOG.md index eaf015b..f38b020 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixed - Adding a keyword from a transaction's right-click menu, creating a category, and the other saves made in several steps, such as a split or a restore, can no longer fail with “database is locked” (#543). +- Reports → Category analysis: clicking a category in a card's increases or decreases now opens the analysis on that category, over the same period, instead of an empty selector; the chosen category stays in the address, so it survives a reload. The donut of a first-level category now shows each subcategory with the total of its own subcategories, where it showed nothing. For a category without subcategories, or with the subcategories left out, the box beside “Evolution” now shows its key metrics for the period instead of “No data”: total, number of transactions, average, largest and smallest transaction, a refund counting as a negative amount and a split transaction once, for its part in the category (#548). ### Security diff --git a/docs/guide-utilisateur.md b/docs/guide-utilisateur.md index 24dbfaa..0bfd94e 100644 --- a/docs/guide-utilisateur.md +++ b/docs/guide-utilisateur.md @@ -461,9 +461,10 @@ Les trois modes ci-dessus, comme le tableau **Par catégorie** des Tendances, pr ### Rapport Analyse par catégorie (`/reports/category`) -Choisissez une catégorie dans la combobox en haut. Par défaut le rapport inclut automatiquement les sous-catégories (toggle *Directe seulement* pour les exclure). Vous voyez : +Choisissez une catégorie dans la combobox en haut, ou cliquez sur une catégorie des hausses et baisses d'une carte : le rapport s'ouvre sur elle, sur la même période, et la catégorie choisie reste dans l'adresse. Par défaut le rapport inclut automatiquement les sous-catégories (toggle *Directe seulement* pour les exclure). Vous voyez : -- Un **donut chart** de la répartition par sous-catégorie avec le total au centre ; une sous-catégorie au montant négatif (des remboursements supérieurs aux achats) n'y figure pas, et une ligne sous le donut le dit +- Un **donut chart** de la répartition par sous-catégorie avec le total au centre, chaque sous-catégorie comptant toutes ses propres sous-catégories ; une sous-catégorie au montant négatif (des remboursements supérieurs aux achats) n'y figure pas, et une ligne sous le donut le dit +- À la place du donut, pour une catégorie sans sous-catégorie, quand les sous-catégories sont exclues, ou quand aucune n'a de montant positif : les **métriques clés** de la période (total, nombre de transactions, moyenne, plus grande et plus petite transaction). Un remboursement y compte comme un montant négatif, et une transaction répartie compte une fois, pour sa part dans la catégorie ; « Aucune donnée » ne s'affiche que s'il n'y a aucune transaction - Un graphique d'évolution mensuelle de la catégorie - Un tableau triable des transactions diff --git a/src/__integration__/category-zoom.test.ts b/src/__integration__/category-zoom.test.ts new file mode 100644 index 0000000..e354340 --- /dev/null +++ b/src/__integration__/category-zoom.test.ts @@ -0,0 +1,176 @@ +/** + * The category zoom, read through its real service on a real SQLite database + * seeded like a new profile (`src/test/sqliteHarness.ts`, #548). + * + * Two defects of the issue: the donut of a first-level category was empty, + * because each subcategory only summed its own transactions while every + * transaction of the seed sits on a leaf; and a leaf, which has no + * subcategory, had nothing to show beside « Évolution ». Each direct child + * now sums its whole subtree, and the zoom returns the key figures of its + * transactions, oriented like its total. + */ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import type { DatabaseSync } from "node:sqlite"; + +vi.mock("../services/db", async () => (await import("../test/sqliteHarness")).dbModule()); + +import { openProfileDb, useDb } from "../test/sqliteHarness"; +import { saveSplitAdjustment } from "../services/transactionService"; +import { getCategoryZoom } from "../services/reportService"; + +// Categories of the seed of a new profile. +const FOOD = 1100; // « Alimentation », level 1, not inputable +const GROCERY_AND_MARKET = 1110; // level 2, parent of the next two, not inputable +const GROCERIES = 1111; // « Épicerie régulière », a leaf +const BUTCHER = 1112; // « Boucherie & poissonnerie », a leaf +const HEALTH = 1600; // « Santé & soins personnels », level 1 +const MEDICAL = 1610; // « Soins médicaux », level 2 +const PHARMACY = 1611; // « Pharmacie », a leaf +const DENTIST = 1613; // « Dentiste & orthodontiste », a leaf +const INCOME_ROOT = 1000; // « Revenus » +const EMPLOYMENT = 1010; // « Emploi » +const PAY = 1011; // « Paie régulière », a leaf +const BONUS = 1012; // « Primes & bonus », a leaf + +const FROM = "2026-10-01"; +const TO = "2026-10-31"; + +let db: DatabaseSync; + +beforeEach(() => { + db = useDb(openProfileDb()); +}); + +afterEach(() => { + db.close(); +}); + +/** A transaction as an import writes it; its id. */ +function insert(date: string, description: string, amount: number, categoryId: number | null): number { + const result = db + .prepare( + `INSERT INTO transactions (date, description, amount, category_id, original_description) + VALUES ($date, $description, $amount, $category, $description)`, + ) + .run({ $date: date, $description: description, $amount: amount, $category: categoryId }); + return Number(result.lastInsertRowid); +} + +describe("getCategoryZoom — a first-level category: each part sums its subcategory's leaves (#548)", () => { + beforeEach(() => { + insert("2026-10-03", "EPICERIE", -120, GROCERIES); + insert("2026-10-10", "EPICERIE", -80, GROCERIES); + insert("2026-10-12", "BOUCHER", -45.5, BUTCHER); + insert("2026-10-20", "REMBOURSEMENT BOUCHER", 10, BUTCHER); + // Outside the period, and outside the category: neither counts. + insert("2026-09-28", "EPICERIE", -999, GROCERIES); + insert("2026-10-05", "PHARMACIE", -30, PHARMACY); + }); + + it("the subcategory's part is the sum of its leaves, and the parts add up to the total", async () => { + const zoom = await getCategoryZoom(FOOD, FROM, TO, true); + expect(zoom.rollupTotal).toBe(235.5); + const part = zoom.byChild.find((c) => c.categoryId === GROCERY_AND_MARKET); + expect(part?.total).toBe(235.5); + // No transaction sits on « Alimentation » itself: the parts are the whole total. + const parts = zoom.byChild.reduce((sum, c) => sum + c.total, 0); + expect(Math.round(parts * 100) / 100).toBe(zoom.rollupTotal); + }); + + it("several subcategories, each with its own leaves", async () => { + insert("2026-10-07", "DENTISTE", -200, DENTIST); + const zoom = await getCategoryZoom(HEALTH, FROM, TO, true); + expect(zoom.rollupTotal).toBe(230); + expect(zoom.byChild.find((c) => c.categoryId === MEDICAL)?.total).toBe(230); + }); + + it("a second-level category still shows one part per leaf", async () => { + const zoom = await getCategoryZoom(GROCERY_AND_MARKET, FROM, TO, true); + const byChild = Object.fromEntries(zoom.byChild.map((c) => [c.categoryId, c.total])); + expect(byChild[GROCERIES]).toBe(200); + expect(byChild[BUTCHER]).toBe(35.5); + }); + + it("an income category keeps its sign: parts shown as they are", async () => { + insert("2026-10-02", "PAIE", 1000, PAY); + insert("2026-10-16", "PRIME", 250, BONUS); + const zoom = await getCategoryZoom(INCOME_ROOT, FROM, TO, true); + expect(zoom.rollupTotal).toBe(1250); + expect(zoom.byChild.find((c) => c.categoryId === EMPLOYMENT)?.total).toBe(1250); + }); +}); + +describe("getCategoryZoom — the key figures of the transactions, oriented like the total (#548)", () => { + it("a leaf: count, average, largest and smallest, a refund included", async () => { + insert("2026-10-03", "EPICERIE", -120, GROCERIES); + insert("2026-10-10", "EPICERIE", -80, GROCERIES); + insert("2026-10-12", "EPICERIE", -25, GROCERIES); + insert("2026-10-20", "REMBOURSEMENT", 15, GROCERIES); + insert("2026-09-28", "EPICERIE", -999, GROCERIES); // outside the period + + const zoom = await getCategoryZoom(GROCERIES, FROM, TO, true); + expect(zoom.rollupTotal).toBe(210); + expect(zoom.byChild).toEqual([]); + expect(zoom.metrics).toEqual({ + transactionCount: 4, + average: 52.5, + largest: 120, + // The refund lowers the spending: the smallest oriented figure. + smallest: -15, + }); + }); + + it("an income leaf keeps its sign", async () => { + insert("2026-10-02", "PAIE", 1000, PAY); + insert("2026-10-16", "PAIE", 1100, PAY); + insert("2026-10-20", "CORRECTION PAIE", -50, PAY); + const zoom = await getCategoryZoom(PAY, FROM, TO, true); + expect(zoom.metrics).toEqual({ transactionCount: 3, average: 683.33, largest: 1100, smallest: -50 }); + }); + + it("direct only: the figures of the category's own transactions", async () => { + insert("2026-10-03", "EPICERIE", -120, GROCERIES); + insert("2026-10-12", "BOUCHER", -40, BUTCHER); + const zoom = await getCategoryZoom(GROCERIES, FROM, TO, false); + expect(zoom.metrics).toEqual({ transactionCount: 1, average: 120, largest: 120, smallest: 120 }); + }); + + it("the figures cover every transaction, not the 500 rows of the table", async () => { + for (let i = 0; i < 520; i++) insert("2026-10-15", `EPICERIE ${i}`, -1, GROCERIES); + const zoom = await getCategoryZoom(GROCERIES, FROM, TO, true); + expect(zoom.transactions).toHaveLength(500); + expect(zoom.metrics.transactionCount).toBe(520); + expect(zoom.rollupTotal).toBe(520); + }); + + it("no transaction in the period: a count of 0 and no figure", async () => { + insert("2026-09-28", "EPICERIE", -999, GROCERIES); + const zoom = await getCategoryZoom(GROCERIES, FROM, TO, true); + expect(zoom.metrics).toEqual({ transactionCount: 0, average: null, largest: null, smallest: null }); + }); + + it("a split transaction counts once, for the part that stays in the category", async () => { + // −100 in Groceries, −30 of it split to Pharmacy: the service writes the + // −30 line and a +30 offset line in Groceries. + const groceries = insert("2026-10-05", "EPICERIE METRO", -100, GROCERIES); + await saveSplitAdjustment(groceries, [{ category_id: PHARMACY, amount: -30, description: "PHARMACIE" }]); + insert("2026-10-08", "EPICERIE", -20, GROCERIES); + + const leaf = await getCategoryZoom(GROCERIES, FROM, TO, true); + expect(leaf.rollupTotal).toBe(90); + expect(leaf.metrics).toEqual({ transactionCount: 2, average: 45, largest: 70, smallest: 20 }); + + const pharmacy = await getCategoryZoom(PHARMACY, FROM, TO, true); + expect(pharmacy.metrics).toEqual({ transactionCount: 1, average: 30, largest: 30, smallest: 30 }); + }); + + it("a transaction split entirely out of the category is not counted", async () => { + const groceries = insert("2026-10-05", "EPICERIE METRO", -100, GROCERIES); + await saveSplitAdjustment(groceries, [{ category_id: PHARMACY, amount: -100, description: "PHARMACIE" }]); + insert("2026-10-08", "EPICERIE", -20, GROCERIES); + + const leaf = await getCategoryZoom(GROCERIES, FROM, TO, true); + expect(leaf.rollupTotal).toBe(20); + expect(leaf.metrics).toEqual({ transactionCount: 1, average: 20, largest: 20, smallest: 20 }); + }); +}); diff --git a/src/components/reports/CategoryZoomBreakdown.render.test.tsx b/src/components/reports/CategoryZoomBreakdown.render.test.tsx new file mode 100644 index 0000000..9369d40 --- /dev/null +++ b/src/components/reports/CategoryZoomBreakdown.render.test.tsx @@ -0,0 +1,72 @@ +// The box left of « Évolution » in the category zoom (#548): the donut when it +// has a part to draw, the key figures of the transactions otherwise. No jsdom: +// react-dom/server renders the markup; Recharts draws nothing without a size, +// the donut is recognised by its centre label. +import { describe, it, expect, vi } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; + +vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); + +import CategoryZoomBreakdown from "./CategoryZoomBreakdown"; +import type { CategoryZoomChild, CategoryZoomData, CategoryZoomMetrics } from "../../shared/types"; + +const child = (categoryId: number, total: number): CategoryZoomChild => ({ + categoryId, + categoryName: `C${categoryId}`, + categoryColor: "#000", + total, +}); + +const FIGURES: CategoryZoomMetrics = { transactionCount: 4, average: 52.5, largest: 120, smallest: -15 }; + +function zoom(byChild: CategoryZoomChild[], metrics: CategoryZoomMetrics = FIGURES): CategoryZoomData { + return { rollupTotal: 210, metrics, byChild, monthlyEvolution: [], transactions: [] }; +} + +const render = (data: CategoryZoomData) => + renderToStaticMarkup(); + +/** `Intl` in fr-CA separates thousands and currency by narrow or plain no-break spaces. */ +const plain = (html: string) => html.replace(/[  ]/g, " "); + +describe("CategoryZoomBreakdown — the donut, or the key figures (#548)", () => { + it("a category with positive subcategories keeps its donut", () => { + const html = render(zoom([child(1, 150), child(2, 60)])); + expect(html).toContain("CENTRE"); + expect(html).not.toContain("reports.category.metrics.title"); + }); + + it("a leaf (no subcategory): the key figures, never « Aucune donnée »", () => { + const html = plain(render(zoom([]))); + expect(html).not.toContain("CENTRE"); + expect(html).not.toContain("t(reports.empty.noData)"); + expect(html).toContain("t(reports.category.metrics.title)"); + expect(html).toContain("t(reports.category.breakdown)"); + expect(html).toContain("210,00 $"); + expect(html).toContain("t(reports.category.metrics.count)"); + expect(html).toContain(">4<"); + expect(html).toContain("52,50 $"); + expect(html).toContain("120,00 $"); + expect(html).toContain("-15,00 $"); + }); + + it("subcategories left out (the box unchecked gives no part): the key figures too", () => { + // `byChild` is only computed with the subcategories included. + const html = render(zoom([])); + expect(html).toContain("t(reports.category.metrics.average)"); + expect(html).toContain("t(reports.category.metrics.largest)"); + expect(html).toContain("t(reports.category.metrics.smallest)"); + }); + + it("every subcategory negative or zero: the key figures, and the line that says why", () => { + const html = render(zoom([child(1, 0), child(2, -50)])); + expect(html).toContain("t(reports.category.metrics.title)"); + expect(html).toContain("t(reports.category.donutOmitted[count=1])"); + }); + + it("« Aucune donnée » only when the period has no transaction", () => { + const html = render(zoom([], { transactionCount: 0, average: null, largest: null, smallest: null })); + expect(html).toContain("t(reports.empty.noData)"); + expect(html).not.toContain("t(reports.category.metrics.title)"); + }); +}); diff --git a/src/components/reports/CategoryZoomBreakdown.tsx b/src/components/reports/CategoryZoomBreakdown.tsx new file mode 100644 index 0000000..a3ce7a5 --- /dev/null +++ b/src/components/reports/CategoryZoomBreakdown.tsx @@ -0,0 +1,25 @@ +import type { CategoryZoomData } from "../../shared/types"; +import CategoryDonutChart from "./CategoryDonutChart"; +import CategoryZoomMetrics from "./CategoryZoomMetrics"; +import { donutParts } from "./donutParts"; + +export interface CategoryZoomBreakdownProps { + data: CategoryZoomData; + centerLabel: string; + centerValue: string; +} + +/** + * The box left of « Évolution » in the category zoom (#548): the donut of the + * subcategories when it has a part to draw, the key figures of the + * transactions otherwise (a leaf, the subcategories left out, or none with a + * positive amount), so the box never stays empty while the period has + * transactions. + */ +export default function CategoryZoomBreakdown({ data, centerLabel, centerValue }: CategoryZoomBreakdownProps) { + const { parts, negativeCount } = donutParts(data.byChild); + if (parts.length > 0) { + return ; + } + return ; +} diff --git a/src/components/reports/CategoryZoomMetrics.tsx b/src/components/reports/CategoryZoomMetrics.tsx new file mode 100644 index 0000000..ce8692a --- /dev/null +++ b/src/components/reports/CategoryZoomMetrics.tsx @@ -0,0 +1,66 @@ +import { useTranslation } from "react-i18next"; +import type { CategoryZoomMetrics as Metrics } from "../../shared/types"; + +export interface CategoryZoomMetricsProps { + /** The zoom's total over the period, oriented like the figures (`rollupTotal`). */ + total: number; + metrics: Metrics; + /** Subcategories left out of the donut for a negative amount (D7, #392). */ + omittedCount?: number; +} + +/** + * Key figures of the zoomed category's transactions (#548), shown in place of + * the donut when it has no part to draw: a leaf, the subcategories left out, + * or no subcategory with a positive amount. « Aucune donnée » only when the + * period has no transaction at all. + */ +export default function CategoryZoomMetrics({ total, metrics, omittedCount = 0 }: CategoryZoomMetricsProps) { + const { t, i18n } = useTranslation(); + const money = new Intl.NumberFormat(i18n.language === "fr" ? "fr-CA" : "en-CA", { + style: "currency", + currency: "CAD", + }); + const omitted = + omittedCount > 0 ? ( +

+ {t("reports.category.donutOmitted", { count: omittedCount })} +

+ ) : null; + + if (metrics.transactionCount === 0) { + return ( +
+ {t("reports.empty.noData")} + {omitted} +
+ ); + } + + const figure = (value: number | null) => (value === null ? "—" : money.format(value)); + const rows: Array<[string, string]> = [ + [t("reports.category.metrics.count"), new Intl.NumberFormat(i18n.language).format(metrics.transactionCount)], + [t("reports.category.metrics.average"), figure(metrics.average)], + [t("reports.category.metrics.largest"), figure(metrics.largest)], + [t("reports.category.metrics.smallest"), figure(metrics.smallest)], + ]; + + return ( +
+

{t("reports.category.metrics.title")}

+
+ {t("reports.category.breakdown")} + {money.format(total)} +
+
+ {rows.map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ {omitted} +
+ ); +} diff --git a/src/hooks/useCategoryZoom.ts b/src/hooks/useCategoryZoom.ts index 53e2e03..2ea7ec5 100644 --- a/src/hooks/useCategoryZoom.ts +++ b/src/hooks/useCategoryZoom.ts @@ -1,41 +1,60 @@ 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 { - zoomedCategoryId: number | null; 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: "SET_CATEGORY"; payload: number | null } | { type: "TOGGLE_ROLLUP"; payload: boolean } | { type: "SET_LOADING"; payload: boolean } - | { type: "SET_DATA"; payload: CategoryZoomData } + | { type: "SET_DATA"; payload: { categoryId: number; data: CategoryZoomData } } | { type: "SET_ERROR"; payload: string }; const initialState: State = { - zoomedCategoryId: null, rollupChildren: true, data: null, + dataCategoryId: null, isLoading: false, error: null, }; function reducer(state: State, action: Action): State { switch (action.type) { - case "SET_CATEGORY": - return { ...state, zoomedCategoryId: action.payload, data: null }; case "TOGGLE_ROLLUP": return { ...state, rollupChildren: action.payload }; case "SET_LOADING": return { ...state, isLoading: action.payload }; case "SET_DATA": - return { ...state, data: action.payload, isLoading: false, error: null }; + 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: @@ -43,8 +62,16 @@ function reducer(state: State, action: Action): 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); @@ -63,7 +90,7 @@ export function useCategoryZoom() { try { const data = await getCategoryZoom(categoryId, dateFrom, dateTo, includeChildren); if (id !== fetchIdRef.current) return; - dispatch({ type: "SET_DATA", payload: data }); + 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) }); @@ -73,20 +100,37 @@ export function useCategoryZoom() { ); useEffect(() => { - fetch(state.zoomedCategoryId, state.rollupChildren, from, to); - }, [fetch, state.zoomedCategoryId, state.rollupChildren, from, to]); + fetch(zoomedCategoryId, state.rollupChildren, from, to); + }, [fetch, zoomedCategoryId, state.rollupChildren, from, to]); - const setCategory = useCallback((id: number | null) => { - dispatch({ type: "SET_CATEGORY", payload: id }); - }, []); + 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(state.zoomedCategoryId, state.rollupChildren, from, to); - }, [fetch, state.zoomedCategoryId, state.rollupChildren, from, to]); + fetch(zoomedCategoryId, state.rollupChildren, from, to); + }, [fetch, zoomedCategoryId, state.rollupChildren, from, to]); - return { ...state, setCategory, setRollupChildren, refetch, from, to }; + const { dataCategoryId, ...rest } = state; + const data = zoomedCategoryId !== null && dataCategoryId === zoomedCategoryId ? state.data : null; + + return { ...rest, data, zoomedCategoryId, setCategory, setRollupChildren, refetch, from, to }; } diff --git a/src/hooks/useCategoryZoom.wiring.test.ts b/src/hooks/useCategoryZoom.wiring.test.ts index eb7094b..fc43012 100644 --- a/src/hooks/useCategoryZoom.wiring.test.ts +++ b/src/hooks/useCategoryZoom.wiring.test.ts @@ -1,12 +1,14 @@ -// useCategoryZoom — the period's bounds reach the service as they are, so -// « Tout » asks for every date (#479). +// useCategoryZoom — the zoomed category lives in the URL (`cat`, #548), and +// the period's bounds reach the service as they are, so « Tout » asks for +// every date (#479). // // React's hooks come from the shared harness (src/test/hookHarness.ts, #409): // the hook runs as a plain function, its reducer is applied, and `commit()` -// runs its effects. The service and the reports period are mocked: on -// « Tout », `from` and `to` are absent (resolveReportsPeriod). What is pinned: -// the zoom hands those absent bounds to `getCategoryZoom`, which binds them as -// NULL and skips them (reportService.test.ts), instead of a range of its own. +// runs its effects. The service, the reports period and the router's search +// params are mocked: on « Tout », `from` and `to` are absent +// (resolveReportsPeriod). The setter of the search params applies the +// functional update it receives to the mocked URL, as react-router does, so +// what the hook writes is read back at the next render. import { describe, it, expect, vi, beforeEach } from "vitest"; vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig())); @@ -17,18 +19,32 @@ const period = vi.hoisted(() => ({ vi.mock("./useReportsPeriod", () => ({ useReportsPeriod: () => ({ from: period.from, to: period.to }), })); +const router = vi.hoisted(() => ({ + params: new URLSearchParams(), + setSearchParams: vi.fn(), +})); +vi.mock("react-router-dom", () => ({ + useSearchParams: () => [router.params, router.setSearchParams], +})); const services = vi.hoisted(() => ({ getCategoryZoom: vi.fn() })); vi.mock("../services/reportService", () => services); import { hookHarness } from "../test/hookHarness"; -import { useCategoryZoom } from "./useCategoryZoom"; +import { parseCategoryId, useCategoryZoom } from "./useCategoryZoom"; const harness = hookHarness(); +/** Mounts the hook on the URL `search` and runs the effects of its first render. */ +function mountOn(search: string) { + router.params = new URLSearchParams(search); + const first = harness.render(useCategoryZoom); + harness.commit(); + return first; +} + /** Mounts the hook, picks a category, and runs the effects of that render. */ function zoomOn(categoryId: number) { - harness.render(useCategoryZoom); - harness.commit(); // no category yet: nothing is asked + mountOn(""); harness.render(useCategoryZoom).setCategory(categoryId); harness.render(useCategoryZoom); harness.commit(); @@ -38,11 +54,89 @@ beforeEach(() => { harness.clear(); period.from = undefined; period.to = undefined; - // Never settles: only the arguments are read, and a late dispatch would - // land in the next test's mount. + router.params = new URLSearchParams(); + router.setSearchParams.mockReset().mockImplementation( + (update: URLSearchParams | ((prev: URLSearchParams) => URLSearchParams)) => { + router.params = typeof update === "function" ? update(router.params) : update; + }, + ); + // Never settles by default: only the arguments are read, and a late + // dispatch would land in the next test's mount. services.getCategoryZoom.mockReset().mockReturnValue(new Promise(() => {})); }); +describe("parseCategoryId — a positive integer, or no category (#548)", () => { + it.each([ + ["42", 42], + ["7", 7], + ])("%s → %s", (raw, id) => { + expect(parseCategoryId(raw)).toBe(id); + }); + + it.each([null, "", "abc", "0", "-3", "1.5", "1e3", " 5", "0x10", "99999999999999999999"])( + "%s → null", + (raw) => { + expect(parseCategoryId(raw)).toBeNull(); + }, + ); +}); + +describe("useCategoryZoom — the category clicked on a card is the one zoomed (#548)", () => { + it("mounted on ?cat=: the zoom asks for that category at the first commit", () => { + const first = mountOn("period=year&cat=1111"); + expect(first.zoomedCategoryId).toBe(1111); + expect(services.getCategoryZoom).toHaveBeenCalledTimes(1); + expect(services.getCategoryZoom).toHaveBeenCalledWith(1111, undefined, undefined, true); + }); + + it.each(["abc", "0", "-3"])("mounted on ?cat=%s: no category, nothing is asked", (raw) => { + const first = mountOn(`cat=${raw}`); + expect(first.zoomedCategoryId).toBeNull(); + harness.render(useCategoryZoom); + harness.commit(); + expect(services.getCategoryZoom).not.toHaveBeenCalled(); + }); + + it("a new category is written to `cat`, replacing the entry, the other parameters kept", () => { + mountOn("period=custom&from=2026-01-01&to=2026-03-31&sources=3,4&cat=1111"); + harness.render(useCategoryZoom).setCategory(1600); + + expect(router.setSearchParams).toHaveBeenCalledTimes(1); + expect(router.setSearchParams.mock.calls[0][1]).toEqual({ replace: true }); + expect(Object.fromEntries(router.params)).toEqual({ + period: "custom", + from: "2026-01-01", + to: "2026-03-31", + sources: "3,4", + cat: "1600", + }); + + // The selector reads the URL back: both agree. + expect(harness.render(useCategoryZoom).zoomedCategoryId).toBe(1600); + harness.commit(); + expect(services.getCategoryZoom).toHaveBeenLastCalledWith(1600, undefined, undefined, true); + }); + + it("clearing the selection removes `cat`, nothing else", () => { + mountOn("period=year&cat=1111"); + harness.render(useCategoryZoom).setCategory(null); + expect(Object.fromEntries(router.params)).toEqual({ period: "year" }); + expect(harness.render(useCategoryZoom).zoomedCategoryId).toBeNull(); + }); + + it("the data of a former category is never shown next to a new one", async () => { + const zoom = { rollupTotal: 1, byChild: [], monthlyEvolution: [], transactions: [] }; + services.getCategoryZoom.mockResolvedValueOnce(zoom); + mountOn("cat=1111"); + await Promise.resolve(); + expect(harness.render(useCategoryZoom).data).toBe(zoom); + + // The URL changes without setCategory (back, forward, a card link). + router.params = new URLSearchParams("cat=1600"); + expect(harness.render(useCategoryZoom).data).toBeNull(); + }); +}); + describe("useCategoryZoom — the period's bounds reach the service (#479)", () => { it("« Tout »: the zoom asks for no date bound", () => { zoomOn(42); diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 843f83c..860777e 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -697,7 +697,14 @@ "donutOmitted_one": "{{count}} subcategory with a negative amount is not drawn", "donutOmitted_other": "{{count}} subcategories with a negative amount are not drawn", "evolution": "Evolution", - "transactions": "Transactions" + "transactions": "Transactions", + "metrics": { + "title": "Key metrics", + "count": "Transactions", + "average": "Average per transaction", + "largest": "Largest transaction", + "smallest": "Smallest transaction" + } }, "keyword": { "addFromTransaction": "Add as keyword", @@ -1312,7 +1319,7 @@ "Cartes: single-month KPI dashboard (income, expenses, net, savings rate) with a Monthly/YTD toggle, 13-month sparklines, top movers, budget adherence, and seasonality", "Trends: global flow (income vs. expenses) and by-category evolution with a chart/table toggle", "Compare: Month vs. Previous Month, Year vs. Previous Year, and Actual vs. Budget", - "Category Analysis: single-category drill-down with donut, monthly evolution, and filterable transaction table; auto-rollup of subcategories", + "Category Analysis: single-category drill-down with a donut of its subcategories (or, for a category without subcategories, its key metrics: total, count, average, largest and smallest transaction), monthly evolution, and filterable transaction table; auto-rollup of subcategories; clicking a category on a card opens the analysis on that category", "Contextual keyword editing: right-click a transaction row to add its description as a keyword with a live preview of the matches", "SVG patterns (lines, dots, crosshatch) to distinguish categories", "View mode preference (chart vs. table) persisted per report section", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index f98fdcc..4e54408 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -697,7 +697,14 @@ "donutOmitted_one": "{{count}} sous-catégorie au montant négatif n'apparaît pas dans le graphique", "donutOmitted_other": "{{count}} sous-catégories au montant négatif n'apparaissent pas dans le graphique", "evolution": "Évolution", - "transactions": "Transactions" + "transactions": "Transactions", + "metrics": { + "title": "Métriques clés", + "count": "Transactions", + "average": "Moyenne par transaction", + "largest": "Plus grande transaction", + "smallest": "Plus petite transaction" + } }, "keyword": { "addFromTransaction": "Ajouter comme mot-clé", @@ -1312,7 +1319,7 @@ "Cartes : tableau de bord KPI d'un mois (revenus, dépenses, solde net, taux d'épargne) avec toggle Mensuel/YTD, sparklines 13 mois, top mouvements, adhésion budgétaire et saisonnalité", "Tendances : flux global (revenus vs dépenses) et évolution par catégorie avec toggle graphique/tableau", "Comparables : Mois vs Mois précédent, Année vs Année précédente, et Réel vs Budget", - "Analyse par catégorie : analyse d'une seule catégorie avec donut, évolution mensuelle et tableau de transactions filtrable ; rollup automatique des sous-catégories", + "Analyse par catégorie : analyse d'une seule catégorie avec donut des sous-catégories (ou, pour une catégorie sans sous-catégorie, ses métriques clés : total, nombre, moyenne, plus grande et plus petite transaction), évolution mensuelle et tableau de transactions filtrable ; rollup automatique des sous-catégories ; un clic sur une catégorie d'une carte ouvre l'analyse sur cette catégorie", "Édition contextuelle des mots-clés : clic droit sur une ligne de transaction pour ajouter sa description comme mot-clé avec prévisualisation en direct des matches", "Motifs SVG (lignes, points, hachures) pour distinguer les catégories", "Préférence chart/table mémorisée par section de rapport", diff --git a/src/pages/ReportsCategoryPage.tsx b/src/pages/ReportsCategoryPage.tsx index 6790928..ecf7b9b 100644 --- a/src/pages/ReportsCategoryPage.tsx +++ b/src/pages/ReportsCategoryPage.tsx @@ -4,7 +4,7 @@ import { Link } from "react-router-dom"; import { ArrowLeft } from "lucide-react"; import PeriodSelector from "../components/dashboard/PeriodSelector"; import CategoryZoomHeader from "../components/reports/CategoryZoomHeader"; -import CategoryDonutChart from "../components/reports/CategoryDonutChart"; +import CategoryZoomBreakdown from "../components/reports/CategoryZoomBreakdown"; import CategoryEvolutionChart from "../components/reports/CategoryEvolutionChart"; import CategoryTransactionsTable from "../components/reports/CategoryTransactionsTable"; import AddKeywordDialog from "../components/categories/AddKeywordDialog"; @@ -82,11 +82,7 @@ export default function ReportsCategoryPage() { ) : data ? (
- +

{t("reports.category.transactions")}

diff --git a/src/services/reportService.test.ts b/src/services/reportService.test.ts index 70f246f..da983d0 100644 --- a/src/services/reportService.test.ts +++ b/src/services/reportService.test.ts @@ -929,13 +929,36 @@ describe("getCategoryZoom", () => { .map(([sql]) => sql as string) .find((sql) => sql.includes("FROM categories child")); expect(childSql).toBeDefined(); - const [join, rest] = childSql!.split(/\bWHERE\b/); + // The query after its recursive CTE (which has WHEREs of its own). + const query = childSql!.slice(childSql!.indexOf("SELECT child.id")); + const [join, rest] = query.split(/\bWHERE\b/); expect(join.replace(/\s+/g, " ")).toContain( - `LEFT JOIN transactions t ON t.category_id = child.id AND ${BOUNDS}`, + `LEFT JOIN transactions t ON t.category_id = ct.id AND ${BOUNDS}`, ); expect(rest).not.toContain("t.date"); }); + it("sums each child over its subtree, with a depth guard of its own (#548)", async () => { + answerFourQueries(); + + await getCategoryZoom(42, undefined, undefined, true); + + const childSql = mockSelect.mock.calls + .map(([sql]) => sql as string) + .find((sql) => sql.includes("FROM categories child"))!; + expect(childSql).toContain("WITH RECURSIVE child_tree(root_id, id, depth)"); + expect(childSql).toContain("WHERE ct.depth < 4"); + expect(childSql.replace(/\s+/g, " ")).toContain("JOIN child_tree ct ON ct.root_id = child.id"); + }); + + it("a mocked rollup without figures gives a count of 0 and no figure (#548)", async () => { + answerFourQueries(); + + const zoom = await getCategoryZoom(42, undefined, undefined, true); + + expect(zoom.metrics).toEqual({ transactionCount: 0, average: null, largest: null, smallest: null }); + }); + it("direct only: its three queries skip a NULL bound too (#479)", async () => { mockSelect .mockResolvedValueOnce([]) // transactions diff --git a/src/services/reportService.ts b/src/services/reportService.ts index d6d5af7..12734aa 100644 --- a/src/services/reportService.ts +++ b/src/services/reportService.ts @@ -23,6 +23,7 @@ import type { CategoryDelta, CategoryZoomData, CategoryZoomChild, + CategoryZoomMetrics, CategoryZoomEvolutionPoint, MonthBalance, RecentTransaction, @@ -1106,16 +1107,10 @@ export async function getCategoryZoom( const db = await getDb(); const params = [categoryId, dateFrom ?? null, dateTo ?? null]; - const categoryFilter = includeSubcategories - ? `${CATEGORY_TREE_CTE} - SELECT t.id, t.date, t.description, t.amount, t.category_id - FROM transactions t - WHERE t.category_id IN (SELECT id FROM cat_tree) - AND ${ZOOM_DATE_BOUNDS}` - : `SELECT t.id, t.date, t.description, t.amount, t.category_id - FROM transactions t - WHERE t.category_id = $1 - AND ${ZOOM_DATE_BOUNDS}`; + // Rows of the zoom: the category's subtree, or the category alone. + const scope = includeSubcategories + ? "t.category_id IN (SELECT id FROM cat_tree)" + : "t.category_id = $1"; // 1. Transactions (with join for display) const txRows = await db.select( @@ -1123,39 +1118,89 @@ export async function getCategoryZoom( SELECT t.id, t.date, t.description, t.amount, c.name AS category_name, c.color AS category_color FROM transactions t LEFT JOIN categories c ON t.category_id = c.id - WHERE ${includeSubcategories - ? "t.category_id IN (SELECT id FROM cat_tree)" - : "t.category_id = $1"} + WHERE ${scope} AND ${ZOOM_DATE_BOUNDS} ORDER BY ABS(t.amount) DESC LIMIT 500`, params, ); - // 2. Rollup total: the signed balance of the matching rows, with the type of - // the zoomed category, which orients every figure of the zoom. - const totalRows = await db.select>( - `${categoryFilter.replace( - "SELECT t.id, t.date, t.description, t.amount, t.category_id", - "SELECT COALESCE(SUM(t.amount), 0) AS rollup, (SELECT type FROM categories WHERE id = $1) AS category_type", - )}`, + // 2. Rollup total and key figures (#548), in one pass over every matching + // row (not the 500 of the table), with the type of the zoomed category, + // which orients every figure of the zoom. Rows are grouped by transaction: + // a split parent and its lines in the scope (its offset line included) are + // one transaction, for their net. A group of several lines whose net is nil + // (a transaction split entirely out of the scope) is not counted; a single + // transaction of 0.00 is. + const totalRows = await db.select< + Array<{ + rollup: number | null; + tx_count: number | null; + min_net: number | null; + max_net: number | null; + category_type: string | null; + }> + >( + `${includeSubcategories ? CATEGORY_TREE_CTE : ""} + SELECT COALESCE(SUM(g.net), 0) AS rollup, + COALESCE(SUM(g.counted), 0) AS tx_count, + MIN(CASE WHEN g.counted = 1 THEN g.net END) AS min_net, + MAX(CASE WHEN g.counted = 1 THEN g.net END) AS max_net, + (SELECT type FROM categories WHERE id = $1) AS category_type + FROM (SELECT SUM(t.amount) AS net, + CASE WHEN COUNT(*) = 1 OR ABS(SUM(t.amount)) >= 0.005 THEN 1 ELSE 0 END AS counted + FROM transactions t + WHERE ${scope} + AND ${ZOOM_DATE_BOUNDS} + GROUP BY COALESCE(t.parent_transaction_id, t.id)) g`, params, ); - const section = toSection(totalRows[0]?.category_type); - const rollupTotal = orient(section, Number(totalRows[0]?.rollup ?? 0)); + const totals = totalRows[0]; + const section = toSection(totals?.category_type); + const rollupTotal = orient(section, Number(totals?.rollup ?? 0)); + const transactionCount = Number(totals?.tx_count ?? 0); + const metrics: CategoryZoomMetrics = { + transactionCount, + average: null, + largest: null, + smallest: null, + }; + if (transactionCount > 0 && totals?.min_net != null && totals?.max_net != null) { + // Orienting an expense flips the sign, so the largest figure may come + // from either bound. + const a = orient(section, Number(totals.min_net)); + const b = orient(section, Number(totals.max_net)); + metrics.average = toCents(rollupTotal / transactionCount); + metrics.largest = Math.max(a, b); + metrics.smallest = Math.min(a, b); + } - // 3. Breakdown by direct child (only meaningful when includeSubcategories is true) + // 3. Breakdown by direct child (only meaningful when includeSubcategories + // is true). Each child sums its whole subtree (#548): in the seeded + // taxonomies a category with children takes no transaction, every amount + // sits on a leaf. The walk starts at the children, one level below the + // zoomed category, so `depth < 4` reaches as deep as CATEGORY_TREE_CTE's + // `depth < 5` and guards a cyclic parent_id chain the same way. const byChild: CategoryZoomChild[] = []; if (includeSubcategories) { const childRows = await db.select< Array<{ child_id: number; child_name: string; child_color: string; total: number | null }> >( - `SELECT child.id AS child_id, + `WITH RECURSIVE child_tree(root_id, id, depth) AS ( + SELECT id, id, 0 FROM categories WHERE parent_id = $1 + UNION ALL + SELECT ct.root_id, c.id, ct.depth + 1 + FROM categories c + JOIN child_tree ct ON c.parent_id = ct.id + WHERE ct.depth < 4 + ) + SELECT child.id AS child_id, child.name AS child_name, COALESCE(child.color, '#9ca3af') AS child_color, COALESCE(SUM(t.amount), 0) AS total FROM categories child - LEFT JOIN transactions t ON t.category_id = child.id + JOIN child_tree ct ON ct.root_id = child.id + LEFT JOIN transactions t ON t.category_id = ct.id AND ${ZOOM_DATE_BOUNDS} WHERE child.parent_id = $1 GROUP BY child.id, child.name, child.color`, @@ -1179,9 +1224,7 @@ export async function getCategoryZoom( SELECT strftime('%Y-%m', t.date) AS month, COALESCE(SUM(t.amount), 0) AS total FROM transactions t - WHERE ${includeSubcategories - ? "t.category_id IN (SELECT id FROM cat_tree)" - : "t.category_id = $1"} + WHERE ${scope} AND ${ZOOM_DATE_BOUNDS} GROUP BY month ORDER BY month ASC`, @@ -1194,6 +1237,7 @@ export async function getCategoryZoom( return { rollupTotal, + metrics, byChild, monthlyEvolution, transactions: txRows, diff --git a/src/shared/types/index.ts b/src/shared/types/index.ts index 18764ee..e1fb28d 100644 --- a/src/shared/types/index.ts +++ b/src/shared/types/index.ts @@ -442,8 +442,22 @@ export interface CategoryZoomEvolutionPoint { total: number; } +/** + * Key figures of the zoomed category's transactions over the period (#548), + * oriented like `rollupTotal`: a purchase is positive in an expense zoom, a + * refund negative. A split transaction counts once, for its net in the scope. + * `average`, `largest` and `smallest` are null when there is no transaction. + */ +export interface CategoryZoomMetrics { + transactionCount: number; + average: number | null; + largest: number | null; + smallest: number | null; +} + export interface CategoryZoomData { rollupTotal: number; + metrics: CategoryZoomMetrics; byChild: CategoryZoomChild[]; monthlyEvolution: CategoryZoomEvolutionPoint[]; transactions: RecentTransaction[];