Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat(frontend): remember the date range on Transactions and Reports (#1130)

Rogerio Camorimf7886f5bcafc
diff --git a/frontend/src/lib/remembered-range.test.ts b/frontend/src/lib/remembered-range.test.ts
new file mode 100644
index 00000000..477a9044
--- /dev/null
+++ b/frontend/src/lib/remembered-range.test.ts
@@ -0,0 +1,75 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { loadRange, loadReportsRange, saveRange, saveReportsRange } from './remembered-range'
+
+// lib suites run under the node environment; give them an in-memory storage.
+function memoryStorage(): Storage {
+ const data = new Map<string, string>()
+ return {
+ get length() { return data.size },
+ clear: () => data.clear(),
+ getItem: (k) => data.get(k) ?? null,
+ key: (i) => [...data.keys()][i] ?? null,
+ removeItem: (k) => { data.delete(k) },
+ setItem: (k, v) => { data.set(k, String(v)) },
+ }
+}
+
+describe('remembered date range', () => {
+ beforeEach(() => {
+ vi.stubGlobal('localStorage', memoryStorage())
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-03-15T12:00:00'))
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.unstubAllGlobals()
+ })
+
+ it('returns null when nothing was stored', () => {
+ expect(loadRange('transactions')).toBeNull()
+ expect(loadReportsRange('net_worth')).toBeNull()
+ })
+
+ it('round-trips a custom range, including an open-ended one', () => {
+ saveRange('transactions', '2025-01-01', '2025-06-30')
+ expect(loadRange('transactions')).toEqual({ from: '2025-01-01', to: '2025-06-30' })
+ saveRange('transactions', '', '')
+ expect(loadRange('transactions')).toEqual({ from: '', to: '' })
+ })
+
+ it('remembers the current month as a moving target', () => {
+ saveRange('transactions', '2026-03-01', '2026-03-31')
+ vi.setSystemTime(new Date('2026-04-02T12:00:00'))
+ expect(loadRange('transactions')).toEqual({ from: '2026-04-01', to: '2026-04-30' })
+ })
+
+ it('keeps a past month as that month', () => {
+ saveRange('transactions', '2026-01-01', '2026-01-31')
+ vi.setSystemTime(new Date('2026-04-02T12:00:00'))
+ expect(loadRange('transactions')).toEqual({ from: '2026-01-01', to: '2026-01-31' })
+ })
+
+ it('ignores unreadable or tampered storage', () => {
+ localStorage.setItem('securo.dateRange.transactions', '{not json')
+ expect(loadRange('transactions')).toBeNull()
+ localStorage.setItem('securo.dateRange.transactions', JSON.stringify({ kind: 'range', from: 'yesterday', to: '' }))
+ expect(loadRange('transactions')).toBeNull()
+ })
+
+ it('rejects impossible calendar dates', () => {
+ localStorage.setItem('securo.dateRange.transactions', JSON.stringify({ kind: 'range', from: '2026-02-30', to: '' }))
+ expect(loadRange('transactions')).toBeNull()
+ saveRange('transactions', '2028-02-29', '2028-03-01')
+ expect(loadRange('transactions')).toEqual({ from: '2028-02-29', to: '2028-03-01' })
+ })
+
+ it('keeps a separate reports range per tab', () => {
+ const netWorth = { rangeKey: '2y', from: '', to: '', interval: 'monthly' }
+ const cashFlow = { rangeKey: '6m', from: '', to: '', interval: 'daily' }
+ 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()
+ })
+})
diff --git a/frontend/src/lib/remembered-range.ts b/frontend/src/lib/remembered-range.ts
new file mode 100644
index 00000000..0b13b71c
--- /dev/null
+++ b/frontend/src/lib/remembered-range.ts
@@ -0,0 +1,82 @@
+/**
+ * Per-page memory of the last date range picked (issue #1053), so leaving
+ * Transactions or Reports and coming back shows the range the user was on
+ * instead of the page's default.
+ *
+ * Only a convenience: a range in the URL (bookmark, drill-down link) always
+ * wins, and storage that is blocked or holds something unreadable falls back
+ * to the default. The current month is remembered as "the current month",
+ * not as its dates, so a range saved in March doesn't pin the page to March
+ * once April starts.
+ */
+import { currentMonth, monthFromRange, monthRange } from '@/lib/month-utils'
+
+const PREFIX = 'securo.dateRange.'
+
+export type RememberedPage = 'transactions' | 'reports'
+
+function read(page: RememberedPage): unknown {
+ try {
+ const raw = localStorage.getItem(PREFIX + page)
+ return raw ? JSON.parse(raw) : null
+ } catch {
+ return null
+ }
+}
+
+function write(page: RememberedPage, value: unknown): void {
+ try {
+ localStorage.setItem(PREFIX + page, JSON.stringify(value))
+ } catch {
+ // Private mode or quota: remembering is best-effort.
+ }
+}
+
+/** '' (open end) or a real calendar date as YYYY-MM-DD — not "2026-02-30". */
+function isDate(v: unknown): v is string {
+ if (v === '') return true
+ if (typeof v !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(v)) return false
+ const [y, m, d] = v.split('-').map(Number)
+ const date = new Date(Date.UTC(y, m - 1, d))
+ return date.getUTCFullYear() === y && date.getUTCMonth() === m - 1 && date.getUTCDate() === d
+}
+
+/** A from/to range ('' on either side means open-ended). */
+export function loadRange(page: RememberedPage): { from: string; to: string } | null {
+ const v = read(page) as { kind?: string; from?: unknown; to?: unknown } | null
+ if (v?.kind === 'current-month') return monthRange(currentMonth())
+ if (v?.kind === 'range' && isDate(v.from) && isDate(v.to)) return { from: v.from, to: v.to }
+ return null
+}
+
+export function saveRange(page: RememberedPage, from: string, to: string): void {
+ write(page, monthFromRange(from, to) === currentMonth() ? { kind: 'current-month' } : { kind: 'range', from, to })
+}
+
+/** Reports, per tab: a preset key (relative, e.g. "1y") or custom dates, plus the interval. */
+export interface ReportsRange {
+ rangeKey: string
+ from: string
+ to: string
+ interval: string
+}
+
+/** Stored per-tab entries; anything that isn't an object (an older flat shape) is dropped. */
+function readReportsTabs(): Record<string, unknown> {
+ const v = read('reports')
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return {}
+ return Object.fromEntries(
+ Object.entries(v).filter(([, entry]) => entry !== null && typeof entry === 'object'),
+ )
+}
+
+export function loadReportsRange(tab: string): ReportsRange | null {
+ const v = readReportsTabs()[tab] as Partial<Record<keyof ReportsRange, unknown>> | undefined
+ if (!v || typeof v.rangeKey !== 'string' || typeof v.interval !== 'string') return null
+ if (!isDate(v.from) || !isDate(v.to)) return null
+ return { rangeKey: v.rangeKey, from: v.from, to: v.to, interval: v.interval }
+}
+
+export function saveReportsRange(tab: string, range: ReportsRange): void {
+ write('reports', { ...readReportsTabs(), [tab]: range })
+}
diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsx
index 61fe2b18..8b050986 100644
--- a/frontend/src/pages/reports.tsx
+++ b/frontend/src/pages/reports.tsx
@@ -1,4 +1,5 @@
-import { useState } from 'react'
+import { 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'
import { useQuery } from '@tanstack/react-query'
@@ -176,6 +177,21 @@ const REPORT_TABS: ReportTab[] = [
},
]
+/** The range last used on `tab`, if it is still one the tab offers. */
+function storedReportsRange(tab: ReportTab): ReportsRange | null {
+ const stored = loadReportsRange(tab.key)
+ if (!stored) return null
+ const isCustom = stored.rangeKey === CUSTOM_RANGE_KEY
+ const rangeOk = isCustom
+ ? tab.supportsCustomRange && !!stored.from && !!stored.to
+ : tab.rangeOptions.some((r) => r.key === stored.rangeKey)
+ if (!rangeOk) return null
+ const interval = tab.intervalOptions.some((i) => i.value === stored.interval)
+ ? stored.interval
+ : tab.fallbackInterval
+ return { ...stored, interval, ...(isCustom ? {} : { from: '', to: '' }) }
+}
+
export default function ReportsPage() {
const timeZone = useEffectiveTimezone()
const { t } = useTranslation()
@@ -185,15 +201,28 @@ export default function ReportsPage() {
const locale = useDisplayLocale()
const customDefaults = defaultCustomRange()
- const [rangeKey, setRangeKey] = useState('1y')
- const [interval, setInterval] = useState('monthly')
+ // The page opens on the first tab with the range last used there (issue
+ // #1053), or that tab's defaults if what was stored doesn't apply to it.
+ const [initialRange] = useState<ReportsRange>(() => storedReportsRange(REPORT_TABS[0]) ?? {
+ rangeKey: REPORT_TABS[0].fallbackRangeKey,
+ from: '',
+ to: '',
+ interval: REPORT_TABS[0].fallbackInterval,
+ })
+ const [rangeKey, setRangeKey] = useState(initialRange.rangeKey)
+ const [interval, setInterval] = useState(initialRange.interval)
// Custom range endpoints (YYYY-MM-DD) — populated when the user opens the
// Custom preset and confirms a date range. Preserved across tab switches
// that still support custom ranges so the picker doesn't forget its
// selection while the user compares views.
- const [customFrom, setCustomFrom] = useState('')
- const [customTo, setCustomTo] = useState('')
- const [activeTab, setActiveTab] = useState('net_worth')
+ const [customFrom, setCustomFrom] = useState(initialRange.from)
+ const [customTo, setCustomTo] = useState(initialRange.to)
+ 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])
const [compositionView, setCompositionView] = useState<string>('netWorth')
const [sparklineView, setSparklineView] = useState<'byExpenses' | 'byIncome'>('byExpenses')
const [sparklinePage, setSparklinePage] = useState(0)
@@ -252,6 +281,16 @@ export default function ReportsPage() {
setCompositionView(key === 'net_worth' ? 'netWorth' : 'net')
setSparklinePage(0)
setSelectedDate(null)
+ const remembered = storedReportsRange(nextTab)
+ if (remembered) {
+ setRangeKey(remembered.rangeKey)
+ setInterval(remembered.interval)
+ if (remembered.rangeKey === CUSTOM_RANGE_KEY) {
+ setCustomFrom(remembered.from)
+ setCustomTo(remembered.to)
+ }
+ return
+ }
// Clamp the range/interval preset to what the new tab supports.
const stillValid =
(rangeKey === CUSTOM_RANGE_KEY && nextTab.supportsCustomRange) ||
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index f839ad50..662f2055 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -3,6 +3,7 @@ import { useRegisterPageChatContext } from '@/lib/page-chat-context'
import { getAccountName } from '@/lib/account-utils'
import { AccountIcon } from '@/components/account-icon'
import { currentMonth, monthRange, monthFromRange } from '@/lib/month-utils'
+import { loadRange, saveRange } from '@/lib/remembered-range'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
@@ -116,19 +117,21 @@ export default function TransactionsPage() {
return initial ? [initial] : []
})
const [filterUncategorized, setFilterUncategorized] = useState<boolean>(false)
- // Seed the date range from the URL, or default to the current month on first
- // open (no ?from/?to). Done in the initializer so it survives effect re-runs
- // (e.g. React StrictMode's double-invoke in development).
- const [filterFrom, setFilterFrom] = useState<string>(() => {
+ // Seed the date range from the URL, else the range last used on this page
+ // (issue #1053), else the current month. Done in the initializer so it
+ // survives effect re-runs (e.g. React StrictMode's double-invoke in
+ // development).
+ const [initialRange] = useState(() => {
const f = searchParams.get('from')
const t = searchParams.get('to')
- return f || t ? (f ?? '') : monthRange(currentMonth()).from
- })
- const [filterTo, setFilterTo] = useState<string>(() => {
- const f = searchParams.get('from')
- const t = searchParams.get('to')
- return f || t ? (t ?? '') : monthRange(currentMonth()).to
+ if (f || t) return { from: f ?? '', to: t ?? '' }
+ return loadRange('transactions') ?? monthRange(currentMonth())
})
+ const [filterFrom, setFilterFrom] = useState<string>(initialRange.from)
+ const [filterTo, setFilterTo] = useState<string>(initialRange.to)
+ useEffect(() => {
+ saveRange('transactions', filterFrom, filterTo)
+ }, [filterFrom, filterTo])
// Month reflected by the stepper: the active range when it spans exactly one
// full month, otherwise the current month (custom ranges still navigable).
const steppedMonth = monthFromRange(filterFrom, filterTo) ?? currentMonth()