From ce25ddc1914282272a129da32be2141ba7982bd0 Mon Sep 17 00:00:00 2001 From: le king fu Date: Tue, 27 Oct 2026 23:04:27 -0400 Subject: [PATCH] =?UTF-8?q?feat:=20open=20the=20Reports=20on=20=C2=AB=20Ce?= =?UTF-8?q?tte=20ann=C3=A9e=20=C2=BB=20and=20let=20=C2=AB=20Tout=20=C2=BB?= =?UTF-8?q?=20reach=20every=20date=20(#479)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Without any period in the URL, the Reports opened on the whole calendar year (January 1st to December 31st, months to come included) under the « Personnalisé » button. They now open on « Cette année », the year to date (January 1st to today), as the Dashboard does, with its button lit (decision 1 of Max, 2026-10-20). « Tout » showed the current calendar year too: resolveReportsPeriod replaced its empty range by that year. It now leaves `from` and `to` absent, and the services add no date clause (decision 2). - computeDateRange takes `today` as a last optional parameter (default: the current day); no existing caller changes, the Dashboard included. - resolveReportsPeriod: a bookmark with two valid dates is kept as it is; a valid preset other than `custom` gets its range for `today` (`all`: none); anything else (no parameter, an invalid period, `custom` without two valid dates) falls back to « Cette année ». currentYearRange is gone; `from` and `to` are optional in UseReportsPeriodResult. - getCategoryZoom takes optional bounds: its four queries skip a bound bound to NULL, `($2 IS NULL OR t.date >= $2) AND ($3 IS NULL OR t.date <= $3)`, with the same parameters in the same order ([id, from ?? null, to ?? null]). In the per-child query the condition stays in the LEFT JOIN's ON, so a subcategory without any transaction in the period keeps its row (total 0). - useTrends and useCategoryZoom pass absent bounds through. - useCompare: syncReferenceOnPeriodChange takes an absent `to`; on « Tout » the reference month shown does not move, and a later switch to a dated period syncs it to the end of that period (decision of Max, 2026-10-27). The ref is typed `string | undefined`, so a direct opening on ?period=all works. - Texts fixed by Max (2026-10-27): reports.help.tips[2] and reports.hub.trendsDescription, FR and EN, no longer say "12 months": Trends follows the period selector. Tests: the default, a custom bookmark, `custom` without dates, a preset and `all` resolved for a fixed day; computeDateRange with `today`; getCategoryZoom without bounds ([42, null, null] in every query, no bare date condition), with bounds, and the per-child bounds in the ON; the sync on « Tout »; wiring tests (src/test/hookHarness.ts) of useCompare (mount on « Cette année » or « Tout », « Tout » then a dated period, a user-picked month kept), useTrends (both views) and useCategoryZoom (absent bounds reach the service). Co-Authored-By: Claude Opus 5.5 --- src/hooks/useCategoryZoom.ts | 9 ++- src/hooks/useCategoryZoom.wiring.test.ts | 59 ++++++++++++++ src/hooks/useCompare.test.ts | 25 ++++++ src/hooks/useCompare.ts | 25 +++--- src/hooks/useCompare.wiring.test.ts | 99 ++++++++++++++++++++++++ src/hooks/useReportsPeriod.test.ts | 60 ++++++++------ src/hooks/useReportsPeriod.ts | 38 ++++----- src/hooks/useTrends.ts | 9 ++- src/hooks/useTrends.wiring.test.ts | 76 ++++++++++++++++++ src/i18n/locales/en.json | 4 +- src/i18n/locales/fr.json | 4 +- src/services/reportService.test.ts | 73 +++++++++++++++++ src/services/reportService.ts | 36 ++++++--- src/utils/dateRange.test.ts | 12 +++ src/utils/dateRange.ts | 14 ++-- 15 files changed, 469 insertions(+), 74 deletions(-) create mode 100644 src/hooks/useCategoryZoom.wiring.test.ts create mode 100644 src/hooks/useCompare.wiring.test.ts create mode 100644 src/hooks/useTrends.wiring.test.ts diff --git a/src/hooks/useCategoryZoom.ts b/src/hooks/useCategoryZoom.ts index e888b5b..53e2e03 100644 --- a/src/hooks/useCategoryZoom.ts +++ b/src/hooks/useCategoryZoom.ts @@ -48,8 +48,15 @@ export function useCategoryZoom() { const [state, dispatch] = useReducer(reducer, initialState); const fetchIdRef = useRef(0); + // `dateFrom` / `dateTo` are absent on « Tout »: getCategoryZoom then binds + // them as NULL and reads every date (#479). const fetch = useCallback( - async (categoryId: number | null, includeChildren: boolean, dateFrom: string, dateTo: string) => { + async ( + categoryId: number | null, + includeChildren: boolean, + dateFrom: string | undefined, + dateTo: string | undefined, + ) => { if (categoryId === null) return; const id = ++fetchIdRef.current; dispatch({ type: "SET_LOADING", payload: true }); diff --git a/src/hooks/useCategoryZoom.wiring.test.ts b/src/hooks/useCategoryZoom.wiring.test.ts new file mode 100644 index 0000000..eb7094b --- /dev/null +++ b/src/hooks/useCategoryZoom.wiring.test.ts @@ -0,0 +1,59 @@ +// useCategoryZoom — 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. +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig())); +const period = vi.hoisted(() => ({ + from: undefined as string | undefined, + to: undefined as string | undefined, +})); +vi.mock("./useReportsPeriod", () => ({ + useReportsPeriod: () => ({ from: period.from, to: period.to }), +})); +const services = vi.hoisted(() => ({ getCategoryZoom: vi.fn() })); +vi.mock("../services/reportService", () => services); + +import { hookHarness } from "../test/hookHarness"; +import { useCategoryZoom } from "./useCategoryZoom"; + +const harness = hookHarness(); + +/** 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 + harness.render(useCategoryZoom).setCategory(categoryId); + harness.render(useCategoryZoom); + harness.commit(); +} + +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. + services.getCategoryZoom.mockReset().mockReturnValue(new Promise(() => {})); +}); + +describe("useCategoryZoom — the period's bounds reach the service (#479)", () => { + it("« Tout »: the zoom asks for no date bound", () => { + zoomOn(42); + expect(services.getCategoryZoom).toHaveBeenCalledTimes(1); + expect(services.getCategoryZoom).toHaveBeenCalledWith(42, undefined, undefined, true); + }); + + it("a dated period passes its bounds as they are", () => { + period.from = "2026-01-01"; + period.to = "2026-04-14"; + zoomOn(42); + expect(services.getCategoryZoom).toHaveBeenCalledWith(42, "2026-01-01", "2026-04-14", true); + }); +}); diff --git a/src/hooks/useCompare.test.ts b/src/hooks/useCompare.test.ts index 500d293..4103b3e 100644 --- a/src/hooks/useCompare.test.ts +++ b/src/hooks/useCompare.test.ts @@ -84,5 +84,30 @@ describe("useCompare helpers", () => { expect(r.next).toBeNull(); expect(r.lastSyncedTo).toBe("garbage"); }); + + // « Tout » (#479) has no upper bound: `to` is absent. The reference month + // shown does not move; only a later switch to a dated period syncs it. + it("keeps the reference month when `to` goes absent (« Tout »)", () => { + const r = syncReferenceOnPeriodChange("2026-04-14", undefined, 2026, 9); + expect(r.next).toBeNull(); + expect(r.lastSyncedTo).toBeUndefined(); + }); + + it("mounted on « Tout », then « Cette année »: syncs to the end of that period", () => { + const mount = syncReferenceOnPeriodChange(undefined, undefined, 2026, 9); + expect(mount.next).toBeNull(); + const year = syncReferenceOnPeriodChange(mount.lastSyncedTo, "2026-04-14", 2026, 9); + expect(year.next).toEqual({ year: 2026, month: 4 }); + expect(year.lastSyncedTo).toBe("2026-04-14"); + }); + + it("« Cette année » → « Tout » → « Cette année »: unchanged on « Tout », synced on the way back", () => { + const mount = syncReferenceOnPeriodChange("2026-04-14", "2026-04-14", 2026, 9); + const all = syncReferenceOnPeriodChange(mount.lastSyncedTo, undefined, 2026, 9); + const back = syncReferenceOnPeriodChange(all.lastSyncedTo, "2026-04-14", 2026, 9); + expect(mount.next).toBeNull(); + expect(all.next).toBeNull(); + expect(back.next).toEqual({ year: 2026, month: 4 }); + }); }); }); diff --git a/src/hooks/useCompare.ts b/src/hooks/useCompare.ts index 7e1f14d..69501dd 100644 --- a/src/hooks/useCompare.ts +++ b/src/hooks/useCompare.ts @@ -69,20 +69,26 @@ export function comparisonMeta( * Gates on a *change* of `to` (the period's upper bound) rather than a * fire-once flag: seeded with the initial `to`, the mount is a no-op, so the * previous-month default from initialState survives instead of snapping to the - * civil-year December that useReportsPeriod yields by default (Issue #253). - * Because it keys off a value change, it is idempotent under React StrictMode's - * dev double-invoke of effects — called twice with the same `to` it dispatches - * nothing the second time (a fire-once boolean would wrongly sync on run #2). + * month that ends useReportsPeriod's default period, « Cette année », which + * ends today (Issues #253, #479). Because it keys off a value change, it is + * idempotent under React StrictMode's dev double-invoke of effects — called + * twice with the same `to` it dispatches nothing the second time (a fire-once + * boolean would wrongly sync on run #2). + * + * `to` is absent on « Tout » (`all`, no upper bound): the reference month shown + * stays as it is, and the absent `to` is remembered, so a later switch to a + * dated period syncs it to the end of that period (#479). * * Returns the `to` to remember plus an optional reference period to dispatch. */ export function syncReferenceOnPeriodChange( - lastSyncedTo: string, - to: string, + lastSyncedTo: string | undefined, + to: string | undefined, currentYear: number, currentMonth: number, -): { lastSyncedTo: string; next: { year: number; month: number } | null } { +): { lastSyncedTo: string | undefined; next: { year: number; month: number } | null } { if (to === lastSyncedTo) return { lastSyncedTo, next: null }; + if (to === undefined) return { lastSyncedTo: to, next: null }; const [y, m] = to.split("-").map(Number); if (!Number.isFinite(y) || !Number.isFinite(m)) return { lastSyncedTo: to, next: null }; if (y === currentYear && m === currentMonth) return { lastSyncedTo: to, next: null }; @@ -174,8 +180,9 @@ export function useCompare() { // via PeriodSelector — but not on mount. The ref is seeded with the initial // `to`, so syncReferenceOnPeriodChange only fires on an actual change of `to`, // leaving the previous-month default from initialState intact (Issue #253) and - // staying idempotent under StrictMode's dev double-invoke. - const lastSyncedToRef = useRef(to); + // staying idempotent under StrictMode's dev double-invoke. `to` is undefined + // on « Tout », a direct opening on `?period=all` included (#479). + const lastSyncedToRef = useRef(to); useEffect(() => { const { lastSyncedTo, next } = syncReferenceOnPeriodChange( lastSyncedToRef.current, diff --git a/src/hooks/useCompare.wiring.test.ts b/src/hooks/useCompare.wiring.test.ts new file mode 100644 index 0000000..4c0b775 --- /dev/null +++ b/src/hooks/useCompare.wiring.test.ts @@ -0,0 +1,99 @@ +// useCompare — the reference month follows the URL period, never at mount +// (#253), and « Tout » leaves it where it is (#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 services and the reports period are mocked; a test +// changes `period.to` between renders, as the period selector does through +// the URL. What is pinned: the ref the sync effect compares against is seeded +// with the first `to`, a mount on « Tout » (`to` absent, `?period=all`) neither +// throws nor moves the month, and a switch to a dated period afterwards syncs +// it to the end of that period. +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig())); +const period = vi.hoisted(() => ({ + to: undefined as string | undefined, + // One array for every render: a new one would read as a changed filter. + accountIds: [] as number[], +})); +vi.mock("./useReportsPeriod", () => ({ + useReportsPeriod: () => ({ from: undefined, to: period.to, accountIds: period.accountIds }), +})); +// Never settle: the rows and the accounts are not what is tested here, and a +// late dispatch would land in the next test's mount. +vi.mock("../services/reportService", () => ({ + getCompareMonthOverMonth: vi.fn(() => new Promise(() => {})), + getCompareYearOverYear: vi.fn(() => new Promise(() => {})), +})); +vi.mock("../services/transactionService", () => ({ + getAllImportSources: vi.fn(() => new Promise(() => {})), +})); + +import { hookHarness } from "../test/hookHarness"; +import { useCompare, defaultReferencePeriod } from "./useCompare"; + +const harness = hookHarness(); + +/** The end of « Cette année » on 2026-04-14: a month gone by, never the default (the month before today). */ +const YEAR_TO = "2026-04-14"; + +/** Renders the mounted hook with the given `to`, runs its effects, and renders again to read the state. */ +function step(to: string | undefined) { + period.to = to; + harness.render(useCompare); + harness.commit(); + return harness.render(useCompare); +} + +/** The reference month a render shows. */ +const shown = (result: { year: number; month: number }) => ({ year: result.year, month: result.month }); + +/** The reference periods the sync effect dispatched, in order. */ +const synced = () => + harness.dispatch.mock.calls + .map(([action]) => action as { type: string; payload?: unknown }) + .filter((action) => action.type === "SET_REFERENCE_PERIOD") + .map((action) => action.payload); + +beforeEach(() => { + harness.clear(); +}); + +describe("useCompare — the reference month and the URL period (#253, #479)", () => { + it("a mount on « Cette année » keeps the previous month (#253)", () => { + const result = step(YEAR_TO); + expect(synced()).toEqual([]); + expect(shown(result)).toEqual(defaultReferencePeriod()); + }); + + it("a mount on « Tout » neither throws nor moves the reference month", () => { + const result = step(undefined); + expect(synced()).toEqual([]); + expect(shown(result)).toEqual(defaultReferencePeriod()); + }); + + it("mounted on « Tout », a switch to « Cette année » syncs to the end of that period", () => { + step(undefined); + const result = step(YEAR_TO); + expect(synced()).toEqual([{ year: 2026, month: 4 }]); + expect(shown(result)).toEqual({ year: 2026, month: 4 }); + }); + + it("« Cette année » → « Tout » → « Cette année »: unchanged on « Tout », synced on the way back", () => { + step(YEAR_TO); + const onAll = step(undefined); + expect(synced()).toEqual([]); + expect(shown(onAll)).toEqual(defaultReferencePeriod()); + + const back = step(YEAR_TO); + expect(synced()).toEqual([{ year: 2026, month: 4 }]); + expect(shown(back)).toEqual({ year: 2026, month: 4 }); + }); + + it("« Tout » keeps a reference month the user picked", () => { + step(YEAR_TO).setReferencePeriod(2025, 12); + const onAll = step(undefined); + expect(shown(onAll)).toEqual({ year: 2025, month: 12 }); + }); +}); diff --git a/src/hooks/useReportsPeriod.test.ts b/src/hooks/useReportsPeriod.test.ts index 1597c27..ad880f7 100644 --- a/src/hooks/useReportsPeriod.test.ts +++ b/src/hooks/useReportsPeriod.test.ts @@ -2,13 +2,14 @@ import { describe, it, expect } from "vitest"; import { resolveReportsPeriod, parseAccountIds, serializeAccountIds } from "./useReportsPeriod"; describe("resolveReportsPeriod", () => { + // A day far from the clock: a range computed from `new Date()` instead of + // the given day ends elsewhere, and these tests go red. const fixedToday = new Date("2026-04-14T12:00:00Z"); + /** « Cette année » on that day: January 1st to that day (#479). */ + const YEAR_TO_DATE = { from: "2026-01-01", to: "2026-04-14", period: "year" }; - it("defaults to current civil year when no URL params are set", () => { - const result = resolveReportsPeriod(null, null, null, fixedToday); - expect(result.from).toBe("2026-01-01"); - expect(result.to).toBe("2026-12-31"); - expect(result.period).toBe("custom"); + it("defaults to « Cette année », the year to date, when no URL params are set (#479)", () => { + expect(resolveReportsPeriod(null, null, null, fixedToday)).toEqual(YEAR_TO_DATE); }); it("restores state from bookmarked from/to params", () => { @@ -18,37 +19,50 @@ describe("resolveReportsPeriod", () => { expect(result.period).toBe("custom"); }); + it("keeps a ?period=custom&from=…&to=… bookmark as it is (#479)", () => { + expect(resolveReportsPeriod("2025-03-01", "2025-06-30", "custom", fixedToday)).toEqual({ + from: "2025-03-01", + to: "2025-06-30", + period: "custom", + }); + }); + it("keeps period=yearly alongside explicit from/to", () => { const result = resolveReportsPeriod("2024-01-01", "2024-12-31", "year", fixedToday); expect(result.period).toBe("year"); }); - it("ignores malformed dates and falls back to the civil year", () => { - const result = resolveReportsPeriod("not-a-date", "also-not", null, fixedToday); - expect(result.from).toBe("2026-01-01"); - expect(result.to).toBe("2026-12-31"); - expect(result.period).toBe("custom"); + it("ignores malformed dates and falls back to the year to date (#479)", () => { + expect(resolveReportsPeriod("not-a-date", "also-not", null, fixedToday)).toEqual(YEAR_TO_DATE); }); - it("resolves preset period values without from/to", () => { - const result = resolveReportsPeriod(null, null, "6months", fixedToday); - expect(result.period).toBe("6months"); - expect(result.from).toBeTruthy(); - expect(result.to).toBeTruthy(); + it("falls back to the year to date for `custom` without two valid dates (#479)", () => { + expect(resolveReportsPeriod(null, null, "custom", fixedToday)).toEqual(YEAR_TO_DATE); + // One valid bound is not a range. + expect(resolveReportsPeriod("2025-03-01", null, "custom", fixedToday)).toEqual(YEAR_TO_DATE); }); - it("rejects an invalid period string and falls back to civil year custom", () => { - const result = resolveReportsPeriod(null, null, "bogus", fixedToday); - expect(result.period).toBe("custom"); - expect(result.from).toBe("2026-01-01"); + it("resolves preset period values without from/to, from the given day (#479)", () => { + expect(resolveReportsPeriod(null, null, "6months", fixedToday)).toEqual({ + from: "2025-11-01", + to: "2026-04-14", + period: "6months", + }); }); - it("treats `all` as a preset with empty range (service handles the clauses)", () => { + it("resolves `year` to the year to date (#479)", () => { + expect(resolveReportsPeriod(null, null, "year", fixedToday)).toEqual(YEAR_TO_DATE); + }); + + it("rejects an invalid period string and falls back to the year to date (#479)", () => { + expect(resolveReportsPeriod(null, null, "bogus", fixedToday)).toEqual(YEAR_TO_DATE); + }); + + it("leaves the range absent for `all`: the services get no date bound (#479)", () => { const result = resolveReportsPeriod(null, null, "all", fixedToday); expect(result.period).toBe("all"); - // Fallback civil year when computeDateRange returns empty - expect(result.from).toBe("2026-01-01"); - expect(result.to).toBe("2026-12-31"); + expect(result.from).toBeUndefined(); + expect(result.to).toBeUndefined(); }); }); diff --git a/src/hooks/useReportsPeriod.ts b/src/hooks/useReportsPeriod.ts index c1e9d52..afc7b0e 100644 --- a/src/hooks/useReportsPeriod.ts +++ b/src/hooks/useReportsPeriod.ts @@ -21,11 +21,6 @@ function isValidIsoDate(s: string | null): s is string { return !!s && /^\d{4}-\d{2}-\d{2}$/.test(s); } -function currentYearRange(today: Date = new Date()): { from: string; to: string } { - const year = today.getFullYear(); - return { from: `${year}-01-01`, to: `${year}-12-31` }; -} - // Matches a bare (optionally negative) integer token, e.g. "3" or "-3", but // not "3.5", "abc", "" or "1e3" — deliberately stricter than `Number(...)` so // that hex/exponential-notation strings from a hand-edited URL don't sneak @@ -66,33 +61,37 @@ export function serializeAccountIds(accountIds: number[]): string | null { /** * Pure resolver used by the hook and unit tests. Exposed to keep the core * logic hookless and testable without rendering a router. + * + * - Two valid dates (a bookmark): kept as they are. + * - A valid preset other than `custom`: its range, computed for `today`; + * `all` has none, so `from` and `to` are absent and the services add no + * date clause (#479). + * - Anything else (no parameter, an invalid period, `custom` without two + * valid dates): « Cette année », the year to date (#479). */ export function resolveReportsPeriod( rawFrom: string | null, rawTo: string | null, rawPeriod: string | null, today: Date = new Date(), -): { from: string; to: string; period: DashboardPeriod } { +): { from?: string; to?: string; period: DashboardPeriod } { if (isValidIsoDate(rawFrom) && isValidIsoDate(rawTo)) { const p = isValidPeriod(rawPeriod) ? rawPeriod : "custom"; return { from: rawFrom, to: rawTo, period: p }; } if (isValidPeriod(rawPeriod) && rawPeriod !== "custom") { - const range = computeDateRange(rawPeriod); - const { from: defaultFrom, to: defaultTo } = currentYearRange(today); - return { - from: range.dateFrom ?? defaultFrom, - to: range.dateTo ?? defaultTo, - period: rawPeriod, - }; + const { dateFrom, dateTo } = computeDateRange(rawPeriod, undefined, undefined, today); + return { from: dateFrom, to: dateTo, period: rawPeriod }; } - const { from, to } = currentYearRange(today); - return { from, to, period: "custom" }; + const { dateFrom, dateTo } = computeDateRange("year", undefined, undefined, today); + return { from: dateFrom, to: dateTo, period: "year" }; } export interface UseReportsPeriodResult { - from: string; - to: string; + /** First day of the period (ISO date); absent for « Tout » (`all`). */ + from?: string; + /** Last day of the period (ISO date); absent for « Tout » (`all`). */ + to?: string; period: DashboardPeriod; accountIds: number[]; setPeriod: (period: DashboardPeriod) => void; @@ -105,8 +104,9 @@ export interface UseReportsPeriodResult { * (import source) filter — via the URL query string so both are bookmarkable * and shared across the report sub-routes. * - * Defaults to the current civil year (Jan 1 → Dec 31) with no account filter - * (`accountIds: []`, meaning all accounts). + * Defaults to « Cette année » (`year`: Jan 1 → today, the year to date, as on + * the Dashboard) with no account filter (`accountIds: []`, meaning all + * accounts). « Tout » (`all`) leaves `from` and `to` undefined (#479). */ export function useReportsPeriod(): UseReportsPeriodResult { const [searchParams, setSearchParams] = useSearchParams(); diff --git a/src/hooks/useTrends.ts b/src/hooks/useTrends.ts index 946e953..b85be0e 100644 --- a/src/hooks/useTrends.ts +++ b/src/hooks/useTrends.ts @@ -56,8 +56,15 @@ export function useTrends() { const [state, dispatch] = useReducer(reducer, initialState); const fetchIdRef = useRef(0); + // `dateFrom` / `dateTo` are absent on « Tout »: the services then add no + // date clause (#479). const fetch = useCallback( - async (subView: TrendsSubView, dateFrom: string, dateTo: string, ids: number[]) => { + async ( + subView: TrendsSubView, + dateFrom: string | undefined, + dateTo: string | undefined, + ids: number[], + ) => { const id = ++fetchIdRef.current; dispatch({ type: "SET_LOADING", payload: true }); try { diff --git a/src/hooks/useTrends.wiring.test.ts b/src/hooks/useTrends.wiring.test.ts new file mode 100644 index 0000000..9206aff --- /dev/null +++ b/src/hooks/useTrends.wiring.test.ts @@ -0,0 +1,76 @@ +// useTrends — the period's bounds reach both services 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 services and the reports period are mocked: on +// « Tout », `from` and `to` are absent (resolveReportsPeriod). What is pinned: +// the by-category view and the global flow hand those absent bounds to their +// service, which then adds no date clause, instead of a range of their own. +import { describe, it, expect, vi, beforeEach } from "vitest"; + +vi.mock("react", async (orig) => (await import("../test/hookHarness")).fakeReact(await orig())); +const period = vi.hoisted(() => ({ + from: undefined as string | undefined, + to: undefined as string | undefined, + // One array for every render: a new one would read as a changed filter. + accountIds: [] as number[], +})); +vi.mock("./useReportsPeriod", () => ({ + useReportsPeriod: () => ({ from: period.from, to: period.to, accountIds: period.accountIds }), +})); +const services = vi.hoisted(() => ({ + getMonthlyTrends: vi.fn(), + getCategoryOverTime: vi.fn(), +})); +vi.mock("../services/reportService", () => services); +// Never settles: the accounts of the filter are not what is tested here. +vi.mock("../services/transactionService", () => ({ + getAllImportSources: vi.fn(() => new Promise(() => {})), +})); + +import { hookHarness } from "../test/hookHarness"; +import { useTrends } from "./useTrends"; + +const harness = hookHarness(); + +beforeEach(() => { + harness.clear(); + period.from = undefined; + period.to = undefined; + // Never settle: only the arguments are read, and a late dispatch would land + // in the next test's mount. + services.getMonthlyTrends.mockReset().mockReturnValue(new Promise(() => {})); + services.getCategoryOverTime.mockReset().mockReturnValue(new Promise(() => {})); +}); + +describe("useTrends — the period's bounds reach the services (#479)", () => { + it("« Tout »: the by-category view asks for no date bound", () => { + harness.render(useTrends); + harness.commit(); + expect(services.getCategoryOverTime).toHaveBeenCalledTimes(1); + expect(services.getCategoryOverTime).toHaveBeenCalledWith(undefined, undefined, undefined, period.accountIds); + }); + + it("« Tout »: the global flow asks for no date bound", () => { + harness.render(useTrends).setSubView("global"); + harness.render(useTrends); + harness.commit(); + expect(services.getMonthlyTrends).toHaveBeenCalledTimes(1); + expect(services.getMonthlyTrends).toHaveBeenCalledWith(undefined, undefined, period.accountIds); + expect(services.getCategoryOverTime).not.toHaveBeenCalled(); + }); + + it("a dated period passes its bounds as they are", () => { + period.from = "2026-01-01"; + period.to = "2026-04-14"; + harness.render(useTrends); + harness.commit(); + expect(services.getCategoryOverTime).toHaveBeenCalledWith( + "2026-01-01", + "2026-04-14", + undefined, + period.accountIds, + ); + }); +}); diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index 6b49839..fedce44 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -606,7 +606,7 @@ "highlights": "Highlights", "highlightsDescription": "What moved this month", "trends": "Trends", - "trendsDescription": "Where you're heading over 12 months", + "trendsDescription": "Where you're heading, month by month", "compare": "Compare", "compareDescription": "Compare a reference month against previous month, previous year, or budget", "categoryZoom": "Category Analysis", @@ -709,7 +709,7 @@ "tips": [ "The cards at the bottom of the page open the five reports: Highlights, Trends, Compare, Category Analysis and Cards", "Use the period selector to adjust the time range for all charts", - "Trends shows your income and expenses month by month over 12 months", + "Trends shows your income and expenses month by month over the selected period", "Category Analysis tracks how a single category evolves over time" ] } diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index fe602fc..5cb6664 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -606,7 +606,7 @@ "highlights": "Faits saillants", "highlightsDescription": "Ce qui a bougé ce mois-ci", "trends": "Tendances", - "trendsDescription": "Où vous allez sur 12 mois", + "trendsDescription": "Où vous allez, mois par mois", "compare": "Comparables", "compareDescription": "Comparer un mois de référence au précédent, à l'année passée ou au budget", "categoryZoom": "Analyse par catégorie", @@ -709,7 +709,7 @@ "tips": [ "Les cartes du bas de la page ouvrent les cinq rapports : Faits saillants, Tendances, Comparables, Analyse par catégorie et Cartes", "Utilisez le sélecteur de période pour ajuster la plage de dates de tous les graphiques", - "Tendances montre vos revenus et dépenses mois par mois sur 12 mois", + "Tendances montre vos revenus et dépenses mois par mois sur la période choisie", "Analyse par catégorie suit l'évolution d'une catégorie dans le temps" ] } diff --git a/src/services/reportService.test.ts b/src/services/reportService.test.ts index d1ea76e..359961a 100644 --- a/src/services/reportService.test.ts +++ b/src/services/reportService.test.ts @@ -880,6 +880,79 @@ describe("getCategoryZoom", () => { expect(txSql).not.toContain("cat_tree"); expect(txSql).toContain("t.category_id = $1"); }); + + // « Tout » (#479): no bound at all. Each bound is skipped when bound to + // NULL, with the same three parameters in the same order: spelled out here + // rather than imported, so a typo in the service goes red. + const BOUNDS = "($2 IS NULL OR t.date >= $2) AND ($3 IS NULL OR t.date <= $3)"; + /** A date condition left outside the NULL-skipping form. */ + const BARE_BOUND = /t\.date\s*[<>]=/; + + const answerFourQueries = () => + mockSelect + .mockResolvedValueOnce([]) // transactions + .mockResolvedValueOnce([{ rollup: 0 }]) // rollup + .mockResolvedValueOnce([]) // byChild + .mockResolvedValueOnce([]); // evolution + + it("sends no date bound for « Tout »: [id, null, null], skipped by every query (#479)", async () => { + answerFourQueries(); + + await getCategoryZoom(42, undefined, undefined, true); + + expect(mockSelect).toHaveBeenCalledTimes(4); + for (const [sql, params] of mockSelect.mock.calls) { + expect(params).toEqual([42, null, null]); + expect(sql).toContain(BOUNDS); + expect((sql as string).split(BOUNDS).join("")).not.toMatch(BARE_BOUND); + } + }); + + it("passes the bounds of a dated period to every query, in number and order (#479)", async () => { + answerFourQueries(); + + await getCategoryZoom(42, "2026-01-01", "2026-04-14", true); + + expect(mockSelect).toHaveBeenCalledTimes(4); + for (const [sql, params] of mockSelect.mock.calls) { + expect(params).toEqual([42, "2026-01-01", "2026-04-14"]); + expect(sql).toContain(BOUNDS); + } + }); + + it("keeps the per-child bounds in the LEFT JOIN's ON, never in the WHERE (#479)", async () => { + // In the WHERE, the join would turn inner: a subcategory without any + // transaction in the period would lose its row instead of showing 0. + 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).toBeDefined(); + const [join, rest] = childSql!.split(/\bWHERE\b/); + expect(join.replace(/\s+/g, " ")).toContain( + `LEFT JOIN transactions t ON t.category_id = child.id AND ${BOUNDS}`, + ); + expect(rest).not.toContain("t.date"); + }); + + it("direct only: its three queries skip a NULL bound too (#479)", async () => { + mockSelect + .mockResolvedValueOnce([]) // transactions + .mockResolvedValueOnce([{ rollup: 0 }]) // rollup + .mockResolvedValueOnce([]); // evolution + + await getCategoryZoom(7, undefined, undefined, false); + + expect(mockSelect).toHaveBeenCalledTimes(3); + for (const [sql, params] of mockSelect.mock.calls) { + expect(params).toEqual([7, null, null]); + expect(sql).toContain(BOUNDS); + expect((sql as string).split(BOUNDS).join("")).not.toMatch(BARE_BOUND); + } + }); }); describe("buildCompareTree — hierarchical real-vs-real (Issue #247)", () => { diff --git a/src/services/reportService.ts b/src/services/reportService.ts index 3b72a17..ec39f3c 100644 --- a/src/services/reportService.ts +++ b/src/services/reportService.ts @@ -1020,32 +1020,44 @@ const CATEGORY_TREE_CTE = ` ) `; +/** + * Date bounds of the zoom queries: `$2` (first day) and `$3` (last day), each + * skipped when bound to NULL, so « Tout » (`all`, no bound) reads every date + * while the parameters keep their number and order (#479). In the per-child + * query it stays in the LEFT JOIN's ON: in the WHERE, the join would turn + * inner and a subcategory without any transaction in the period would lose + * its row instead of showing 0. + */ +const ZOOM_DATE_BOUNDS = "($2 IS NULL OR t.date >= $2) AND ($3 IS NULL OR t.date <= $3)"; + /** * Returns the zoom-on-category report for the given category id. * * When `includeSubcategories` is true the recursive CTE walks down the * category tree (capped at 5 levels) and aggregates matching rows. When * false, only direct transactions on `categoryId` are considered. Every - * query is parameterised; the category id is never interpolated. + * query is parameterised; the category id is never interpolated. An absent + * `dateFrom` or `dateTo` is no bound on that side (« Tout »). */ export async function getCategoryZoom( categoryId: number, - dateFrom: string, - dateTo: string, + dateFrom?: string, + dateTo?: string, includeSubcategories: boolean = true, ): Promise { 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 t.date >= $2 AND t.date <= $3` + 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 t.date >= $2 AND t.date <= $3`; + AND ${ZOOM_DATE_BOUNDS}`; // 1. Transactions (with join for display) const txRows = await db.select( @@ -1056,16 +1068,16 @@ export async function getCategoryZoom( WHERE ${includeSubcategories ? "t.category_id IN (SELECT id FROM cat_tree)" : "t.category_id = $1"} - AND t.date >= $2 AND t.date <= $3 + AND ${ZOOM_DATE_BOUNDS} ORDER BY ABS(t.amount) DESC LIMIT 500`, - [categoryId, dateFrom, dateTo], + params, ); // 2. Rollup total (sum of absolute amounts of matching rows) const totalRows = await db.select>( `${categoryFilter.replace("SELECT t.id, t.date, t.description, t.amount, t.category_id", "SELECT COALESCE(SUM(ABS(t.amount)), 0) AS rollup")}`, - [categoryId, dateFrom, dateTo], + params, ); const rollupTotal = Number(totalRows[0]?.rollup ?? 0); @@ -1081,11 +1093,11 @@ export async function getCategoryZoom( COALESCE(SUM(ABS(t.amount)), 0) AS total FROM categories child LEFT JOIN transactions t ON t.category_id = child.id - AND t.date >= $2 AND t.date <= $3 + AND ${ZOOM_DATE_BOUNDS} WHERE child.parent_id = $1 GROUP BY child.id, child.name, child.color ORDER BY total DESC`, - [categoryId, dateFrom, dateTo], + params, ); for (const r of childRows) { byChild.push({ @@ -1106,10 +1118,10 @@ export async function getCategoryZoom( WHERE ${includeSubcategories ? "t.category_id IN (SELECT id FROM cat_tree)" : "t.category_id = $1"} - AND t.date >= $2 AND t.date <= $3 + AND ${ZOOM_DATE_BOUNDS} GROUP BY month ORDER BY month ASC`, - [categoryId, dateFrom, dateTo], + params, ); const monthlyEvolution: CategoryZoomEvolutionPoint[] = evolutionRows.map((r) => ({ month: r.month, diff --git a/src/utils/dateRange.test.ts b/src/utils/dateRange.test.ts index 2c2ccfb..9405e89 100644 --- a/src/utils/dateRange.test.ts +++ b/src/utils/dateRange.test.ts @@ -55,6 +55,18 @@ describe("computeDateRange", () => { expect(result).toEqual({ dateFrom: "2024-08-01", dateTo: "2025-07-15" }); }); + // `today` is injectable (#479): the Reports resolve their default, the year + // to date, from a fixed day in tests, whatever the clock says. + it('computes "year" from the given today, not the clock (#479)', () => { + const result = computeDateRange("year", undefined, undefined, new Date(2026, 3, 14)); + expect(result).toEqual({ dateFrom: "2026-01-01", dateTo: "2026-04-14" }); + }); + + it("computes a rolling preset from the given today too (#479)", () => { + const result = computeDateRange("6months", undefined, undefined, new Date(2026, 0, 20)); + expect(result).toEqual({ dateFrom: "2025-08-01", dateTo: "2026-01-20" }); + }); + it("handles January rollover for 3months period", () => { vi.setSystemTime(new Date(2025, 1, 10)); // Feb 10, 2025 const result = computeDateRange("3months"); diff --git a/src/utils/dateRange.ts b/src/utils/dateRange.ts index 23ba65d..d33331b 100644 --- a/src/utils/dateRange.ts +++ b/src/utils/dateRange.ts @@ -2,22 +2,26 @@ import type { DashboardPeriod } from "../shared/types"; /** * Compute a date range (dateFrom / dateTo) based on the selected period. - * Shared between useDashboard, useReports, DashboardPage and ReportsPage. + * Shared between useDashboard, DashboardPage and useReportsPeriod (the + * Reports). "all" has no range: both bounds are absent. + * + * `today` is the day the presets end on, the current day by default; the + * Reports pass theirs so a test can fix it (#479). */ export function computeDateRange( period: DashboardPeriod, customDateFrom?: string, customDateTo?: string, + today: Date = new Date(), ): { dateFrom?: string; dateTo?: string } { if (period === "all") return {}; if (period === "custom" && customDateFrom && customDateTo) { return { dateFrom: customDateFrom, dateTo: customDateTo }; } - const now = new Date(); - const year = now.getFullYear(); - const month = now.getMonth(); - const day = now.getDate(); + const year = today.getFullYear(); + const month = today.getMonth(); + const day = today.getDate(); const dateTo = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;