Open-source personal finance manager. Self-hosted, privacy-first.
feat(reports): add month presets and period navigation to the range selector (#1244)
Tássio Noronha8cf0791062b7
diff --git a/frontend/src/lib/remembered-range.test.ts b/frontend/src/lib/remembered-range.test.tsindex 477a9044..f046d131 100644--- a/frontend/src/lib/remembered-range.test.ts+++ b/frontend/src/lib/remembered-range.test.ts@@ -64,12 +64,26 @@ describe('remembered date range', () => {})it('keeps a separate reports range per tab', () => {- const netWorth = { rangeKey: '2y', from: '', to: '', interval: 'monthly' }- const cashFlow = { rangeKey: '6m', from: '', to: '', interval: 'daily' }+ const netWorth = { rangeKey: '2y', from: '', to: '', interval: 'monthly', periodOffset: 0 }+ const cashFlow = { rangeKey: '6m', from: '', to: '', interval: 'daily', periodOffset: -1 }saveReportsRange('net_worth', netWorth)saveReportsRange('cash_flow', cashFlow)expect(loadReportsRange('net_worth')).toEqual(netWorth)expect(loadReportsRange('cash_flow')).toEqual(cashFlow)expect(loadReportsRange('money_map')).toBeNull()})++ it('normalizes the stored period offset to whole past periods', () => {+ saveReportsRange('net_worth', { rangeKey: '1y', from: '', to: '', interval: 'monthly', periodOffset: -3 })+ expect(loadReportsRange('net_worth')?.periodOffset).toBe(-3)++ saveReportsRange('net_worth', { rangeKey: '1y', from: '', to: '', interval: 'monthly', periodOffset: 2 })+ expect(loadReportsRange('net_worth')?.periodOffset).toBe(0)++ localStorage.setItem(+ 'securo.dateRange.reports',+ JSON.stringify({ net_worth: { rangeKey: '1y', from: '', to: '', interval: 'monthly', periodOffset: 'nope' } }),+ )+ expect(loadReportsRange('net_worth')?.periodOffset).toBe(0)+ })})diff --git a/frontend/src/lib/remembered-range.ts b/frontend/src/lib/remembered-range.tsindex 8115a7ca..3354d9af 100644--- a/frontend/src/lib/remembered-range.ts+++ b/frontend/src/lib/remembered-range.ts@@ -59,6 +59,8 @@ export interface ReportsRange {from: stringto: stringinterval: string+ /** Period navigation offset in periods of the preset (issue #519); 0 means the window ends today. */+ periodOffset?: number}/** Stored per-tab entries; anything that isn't an object (an older flat shape) is dropped. */@@ -74,7 +76,13 @@ export function loadReportsRange(tab: string): ReportsRange | null {const v = readReportsTabs()[tab] as Partial<Record<keyof ReportsRange, unknown>> | undefinedif (!v || typeof v.rangeKey !== 'string' || typeof v.interval !== 'string') return nullif (!isDate(v.from) || !isDate(v.to)) return null- return { rangeKey: v.rangeKey, from: v.from, to: v.to, interval: v.interval }+ // A stored offset that is not an integer (older writes, or+ // corrupted storage) is dropped; a sane floor keeps the window reachable.+ const periodOffset =+ typeof v.periodOffset === 'number' && Number.isInteger(v.periodOffset)+ ? Math.max(-1200, Math.min(0, v.periodOffset))+ : 0+ return { rangeKey: v.rangeKey, from: v.from, to: v.to, interval: v.interval, periodOffset }}export function saveReportsRange(tab: string, range: ReportsRange): void {diff --git a/frontend/src/lib/report-period.test.ts b/frontend/src/lib/report-period.test.tsnew file mode 100644index 00000000..50ccf136--- /dev/null+++ b/frontend/src/lib/report-period.test.ts@@ -0,0 +1,181 @@+import { describe, expect, it } from 'vitest'+import { addDaysIso, addMonthsIso, daysBetween, periodWindow, rollingStart, windowMonths } from './report-period'++describe('addDaysIso', () => {+ it('shifts within a month', () => {+ expect(addDaysIso('2026-09-12', -29)).toBe('2026-08-14')+ expect(addDaysIso('2026-09-12', 10)).toBe('2026-09-22')+ })++ it('rolls across month and year boundaries', () => {+ expect(addDaysIso('2026-01-01', -1)).toBe('2025-12-31')+ expect(addDaysIso('2025-12-31', 1)).toBe('2026-01-01')+ })+})++describe('addMonthsIso', () => {+ it('clamps the day to the target month length', () => {+ expect(addMonthsIso('2026-01-31', -1)).toBe('2025-12-31')+ expect(addMonthsIso('2026-03-31', -1)).toBe('2026-02-28')+ expect(addMonthsIso('2024-03-31', -1)).toBe('2024-02-29')+ })++ it('rolls across year boundaries', () => {+ expect(addMonthsIso('2026-12-15', 1)).toBe('2027-01-15')+ expect(addMonthsIso('2026-01-15', -1)).toBe('2025-12-15')+ })+})++describe('daysBetween', () => {+ it('counts whole days from one date to another', () => {+ expect(daysBetween('2026-01-01', '2026-01-01')).toBe(0)+ expect(daysBetween('2026-01-01', '2026-01-31')).toBe(30)+ expect(daysBetween('2026-01-31', '2026-01-01')).toBe(-30)+ })+})++describe('rollingStart', () => {+ it('snaps the current month back by months * 30 days to the 1st', () => {+ expect(rollingStart('2026-09-15', 1)).toBe('2026-08-01')+ expect(rollingStart('2026-09-15', 6)).toBe('2026-03-01')+ })+})++describe('windowMonths', () => {+ it('rounds the span up to months, clamped to 1..24', () => {+ expect(windowMonths({ from: '2026-09-01', to: '2026-09-30' })).toBe(1)+ expect(windowMonths({ from: '2026-01-01', to: '2026-12-31' })).toBe(13)+ expect(windowMonths({ from: '2022-01-01', to: '2026-12-31' })).toBe(24)+ })+})++describe('periodWindow: month presets', () => {+ const today = '2026-09-15'++ it('This Month at offset 0 spans the 1st to today', () => {+ expect(periodWindow({ kind: 'month', anchorDelta: 0 }, today, 0)).toEqual({+ from: '2026-09-01',+ to: '2026-09-15',+ })+ })++ it('This Month steps back to whole previous months', () => {+ expect(periodWindow({ kind: 'month', anchorDelta: 0 }, today, -1)).toEqual({+ from: '2026-08-01',+ to: '2026-08-31',+ })+ })++ it('Last Month at offset 0 is the whole previous month', () => {+ expect(periodWindow({ kind: 'month', anchorDelta: -1 }, today, 0)).toEqual({+ from: '2026-08-01',+ to: '2026-08-31',+ })+ })++ it('Last Month steps back through earlier months', () => {+ expect(periodWindow({ kind: 'month', anchorDelta: -1 }, today, -1)).toEqual({+ from: '2026-07-01',+ to: '2026-07-31',+ })+ })++ it('crosses the year boundary', () => {+ expect(periodWindow({ kind: 'month', anchorDelta: -1 }, '2026-01-15', 0)).toEqual({+ from: '2025-12-01',+ to: '2025-12-31',+ })+ expect(periodWindow({ kind: 'month', anchorDelta: 0 }, '2026-01-15', 0)).toEqual({+ from: '2026-01-01',+ to: '2026-01-15',+ })+ })+})++describe('periodWindow: ytd', () => {+ it('offset 0 defers to the API period=ytd path', () => {+ expect(periodWindow({ kind: 'ytd' }, '2026-09-15', 0)).toBeNull()+ })++ it('negative offsets span whole previous years', () => {+ expect(periodWindow({ kind: 'ytd' }, '2026-09-15', -1)).toEqual({+ from: '2025-01-01',+ to: '2025-12-31',+ })+ expect(periodWindow({ kind: 'ytd' }, '2026-09-15', -2)).toEqual({+ from: '2024-01-01',+ to: '2024-12-31',+ })+ })++ it('follows a financial year that starts in April', () => {+ expect(periodWindow({ kind: 'ytd', fyStartMonth: 4 }, '2026-09-15', -1)).toEqual({+ from: '2025-04-01',+ to: '2026-03-31',+ })+ // Before April the current financial year began the previous calendar year.+ expect(periodWindow({ kind: 'ytd', fyStartMonth: 4 }, '2026-02-10', -1)).toEqual({+ from: '2024-04-01',+ to: '2025-03-31',+ })+ })+})++describe('periodWindow: rolling presets', () => {+ it('offset 0 defers to the API months path', () => {+ expect(periodWindow({ kind: 'rolling', months: 6 }, '2026-09-15', 0)).toBeNull()+ })++ it('steps back by whole windows that touch but never overlap', () => {+ // 6M on 2026-09-15 covers 2026-03-01 to today: seven calendar months.+ expect(periodWindow({ kind: 'rolling', months: 6 }, '2026-09-15', -1)).toEqual({+ from: '2025-08-01',+ to: '2026-02-28',+ })+ expect(periodWindow({ kind: 'rolling', months: 6 }, '2026-09-15', -2)).toEqual({+ from: '2025-01-01',+ to: '2025-07-31',+ })+ // 1Y on 2026-09-15 covers 2025-09-01 to today: thirteen calendar months.+ expect(periodWindow({ kind: 'rolling', months: 12 }, '2026-09-15', -1)).toEqual({+ from: '2024-08-01',+ to: '2025-08-31',+ })+ })++ it('ends the previous window the day before the current one starts', () => {+ const today = '2026-10-23'+ for (const months of [3, 6, 12, 24]) {+ const previous = periodWindow({ kind: 'rolling', months }, today, -1)+ expect(previous && addDaysIso(previous.to, 1)).toBe(rollingStart(today, months))+ }+ })+})++describe('periodWindow: days presets', () => {+ it('offset 0 defers to the API days path', () => {+ expect(periodWindow({ kind: 'days', days: 30 }, '2026-09-15', 0)).toBeNull()+ })++ it('steps the rolling window back by its own length', () => {+ expect(periodWindow({ kind: 'days', days: 30 }, '2026-09-15', -1)).toEqual({+ from: '2026-07-18',+ to: '2026-08-16',+ })+ })+})++describe('periodWindow: custom ranges', () => {+ const range = { from: '2026-05-10', to: '2026-08-20' }++ it('offset 0 defers to the page-sent dates', () => {+ expect(periodWindow({ kind: 'custom' }, '2026-09-15', 0, range)).toBeNull()+ })++ it('steps the picked range back by its own length in months', () => {+ expect(periodWindow({ kind: 'custom' }, '2026-09-15', -1, range)).toEqual({+ from: '2026-01-10',+ to: '2026-04-20',+ })+ })+})diff --git a/frontend/src/lib/report-period.ts b/frontend/src/lib/report-period.tsnew file mode 100644index 00000000..912163f4--- /dev/null+++ b/frontend/src/lib/report-period.ts@@ -0,0 +1,150 @@+/**+ * Period window math for the Reports date range selector.+ *+ * Presets (6M, YTD, 1Y, ...) and the custom range are normally anchored to+ * today: the API derives the start from `months` / `period` / `days` (or the+ * page sends the picked custom dates). Period navigation (issue #519) steps+ * the same window back by its own length: the window keeps its shape and every+ * date inside it moves back together. Shifted windows are sent to the API as+ * explicit `start_date` / `end_date`.+ */++import { monthRange, shiftMonth } from './month-utils'++/** Explicit report window as timezone-naive `YYYY-MM-DD` strings. */+export interface PeriodWindow {+ from: string+ to: string+}++/** The five shapes a range preset can have. */+export type PeriodPreset =+ | { kind: 'month'; anchorDelta: number } // This Month (0) / Last Month (-1)+ | { kind: 'ytd'; fyStartMonth?: number } // YTD, start of the financial year (1 = January)+ | { kind: 'rolling'; months: number } // 6M / 1Y / 2Y ...+ | { kind: 'days'; days: number } // 30D rolling window+ | { kind: 'custom' } // user-picked from/to++function parseIso(iso: string): { y: number; m: number; d: number } {+ const [y, m, d] = iso.split('-').map(Number)+ return { y, m, d }+}++function iso(y: number, m: number, d: number): string {+ return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`+}++/** Shift a date by whole days (calendar math, DST safe). */+export function addDaysIso(isoDate: string, delta: number): string {+ const { y, m, d } = parseIso(isoDate)+ const t = new Date(y, m - 1, d + delta)+ return iso(t.getFullYear(), t.getMonth() + 1, t.getDate())+}++/** Shift a date by whole months, clamping the day to the target month's end. */+export function addMonthsIso(isoDate: string, delta: number): string {+ const { y, m, d } = parseIso(isoDate)+ const target = new Date(y, m - 1 + delta, 1)+ const lastDay = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate()+ return iso(target.getFullYear(), target.getMonth() + 1, Math.min(d, lastDay))+}++/** Whole days from `from` to `to` (negative when `to` is earlier). */+export function daysBetween(fromIso: string, toIso: string): number {+ const f = parseIso(fromIso)+ const t = parseIso(toIso)+ return Math.round((Date.UTC(t.y, t.m - 1, t.d) - Date.UTC(f.y, f.m - 1, f.d)) / 86_400_000)+}++/**+ * Start of the rolling window for a `months` preset. Mirrors the backend:+ * first day of the current month, back by `months * 30` days, snapped to the+ * first day of that month (so 6M today means "since the 1st, ~6 months back").+ */+export function rollingStart(today: string, months: number): string {+ const { y, m } = parseIso(today)+ return addDaysIso(iso(y, m, 1), -(months * 30)).slice(0, 8) + '01'+}++/**+ * Window width in months: ceil of the span in days / 30, clamped to 1..24.+ * Same rule the page uses when it sends a custom range, so shifted windows+ * keep the `months` parameter the API expects.+ */+export function windowMonths(window: PeriodWindow): number {+ return Math.max(1, Math.min(24, Math.ceil(daysBetween(window.from, window.to) / 30)))+}++/**+ * Explicit window for a preset at a period offset.+ *+ * - Month presets (This Month / Last Month) always return dates: the API has+ * no equivalent preset. `This Month` at offset 0 ends on `today`; every+ * other combination is a full calendar month.+ * - `ytd` at offset 0 returns null (the API's `period=ytd` path); other+ * offsets span whole previous financial years.+ * - `rolling` / `days` at offset 0 return null (the API's `months` / `days`+ * path); negative offsets step back by whole windows of the same number+ * of calendar months, each ending the day before the next one starts.+ *+ * `offset` counts periods of the preset (months, financial years, the+ * rolling length or the custom span), not calendar months.+ * - `custom` at offset 0 returns null (the page already sends the picked+ * dates); negative offsets step the picked range back by its own length in+ * months.+ */+export function periodWindow(+ preset: PeriodPreset,+ today: string,+ offset: number,+ customRange?: PeriodWindow,+): PeriodWindow | null {+ switch (preset.kind) {+ case 'month': {+ const anchor = shiftMonth(today.slice(0, 7), preset.anchorDelta + offset)+ const full = monthRange(anchor)+ if (offset === 0 && preset.anchorDelta === 0) {+ return { from: full.from, to: today }+ }+ return full+ }+ case 'ytd': {+ if (offset === 0) return null+ const fy = preset.fyStartMonth ?? 1+ const t = parseIso(today)+ const startYear = t.y - (t.m < fy ? 1 : 0) + offset+ const from = iso(startYear, fy, 1)+ return { from, to: addDaysIso(addMonthsIso(from, 12), -1) }+ }+ case 'rolling': {+ if (offset === 0) return null+ // The current window runs from the 1st of its first month to today, so+ // it spans whole calendar months. Earlier windows are that many full+ // months each and end the day before the next one starts: no overlap.+ const start = rollingStart(today, preset.months)+ const s = parseIso(start)+ const t = parseIso(today)+ const span = (t.y - s.y) * 12 + (t.m - s.m) + 1+ return {+ from: addMonthsIso(start, span * offset),+ to: addDaysIso(addMonthsIso(start, span * (offset + 1)), -1),+ }+ }+ case 'days': {+ if (offset === 0) return null+ const step = preset.days * offset+ return {+ from: addDaysIso(today, -(preset.days - 1) + step),+ to: addDaysIso(today, step),+ }+ }+ case 'custom': {+ if (offset === 0 || !customRange) return null+ const spanMonths = Math.max(1, Math.ceil(daysBetween(customRange.from, customRange.to) / 30))+ return {+ from: addMonthsIso(customRange.from, spanMonths * offset),+ to: addMonthsIso(customRange.to, spanMonths * offset),+ }+ }+ }+}diff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.jsonindex 19c7fdd7..60593938 100644--- a/frontend/src/locales/cs.json+++ b/frontend/src/locales/cs.json@@ -2162,6 +2162,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2R",+ "rangeThisMonth": "Tento měsíc",+ "rangeLastMonth": "Minulý měsíc",+ "periodPrev": "Předchozí období",+ "periodNext": "Následující období","intervalDaily": "D","intervalWeekly": "T","intervalMonthly": "M",diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 262f8511..e1e95a2c 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -2031,6 +2031,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2J",+ "rangeThisMonth": "Dieser Monat",+ "rangeLastMonth": "Letzter Monat",+ "periodPrev": "Vorheriger Zeitraum",+ "periodNext": "Nächster Zeitraum","intervalDaily": "T","intervalWeekly": "W","intervalMonthly": "M",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex ec5a3ef2..03424ecc 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -2086,6 +2086,10 @@"rangeYtd": "YTD","range12m": "12Μ","range2y": "2Ε",+ "rangeThisMonth": "Αυτός ο μήνας",+ "rangeLastMonth": "Προηγούμενος μήνας",+ "periodPrev": "Προηγούμενη περίοδος",+ "periodNext": "Επόμενη περίοδος","intervalDaily": "Η","intervalWeekly": "Ε","intervalMonthly": "Μ",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex a39dfb82..f5b8072b 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -2030,6 +2030,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2Y",+ "rangeThisMonth": "This Month",+ "rangeLastMonth": "Last Month",+ "periodPrev": "Previous period",+ "periodNext": "Next period","intervalDaily": "D","intervalWeekly": "W","intervalMonthly": "M",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 2dd2ab4f..a72dc61c 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -2034,6 +2034,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2A",+ "rangeThisMonth": "Este mes",+ "rangeLastMonth": "Mes pasado",+ "periodPrev": "Período anterior",+ "periodNext": "Período siguiente","intervalDaily": "D","intervalWeekly": "S","intervalMonthly": "M",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex d9a22ecc..603196de 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -2034,6 +2034,10 @@"rangeYtd": "Depuis janv.","range12m": "12M","range2y": "2A",+ "rangeThisMonth": "Ce mois-ci",+ "rangeLastMonth": "Mois dernier",+ "periodPrev": "Période précédente",+ "periodNext": "Période suivante","intervalDaily": "J","intervalWeekly": "S","intervalMonthly": "M",diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex ee2cb131..edb4afbb 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -2030,6 +2030,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2Y",+ "rangeThisMonth": "इस महीने",+ "rangeLastMonth": "पिछला महीना",+ "periodPrev": "पिछली अवधि",+ "periodNext": "अगली अवधि","intervalDaily": "दि","intervalWeekly": "सा","intervalMonthly": "मा",diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.jsonindex 4ca7ebb3..45a6414c 100644--- a/frontend/src/locales/hu.json+++ b/frontend/src/locales/hu.json@@ -2030,6 +2030,10 @@"rangeYtd": "Idén","range12m": "12 hó","range2y": "2 év",+ "rangeThisMonth": "Ez a hónap",+ "rangeLastMonth": "Múlt hónap",+ "periodPrev": "Előző időszak",+ "periodNext": "Következő időszak","intervalDaily": "N","intervalWeekly": "Hé","intervalMonthly": "Hó",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex f6070972..adc86193 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -2034,6 +2034,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2A",+ "rangeThisMonth": "Questo mese",+ "rangeLastMonth": "Mese scorso",+ "periodPrev": "Periodo precedente",+ "periodNext": "Periodo successivo","intervalDaily": "G","intervalWeekly": "S","intervalMonthly": "M",diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex ccb70635..3b052564 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -2030,6 +2030,10 @@"rangeYtd": "年初から","range12m": "12ヶ月","range2y": "2年",+ "rangeThisMonth": "今月",+ "rangeLastMonth": "先月",+ "periodPrev": "前の期間",+ "periodNext": "次の期間","intervalDaily": "日","intervalWeekly": "週","intervalMonthly": "月",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex fe627491..b3f3595c 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -2032,6 +2032,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2J",+ "rangeThisMonth": "Deze maand",+ "rangeLastMonth": "Vorige maand",+ "periodPrev": "Vorige periode",+ "periodNext": "Volgende periode","intervalDaily": "D","intervalWeekly": "W","intervalMonthly": "M",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex b2fe2b79..69167d70 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -2119,6 +2119,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2L",+ "rangeThisMonth": "Ten miesiąc",+ "rangeLastMonth": "Miesiąc ubiegły",+ "periodPrev": "Poprzedni okres",+ "periodNext": "Następny okres","intervalDaily": "D","intervalWeekly": "T","intervalMonthly": "M",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 6bf8962f..c480cab6 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -2034,6 +2034,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2A",+ "rangeThisMonth": "Este mês",+ "rangeLastMonth": "Mês passado",+ "periodPrev": "Período anterior",+ "periodNext": "Próximo período","intervalDaily": "D","intervalWeekly": "S","intervalMonthly": "M",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 2ad143cc..2a4dba48 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -2034,6 +2034,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2A",+ "rangeThisMonth": "Este mês",+ "rangeLastMonth": "Mês passado",+ "periodPrev": "Período anterior",+ "periodNext": "Próximo período","intervalDaily": "D","intervalWeekly": "S","intervalMonthly": "M",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex cac7a041..57a189d0 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -2047,6 +2047,10 @@"rangeYtd": "СНГ","range12m": "12М","range2y": "2Г",+ "rangeThisMonth": "Этот месяц",+ "rangeLastMonth": "Прошлый месяц",+ "periodPrev": "Предыдущий период",+ "periodNext": "Следующий период","intervalDaily": "Д","intervalWeekly": "Н","intervalMonthly": "М",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 432368a5..8120a0d0 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -2146,6 +2146,10 @@"rangeYtd": "YTD","range12m": "12M","range2y": "2R",+ "rangeThisMonth": "Tento mesiac",+ "rangeLastMonth": "Minulý mesiac",+ "periodPrev": "Predchádzajúce obdobie",+ "periodNext": "Nasledujúce obdobie","intervalDaily": "D","intervalWeekly": "T","intervalMonthly": "M",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex f02bd506..c5e07c1b 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -2047,6 +2047,10 @@"rangeYtd": "ВПР","range12m": "12М","range2y": "2Р",+ "rangeThisMonth": "Цей місяць",+ "rangeLastMonth": "Минулий місяць",+ "periodPrev": "Попередній період",+ "periodNext": "Наступний період","intervalDaily": "Д","intervalWeekly": "Т","intervalMonthly": "М",diff --git a/frontend/src/pages/reports.test.tsx b/frontend/src/pages/reports.test.tsxindex a7d2ab94..b3118bdf 100644--- a/frontend/src/pages/reports.test.tsx+++ b/frontend/src/pages/reports.test.tsx@@ -334,3 +334,75 @@ describe('Reports page, cash-flow runway', () => {expect(screen.queryByTestId('cash-flow-runway')).not.toBeInTheDocument()})})++describe('Reports page: month presets and period navigation (issue #519)', () => {+ it('offers This Month and Last Month with exact month windows', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ expect(await screen.findByRole('heading', { name: 'Net Worth' })).toBeInTheDocument()++ // The default preset (1Y) keeps the API-anchored window: no explicit dates.+ expect(api.reports.netWorth.mock.calls.at(-1)?.slice(-2)).toEqual([undefined, undefined])++ await user.click(screen.getByRole('button', { name: 'This Month' }))+ expect(api.reports.netWorth.mock.calls.at(-1)?.slice(-2)).toEqual(['2026-09-01', '2026-09-12'])+ expect(screen.getByTestId('reports-period-label')).toHaveTextContent('September 2026')++ await user.click(screen.getByRole('button', { name: 'Last Month' }))+ expect(api.reports.netWorth.mock.calls.at(-1)?.slice(-2)).toEqual(['2026-08-01', '2026-08-31'])+ expect(screen.getByTestId('reports-period-label')).toHaveTextContent('August 2026')+ })++ it('steps the active period back and forward with the arrows', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await screen.findByRole('heading', { name: 'Net Worth' })+ await user.click(screen.getByRole('button', { name: 'This Month' }))++ const prev = screen.getByRole('button', { name: 'Previous period' })+ const next = screen.getByRole('button', { name: 'Next period' })+ expect(next).toBeDisabled()++ await user.click(prev)+ expect(screen.getByTestId('reports-period-label')).toHaveTextContent('August 2026')+ expect(api.reports.netWorth.mock.calls.at(-1)?.slice(-2)).toEqual(['2026-08-01', '2026-08-31'])+ expect(next).not.toBeDisabled()++ await user.click(next)+ expect(screen.getByTestId('reports-period-label')).toHaveTextContent('September 2026')+ expect(api.reports.netWorth.mock.calls.at(-1)?.slice(-2)).toEqual(['2026-09-01', '2026-09-12'])+ expect(next).toBeDisabled()+ })++ it('steps a macro preset back by a whole window and labels the covered span', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await screen.findByRole('heading', { name: 'Net Worth' })+ await user.click(screen.getByRole('button', { name: '6M' }))++ expect(screen.getByTestId('reports-period-label')).toHaveTextContent('6M')+ await user.click(screen.getByRole('button', { name: 'Previous period' }))++ expect(api.reports.netWorth.mock.calls.at(-1)?.slice(-2)).toEqual(['2025-08-01', '2026-02-28'])+ expect(screen.getByTestId('reports-period-label')).toHaveTextContent('Aug 2025 - Feb 2026')+ })++ it('does not carry a stepped window into the Cash Flow forecast', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await screen.findByRole('heading', { name: 'Net Worth' })+ await user.click(screen.getByRole('button', { name: '6M' }))+ await user.click(screen.getByRole('button', { name: 'Previous period' }))++ await user.click(screen.getByRole('button', { name: t('reports.cashFlow') }))+ await waitFor(() => expect(api.reports.cashFlow).toHaveBeenCalled())++ expect(api.reports.cashFlow.mock.calls.at(-1)?.[0]).toBe(6)+ })++ it('hides period navigation on the forward-only Cash Flow tab', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await screen.findByRole('heading', { name: 'Net Worth' })+ expect(screen.getByRole('button', { name: 'Previous period' })).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: t('reports.cashFlow') }))+ expect(screen.queryByRole('button', { name: 'Previous period' })).not.toBeInTheDocument()+ expect(screen.queryByTestId('reports-period-nav')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex 519fe627..121c5235 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from 'react'+import { useContext, useEffect, useState } from 'react'import { loadReportsRange, saveReportsRange, type ReportsRange } from '@/lib/remembered-range'import { useTranslation } from 'react-i18next'import { useDisplayLocale } from '@/hooks/use-display-locale'@@ -19,7 +19,7 @@ import {ReferenceLine,ResponsiveContainer,} from 'recharts'-import { AlertCircle, HelpCircle, X } from 'lucide-react'+import { AlertCircle, ChevronLeft, ChevronRight, HelpCircle, X } from 'lucide-react'import { reports } from '@/lib/api'import { extractApiError } from '@/lib/api-errors'import { Skeleton } from '@/components/ui/skeleton'@@ -33,7 +33,10 @@ import { useCollectionFilter } from '@/contexts/collection-filter-context'import type { ReportResponse, CategoryTrendItem } from '@/types'import { formatCurrency } from '@/lib/format'import { localDateString, todayInTimezone } from '@/lib/date-utils'+import { monthLabel } from '@/lib/month-utils'+import { periodWindow, windowMonths, type PeriodPreset } from '@/lib/report-period'import { useEffectiveTimezone } from '@/hooks/use-timezone'+import { WorkspaceContext } from '@/contexts/workspace-context'import {formatNetWorthAxisTick,getNetWorthDomain,@@ -69,13 +72,22 @@ function formatCompact(value: number, currency = 'USD', locale = 'en-US') {}).format(value)}+/** "Apr 2026" from a YYYY-MM-DD date, in the display locale. */+function formatShortMonth(isoDate: string, locale: string) {+ const [y, m] = isoDate.split('-').map(Number)+ return new Date(y, m - 1, 1).toLocaleDateString(locale, { month: 'short', year: 'numeric' })+}+// `days` (when set) asks for an exact rolling window ending today rather than-// the month-aligned window `months` produces.-type RangeOption = { key: string; months: number; period?: 'ytd'; days?: number }+// the month-aligned window `months` produces. `monthAnchor` marks the month+// presets (This Month / Last Month), which always send explicit dates.+type RangeOption = { key: string; months: number; period?: 'ytd'; days?: number; monthAnchor?: number }const HISTORICAL_RANGE_OPTIONS: readonly RangeOption[] = [+ { key: 'this_month', months: 1, monthAnchor: 0 },+ { key: 'last_month', months: 1, monthAnchor: -1 },{ key: '6m', months: 6 },{ key: 'ytd', months: 12, period: 'ytd' },{ key: '1y', months: 12 },@@ -91,6 +103,8 @@ const FORWARD_RANGE_OPTIONS: readonly RangeOption[] = [// The Money Map answers "where did my money go lately", so it leans on recent// windows (down to 30 days) and drops the 2Y trend view the other tabs keep.const MONEY_MAP_RANGE_OPTIONS: readonly RangeOption[] = [+ { key: 'this_month', months: 1, monthAnchor: 0 },+ { key: 'last_month', months: 1, monthAnchor: -1 },{ key: '30d', months: 1, days: 30 },{ key: '3m', months: 3 },{ key: '6m', months: 6 },@@ -126,6 +140,8 @@ const RANGE_LABELS: Record<string, string> = {ytd: 'rangeYtd','12m': 'range12m','2y': 'range2y',+ this_month: 'rangeThisMonth',+ last_month: 'rangeLastMonth',custom: 'customRange',}@@ -199,6 +215,12 @@ function storedReportsRange(tab: ReportTab): ReportsRange | null {export default function ReportsPage() {const timeZone = useEffectiveTimezone()+ // Read through the context object so the page still renders outside a+ // WorkspaceProvider. Mirrors the backend's financial year start (April for+ // India, January elsewhere), so stepping back from YTD lands on whole+ // financial years.+ const workspaceCtx = useContext(WorkspaceContext)+ const fyStartMonth = (workspaceCtx?.current?.tax_jurisdiction ?? '').toUpperCase() === 'IN' ? 4 : 1const { t } = useTranslation()const { mask, privacyMode, MASK } = usePrivacyMode()const { user } = useAuth()@@ -222,12 +244,15 @@ export default function ReportsPage() {// selection while the user compares views.const [customFrom, setCustomFrom] = useState(initialRange.from)const [customTo, setCustomTo] = useState(initialRange.to)+ // Period navigation (issue #519): how many periods of the active preset the+ // window has been stepped back. 0 means the window still ends today.+ const [periodOffset, setPeriodOffset] = useState(initialRange.periodOffset ?? 0)const [activeTab, setActiveTab] = useState(REPORT_TABS[0].key)// Each tab keeps its own range: Cash Flow clamping to its forward presets// must not overwrite what Net Worth was showing.useEffect(() => {- saveReportsRange(activeTab, { rangeKey, from: customFrom, to: customTo, interval })- }, [activeTab, rangeKey, customFrom, customTo, interval])+ saveReportsRange(activeTab, { rangeKey, from: customFrom, to: customTo, interval, periodOffset })+ }, [activeTab, rangeKey, customFrom, customTo, interval, periodOffset])const [compositionView, setCompositionView] = useState<string>('netWorth')const [sparklineView, setSparklineView] = useState<'byExpenses' | 'byIncome'>('byExpenses')const [sparklinePage, setSparklinePage] = useState(0)@@ -258,6 +283,24 @@ export default function ReportsPage() {const isCustomRange = supportsCustomRange && rangeKey === CUSTOM_RANGE_KEYconst hasCustomRange = isCustomRange && !!customFrom && !!customToconst selectedRange = rangeOptions.find((r) => r.key === rangeKey) ?? rangeOptions[0]+ // Period navigation (issue #519): a nonzero offset re-sends the same window+ // stepped back by its own length, as explicit start/end dates. At offset 0+ // the presets keep the API's `months` / `period` / `days` anchoring, so+ // existing behavior and cache keys are untouched.+ const periodPreset: PeriodPreset = isCustomRange+ ? { kind: 'custom' }+ : selectedRange.monthAnchor !== undefined+ ? { kind: 'month', anchorDelta: selectedRange.monthAnchor }+ : selectedRange.period === 'ytd'+ ? { kind: 'ytd', fyStartMonth }+ : selectedRange.days+ ? { kind: 'days', days: selectedRange.days }+ : { kind: 'rolling', months: selectedRange.months }+ // Cash Flow is a forward projection with no period navigation: it never+ // takes a stepped window, even if an offset was carried over from another tab.+ const navWindow = isCashFlow+ ? null+ : periodWindow(periodPreset, todayInTimezone(timeZone), periodOffset, { from: customFrom, to: customTo })// In custom mode, translate the picked span into an equivalent `months`// value so downstream logic (interval bucketing, forecast fan-out) keeps// working. Backend uses start_date/end_date directly when they're set.@@ -274,11 +317,23 @@ export default function ReportsPage() {),): selectedRange.months- const months = isCustomRange ? customMonths : selectedRange.months- const period = isCustomRange ? undefined : selectedRange.period- const days = isCustomRange ? undefined : selectedRange.days- const apiStart = hasCustomRange ? customFrom : undefined- const apiEnd = hasCustomRange ? customTo : undefined+ const months = navWindow ? windowMonths(navWindow) : isCustomRange ? customMonths : selectedRange.months+ const period = navWindow || isCustomRange ? undefined : selectedRange.period+ const days = navWindow || isCustomRange ? undefined : selectedRange.days+ const apiStart = navWindow ? navWindow.from : hasCustomRange ? customFrom : undefined+ const apiEnd = navWindow ? navWindow.to : hasCustomRange ? customTo : undefined+ // Label for the period being viewed: the month name for the month presets,+ // the covered span when the window has been stepped back or is custom, and+ // the preset's own name while the window still ends today.+ const activeWindow = navWindow ?? (hasCustomRange ? { from: customFrom, to: customTo } : null)+ const periodLabel =+ isCustomRange && !activeWindow+ ? t('reports.customRange')+ : activeWindow && selectedRange.monthAnchor !== undefined+ ? monthLabel(activeWindow.from.slice(0, 7), locale)+ : activeWindow+ ? `${formatShortMonth(activeWindow.from, locale)} - ${formatShortMonth(activeWindow.to, locale)}`+ : t(`reports.${RANGE_LABELS[selectedRange.key]}`)const handleSelectTab = (key: string) => {const nextTab = REPORT_TABS.find((tab) => tab.key === key) ?? REPORT_TABS[0]@@ -290,6 +345,7 @@ export default function ReportsPage() {if (remembered) {setRangeKey(remembered.rangeKey)setInterval(remembered.interval)+ setPeriodOffset(nextTab.key === 'cash_flow' ? 0 : (remembered.periodOffset ?? 0))if (remembered.rangeKey === CUSTOM_RANGE_KEY) {setCustomFrom(remembered.from)setCustomTo(remembered.to)@@ -302,6 +358,9 @@ export default function ReportsPage() {nextTab.rangeOptions.some((r) => r.key === rangeKey)if (!stillValid) {setRangeKey(nextTab.fallbackRangeKey)+ setPeriodOffset(0)+ } else if (nextTab.key === 'cash_flow') {+ setPeriodOffset(0)}if (!nextTab.intervalOptions.some((i) => i.value === interval)) {setInterval(nextTab.fallbackInterval)@@ -603,7 +662,7 @@ export default function ReportsPage() {section={t('reports.section')}title={t(currentTab.labelKey)}action={- <div className="flex items-center gap-2">+ <div className="flex flex-wrap items-center gap-2">{isCashFlow && (<divclassName={`flex items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-semibold transition-colors ${@@ -644,7 +703,7 @@ export default function ReportsPage() {{rangeOptions.map((opt) => (<buttonkey={opt.key}- onClick={() => { setRangeKey(opt.key); setSelectedDate(null) }}+ onClick={() => { setRangeKey(opt.key); setPeriodOffset(0); setSelectedDate(null) }}className={`px-3 py-1.5 text-xs font-semibold transition-colors ${rangeKey === opt.key? 'bg-primary text-primary-foreground'@@ -667,6 +726,7 @@ export default function ReportsPage() {onChange={(f, to) => {setCustomFrom(f)setCustomTo(to)+ setPeriodOffset(0)setRangeKey(f && to ? CUSTOM_RANGE_KEY : currentTab.fallbackRangeKey)setSelectedDate(null)}}@@ -675,6 +735,39 @@ export default function ReportsPage() {/>)}</div>+ {/* Period navigation (issue #519): step the active window back and+ forward through history, labeled with the period it shows. The+ Cash Flow tab is a forward-only forecast, so it has no past to+ step through. */}+ {!isCashFlow && (+ <div+ className="flex items-center rounded-lg border border-border bg-card overflow-hidden"+ data-testid="reports-period-nav"+ >+ <button+ type="button"+ aria-label={t('reports.periodPrev')}+ title={t('reports.periodPrev')}+ onClick={() => { setPeriodOffset((o) => o - 1); setSelectedDate(null) }}+ className="px-2 py-1.5 text-muted-foreground transition-colors hover:text-foreground hover:bg-muted/50"+ >+ <ChevronLeft className="h-4 w-4" />+ </button>+ <span className="min-w-24 px-1 text-center text-xs font-semibold tabular-nums" data-testid="reports-period-label">+ {periodLabel}+ </span>+ <button+ type="button"+ aria-label={t('reports.periodNext')}+ title={t('reports.periodNext')}+ disabled={periodOffset === 0}+ onClick={() => { setPeriodOffset((o) => o + 1); setSelectedDate(null) }}+ className="px-2 py-1.5 text-muted-foreground transition-colors hover:text-foreground hover:bg-muted/50 disabled:opacity-40 disabled:hover:bg-transparent"+ >+ <ChevronRight className="h-4 w-4" />+ </button>+ </div>+ )}<div className={`flex items-center rounded-lg border border-border bg-card overflow-hidden ${isMoneyMap ? 'hidden' : ''}`}>{intervalOptions.map((opt) => (<button