Skip to content

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

feat(reports): add a year picker for the reports date range (#1273)

Tássio Noronhac10f011845d7
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.py
index 61608c10..d7a26651 100644
--- a/backend/app/api/reports.py
+++ b/backend/app/api/reports.py
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.app_clock import app_today
from app.core.database import get_async_session
from app.core.workspace_context import WorkspaceContext, current_workspace
-from app.schemas.report import ReportResponse
+from app.schemas.report import ReportDataRange, ReportResponse
from app.services import report_service
router = APIRouter(prefix="/api/reports", tags=["reports"])
@@ -89,6 +89,26 @@ def _resolve_custom_range(
return start_date, end_date
[email protected]("/data-range", response_model=ReportDataRange)
+async def get_data_range(
+ ctx: WorkspaceContext = Depends(current_workspace),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """The span of transaction data this workspace actually has.
+
+ The Reports page builds its year picker from these bounds (issue #765).
+ Opening balances are excluded: their dates are synthetic. Both bounds
+ are null when the workspace has no reportable transactions.
+ """
+ min_date, max_date = await report_service.get_report_data_range(
+ session, ctx.workspace.id
+ )
+ return ReportDataRange(
+ min_date=min_date.isoformat() if min_date else None,
+ max_date=max_date.isoformat() if max_date else None,
+ )
+
+
@router.get("/net-worth", response_model=ReportResponse)
async def get_net_worth(
months: int = Query(12, ge=1, le=24),
diff --git a/backend/app/schemas/report.py b/backend/app/schemas/report.py
index 534ba213..22adfd06 100644
--- a/backend/app/schemas/report.py
+++ b/backend/app/schemas/report.py
@@ -8,6 +8,13 @@ class ReportBreakdown(BaseModel):
color: str
+class ReportDataRange(BaseModel):
+ """Oldest and newest transaction dates the workspace has (issue #765)."""
+
+ min_date: str | None = None
+ max_date: str | None = None
+
+
class ReportSummary(BaseModel):
primary_value: float
change_amount: float
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.py
index 536c171d..90eafc7c 100644
--- a/backend/app/services/report_service.py
+++ b/backend/app/services/report_service.py
@@ -4,7 +4,7 @@ from datetime import date, timedelta
from decimal import Decimal
from typing import Optional
-from sqlalchemy import String, select, desc, func, case
+from sqlalchemy import String, select, desc, func, case, or_
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.app_clock import app_today
@@ -318,6 +318,37 @@ def _date_points(
return points
+async def get_report_data_range(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+) -> tuple[date | None, date | None]:
+ """The span of transaction data the workspace actually has (issue #765).
+
+ Feeds the Reports page year picker: the UI lists one entry per year
+ between the lower bound and the current year. Buckets by the same
+ reporting date the reports aggregate on, so a year only shows up when
+ the reports can actually display it. Opening balances are excluded,
+ their dates are synthetic. Ignored transactions and transactions in
+ ignored categories are excluded too, as every report tab drops them.
+ """
+ accounting_mode = await get_credit_card_accounting_mode(session)
+ result = await session.execute(
+ select(
+ func.min(reporting_date_col(accounting_mode)),
+ func.max(reporting_date_col(accounting_mode)),
+ )
+ .outerjoin(Category, Transaction.category_id == Category.id)
+ .where(
+ Transaction.workspace_id == workspace_id,
+ Transaction.source != "opening_balance",
+ Transaction.is_ignored.is_(False),
+ or_(Transaction.category_id.is_(None), Category.is_ignored.is_(False)),
+ )
+ )
+ min_date, max_date = result.one()
+ return min_date, max_date
+
+
async def get_net_worth_report(
session: AsyncSession,
workspace_id: uuid.UUID,
diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.json
index 197a2edb..4bc335ac 100644
--- a/backend/tests/api_contract/baseline.json
+++ b/backend/tests/api_contract/baseline.json
@@ -147,6 +147,7 @@
"GET /api/reconciliation/suggestions": 401,
"GET /api/recurring-transactions": 401,
"GET /api/reports/cash-flow": 401,
+ "GET /api/reports/data-range": 401,
"GET /api/reports/income-expenses": 401,
"GET /api/reports/net-worth": 401,
"GET /api/rules": 401,
@@ -534,6 +535,7 @@
"GET /api/reconciliation/suggestions": 200,
"GET /api/recurring-transactions": 200,
"GET /api/reports/cash-flow": 200,
+ "GET /api/reports/data-range": 200,
"GET /api/reports/net-worth": 200,
"GET /api/rules": 200,
"GET /api/rules/export": 200,
diff --git a/backend/tests/test_reports_postgres.py b/backend/tests/test_reports_postgres.py
index 17aa385b..1ffafdc1 100644
--- a/backend/tests/test_reports_postgres.py
+++ b/backend/tests/test_reports_postgres.py
@@ -239,3 +239,132 @@ async def test_monthly_report_follows_mode(session, test_user, test_account, mon
assert {month: buckets[month] for month in expected} == expected
assert sum(buckets.values()) == 150
assert next(b.value for b in report.summary.breakdowns if b.key == "expenses") == 150
+
+
+async def test_reports_data_range_returns_min_max(
+ client, auth_headers, session, test_user, test_account, test_transactions
+):
+ """GET /reports/data-range reports the oldest and newest transaction dates."""
+ expected_max = max(t.date for t in test_transactions)
+ old = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id, account_id=test_account.id,
+ description="STORE PURCHASE", amount=Decimal("10.00"),
+ date=date(2024, 6, 15), type="debit", source="manual",
+ )
+ session.add(old)
+ await session.commit()
+ response = await client.get("/api/reports/data-range", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert data["min_date"] == "2024-06-15"
+ assert data["max_date"] == expected_max.strftime("%Y-%m-%d")
+
+
+async def test_reports_data_range_excludes_opening_balance(
+ client, auth_headers, session, test_user, test_account, test_transactions
+):
+ """Opening balances are synthetic; their date must not stretch the range."""
+ opening = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id, account_id=test_account.id,
+ description="OPENING BALANCE ENTRY", amount=Decimal("100.00"),
+ date=date(2010, 1, 1), type="credit", source="opening_balance",
+ )
+ session.add(opening)
+ await session.commit()
+ response = await client.get("/api/reports/data-range", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert data["min_date"] == min(t.date for t in test_transactions).strftime("%Y-%m-%d")
+ assert data["max_date"] == max(t.date for t in test_transactions).strftime("%Y-%m-%d")
+
+
+async def test_reports_data_range_empty_workspace(client, auth_headers, test_user, test_workspace):
+ """No transactions at all: both bounds are null."""
+ response = await client.get("/api/reports/data-range", headers=auth_headers)
+ assert response.status_code == 200
+ assert response.json() == {"min_date": None, "max_date": None}
+
+
+async def test_reports_data_range_scoped_to_workspace(
+ client, auth_headers, session, test_user, test_account, test_transactions
+):
+ """A transaction in another workspace must not stretch this workspace's range."""
+ from app.models.account import Account
+
+ ws_resp = await client.post(
+ "/api/workspaces", json={"name": "Second workspace"}, headers=auth_headers
+ )
+ assert ws_resp.status_code in (200, 201), ws_resp.text
+ other_ws_id = ws_resp.json()["id"]
+
+ other_account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=other_ws_id,
+ name="Other checking",
+ type="checking",
+ balance=Decimal("0.00"),
+ currency="BRL",
+ )
+ session.add(other_account)
+ await session.commit()
+ await session.refresh(other_account)
+
+ other_txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id, account_id=other_account.id,
+ description="OTHER STORE PURCHASE", amount=Decimal("5.00"),
+ date=date(2015, 3, 1), type="debit", source="manual",
+ )
+ session.add(other_txn)
+ await session.commit()
+ await session.refresh(other_txn)
+ assert other_txn.workspace_id == uuid.UUID(other_ws_id)
+
+ response = await client.get("/api/reports/data-range", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert data["min_date"] == min(t.date for t in test_transactions).strftime("%Y-%m-%d")
+ assert data["max_date"] == max(t.date for t in test_transactions).strftime("%Y-%m-%d")
+
+
+async def test_reports_data_range_excludes_ignored_rows(
+ client, auth_headers, session, test_user, test_account, test_transactions
+):
+ """Ignored rows, or rows in an ignored category, show in no report tab,
+ so they must not stretch the range either."""
+ from app.models.category import Category
+
+ ignored_category = Category(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="Ignored bucket",
+ icon="x",
+ color="#000000",
+ is_ignored=True,
+ )
+ session.add(ignored_category)
+ await session.commit()
+ session.add_all([
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id, account_id=test_account.id,
+ description="IGNORED PURCHASE", amount=Decimal("10.00"),
+ date=date(2012, 5, 1), type="debit", source="manual",
+ is_ignored=True,
+ ),
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id, account_id=test_account.id,
+ description="IGNORED CATEGORY PURCHASE", amount=Decimal("10.00"),
+ date=date(2013, 5, 1), type="debit", source="manual",
+ category_id=ignored_category.id,
+ ),
+ ])
+ await session.commit()
+ response = await client.get("/api/reports/data-range", headers=auth_headers)
+ assert response.status_code == 200
+ data = response.json()
+ assert data["min_date"] == min(t.date for t in test_transactions).strftime("%Y-%m-%d")
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index c55f9f49..6396df77 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1571,6 +1571,13 @@ export const reports = {
const { data } = await api.get('/reports/cash-flow', { params: { months, interval, baseline, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })
return data
},
+ // Oldest and newest transaction dates in the workspace (opening
+ // balances excluded). The reports page builds its year picker from
+ // these bounds (issue #765).
+ dataRange: async (): Promise<{ min_date: string | null; max_date: string | null }> => {
+ const { data } = await api.get('/reports/data-range')
+ return data
+ },
}
// Currencies
diff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.json
index 01559217..b2fd50f6 100644
--- a/frontend/src/locales/cs.json
+++ b/frontend/src/locales/cs.json
@@ -2166,6 +2166,8 @@
"rangeLastMonth": "Minulý měsíc",
"periodPrev": "Předchozí období",
"periodNext": "Následující období",
+ "year": "Rok",
+ "yearPickerHelp": "Zobrazit jeden kalendářní rok svých dat",
"intervalDaily": "D",
"intervalWeekly": "T",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 9b145410..8ca360ba 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -2035,6 +2035,8 @@
"rangeLastMonth": "Letzter Monat",
"periodPrev": "Vorheriger Zeitraum",
"periodNext": "Nächster Zeitraum",
+ "year": "Jahr",
+ "yearPickerHelp": "Ein Kalenderjahr deiner Daten anzeigen",
"intervalDaily": "T",
"intervalWeekly": "W",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.json
index 59204fd0..8dbcf3ef 100644
--- a/frontend/src/locales/el.json
+++ b/frontend/src/locales/el.json
@@ -2090,6 +2090,8 @@
"rangeLastMonth": "Προηγούμενος μήνας",
"periodPrev": "Προηγούμενη περίοδος",
"periodNext": "Επόμενη περίοδος",
+ "year": "Έτος",
+ "yearPickerHelp": "Εμφάνιση ενός ημερολογιακού έτους των δεδομένων σας",
"intervalDaily": "Η",
"intervalWeekly": "Ε",
"intervalMonthly": "Μ",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 2fbe7913..72b91edd 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -2034,6 +2034,8 @@
"rangeLastMonth": "Last Month",
"periodPrev": "Previous period",
"periodNext": "Next period",
+ "year": "Year",
+ "yearPickerHelp": "Show one calendar year of your data",
"intervalDaily": "D",
"intervalWeekly": "W",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index c182684a..e35e8cd5 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -2038,6 +2038,8 @@
"rangeLastMonth": "Mes pasado",
"periodPrev": "Período anterior",
"periodNext": "Período siguiente",
+ "year": "Año",
+ "yearPickerHelp": "Mostrar un año calendario de tus datos",
"intervalDaily": "D",
"intervalWeekly": "S",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index a72bd8ad..d1fbd472 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -2038,6 +2038,8 @@
"rangeLastMonth": "Mois dernier",
"periodPrev": "Période précédente",
"periodNext": "Période suivante",
+ "year": "Année",
+ "yearPickerHelp": "Afficher une année calendaire de vos données",
"intervalDaily": "J",
"intervalWeekly": "S",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.json
index 38e28c55..af4fd0c4 100644
--- a/frontend/src/locales/hi.json
+++ b/frontend/src/locales/hi.json
@@ -2034,6 +2034,8 @@
"rangeLastMonth": "पिछला महीना",
"periodPrev": "पिछली अवधि",
"periodNext": "अगली अवधि",
+ "year": "वर्ष",
+ "yearPickerHelp": "अपने डेटा का एक कैलेंडर वर्ष दिखाएं",
"intervalDaily": "दि",
"intervalWeekly": "सा",
"intervalMonthly": "मा",
diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.json
index a795c1bb..19b8f10c 100644
--- a/frontend/src/locales/hu.json
+++ b/frontend/src/locales/hu.json
@@ -2034,6 +2034,8 @@
"rangeLastMonth": "Múlt hónap",
"periodPrev": "Előző időszak",
"periodNext": "Következő időszak",
+ "year": "Év",
+ "yearPickerHelp": "Egy naptári év megjelenítése az adataidból",
"intervalDaily": "N",
"intervalWeekly": "Hé",
"intervalMonthly": "Hó",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index d0558d83..66a92a74 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -2038,6 +2038,8 @@
"rangeLastMonth": "Mese scorso",
"periodPrev": "Periodo precedente",
"periodNext": "Periodo successivo",
+ "year": "Anno",
+ "yearPickerHelp": "Mostra un anno solare dei tuoi dati",
"intervalDaily": "G",
"intervalWeekly": "S",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json
index 3c4ffe48..6ffae2e4 100644
--- a/frontend/src/locales/ja.json
+++ b/frontend/src/locales/ja.json
@@ -2034,6 +2034,8 @@
"rangeLastMonth": "先月",
"periodPrev": "前の期間",
"periodNext": "次の期間",
+ "year": "年",
+ "yearPickerHelp": "データの1暦年を表示",
"intervalDaily": "日",
"intervalWeekly": "週",
"intervalMonthly": "月",
diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json
index 224577bd..3a759367 100644
--- a/frontend/src/locales/nl.json
+++ b/frontend/src/locales/nl.json
@@ -2036,6 +2036,8 @@
"rangeLastMonth": "Vorige maand",
"periodPrev": "Vorige periode",
"periodNext": "Volgende periode",
+ "year": "Jaar",
+ "yearPickerHelp": "Eén kalenderjaar van je gegevens tonen",
"intervalDaily": "D",
"intervalWeekly": "W",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index d383df91..860681a3 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -2123,6 +2123,8 @@
"rangeLastMonth": "Miesiąc ubiegły",
"periodPrev": "Poprzedni okres",
"periodNext": "Następny okres",
+ "year": "Rok",
+ "yearPickerHelp": "Pokaż jeden rok kalendarzowy swoich danych",
"intervalDaily": "D",
"intervalWeekly": "T",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 17281564..e5b89220 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -2038,6 +2038,8 @@
"rangeLastMonth": "Mês passado",
"periodPrev": "Período anterior",
"periodNext": "Próximo período",
+ "year": "Ano",
+ "yearPickerHelp": "Mostrar um ano-calendário dos seus dados",
"intervalDaily": "D",
"intervalWeekly": "S",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 5a0fb54a..9d96ba40 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -2038,6 +2038,8 @@
"rangeLastMonth": "Mês passado",
"periodPrev": "Período anterior",
"periodNext": "Próximo período",
+ "year": "Ano",
+ "yearPickerHelp": "Mostrar um ano-calendário dos seus dados",
"intervalDaily": "D",
"intervalWeekly": "S",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index fa95cc2e..74f7b210 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -2051,6 +2051,8 @@
"rangeLastMonth": "Прошлый месяц",
"periodPrev": "Предыдущий период",
"periodNext": "Следующий период",
+ "year": "Год",
+ "yearPickerHelp": "Показать один календарный год ваших данных",
"intervalDaily": "Д",
"intervalWeekly": "Н",
"intervalMonthly": "М",
diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.json
index 6e877ae7..c76b31dd 100644
--- a/frontend/src/locales/sk.json
+++ b/frontend/src/locales/sk.json
@@ -2150,6 +2150,8 @@
"rangeLastMonth": "Minulý mesiac",
"periodPrev": "Predchádzajúce obdobie",
"periodNext": "Nasledujúce obdobie",
+ "year": "Rok",
+ "yearPickerHelp": "Zobraziť jeden kalendárny rok svojich dát",
"intervalDaily": "D",
"intervalWeekly": "T",
"intervalMonthly": "M",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index dd3bfee3..018a30e1 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -2051,6 +2051,8 @@
"rangeLastMonth": "Минулий місяць",
"periodPrev": "Попередній період",
"periodNext": "Наступний період",
+ "year": "Рік",
+ "yearPickerHelp": "Показати один календарний рік ваших даних",
"intervalDaily": "Д",
"intervalWeekly": "Т",
"intervalMonthly": "М",
diff --git a/frontend/src/pages/reports.test.tsx b/frontend/src/pages/reports.test.tsx
index b3118bdf..beffa4a0 100644
--- a/frontend/src/pages/reports.test.tsx
+++ b/frontend/src/pages/reports.test.tsx
@@ -10,6 +10,7 @@ const api = vi.hoisted(() => ({
netWorth: vi.fn(),
incomeExpenses: vi.fn(),
cashFlow: vi.fn(),
+ dataRange: vi.fn(),
},
// The page reads the workspace timezone to tell a balance that is already
// negative from one that crosses later. Unresolved here, which lands on the
@@ -53,6 +54,8 @@ beforeEach(() => {
api.reports.netWorth.mockResolvedValue(emptyReport('net_worth'))
api.reports.incomeExpenses.mockResolvedValue(emptyReport('income_expenses'))
api.reports.cashFlow.mockResolvedValue(emptyReport('cash_flow'))
+ // No data by default: the year picker stays hidden unless a test opts in.
+ api.reports.dataRange.mockResolvedValue({ min_date: null, max_date: null })
})
afterEach(() => vi.useRealTimers())
@@ -406,3 +409,83 @@ describe('Reports page: month presets and period navigation (issue #519)', () =>
expect(screen.queryByTestId('reports-period-nav')).not.toBeInTheDocument()
})
})
+
+describe('Reports page - year picker (issue #765)', () => {
+ beforeEach(() => {
+ api.reports.dataRange.mockResolvedValue({ min_date: '2023-04-10', max_date: '2026-09-12' })
+ })
+
+ it('lists every year from this year back to the oldest transaction', async () => {
+ const { user } = renderWithProviders(<ReportsPage />)
+ const trigger = await screen.findByRole('button', { name: t('reports.year') })
+ await user.click(trigger)
+ await screen.findByRole('button', { name: '2026' })
+ expect(screen.getByRole('button', { name: '2025' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: '2024' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: '2023' })).toBeInTheDocument()
+ })
+
+ it('commits the picked past year as a Jan 1 to Dec 31 range', async () => {
+ const { user } = renderWithProviders(<ReportsPage />)
+ const trigger = await screen.findByRole('button', { name: t('reports.year') })
+ await user.click(trigger)
+ await user.click(await screen.findByRole('button', { name: '2023' }))
+
+ // Full calendar year: 364 days, ceil(364/30) = 13 monthly buckets.
+ expect(api.reports.netWorth).toHaveBeenCalledWith(
+ 13, 'monthly', undefined, undefined, undefined, '2023-01-01', '2023-12-31',
+ )
+ // The custom segment is now the active range and shows the span.
+ expect(screen.getByRole('button', { name: t('reports.customRange') })).toHaveClass('bg-primary')
+ expect(screen.getByRole('button', { name: t('reports.customRange') })).toHaveTextContent('Jan 01 - Dec 31')
+ // The trigger highlights the year that is currently on screen.
+ expect(screen.getByRole('button', { name: `${t('reports.year')} 2023` })).toHaveClass('bg-primary')
+ })
+
+ it('ends the current year at today', async () => {
+ const { user } = renderWithProviders(<ReportsPage />)
+ const trigger = await screen.findByRole('button', { name: t('reports.year') })
+ await user.click(trigger)
+ await user.click(await screen.findByRole('button', { name: '2026' }))
+
+ // Jan 1 through today (2026-09-12): 254 days, ceil(254/30) = 9.
+ expect(api.reports.netWorth).toHaveBeenCalledWith(
+ 9, 'monthly', undefined, undefined, undefined, '2026-01-01', '2026-09-12',
+ )
+ })
+
+ it('hides the picker when the data spans a single year', async () => {
+ // Two phases: the same widget shows for multi-year data and disappears
+ // once the data no longer covers a previous year.
+ renderWithProviders(<ReportsPage />)
+ await screen.findByRole('button', { name: t('reports.year') })
+ cleanup()
+
+ api.reports.dataRange.mockResolvedValue({ min_date: '2026-01-05', max_date: '2026-09-12' })
+ renderWithProviders(<ReportsPage />)
+ await screen.findByRole('heading', { name: 'Net Worth' })
+ expect(screen.queryByRole('button', { name: t('reports.year') })).not.toBeInTheDocument()
+ })
+
+ it('hides the picker when the data range fails to load', async () => {
+ renderWithProviders(<ReportsPage />)
+ await screen.findByRole('button', { name: t('reports.year') })
+ cleanup()
+
+ api.reports.dataRange.mockRejectedValue(new Error('network down'))
+ renderWithProviders(<ReportsPage />)
+ await screen.findByRole('heading', { name: 'Net Worth' })
+ expect(screen.queryByRole('button', { name: t('reports.year') })).not.toBeInTheDocument()
+ })
+
+ it('is not offered on the forward-only Cash Flow tab', async () => {
+ const { user } = renderWithProviders(<ReportsPage />)
+ const trigger = await screen.findByRole('button', { name: t('reports.year') })
+ expect(trigger).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: t('reports.cashFlow') }))
+ await screen.findByRole('heading', { name: t('reports.cashFlow') })
+ expect(screen.queryByRole('button', { name: t('reports.year') })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: `${t('reports.year')} 2026` })).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsx
index 121c5235..242cfba6 100644
--- a/frontend/src/pages/reports.tsx
+++ b/frontend/src/pages/reports.tsx
@@ -19,7 +19,7 @@ import {
ReferenceLine,
ResponsiveContainer,
} from 'recharts'
-import { AlertCircle, ChevronLeft, ChevronRight, HelpCircle, X } from 'lucide-react'
+import { AlertCircle, CalendarDays, ChevronLeft, ChevronRight, HelpCircle, X } from 'lucide-react'
import { reports } from '@/lib/api'
import { extractApiError } from '@/lib/api-errors'
import { Skeleton } from '@/components/ui/skeleton'
@@ -367,6 +367,38 @@ export default function ReportsPage() {
}
}
+ // Year picker (issue #765): one entry per year the workspace's data
+ // covers, from this year back to the oldest transaction. Hidden until the
+ // data spans at least two years, and never on Cash Flow, which has no
+ // custom range a picked year can be committed into.
+ const { data: dataRange } = useQuery({
+ queryKey: ['reports', 'data-range'],
+ queryFn: reports.dataRange,
+ staleTime: 5 * 60 * 1000,
+ })
+ const todayStr = todayInTimezone(timeZone)
+ const currentYear = Number(todayStr.slice(0, 4))
+ const minYear = dataRange?.min_date ? Number(dataRange.min_date.slice(0, 4)) : null
+ const yearOptions =
+ minYear !== null && minYear < currentYear
+ ? Array.from({ length: currentYear - minYear + 1 }, (_, i) => currentYear - i)
+ : []
+ // The year a committed custom range covers exactly: Jan 1 through
+ // Dec 31, or through today for the current year.
+ const activeYear = yearOptions.find(
+ (year) =>
+ isCustomRange &&
+ customFrom === `${year}-01-01` &&
+ customTo === (year === currentYear ? todayStr : `${year}-12-31`),
+ )
+ const handleYearPick = (year: number) => {
+ setCustomFrom(`${year}-01-01`)
+ setCustomTo(year === currentYear ? todayStr : `${year}-12-31`)
+ setRangeKey(CUSTOM_RANGE_KEY)
+ setPeriodOffset(0)
+ setSelectedDate(null)
+ }
+
const { data, isLoading, isError, error, refetch } = useQuery<ReportResponse>({
queryKey: ['reports', activeTab, rangeKey, months, period ?? null, days ?? null, interval, isCashFlow ? cashFlowBaseline : false, activeAccountIds, activeWalletIds, apiStart ?? null, apiEnd ?? null],
queryFn: () =>
@@ -734,6 +766,43 @@ export default function ReportsPage() {
placeholder={t('reports.pickCustomRange')}
/>
)}
+ {supportsCustomRange && yearOptions.length > 1 && (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ aria-label={activeYear !== undefined ? `${t('reports.year')} ${activeYear}` : t('reports.year')}
+ title={t('reports.yearPickerHelp')}
+ className={`px-3 py-1.5 text-xs font-semibold transition-colors ${
+ activeYear !== undefined
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
+ }`}
+ >
+ <CalendarDays className="mr-1 inline h-3.5 w-3.5" />
+ {activeYear !== undefined ? activeYear : t('reports.year')}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-auto p-1">
+ <div className="max-h-64 overflow-y-auto">
+ {yearOptions.map((year) => (
+ <button
+ key={year}
+ type="button"
+ onClick={() => handleYearPick(year)}
+ className={`block w-full px-3 py-1.5 text-left text-xs font-semibold transition-colors ${
+ activeYear === year
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
+ }`}
+ >
+ {year}
+ </button>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
</div>
{/* Period navigation (issue #519): step the active window back and
forward through history, labeled with the period it shows. The