diff --git a/src/__integration__/report-totals.test.ts b/src/__integration__/report-totals.test.ts index 2bd229e..2ec89c1 100644 --- a/src/__integration__/report-totals.test.ts +++ b/src/__integration__/report-totals.test.ts @@ -309,15 +309,23 @@ describe("the edge cases of #392: every report reads the same net, 710", () => { expect(spark[spark.length - 1]).toEqual({ month: "2026-10", value: 97 }); }); - it("Cartes, year to date: the same figures and the same note", async () => { + it("Cartes, year to date: the figures and the note of January to October", async () => { + // September: 20 spent in Groceries, a credit of +25 without a category. + insert("2026-09-16", "EPICERIE", -20, GROCERIES); + insert("2026-09-15", "VIREMENT INCONNU", 25, null); + const snapshot = await getCartesSnapshot(2026, 10, "ytd"); + expect([ snapshot.kpis.income.current, snapshot.kpis.expenses.current, snapshot.kpis.net.current, snapshot.kpis.savingsRate.current, - ]).toEqual([1000, 30, 710, 97]); - expect(snapshot.netBreakdown).toEqual({ uncategorized: 40, transfers: -300 }); + ]).toEqual([1000, 50, 715, 95]); + // The note follows the period of the cards: the year to date. + expect(snapshot.netBreakdown).toEqual({ uncategorized: 65, transfers: -300 }); + // Seasonality stays on the month, whatever the mode. + expect(snapshot.seasonality.referenceAmount).toBe(30); }); it("Cartes, seasonality: a past year's month reads its expenses, refunds netted, nothing else", async () => { @@ -373,6 +381,10 @@ describe("the edge cases of #392: every report reads the same net, 710", () => { const overTime = await getCategoryOverTime(FROM, TO, undefined, undefined, "expense"); expect(overTime.data).toEqual([{ month: "2026-10", [GROCERIES_NAME]: 80, [BUTCHER_NAME]: -50 }]); expect(overTime.tree.some((row) => row.category_type !== "expense")).toBe(false); + // The top N ranks by the size of the balance: 80 spent outranks 50 refunded. + const topOne = await getCategoryOverTime(FROM, TO, 1, undefined, "expense"); + expect(topOne.categories).toEqual([GROCERIES_NAME, "Other"]); + expect(topOne.data).toEqual([{ month: "2026-10", [GROCERIES_NAME]: 80, Other: -50 }]); }); it("Compare, actual vs budget: the uncategorized line counts in the result", async () => { @@ -391,6 +403,18 @@ describe("the edge cases of #392: every report reads the same net, 710", () => { ]); }); + it("Compare, actual vs budget: the uncategorized line stays when only the year to date holds it", async () => { + db.prepare("DELETE FROM transactions WHERE category_id IS NULL").run(); + insert("2026-09-15", "VIREMENT INCONNU", 25, null); + + const rows = await getBudgetVsActualData(2026, 10); + + expect(rows.filter((row) => row.category_type === "uncategorized")).toEqual([ + expect.objectContaining({ category_id: null, monthActual: 0, ytdActual: 25 }), + ]); + expect(budgetResults(rows).resultNet.ytdActual).toBe(695); + }); + it("Highlights: the net of the month, movers without the transfer", async () => { const highlights = await getHighlights(2026, 10, 2026, 30, 5, 10, TODAY); expect(highlights.netBalanceCurrent).toBe(710); @@ -406,6 +430,9 @@ describe("the edge cases of #392: every report reads the same net, 710", () => { const byChild = Object.fromEntries(zoom.byChild.map((c) => [c.categoryId, c.total])); expect(byChild[GROCERIES]).toBe(80); expect(byChild[BUTCHER]).toBe(-50); + // Largest first, the negative part last. + expect(zoom.byChild[0].categoryId).toBe(GROCERIES); + expect(zoom.byChild[zoom.byChild.length - 1].categoryId).toBe(BUTCHER); expect(zoom.monthlyEvolution).toEqual([{ month: "2026-10", total: 30 }]); }); diff --git a/src/components/reports/incomeStatementCells.render.test.tsx b/src/components/reports/incomeStatementCells.render.test.tsx new file mode 100644 index 0000000..e4d4dde --- /dev/null +++ b/src/components/reports/incomeStatementCells.render.test.tsx @@ -0,0 +1,93 @@ +// The cells that show « Solde net » and its parts (#392, D5): the « Net » of +// Trends' global flow is the net result, every amount of the month, and the +// KPI card shows the note it is given. No jsdom: react-dom/server renders the +// markup. +import { describe, it, expect, vi } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; + +vi.mock("react-i18next", async () => (await import("../../test/i18nMock")).i18nMock()); + +import MonthlyTrendsTable from "./MonthlyTrendsTable"; +import KpiCard from "./cards/KpiCard"; +import type { CartesKpi } from "../../shared/types"; + +/** The text of each cell of the table row at `rowIndex` (the head is row 0). */ +function cellsOf(html: string, rowIndex: number): string[] { + const rows = html.split("]*>(.*?)<\/td>/g)].map((m) => m[1].replace(/<[^>]+>/g, "")); +} + +describe("MonthlyTrendsTable", () => { + // October holds the edge cases of #392: income 1000, expenses 30, + // uncategorized 40, transfers −300. + const html = renderToStaticMarkup( + , + ); + + it("heads its columns income, expenses, uncategorized, transfers and net", () => { + const heads = [...html.matchAll(/]*>(.*?)<\/th>/g)].map((m) => m[1]); + expect(heads.slice(1)).toEqual([ + "t(dashboard.income)", + "t(dashboard.expenses)", + "t(reports.uncategorized)", + "t(reports.compare.sections.transfers)", + "t(dashboard.net)", + ]); + }); + + it("shows the net result in « Net », not income − expenses", () => { + expect(cellsOf(html, 1).slice(1)).toEqual(["$500", "$100", "$0", "$0", "$400"]); + expect(cellsOf(html, 2).slice(1)).toEqual(["$1,000", "$30", "$40", "-$300", "$710"]); + }); + + it("totals every column, the net result included", () => { + expect(cellsOf(html, 3)).toEqual(["t(common.total)", "$1,500", "$130", "$40", "-$300", "$1,110"]); + }); +}); + +describe("KpiCard", () => { + const kpi: CartesKpi = { + current: 710, + previousMonth: null, + previousYear: null, + deltaMoMAbs: null, + deltaMoMPct: null, + deltaYoYAbs: null, + deltaYoYPct: null, + sparkline: [], + }; + const render = (note?: string) => + renderToStaticMarkup(); + const divs = (html: string) => html.split(" { + const html = render("Dont 40 $ non classés"); + expect(html).toContain(">Dont 40 $ non classés<"); + expect(html.indexOf("Dont 40 $ non classés")).toBeGreaterThan(html.indexOf("710")); + }); + + it("adds no line without a note", () => { + expect(divs(render())).toBe(divs(render("Dont 40 $ non classés")) - 1); + }); +}); diff --git a/src/pages/DashboardPage.render.test.tsx b/src/pages/DashboardPage.render.test.tsx index dc88952..216457f 100644 --- a/src/pages/DashboardPage.render.test.tsx +++ b/src/pages/DashboardPage.render.test.tsx @@ -3,23 +3,27 @@ // fake `useOnboarding()`, and the dashboard's data hook and widgets are stubbed // to markers: what is pinned is the page's branching on the path. Since #397 // the page has no list of its own once transactions exist: the banner of -// AppShell replaced the compact bar (D7). +// AppShell replaced the compact bar (D7). The fake KpiCard records its props: +// the page hands « Solde net » the note of the snapshot (#392, D5). import { describe, it, expect, vi, beforeEach } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import { MemoryRouter } from "react-router-dom"; import type { OnboardingValue } from "../hooks/useOnboardingChecklist"; +import type { CartesKpi, CartesSnapshot } from "../shared/types"; vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock()); let onboarding: OnboardingValue; vi.mock("../contexts/OnboardingContext", () => ({ useOnboarding: () => onboarding })); +let cartesSnapshot: CartesSnapshot | null = null; + vi.mock("../hooks/useDashboard", () => ({ useDashboard: () => ({ state: { categoryBreakdown: [], categoryOverTime: { categories: [], data: [] }, - cartesSnapshot: null, + cartesSnapshot, period: "year", customDateFrom: "2026-01-01", customDateTo: "2026-10-08", @@ -39,9 +43,10 @@ vi.mock("../hooks/useDashboard", () => ({ })); // Hoisted with the mocks below, which run before the imports. -const { marker, emptyStateProps } = vi.hoisted(() => ({ +const { marker, emptyStateProps, kpiProps } = vi.hoisted(() => ({ marker: (name: string) => ({ default: () => }), emptyStateProps: { current: null as Record | null }, + kpiProps: new Map>(), })); vi.mock("../components/shared/PageHelp", () => ({ PageHelp: () => null })); vi.mock("../components/dashboard/CategoriesV1DiscoveryBanner", () => marker("discovery")); @@ -59,13 +64,20 @@ vi.mock("../components/dashboard/NetWorthTile", () => marker("net-worth")); vi.mock("../components/reports/CategoryBarChart", () => marker("bar-chart")); vi.mock("../components/reports/CategoryOverTimeChart", () => marker("over-time")); vi.mock("../components/reports/FilterPanel", () => marker("filters")); -vi.mock("../components/reports/cards/KpiCard", () => marker("kpi")); +vi.mock("../components/reports/cards/KpiCard", () => ({ + default: (props: Record) => { + kpiProps.set(props.id as string, props); + return ; + }, +})); vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => marker("overlay")); vi.mock("../components/reports/cards/TopMoversList", () => marker("movers")); vi.mock("../components/reports/cards/BudgetAdherenceCard", () => marker("adherence")); vi.mock("../components/shared/TransactionDetailModal", () => marker("detail")); import DashboardPage from "./DashboardPage"; +import { netNote } from "../components/reports/cards/netNote"; +import { markedT } from "../test/i18nMock"; import { computeChecklist } from "../utils/onboardingChecklist"; import type { OnboardingCounters } from "../shared/types"; @@ -115,6 +127,8 @@ const render = () => beforeEach(() => { onboarding = path(); emptyStateProps.current = null; + cartesSnapshot = null; + kpiProps.clear(); }); describe("DashboardPage on the shared path (#352, #396, #397)", () => { @@ -169,3 +183,36 @@ describe("DashboardPage — texts that go through t (#437)", () => { expect(render()).toContain(">t(dashboard.kpiSectionTitle)<"); }); }); + +describe("DashboardPage — the note under « Solde net » (#392, D5)", () => { + const kpi = (current: number): CartesKpi => ({ + current, + previousMonth: null, + previousYear: null, + deltaMoMAbs: null, + deltaMoMPct: null, + deltaYoYAbs: null, + deltaYoYPct: null, + sparkline: [], + }); + + it("hands the net card the note of the snapshot's breakdown, and no other card a note", () => { + const netBreakdown = { uncategorized: 40, transfers: -300 }; + cartesSnapshot = { + referenceYear: 2026, + referenceMonth: 10, + kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(710), savingsRate: kpi(97) }, + netBreakdown, + flow12Months: [], + topMoversUp: [], + topMoversDown: [], + budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] }, + seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null }, + }; + render(); + expect([...kpiProps.keys()]).toEqual(["income", "expenses", "net", "savingsRate"]); + expect(kpiProps.get("net")!.note).toContain("t(reports.cartes.netNote.both["); + expect(kpiProps.get("net")!.note).toBe(netNote(markedT, "fr", netBreakdown)); + for (const id of ["income", "expenses", "savingsRate"]) expect(kpiProps.get(id)!.note).toBeUndefined(); + }); +}); diff --git a/src/pages/ReportsCartesPage.render.test.tsx b/src/pages/ReportsCartesPage.render.test.tsx new file mode 100644 index 0000000..71aee64 --- /dev/null +++ b/src/pages/ReportsCartesPage.render.test.tsx @@ -0,0 +1,96 @@ +// ReportsCartesPage hands « Solde net » the note of its snapshot (#392, D5). +// No jsdom: react-dom/server renders the page in vitest's node environment. +// The data hook and the widgets are stubbed, and the fake KpiCard records the +// props it receives. +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { renderToStaticMarkup } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import type { CartesKpi, CartesSnapshot } from "../shared/types"; + +vi.mock("react-i18next", async () => (await import("../test/i18nMock")).i18nMock()); + +let snapshot: CartesSnapshot | null = null; +vi.mock("../hooks/useCartes", () => ({ + useCartes: () => ({ + year: 2026, + month: 10, + mode: "month", + snapshot, + isLoading: false, + error: null, + setReferencePeriod: vi.fn(), + setMode: vi.fn(), + }), +})); + +// Hoisted with the mocks below, which run before the imports. +const { marker, kpiProps } = vi.hoisted(() => ({ + marker: (name: string) => ({ default: () => }), + kpiProps: new Map>(), +})); +vi.mock("../components/reports/CompareReferenceMonthPicker", () => marker("month-picker")); +vi.mock("../components/reports/cards/CartesPeriodModeToggle", () => marker("mode-toggle")); +vi.mock("../components/reports/cards/KpiCard", () => ({ + default: (props: Record) => { + kpiProps.set(props.id as string, props); + return ; + }, +})); +vi.mock("../components/reports/cards/IncomeExpenseOverlayChart", () => marker("overlay")); +vi.mock("../components/reports/cards/TopMoversList", () => marker("movers")); +vi.mock("../components/reports/cards/BudgetAdherenceCard", () => marker("adherence")); +vi.mock("../components/reports/cards/SeasonalityCard", () => marker("seasonality")); + +import ReportsCartesPage from "./ReportsCartesPage"; +import { netNote } from "../components/reports/cards/netNote"; +import { markedT } from "../test/i18nMock"; + +const kpi = (current: number): CartesKpi => ({ + current, + previousMonth: null, + previousYear: null, + deltaMoMAbs: null, + deltaMoMPct: null, + deltaYoYAbs: null, + deltaYoYPct: null, + sparkline: [], +}); + +const render = () => + renderToStaticMarkup( + + + , + ); + +beforeEach(() => { + snapshot = null; + kpiProps.clear(); +}); + +describe("ReportsCartesPage — the note under « Solde net » (#392, D5)", () => { + it("hands the net card the note of the snapshot's breakdown, and no other card a note", () => { + const netBreakdown = { uncategorized: 40, transfers: -300 }; + snapshot = { + referenceYear: 2026, + referenceMonth: 10, + kpis: { income: kpi(1000), expenses: kpi(30), net: kpi(710), savingsRate: kpi(97) }, + netBreakdown, + flow12Months: [], + topMoversUp: [], + topMoversDown: [], + budgetAdherence: { categoriesInTarget: 0, categoriesTotal: 0, worstOverruns: [] }, + seasonality: { referenceAmount: 30, historicalYears: [], historicalAverage: null, deviationPct: null }, + }; + render(); + expect([...kpiProps.keys()]).toEqual(["income", "expenses", "net", "savingsRate"]); + expect(kpiProps.get("net")!.note).toContain("t(reports.cartes.netNote.both["); + expect(kpiProps.get("net")!.note).toBe(netNote(markedT, "fr", netBreakdown)); + for (const id of ["income", "expenses", "savingsRate"]) expect(kpiProps.get(id)!.note).toBeUndefined(); + }); + + it("renders no card without a snapshot", () => { + expect(render()).toContain("t(reports.empty.noData)"); + expect(kpiProps.size).toBe(0); + }); +}); diff --git a/src/services/reportService.cartes.test.ts b/src/services/reportService.cartes.test.ts index 96b3264..badb5b8 100644 --- a/src/services/reportService.cartes.test.ts +++ b/src/services/reportService.cartes.test.ts @@ -286,7 +286,7 @@ describe("getCartesSnapshot", () => { ]), ]; routeSelect([ - { match: "strftime('%Y-%m', date)", rows: [{ month: "2026-03", income: 5000, expenses: 400 }] }, + { match: FLOWS, rows: flowRows([{ month: "2026-03", income: 5000, expenses: 400 }]) }, { match: "ORDER BY ABS(month_current_total - month_previous_total) DESC", rows: momRows }, { match: "parent_id FROM categories", rows: [{ id: 99, name: "Salaire", color: null, type: "income", parent_id: null }] }, ]);