fix(reports): open the category zoom on the clicked card category, fill its left box #551
22 changed files with 944 additions and 80 deletions
|
|
@ -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é
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
176
src/__integration__/category-zoom.test.ts
Normal file
176
src/__integration__/category-zoom.test.ts
Normal file
|
|
@ -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 });
|
||||
});
|
||||
});
|
||||
72
src/components/reports/CategoryZoomBreakdown.render.test.tsx
Normal file
72
src/components/reports/CategoryZoomBreakdown.render.test.tsx
Normal file
|
|
@ -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(<CategoryZoomBreakdown data={data} centerLabel="CENTRE" centerValue="210 $" />);
|
||||
|
||||
/** `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)");
|
||||
});
|
||||
});
|
||||
25
src/components/reports/CategoryZoomBreakdown.tsx
Normal file
25
src/components/reports/CategoryZoomBreakdown.tsx
Normal file
|
|
@ -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 <CategoryDonutChart byChild={data.byChild} centerLabel={centerLabel} centerValue={centerValue} />;
|
||||
}
|
||||
return <CategoryZoomMetrics total={data.rollupTotal} metrics={data.metrics} omittedCount={negativeCount} />;
|
||||
}
|
||||
66
src/components/reports/CategoryZoomMetrics.tsx
Normal file
66
src/components/reports/CategoryZoomMetrics.tsx
Normal file
|
|
@ -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 ? (
|
||||
<p className="text-xs text-[var(--muted-foreground)] text-center mt-2">
|
||||
{t("reports.category.donutOmitted", { count: omittedCount })}
|
||||
</p>
|
||||
) : null;
|
||||
|
||||
if (metrics.transactionCount === 0) {
|
||||
return (
|
||||
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-6 text-center text-[var(--muted-foreground)] italic">
|
||||
{t("reports.empty.noData")}
|
||||
{omitted}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-4">
|
||||
<h3 className="text-sm font-semibold mb-3">{t("reports.category.metrics.title")}</h3>
|
||||
<div className="mb-4">
|
||||
<span className="block text-xs text-[var(--muted-foreground)]">{t("reports.category.breakdown")}</span>
|
||||
<span className="text-2xl font-bold">{money.format(total)}</span>
|
||||
</div>
|
||||
<dl className="grid grid-cols-2 gap-3">
|
||||
{rows.map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt className="text-xs text-[var(--muted-foreground)]">{label}</dt>
|
||||
<dd className="text-base font-semibold">{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
{omitted}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
82
src/components/reports/cards/TopMoversList.render.test.tsx
Normal file
82
src/components/reports/cards/TopMoversList.render.test.tsx
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
// The links of a card's increases and decreases (#548): the category zoom opens
|
||||
// on the movers' month, from its first to its last day, whatever reports period
|
||||
// the URL carries. No jsdom: react-dom/server renders the list in vitest's node
|
||||
// environment, and `window` is stubbed for the search the link starts from.
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import type { CartesTopMover } from "../../../shared/types";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../../../test/i18nMock")).i18nMock());
|
||||
|
||||
import TopMoversList from "./TopMoversList";
|
||||
import { resolveReportsPeriod } from "../../../hooks/useReportsPeriod";
|
||||
|
||||
const mover = (categoryId: number | null): CartesTopMover => ({
|
||||
categoryId,
|
||||
categoryName: categoryId === null ? "Uncategorized" : `C${categoryId}`,
|
||||
categoryColor: "#000",
|
||||
previousAmount: 100,
|
||||
currentAmount: 220,
|
||||
deltaAbs: 120,
|
||||
deltaPct: 120,
|
||||
});
|
||||
|
||||
/** The hrefs of the rendered links, in order, from the URL search `search`. */
|
||||
function hrefs(search: string, year: number, month: number, movers = [mover(1111)]): string[] {
|
||||
vi.stubGlobal("window", { location: { search } });
|
||||
const html = renderToStaticMarkup(
|
||||
<MemoryRouter>
|
||||
<TopMoversList movers={movers} direction="up" year={year} month={month} />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
return [...html.matchAll(/href="([^"]*)"/g)].map((m) => m[1].replace(/&/g, "&"));
|
||||
}
|
||||
|
||||
const url = (href: string) => new URL(href, "http://app");
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("TopMoversList — a mover opens the zoom on the card's month (#548)", () => {
|
||||
it("names the category and the month, from its first to its last day", () => {
|
||||
const link = url(hrefs("", 2026, 10)[0]);
|
||||
expect(link.pathname).toBe("/reports/category");
|
||||
expect(link.searchParams.get("cat")).toBe("1111");
|
||||
expect(link.searchParams.get("period")).toBe("custom");
|
||||
expect(link.searchParams.get("from")).toBe("2026-10-01");
|
||||
expect(link.searchParams.get("to")).toBe("2026-10-31");
|
||||
});
|
||||
|
||||
it("the reports period of the zoom reads back the month, over the period of the hub", () => {
|
||||
const p = url(hrefs("?period=month&sources=3,4", 2026, 10)[0]).searchParams;
|
||||
expect(resolveReportsPeriod(p.get("from"), p.get("to"), p.get("period"), new Date(2026, 10, 16))).toEqual({
|
||||
from: "2026-10-01",
|
||||
to: "2026-10-31",
|
||||
period: "custom",
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces the dates of the URL and keeps its sources", () => {
|
||||
const p = url(hrefs("?period=custom&from=2026-01-01&to=2026-03-31&sources=3,4", 2026, 10)[0]).searchParams;
|
||||
expect(p.getAll("period")).toEqual(["custom"]);
|
||||
expect(p.getAll("from")).toEqual(["2026-10-01"]);
|
||||
expect(p.getAll("to")).toEqual(["2026-10-31"]);
|
||||
expect(p.get("sources")).toBe("3,4");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[2026, 2, "2026-02-01", "2026-02-28"],
|
||||
[2028, 2, "2028-02-01", "2028-02-29"],
|
||||
[2026, 4, "2026-04-01", "2026-04-30"],
|
||||
[2026, 12, "2026-12-01", "2026-12-31"],
|
||||
])("%i-%i: from %s to %s", (year, month, from, to) => {
|
||||
const p = url(hrefs("", year, month)[0]).searchParams;
|
||||
expect([p.get("from"), p.get("to")]).toEqual([from, to]);
|
||||
});
|
||||
|
||||
it("an uncategorized mover still links to the transactions", () => {
|
||||
expect(hrefs("?period=month", 2026, 10, [mover(null)])).toEqual(["/transactions"]);
|
||||
});
|
||||
});
|
||||
|
|
@ -6,6 +6,9 @@ import type { CartesTopMover } from "../../../shared/types";
|
|||
export interface TopMoversListProps {
|
||||
movers: CartesTopMover[];
|
||||
direction: "up" | "down";
|
||||
/** Reference month of the movers (the month compared to the one before), 1-12. */
|
||||
year: number;
|
||||
month: number;
|
||||
}
|
||||
|
||||
function formatSignedCurrency(amount: number, language: string): string {
|
||||
|
|
@ -26,14 +29,27 @@ function formatPct(pct: number | null, language: string): string {
|
|||
}).format(pct / 100);
|
||||
}
|
||||
|
||||
function categoryHref(categoryId: number | null): string {
|
||||
function monthDateRange(year: number, month: number): { dateFrom: string; dateTo: string } {
|
||||
const mm = String(month).padStart(2, "0");
|
||||
const lastDay = new Date(year, month, 0).getDate();
|
||||
return { dateFrom: `${year}-${mm}-01`, dateTo: `${year}-${mm}-${String(lastDay).padStart(2, "0")}` };
|
||||
}
|
||||
|
||||
// The zoom opens on the movers' month, from its first to its last day, whatever
|
||||
// reports period the URL carries, so its total and transactions are those of
|
||||
// the amount shown (#548); `sources` and the other params are kept.
|
||||
function categoryHref(categoryId: number | null, year: number, month: number): string {
|
||||
if (categoryId === null) return "/transactions";
|
||||
const { dateFrom, dateTo } = monthDateRange(year, month);
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
params.set("period", "custom");
|
||||
params.set("from", dateFrom);
|
||||
params.set("to", dateTo);
|
||||
params.set("cat", String(categoryId));
|
||||
return `/reports/category?${params.toString()}`;
|
||||
}
|
||||
|
||||
export default function TopMoversList({ movers, direction }: TopMoversListProps) {
|
||||
export default function TopMoversList({ movers, direction, year, month }: TopMoversListProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
|
||||
const title =
|
||||
|
|
@ -58,7 +74,7 @@ export default function TopMoversList({ movers, direction }: TopMoversListProps)
|
|||
{movers.map((m) => (
|
||||
<li key={`${m.categoryId ?? "uncat"}-${m.categoryName}`}>
|
||||
<Link
|
||||
to={categoryHref(m.categoryId)}
|
||||
to={categoryHref(m.categoryId, year, month)}
|
||||
className="flex items-center justify-between gap-3 px-2 py-1.5 rounded-md hover:bg-[var(--muted)] transition-colors"
|
||||
>
|
||||
<span className="flex items-center gap-2 min-w-0">
|
||||
|
|
|
|||
|
|
@ -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 };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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=<id>: 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);
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -43,10 +43,11 @@ vi.mock("../hooks/useDashboard", () => ({
|
|||
}));
|
||||
|
||||
// Hoisted with the mocks below, which run before the imports.
|
||||
const { marker, emptyStateProps, kpiProps } = vi.hoisted(() => ({
|
||||
const { marker, emptyStateProps, kpiProps, moversProps } = vi.hoisted(() => ({
|
||||
marker: (name: string) => ({ default: () => <i data-marker={name} /> }),
|
||||
emptyStateProps: { current: null as Record<string, unknown> | null },
|
||||
kpiProps: new Map<string, Record<string, unknown>>(),
|
||||
moversProps: [] as Record<string, unknown>[],
|
||||
}));
|
||||
vi.mock("../components/shared/PageHelp", () => ({ PageHelp: () => null }));
|
||||
vi.mock("../components/dashboard/CategoriesV1DiscoveryBanner", () => marker("discovery"));
|
||||
|
|
@ -71,7 +72,12 @@ vi.mock("../components/reports/cards/KpiCard", () => ({
|
|||
},
|
||||
}));
|
||||
vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => marker("overlay"));
|
||||
vi.mock("../components/reports/cards/TopMoversList", () => marker("movers"));
|
||||
vi.mock("../components/reports/cards/TopMoversList", () => ({
|
||||
default: (props: Record<string, unknown>) => {
|
||||
moversProps.push(props);
|
||||
return <i data-marker="movers" />;
|
||||
},
|
||||
}));
|
||||
vi.mock("../components/reports/cards/BudgetAdherenceCard", () => marker("adherence"));
|
||||
vi.mock("../components/shared/TransactionDetailModal", () => marker("detail"));
|
||||
|
||||
|
|
@ -129,6 +135,7 @@ beforeEach(() => {
|
|||
emptyStateProps.current = null;
|
||||
cartesSnapshot = null;
|
||||
kpiProps.clear();
|
||||
moversProps.length = 0;
|
||||
});
|
||||
|
||||
describe("DashboardPage on the shared path (#352, #396, #397)", () => {
|
||||
|
|
@ -216,3 +223,39 @@ describe("DashboardPage — the note under « Solde net » (#392, D5)", () => {
|
|||
for (const id of ["income", "expenses", "savingsRate"]) expect(kpiProps.get(id)!.note).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DashboardPage — the movers link to the month of their snapshot (#548)", () => {
|
||||
const kpi = (current: number): CartesKpi => ({
|
||||
current,
|
||||
previousMonth: null,
|
||||
previousYear: null,
|
||||
deltaMoMAbs: null,
|
||||
deltaMoMPct: null,
|
||||
deltaYoYAbs: null,
|
||||
deltaYoYPct: null,
|
||||
sparkline: [],
|
||||
});
|
||||
|
||||
it("hands both lists the snapshot's month, not the picker's, while the next snapshot loads", () => {
|
||||
// The picker is on September (the state's month); October's snapshot is
|
||||
// still on screen until September's arrives.
|
||||
cartesSnapshot = {
|
||||
referenceYear: 2026,
|
||||
referenceMonth: 10,
|
||||
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(970), savingsRate: kpi(97) },
|
||||
netBreakdown: { uncategorized: 0, transfers: 0 },
|
||||
flow12Months: [],
|
||||
topMoversUp: [],
|
||||
topMoversDown: [],
|
||||
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
|
||||
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
|
||||
};
|
||||
render();
|
||||
expect(moversProps.map((p) => [p.direction, p.year, p.month])).toEqual([
|
||||
["up", 2026, 10],
|
||||
["down", 2026, 10],
|
||||
]);
|
||||
expect(moversProps[0].movers).toBe(cartesSnapshot.topMoversUp);
|
||||
expect(moversProps[1].movers).toBe(cartesSnapshot.topMoversDown);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -203,8 +203,18 @@ export default function DashboardPage() {
|
|||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-3 mb-6">
|
||||
<TopMoversList movers={cartesSnapshot.topMoversUp} direction="up" />
|
||||
<TopMoversList movers={cartesSnapshot.topMoversDown} direction="down" />
|
||||
<TopMoversList
|
||||
movers={cartesSnapshot.topMoversUp}
|
||||
direction="up"
|
||||
year={cartesSnapshot.referenceYear}
|
||||
month={cartesSnapshot.referenceMonth}
|
||||
/>
|
||||
<TopMoversList
|
||||
movers={cartesSnapshot.topMoversDown}
|
||||
direction="down"
|
||||
year={cartesSnapshot.referenceYear}
|
||||
month={cartesSnapshot.referenceMonth}
|
||||
/>
|
||||
<BudgetAdherenceCard adherence={cartesSnapshot.budgetAdherence} />
|
||||
</div>
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -24,9 +24,10 @@ vi.mock("../hooks/useCartes", () => ({
|
|||
}));
|
||||
|
||||
// Hoisted with the mocks below, which run before the imports.
|
||||
const { marker, kpiProps } = vi.hoisted(() => ({
|
||||
const { marker, kpiProps, moversProps } = vi.hoisted(() => ({
|
||||
marker: (name: string) => ({ default: () => <i data-marker={name} /> }),
|
||||
kpiProps: new Map<string, Record<string, unknown>>(),
|
||||
moversProps: [] as Record<string, unknown>[],
|
||||
}));
|
||||
vi.mock("../components/reports/CompareReferenceMonthPicker", () => marker("month-picker"));
|
||||
vi.mock("../components/reports/cards/CartesPeriodModeToggle", () => marker("mode-toggle"));
|
||||
|
|
@ -37,7 +38,12 @@ vi.mock("../components/reports/cards/KpiCard", () => ({
|
|||
},
|
||||
}));
|
||||
vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => marker("overlay"));
|
||||
vi.mock("../components/reports/cards/TopMoversList", () => marker("movers"));
|
||||
vi.mock("../components/reports/cards/TopMoversList", () => ({
|
||||
default: (props: Record<string, unknown>) => {
|
||||
moversProps.push(props);
|
||||
return <i data-marker="movers" />;
|
||||
},
|
||||
}));
|
||||
vi.mock("../components/reports/cards/BudgetAdherenceCard", () => marker("adherence"));
|
||||
vi.mock("../components/reports/cards/SeasonalityCard", () => marker("seasonality"));
|
||||
|
||||
|
|
@ -66,6 +72,7 @@ const render = () =>
|
|||
beforeEach(() => {
|
||||
snapshot = null;
|
||||
kpiProps.clear();
|
||||
moversProps.length = 0;
|
||||
});
|
||||
|
||||
describe("ReportsCartesPage — the note under « Solde net » (#392, D5)", () => {
|
||||
|
|
@ -94,3 +101,28 @@ describe("ReportsCartesPage — the note under « Solde net » (#392, D5)", () =
|
|||
expect(kpiProps.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ReportsCartesPage — the movers link to the month of their snapshot (#548)", () => {
|
||||
it("hands both lists the snapshot's month, not the picker's, while the next snapshot loads", () => {
|
||||
// The picker is on October (the hook's month); September's snapshot is
|
||||
// still on screen until October's arrives.
|
||||
snapshot = {
|
||||
referenceYear: 2026,
|
||||
referenceMonth: 9,
|
||||
kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(970), savingsRate: kpi(97) },
|
||||
netBreakdown: { uncategorized: 0, transfers: 0 },
|
||||
flow12Months: [],
|
||||
topMoversUp: [],
|
||||
topMoversDown: [],
|
||||
budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] },
|
||||
seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null },
|
||||
};
|
||||
render();
|
||||
expect(moversProps.map((p) => [p.direction, p.year, p.month])).toEqual([
|
||||
["up", 2026, 9],
|
||||
["down", 2026, 9],
|
||||
]);
|
||||
expect(moversProps[0].movers).toBe(snapshot.topMoversUp);
|
||||
expect(moversProps[1].movers).toBe(snapshot.topMoversDown);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -100,8 +100,18 @@ export default function ReportsCartesPage() {
|
|||
<IncomeExpenseOverlayChart flow={snapshot.flow12Months} />
|
||||
|
||||
<section className="grid grid-cols-1 lg:grid-cols-2 gap-3">
|
||||
<TopMoversList movers={snapshot.topMoversUp} direction="up" />
|
||||
<TopMoversList movers={snapshot.topMoversDown} direction="down" />
|
||||
<TopMoversList
|
||||
movers={snapshot.topMoversUp}
|
||||
direction="up"
|
||||
year={snapshot.referenceYear}
|
||||
month={snapshot.referenceMonth}
|
||||
/>
|
||||
<TopMoversList
|
||||
movers={snapshot.topMoversDown}
|
||||
direction="down"
|
||||
year={snapshot.referenceYear}
|
||||
month={snapshot.referenceMonth}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="grid grid-cols-1 lg:grid-cols-2 gap-3">
|
||||
|
|
|
|||
100
src/pages/ReportsCategoryPage.render.test.tsx
Normal file
100
src/pages/ReportsCategoryPage.render.test.tsx
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// ReportsCategoryPage fills the box left of « Évolution » through
|
||||
// CategoryZoomBreakdown (#548): a leaf, or the subcategories left out, shows
|
||||
// the key figures, never « Aucune donnée ». No jsdom: react-dom/server renders
|
||||
// the page in vitest's node environment. The data hooks are faked, and the
|
||||
// widgets around the box are stubbed to markers, the donut too.
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { MemoryRouter } from "react-router-dom";
|
||||
import type { CategoryZoomChild, CategoryZoomData } from "../shared/types";
|
||||
|
||||
vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock());
|
||||
|
||||
let zoom: { zoomedCategoryId: number | null; rollupChildren: boolean; data: CategoryZoomData | null };
|
||||
vi.mock("../hooks/useCategoryZoom", () => ({
|
||||
useCategoryZoom: () => ({
|
||||
...zoom,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
setCategory: vi.fn(),
|
||||
setRollupChildren: vi.fn(),
|
||||
refetch: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
vi.mock("../hooks/useReportsPeriod", () => ({
|
||||
useReportsPeriod: () => ({
|
||||
period: "custom",
|
||||
from: "2026-10-01",
|
||||
to: "2026-10-31",
|
||||
accountIds: [],
|
||||
setPeriod: vi.fn(),
|
||||
setCustomDates: vi.fn(),
|
||||
setAccountIds: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Hoisted with the mocks below, which run before the imports.
|
||||
const { marker } = vi.hoisted(() => ({
|
||||
marker: (name: string) => ({ default: () => <i data-marker={name} /> }),
|
||||
}));
|
||||
vi.mock("../components/dashboard/PeriodSelector", () => marker("period"));
|
||||
vi.mock("../components/reports/CategoryZoomHeader", () => marker("header"));
|
||||
vi.mock("../components/reports/CategoryDonutChart", () => marker("donut"));
|
||||
vi.mock("../components/reports/CategoryEvolutionChart", () => marker("evolution"));
|
||||
vi.mock("../components/reports/CategoryTransactionsTable", () => marker("transactions"));
|
||||
vi.mock("../components/categories/AddKeywordDialog", () => marker("keyword"));
|
||||
|
||||
import ReportsCategoryPage from "./ReportsCategoryPage";
|
||||
|
||||
const child = (categoryId: number, total: number): CategoryZoomChild => ({
|
||||
categoryId,
|
||||
categoryName: `C${categoryId}`,
|
||||
categoryColor: "#000",
|
||||
total,
|
||||
});
|
||||
|
||||
const zoomData = (byChild: CategoryZoomChild[]): CategoryZoomData => ({
|
||||
rollupTotal: 210,
|
||||
metrics: { transactionCount: 4, average: 52.5, largest: 120, smallest: -15 },
|
||||
byChild,
|
||||
monthlyEvolution: [],
|
||||
transactions: [],
|
||||
});
|
||||
|
||||
const render = () =>
|
||||
renderToStaticMarkup(
|
||||
<MemoryRouter>
|
||||
<ReportsCategoryPage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
zoom = { zoomedCategoryId: 1111, rollupChildren: true, data: null };
|
||||
});
|
||||
|
||||
describe("ReportsCategoryPage — the box left of « Évolution » (#548)", () => {
|
||||
it("a leaf: the key figures beside the evolution, never « Aucune donnée »", () => {
|
||||
zoom.data = zoomData([]);
|
||||
const html = render();
|
||||
expect(html).toContain("t(reports.category.metrics.title)");
|
||||
expect(html).not.toContain('data-marker="donut"');
|
||||
expect(html).not.toContain("t(reports.empty.noData)");
|
||||
expect(html).toContain('data-marker="evolution"');
|
||||
});
|
||||
|
||||
it("the subcategories left out: the key figures too", () => {
|
||||
// `byChild` is only computed with the subcategories included.
|
||||
zoom = { zoomedCategoryId: 11, rollupChildren: false, data: zoomData([]) };
|
||||
const html = render();
|
||||
expect(html).toContain("t(reports.category.metrics.title)");
|
||||
expect(html).not.toContain('data-marker="donut"');
|
||||
expect(html).not.toContain("t(reports.empty.noData)");
|
||||
});
|
||||
|
||||
it("a category with positive subcategories: its donut, without the key figures", () => {
|
||||
zoom.data = zoomData([child(1, 150), child(2, 60)]);
|
||||
const html = render();
|
||||
expect(html).toContain('data-marker="donut"');
|
||||
expect(html).not.toContain("t(reports.category.metrics.title)");
|
||||
});
|
||||
});
|
||||
|
|
@ -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() {
|
|||
</div>
|
||||
) : data ? (
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
|
||||
<CategoryDonutChart
|
||||
byChild={data.byChild}
|
||||
centerLabel={centerLabel}
|
||||
centerValue={centerValue}
|
||||
/>
|
||||
<CategoryZoomBreakdown data={data} centerLabel={centerLabel} centerValue={centerValue} />
|
||||
<CategoryEvolutionChart data={data.monthlyEvolution} />
|
||||
<div className="lg:col-span-2">
|
||||
<h3 className="text-sm font-semibold mb-2">{t("reports.category.transactions")}</h3>
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<RecentTransaction[]>(
|
||||
|
|
@ -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<Array<{ rollup: number | null; category_type: string | null }>>(
|
||||
`${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,
|
||||
|
|
|
|||
|
|
@ -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[];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue