fix(reports): open the category zoom from a card on the card's month

A card's increases and decreases compare its reference month to the
month before, but their links only copied the URL: the zoom opened on
the reports period (the year to date by default), never on that month.
A mover's link now carries the month of the snapshot the list shows,
from its first to its last day (period=custom, from, to), with cat and
the other params kept (Max's answer to the review of PR #551).

test: reproduces #548 (a mover's link, the month both pages hand the
lists, the page's box on a leaf and with the subcategories left out)

Refs #548

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
le king fu 2026-11-16 19:44:38 -05:00 • committed by maximus
commit a4368fbc95
7 changed files with 304 additions and 11 deletions

View 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(/&amp;/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"]);
});
});

View file

@ -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">

View file

@ -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);
});
});

View file

@ -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>
</>

View file

@ -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);
});
});

View file

@ -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">

View 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)");
});
});