{header}
- {state.error && (
+ {error && (
- {state.error}
+ {error}
)}
@@ -153,55 +170,62 @@ export default function DashboardPage() {
- {cartesSnapshot && (
+ {periodKpis && (
<>
>
)}
+ {periodKpis && (
+
+
+
+ )}
+
{cartesSnapshot && (
<>
-
-
-
-
+
{t("dashboard.monthlyAnalysisTitle")}
{
+ snapshot = {
+ 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([...kpiProps.keys()]).toEqual(["income", "expenses", "net", "savingsRate"]);
+ for (const [id, props] of kpiProps) {
+ expect(props.kpi, id).toBe(snapshot.kpis[id as keyof CartesSnapshot["kpis"]]);
+ expect(props.deltaLabels, id).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.ts b/src/services/reportService.ts
index 12734aa..ba39880 100644
--- a/src/services/reportService.ts
+++ b/src/services/reportService.ts
@@ -39,6 +39,8 @@ import type {
CartesKpiPeriodMode,
BudgetVsActualRow,
IncomeStatementFigures,
+ PeriodComparisonRanges,
+ PeriodKpis,
ReportSection,
} from "../shared/types";
@@ -1299,6 +1301,75 @@ function buildKpi(
};
}
+/** The statements of a `getMonthlyTrends` result by month ("YYYY-MM"), for O(1) lookup. */
+function statementsByMonth(rows: MonthlyTrendItem[]): Map {
+ const byMonth = new Map();
+ for (const { month, ...figures } of rows) byMonth.set(month, figures);
+ return byMonth;
+}
+
+/**
+ * The `count` months ending at (year, month), oldest first. A month without
+ * any transaction is filled with zeroes, so consumers get a contiguous series.
+ */
+function monthSeries(
+ byMonth: Map,
+ year: number,
+ month: number,
+ count: number,
+): CartesMonthFlow[] {
+ const series: CartesMonthFlow[] = [];
+ for (let i = count - 1; i >= 0; i--) {
+ const { year: y, month: m } = shiftMonth(year, month, -i);
+ const key = monthKey(y, m);
+ series.push({ month: key, ...(byMonth.get(key) ?? EMPTY_STATEMENT) });
+ }
+ return series;
+}
+
+type KpiSparklines = Record<"income" | "expenses" | "net" | "savings", CartesSparklinePoint[]>;
+
+/** The curve of each KPI card over a series of months. */
+function kpiSparklines(series: CartesMonthFlow[]): KpiSparklines {
+ return {
+ income: series.map((p) => ({ month: p.month, value: p.income })),
+ expenses: series.map((p) => ({ month: p.month, value: p.expenses })),
+ net: series.map((p) => ({ month: p.month, value: p.net })),
+ savings: series.map((p) => ({ month: p.month, value: savingsRate(p.income, p.expenses) ?? 0 })),
+ };
+}
+
+type KpiFigures = Record<"income" | "expenses" | "net" | "savings", number | null>;
+
+/**
+ * The four KPI figures of a period, or null for a period without data.
+ * « Solde net » is the net result (D5); the savings rate is undefined when
+ * income is not positive — null rather than a misleading "0 %" in the UI (D6).
+ */
+function kpiFigures(s: IncomeStatementFigures | null | undefined): KpiFigures {
+ return {
+ income: s ? s.income : null,
+ expenses: s ? s.expenses : null,
+ net: s ? s.net : null,
+ savings: s ? savingsRate(s.income, s.expenses) : null,
+ };
+}
+
+/** The four KPI cards: the figures of a period against those of its two comparisons. */
+function buildKpis(
+ spark: KpiSparklines,
+ current: KpiFigures,
+ previous: KpiFigures,
+ previousYear: KpiFigures,
+): CartesSnapshot["kpis"] {
+ return {
+ income: buildKpi(spark.income, current.income, previous.income, previousYear.income),
+ expenses: buildKpi(spark.expenses, current.expenses, previous.expenses, previousYear.expenses),
+ net: buildKpi(spark.net, current.net, previous.net, previousYear.net),
+ savingsRate: buildKpi(spark.savings, current.savings, previous.savings, previousYear.savings),
+ };
+}
+
interface RawSeasonalityRow {
year: number;
/** Signed balance of the expense categories in that year's month. */
@@ -1383,39 +1454,12 @@ export async function getCartesSnapshot(
getBudgetVsActualData(referenceYear, referenceMonth, accountIds),
]);
- // Index the monthly statements by month for O(1) lookup, then fill missing
- // months with zeroes so downstream consumers get a contiguous series.
- const flowByMonth = new Map();
- for (const { month, ...figures } of flowRows) flowByMonth.set(month, figures);
-
- const buildSeries = (count: number): CartesMonthFlow[] => {
- const series: CartesMonthFlow[] = [];
- for (let i = count - 1; i >= 0; i--) {
- const { year: y, month: m } = shiftMonth(referenceYear, referenceMonth, -i);
- const key = monthKey(y, m);
- series.push({ month: key, ...(flowByMonth.get(key) ?? EMPTY_STATEMENT) });
- }
- return series;
- };
+ // Index the monthly statements by month; `monthSeries` fills missing months
+ // with zeroes so downstream consumers get a contiguous series.
+ const flowByMonth = statementsByMonth(flowRows);
// 13-month sparklines for each KPI (reference month + 12 prior).
- const sparkSeries = buildSeries(13);
- const incomeSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({
- month: p.month,
- value: p.income,
- }));
- const expensesSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({
- month: p.month,
- value: p.expenses,
- }));
- const netSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({
- month: p.month,
- value: p.net,
- }));
- const savingsSpark: CartesSparklinePoint[] = sparkSeries.map((p) => ({
- month: p.month,
- value: savingsRate(p.income, p.expenses) ?? 0,
- }));
+ const spark = kpiSparklines(monthSeries(flowByMonth, referenceYear, referenceMonth, 13));
// Compute MoM / YoY values directly from `flowByMonth` (which preserves the
// "missing" distinction). The sparkline fills gaps with zero for display,
@@ -1426,16 +1470,6 @@ export async function getCartesSnapshot(
const yoyMeta = { year: referenceYear - 1, month: referenceMonth };
const yoyKey = monthKey(yoyMeta.year, yoyMeta.month);
- // The four KPI figures of a period, or null for a period without data.
- // « Solde net » is the net result (D5); the savings rate is undefined when
- // income is not positive — null rather than a misleading "0 %" in the UI (D6).
- const kpiFigures = (s: IncomeStatementFigures | undefined) => ({
- income: s ? s.income : null,
- expenses: s ? s.expenses : null,
- net: s ? s.net : null,
- savings: s ? savingsRate(s.income, s.expenses) : null,
- });
-
// YTD aggregates — sum the monthly statements from January of a given year
// up to (and including) `upToMonth`. Reuses the already-fetched
// `flowByMonth` map, so no additional SQL round trip is required. Missing
@@ -1472,11 +1506,6 @@ export async function getCartesSnapshot(
);
const yoy = kpiFigures(isYtd ? sumYtd(referenceYear - 1, referenceMonth) : flowByMonth.get(yoyKey));
- const incomeKpi = buildKpi(incomeSpark, ref.income, mom.income, yoy.income);
- const expensesKpi = buildKpi(expensesSpark, ref.expenses, mom.expenses, yoy.expenses);
- const netKpi = buildKpi(netSpark, ref.net, mom.net, yoy.net);
- const savingsKpi = buildKpi(savingsSpark, ref.savings, mom.savings, yoy.savings);
-
// What « Solde net » holds beyond income − expenses, for the note under its card (D5).
const netBreakdown = {
uncategorized: refStatement.uncategorized,
@@ -1484,7 +1513,7 @@ export async function getCartesSnapshot(
};
// 12-month income vs expenses series for the overlay chart.
- const flow12Months = buildSeries(12);
+ const flow12Months = monthSeries(flowByMonth, referenceYear, referenceMonth, 12);
// Top movers: biggest MoM increases / decreases. `momRows` now carries the
// compare hierarchy (Issue #247) — skip the subtotal (`is_parent`) rows so a
@@ -1591,12 +1620,7 @@ export async function getCartesSnapshot(
return {
referenceYear,
referenceMonth,
- kpis: {
- income: incomeKpi,
- expenses: expensesKpi,
- net: netKpi,
- savingsRate: savingsKpi,
- },
+ kpis: buildKpis(spark, ref, mom, yoy),
netBreakdown,
flow12Months,
topMoversUp,
@@ -1605,3 +1629,67 @@ export async function getCartesSnapshot(
seasonality,
};
}
+
+// --- Dashboard period KPIs (Issue #549) ---
+
+/**
+ * The income statement of a range of days (#549): the statements that
+ * `getMonthlyTrends` gives for the months of the range, within its exact
+ * bounds, added up. A period that cuts a month counts its own days only, and
+ * every screen keeps reading the one monthly query (ADR 0026). Null when the
+ * range holds no transaction, so that a comparison with an empty period stays
+ * « — » rather than a change against zero. An absent bound is no bound
+ * (« Tout »).
+ */
+export async function getIncomeStatement(
+ dateFrom?: string,
+ dateTo?: string,
+ accountIds?: number[],
+): Promise {
+ const months = await getMonthlyTrends(dateFrom, dateTo, accountIds);
+ if (months.length === 0) return null;
+ return months.reduce((sum, month) => addStatements(sum, month), EMPTY_STATEMENT);
+}
+
+/**
+ * The KPI cards and the 12-month chart of the Dashboard over its period
+ * (#549), against the comparisons of `ranges` (`computeComparisonRanges`).
+ *
+ * Each card holds the figure of the period, to the day, and its changes from
+ * the previous period and from the same period last year: null when that
+ * period holds no transaction, or when the period has no such comparison
+ * (`ranges.previous` or `ranges.previousYear` null). A period without any
+ * transaction shows zero, its savings rate null (D6). The cards' curves cover
+ * the 13 months ending at `ranges.lastMonth`, the chart the last 12 of them,
+ * in whole months. « Solde net » is the net result, its uncategorized and
+ * transfer parts in `netBreakdown` (D5). `accountIds` reaches every query.
+ */
+export async function getPeriodKpis(
+ ranges: PeriodComparisonRanges,
+ accountIds?: number[],
+): Promise {
+ const { current, previous, previousYear, lastMonth } = ranges;
+ const windowStart = shiftMonth(lastMonth.year, lastMonth.month, -12);
+ const { start: windowStartIso } = monthBoundaries(windowStart.year, windowStart.month);
+ const { end: windowEndIso } = monthBoundaries(lastMonth.year, lastMonth.month);
+
+ const [statement, previousStatement, previousYearStatement, flowRows] = await Promise.all([
+ getIncomeStatement(current.dateFrom, current.dateTo, accountIds),
+ previous ? getIncomeStatement(previous.dateFrom, previous.dateTo, accountIds) : null,
+ previousYear ? getIncomeStatement(previousYear.dateFrom, previousYear.dateTo, accountIds) : null,
+ getMonthlyTrends(windowStartIso, windowEndIso, accountIds),
+ ]);
+
+ const flowByMonth = statementsByMonth(flowRows);
+ const spark = kpiSparklines(monthSeries(flowByMonth, lastMonth.year, lastMonth.month, 13));
+ // The period itself always has figures, zero without any transaction: only
+ // a comparison can be missing.
+ const figures = statement ?? EMPTY_STATEMENT;
+
+ return {
+ ranges,
+ kpis: buildKpis(spark, kpiFigures(figures), kpiFigures(previousStatement), kpiFigures(previousYearStatement)),
+ netBreakdown: { uncategorized: figures.uncategorized, transfers: figures.transfers },
+ flow12Months: monthSeries(flowByMonth, lastMonth.year, lastMonth.month, 12),
+ };
+}
diff --git a/src/shared/types/index.ts b/src/shared/types/index.ts
index e1fb28d..c02a02b 100644
--- a/src/shared/types/index.ts
+++ b/src/shared/types/index.ts
@@ -336,6 +336,30 @@ export interface ImportReport {
export type DashboardPeriod = "month" | "3months" | "6months" | "year" | "12months" | "all" | "custom";
+/** A range of ISO dates (YYYY-MM-DD), both bounds included. */
+export interface DateRange {
+ dateFrom: string;
+ dateTo: string;
+}
+
+/**
+ * The Dashboard's period and the two periods its KPI cards compare it with
+ * (#549), from `computeComparisonRanges`. `current` has no bounds for « Tout ».
+ */
+export interface PeriodComparisonRanges {
+ current: { dateFrom?: string; dateTo?: string };
+ /**
+ * The period of the same length just before, or null when the period has
+ * none of its own: « Tout », and a period whose previous one is last year's
+ * very range (« Cette année », « 12 mois »).
+ */
+ previous: DateRange | null;
+ /** The same dates one year earlier (February 29 on the 28th), or null for « Tout ». */
+ previousYear: DateRange | null;
+ /** The month of the period's last day, where the 12-month chart and the cards' curves end. */
+ lastMonth: { year: number; month: number };
+}
+
export interface CategoryBreakdownItem {
category_id: number | null;
category_name: string;
@@ -561,13 +585,18 @@ export interface CartesKpi {
// `current` is nullable for ratio-style KPIs (e.g. savings rate) when the
// denominator is zero and the value is genuinely undefined rather than 0.
current: number | null;
+ // On the Dashboard's cards (#549), `previousMonth` and `deltaMoM*` hold the
+ // previous period of the same length, `previousYear` and `deltaYoY*` the
+ // same period last year.
previousMonth: number | null;
previousYear: number | null;
deltaMoMAbs: number | null;
deltaMoMPct: number | null;
deltaYoYAbs: number | null;
deltaYoYPct: number | null;
- sparkline: CartesSparklinePoint[]; // 13 months ending at reference month
+ // 13 months ending at the reference month (Cartes) or at the period's last
+ // month (the Dashboard, #549).
+ sparkline: CartesSparklinePoint[];
}
export type CartesKpiId = "income" | "expenses" | "net" | "savingsRate";
@@ -645,6 +674,20 @@ export interface CartesSnapshot {
seasonality: CartesSeasonality;
}
+/**
+ * The KPI cards and the 12-month chart of the Dashboard over its period
+ * (#549), from `getPeriodKpis`. The cards keep the shape of Cartes' (see
+ * `CartesKpi`), with `ranges` telling which comparisons the period has.
+ */
+export interface PeriodKpis {
+ ranges: PeriodComparisonRanges;
+ kpis: CartesSnapshot["kpis"];
+ /** What « Solde net » holds beyond income − expenses over the period: the note under its card (D5). */
+ netBreakdown: CartesSnapshot["netBreakdown"];
+ /** The 12 months ending at `ranges.lastMonth`. */
+ flow12Months: CartesMonthFlow[];
+}
+
export type ImportWizardStep =
| "source-list"
| "source-config"
diff --git a/src/utils/dateRange.test.ts b/src/utils/dateRange.test.ts
index 9405e89..4982aec 100644
--- a/src/utils/dateRange.test.ts
+++ b/src/utils/dateRange.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { computeDateRange, buildMonthOptions } from "./dateRange";
+import { computeDateRange, computeComparisonRanges, buildMonthOptions } from "./dateRange";
+import type { DashboardPeriod } from "../shared/types";
describe("computeDateRange", () => {
beforeEach(() => {
@@ -86,6 +87,155 @@ describe("computeDateRange", () => {
});
});
+describe("computeComparisonRanges — the Dashboard's period and its two comparisons (#549)", () => {
+ // Local noon, so the day is the same in every time zone. November 14, 2026
+ // is the day of the issue's example.
+ const NOV_14 = new Date(2026, 10, 14, 12);
+ const at = (period: DashboardPeriod, today: Date, from?: string, to?: string) =>
+ computeComparisonRanges(period, from, to, today);
+ const range = (dateFrom: string, dateTo: string) => ({ dateFrom, dateTo });
+
+ it("« Ce mois », November 1st–14th, is compared with October 1st–14th and November 1st–14th of last year", () => {
+ expect(at("month", NOV_14)).toEqual({
+ current: range("2026-11-01", "2026-11-14"),
+ previous: range("2026-10-01", "2026-10-14"),
+ previousYear: range("2025-11-01", "2025-11-14"),
+ lastMonth: { year: 2026, month: 11 },
+ });
+ });
+
+ it.each([
+ ["3months", "2026-09-01", range("2026-06-01", "2026-08-14"), range("2025-09-01", "2025-11-14")],
+ ["6months", "2026-06-01", range("2025-12-01", "2026-05-14"), range("2025-06-01", "2025-11-14")],
+ ] as const)("« %s » moves back by its own number of months, to the same day", (period, from, previous, previousYear) => {
+ expect(at(period, NOV_14)).toEqual({
+ current: range(from, "2026-11-14"),
+ previous,
+ previousYear,
+ lastMonth: { year: 2026, month: 11 },
+ });
+ });
+
+ it("« Cette année » has no previous period of its own: its previous one is last year's range, kept once", () => {
+ expect(at("year", NOV_14)).toEqual({
+ current: range("2026-01-01", "2026-11-14"),
+ previous: null,
+ previousYear: range("2025-01-01", "2025-11-14"),
+ lastMonth: { year: 2026, month: 11 },
+ });
+ });
+
+ it("« 12 mois » moved back 12 months is last year's range: only last year's is kept", () => {
+ expect(at("12months", NOV_14)).toEqual({
+ current: range("2025-12-01", "2026-11-14"),
+ previous: null,
+ previousYear: range("2024-12-01", "2025-11-14"),
+ lastMonth: { year: 2026, month: 11 },
+ });
+ });
+
+ it("« Tout » has no bound and nothing to compare with; its chart ends this month", () => {
+ expect(at("all", NOV_14)).toEqual({
+ current: {},
+ previous: null,
+ previousYear: null,
+ lastMonth: { year: 2026, month: 11 },
+ });
+ });
+
+ it("a custom period is compared with the same number of days just before, and its own dates last year", () => {
+ // March 10–20: 11 days; the 11 days before are February 27 – March 9.
+ expect(at("custom", NOV_14, "2026-03-10", "2026-03-20")).toEqual({
+ current: range("2026-03-10", "2026-03-20"),
+ previous: range("2026-02-27", "2026-03-09"),
+ previousYear: range("2025-03-10", "2025-03-20"),
+ lastMonth: { year: 2026, month: 3 },
+ });
+ });
+
+ it("a custom period counts its days across a year boundary and a leap day", () => {
+ // December 20 – January 10: 22 days.
+ expect(at("custom", NOV_14, "2025-12-20", "2026-01-10")).toMatchObject({
+ previous: range("2025-11-28", "2025-12-19"),
+ previousYear: range("2024-12-20", "2025-01-10"),
+ lastMonth: { year: 2026, month: 1 },
+ });
+ // February 20 – March 5, 2024: 15 days, February 29 included.
+ expect(at("custom", NOV_14, "2024-02-20", "2024-03-05")).toMatchObject({
+ previous: range("2024-02-05", "2024-02-19"),
+ previousYear: range("2023-02-20", "2023-03-05"),
+ });
+ // One day: the day before.
+ expect(at("custom", NOV_14, "2026-03-01", "2026-03-01").previous).toEqual(range("2026-02-28", "2026-02-28"));
+ });
+
+ it("a custom year: its previous days are last year's range, kept once", () => {
+ // March 1st, 2025 – February 28, 2026: 365 days, the 365 before are last year's dates.
+ expect(at("custom", NOV_14, "2025-03-01", "2026-02-28")).toMatchObject({
+ previous: null,
+ previousYear: range("2024-03-01", "2025-02-28"),
+ });
+ });
+
+ it("a custom period ends its chart at its own last month, not today's", () => {
+ expect(at("custom", NOV_14, "2026-01-01", "2026-06-15").lastMonth).toEqual({ year: 2026, month: 6 });
+ });
+
+ it("a custom period without its two dates is « Ce mois », as computeDateRange reads it", () => {
+ expect(at("custom", NOV_14)).toEqual(at("month", NOV_14));
+ expect(at("custom", NOV_14, "2026-03-10")).toEqual(at("month", NOV_14));
+ });
+
+ it("on the last day of a month, the previous period ends on the last day of a shorter month", () => {
+ // « Ce mois » on March 31: February 1st–28th, 29th in a leap year.
+ expect(at("month", new Date(2026, 2, 31, 12)).previous).toEqual(range("2026-02-01", "2026-02-28"));
+ expect(at("month", new Date(2028, 2, 31, 12)).previous).toEqual(range("2028-02-01", "2028-02-29"));
+ // « 3 mois » on May 31: March 1st – May 31, compared with December 1st – February 28.
+ expect(at("3months", new Date(2026, 4, 31, 12))).toMatchObject({
+ current: range("2026-03-01", "2026-05-31"),
+ previous: range("2025-12-01", "2026-02-28"),
+ });
+ // « 6 mois » on August 31: March 1st – August 31, compared with September 1st – February 28.
+ expect(at("6months", new Date(2026, 7, 31, 12))).toMatchObject({
+ current: range("2026-03-01", "2026-08-31"),
+ previous: range("2025-09-01", "2026-02-28"),
+ });
+ });
+
+ it("January rolls back into the previous year", () => {
+ const jan20 = new Date(2027, 0, 20, 12);
+ expect(at("month", jan20).previous).toEqual(range("2026-12-01", "2026-12-20"));
+ expect(at("3months", jan20)).toMatchObject({
+ current: range("2026-11-01", "2027-01-20"),
+ previous: range("2026-08-01", "2026-10-20"),
+ previousYear: range("2025-11-01", "2026-01-20"),
+ });
+ });
+
+ it("on February 29, last year's range ends on February 28", () => {
+ const feb29 = new Date(2028, 1, 29, 12);
+ expect(at("month", feb29)).toEqual({
+ current: range("2028-02-01", "2028-02-29"),
+ previous: range("2028-01-01", "2028-01-29"),
+ previousYear: range("2027-02-01", "2027-02-28"),
+ lastMonth: { year: 2028, month: 2 },
+ });
+ // « 12 mois »: both comparisons end on February 28, 2027, so one is kept.
+ expect(at("12months", feb29)).toMatchObject({
+ current: range("2027-03-01", "2028-02-29"),
+ previous: null,
+ previousYear: range("2026-03-01", "2027-02-28"),
+ });
+ });
+
+ it.each(["month", "3months", "6months", "year", "12months", "all"] as const)(
+ "« %s »: the current range is computeDateRange's, the one of the widgets that follow the period",
+ (period) => {
+ expect(at(period, NOV_14).current).toEqual(computeDateRange(period, undefined, undefined, NOV_14));
+ },
+ );
+});
+
describe("buildMonthOptions", () => {
beforeEach(() => {
vi.useFakeTimers();
diff --git a/src/utils/dateRange.ts b/src/utils/dateRange.ts
index d33331b..2b4db63 100644
--- a/src/utils/dateRange.ts
+++ b/src/utils/dateRange.ts
@@ -1,4 +1,4 @@
-import type { DashboardPeriod } from "../shared/types";
+import type { DashboardPeriod, DateRange, PeriodComparisonRanges } from "../shared/types";
/**
* Compute a date range (dateFrom / dateTo) based on the selected period.
@@ -52,6 +52,111 @@ export function computeDateRange(
return { dateFrom, dateTo };
}
+/** How many months back the previous period of a rolling preset lies (#549). */
+const PRESET_MONTHS: Partial> = {
+ month: 1,
+ "3months": 3,
+ "6months": 6,
+ "12months": 12,
+};
+
+function parseIso(iso: string): { year: number; monthIndex: number; day: number } {
+ const [year, month, day] = iso.split("-").map(Number);
+ return { year, monthIndex: month - 1, day };
+}
+
+/** A date as YYYY-MM-DD; `monthIndex` and `day` past their range carry over, as `Date.UTC` does. */
+function isoOf(year: number, monthIndex: number, day: number): string {
+ const d = new Date(Date.UTC(year, monthIndex, day));
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}`;
+}
+
+/**
+ * The same day `months` months away, or the last day of the target month when
+ * it is shorter: March 31 one month back is February 28 (29 in a leap year),
+ * and February 29 twelve months back is February 28.
+ */
+function shiftMonths(iso: string, months: number): string {
+ const { year, monthIndex, day } = parseIso(iso);
+ const lastDay = new Date(Date.UTC(year, monthIndex + months + 1, 0)).getUTCDate();
+ return isoOf(year, monthIndex + months, Math.min(day, lastDay));
+}
+
+function shiftDays(iso: string, days: number): string {
+ const { year, monthIndex, day } = parseIso(iso);
+ return isoOf(year, monthIndex, day + days);
+}
+
+/** Days from `dateFrom` to `dateTo`, both included. */
+function dayCount(dateFrom: string, dateTo: string): number {
+ const a = parseIso(dateFrom);
+ const b = parseIso(dateTo);
+ const ms = Date.UTC(b.year, b.monthIndex, b.day) - Date.UTC(a.year, a.monthIndex, a.day);
+ return Math.round(ms / 86_400_000) + 1;
+}
+
+/**
+ * The Dashboard's period and the two periods its KPI cards compare it with
+ * (#549). `current` is `computeDateRange`'s range, the one of every widget
+ * that follows the period.
+ *
+ * - `previous`, the period of the same length just before: a rolling preset
+ * (« Ce mois », « 3 mois », « 6 mois », « 12 mois ») moved back by its own
+ * number of months, its end on the same day of the month or on the last day
+ * of a shorter month (« Ce mois » on November 14 is compared with October
+ * 1–14); a custom period, the same number of days just before its first day;
+ * « Cette année », January 1st to today, last year's range.
+ * - `previousYear`, the same dates one year earlier, February 29 on the 28th.
+ *
+ * When `previous` is the very range of `previousYear` (« Cette année »,
+ * « 12 mois », a custom year), it is null: the cards show the change from last
+ * year alone rather than the same figure twice. « Tout » has neither.
+ * `lastMonth` is the month of the period's last day, today's month for
+ * « Tout »: the 12-month chart and the cards' curves end there.
+ */
+export function computeComparisonRanges(
+ period: DashboardPeriod,
+ customDateFrom?: string,
+ customDateTo?: string,
+ today: Date = new Date(),
+): PeriodComparisonRanges {
+ const current = computeDateRange(period, customDateFrom, customDateTo, today);
+ const { dateFrom, dateTo } = current;
+ if (dateFrom === undefined || dateTo === undefined) {
+ // « Tout », the only period without bounds.
+ return {
+ current,
+ previous: null,
+ previousYear: null,
+ lastMonth: { year: today.getFullYear(), month: today.getMonth() + 1 },
+ };
+ }
+
+ const previousYear: DateRange = { dateFrom: shiftMonths(dateFrom, -12), dateTo: shiftMonths(dateTo, -12) };
+ let previous: DateRange;
+ if (period === "custom" && customDateFrom && customDateTo) {
+ const days = dayCount(dateFrom, dateTo);
+ previous = { dateFrom: shiftDays(dateFrom, -days), dateTo: shiftDays(dateFrom, -1) };
+ } else if (period === "year") {
+ previous = previousYear;
+ } else {
+ // A rolling preset, or a custom period without its two dates, which
+ // `computeDateRange` reads as « Ce mois ».
+ const months = PRESET_MONTHS[period] ?? 1;
+ previous = { dateFrom: shiftMonths(dateFrom, -months), dateTo: shiftMonths(dateTo, -months) };
+ }
+
+ const sameAsLastYear =
+ previous.dateFrom === previousYear.dateFrom && previous.dateTo === previousYear.dateTo;
+ const end = parseIso(dateTo);
+ return {
+ current,
+ previous: sameAsLastYear ? null : previous,
+ previousYear,
+ lastMonth: { year: end.year, month: end.monthIndex + 1 },
+ };
+}
+
/**
* Build an array of month options for the budget month dropdown.
* Returns the last 24 months with localized labels.