Open-source personal finance manager. Self-hosted, privacy-first.
feat(reports): add custom date range for report analysis (#816) (#907)
Yonic Surny37af47f56489
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.pyindex 02ad9a38..84a1f60f 100644--- a/backend/app/api/reports.py+++ b/backend/app/api/reports.py@@ -1,4 +1,5 @@import uuid+from datetime import datefrom typing import Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query@@ -11,6 +12,23 @@ from app.services import report_servicerouter = APIRouter(prefix="/api/reports", tags=["reports"])+# Cap the user-picked custom range so wide windows can't tie up the DB with+# per-day snapshot fan-out. Ten years covers every realistic personal-finance+# question and stays inside the existing daily-interval budget.+_MAX_CUSTOM_RANGE_YEARS = 10+++def _add_years(value: date, years: int) -> date:+ """Add whole calendar years to a date.++ Clamps Feb 29 to Feb 28 when the target year isn't a leap year, so the+ result is always a valid calendar date rather than raising.+ """+ try:+ return value.replace(year=value.year + years)+ except ValueError:+ return date(value.year + years, 2, 28)+def _financial_year_start_month(tax_jurisdiction: str | None) -> int:"""Return the first month of the workspace's financial year."""@@ -27,6 +45,44 @@ def _reject_unsupported_fiscal_year_report()+def _resolve_custom_range(+ start_date: date | None, end_date: date | None+) -> tuple[date | None, date | None]:+ """Validate a user-supplied custom range and return the (start, end) pair.++ Both endpoints must be provided together; the range must be non-empty,+ end no later than today and stay within :data:`_MAX_CUSTOM_RANGE_YEARS`+ calendar years of start_date. Returns ``(None, None)`` when neither is+ set, so callers can use presets.+ """+ if start_date is None and end_date is None:+ return None, None+ if start_date is None or end_date is None:+ raise HTTPException(+ status_code=422,+ detail="start_date and end_date must be provided together",+ )+ if end_date < start_date:+ raise HTTPException(+ status_code=422,+ detail="end_date must be on or after start_date",+ )+ if end_date > date.today():+ raise HTTPException(+ status_code=422,+ detail="end_date must be on or before today",+ )+ max_end_date = _add_years(start_date, _MAX_CUSTOM_RANGE_YEARS)+ if end_date > max_end_date:+ raise HTTPException(+ status_code=422,+ detail=(+ f"Custom range is too wide (max {_MAX_CUSTOM_RANGE_YEARS} years)"+ ),+ )+ return start_date, end_date++@router.get("/net-worth", response_model=ReportResponse)async def get_net_worth(months: int = Query(12, ge=1, le=24),@@ -34,15 +90,22 @@ async def get_net_worth(account_ids: Optional[list[uuid.UUID]] = Query(None),asset_group_ids: Optional[list[uuid.UUID]] = Query(None),period: str | None = Query(None, pattern="^ytd$"),+ start_date: date | None = Query(None),+ end_date: date | None = Query(None),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):financial_year_start_month = _financial_year_start_month(ctx.workspace.tax_jurisdiction)- _reject_unsupported_fiscal_year_report(period, interval, financial_year_start_month)+ custom_start, custom_end = _resolve_custom_range(start_date, end_date)+ effective_period = None if custom_start is not None else period+ _reject_unsupported_fiscal_year_report(+ effective_period, interval, financial_year_start_month+ )return await report_service.get_net_worth_report(session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency,- account_ids=account_ids, asset_group_ids=asset_group_ids, period=period,+ account_ids=account_ids, asset_group_ids=asset_group_ids, period=effective_period,financial_year_start_month=financial_year_start_month,+ start_date=custom_start, end_date=custom_end,)@@ -53,16 +116,28 @@ async def get_income_expenses(account_ids: Optional[list[uuid.UUID]] = Query(None),period: str | None = Query(None, pattern="^ytd$"),days: Optional[int] = Query(None, ge=1, le=730),+ start_date: date | None = Query(None),+ end_date: date | None = Query(None),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):- """`days` overrides `months` with an exact rolling window ending today."""+ """`days` overrides `months` with an exact rolling window ending today.++ Alternatively `start_date`/`end_date` (both required together) pin the+ window to an explicit historical calendar range, overriding `months`,+ `period`, and `days`. Custom ranges include actuals only, without estimates.+ """financial_year_start_month = _financial_year_start_month(ctx.workspace.tax_jurisdiction)- _reject_unsupported_fiscal_year_report(period, interval, financial_year_start_month)+ custom_start, custom_end = _resolve_custom_range(start_date, end_date)+ effective_period = None if custom_start is not None else period+ _reject_unsupported_fiscal_year_report(+ effective_period, interval, financial_year_start_month+ )return await report_service.get_income_expenses_report(session, ctx.workspace.id, ctx.user_id, months, interval, ctx.user.primary_currency,- account_ids=account_ids, period=period, days=days,+ account_ids=account_ids, period=effective_period, days=days,financial_year_start_month=financial_year_start_month,+ start_date=custom_start, end_date=custom_end,)diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 6a7c0909..925174a8 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -64,12 +64,18 @@ def _report_start_date(period: str | None = None,days: int | None = None,financial_year_start_month: int = 1,+ start_date: date | None = None,) -> date:"""Resolve historical report start date.- `days` requests an exact rolling window ending today (inclusive), instead of- the month-aligned window the `months` ranges use.+ An explicit ``start_date`` wins over every other selector so a caller can+ pin the window to a calendar range. `days` requests an exact rolling window+ ending today (inclusive), instead of the month-aligned window the `months`+ ranges use."""+ if start_date is not None:+ return start_date+if days:return today - timedelta(days=days - 1)@@ -127,13 +133,20 @@ async def _net_worth_at(primary_currency: str = "USD",account_ids: Optional[list[uuid.UUID]] = None,asset_group_ids: Optional[list[uuid.UUID]] = None,+ accounts: Optional[list[Account]] = None,) -> ReportDataPoint:"""Compute a single net worth snapshot at a given date, converted to primary currency.Under a Collection filter (``account_ids`` set), only those accounts aresummed and only assets in the collection's wallets (``asset_group_ids``)- are included."""- accounts = await _get_open_accounts(session, workspace_id, account_ids)+ are included.++ ``accounts`` lets a caller that already fetched the (date-independent) open+ account list for this workspace/filter pass it in, instead of re-querying+ it for every snapshot in a multi-point trend. Omit it to fetch as before.+ """+ if accounts is None:+ accounts = await _get_open_accounts(session, workspace_id, account_ids)accounts_total = 0.0liabilities_total = 0.0@@ -291,26 +304,37 @@ async def get_net_worth_report(asset_group_ids: Optional[list[uuid.UUID]] = None,period: str | None = None,financial_year_start_month: int = 1,+ start_date: date | None = None,+ end_date: date | None = None,) -> ReportResponse:"""Build a full ReportResponse for net worth over time."""# A wallet-only collection (wallets, no accounts) still filters.if asset_group_ids is not None and account_ids is None:account_ids = []- today = date.today()+ real_today = date.today()+ axis_end = end_date or real_todaystart = _report_start_date(- today, months, period, financial_year_start_month=financial_year_start_month+ axis_end, months, period, financial_year_start_month=financial_year_start_month,+ start_date=start_date,)# Get user's primary currencyuser = await session.get(User, user_id)primary_currency = user.primary_currency if user else get_settings().default_currency- points = _date_points(start, today, interval)+ points = _date_points(start, axis_end, interval)++ # Fetch the open-account list once: it does not depend on the snapshot+ # date, so every point below reuses it instead of re-querying it.+ accounts = await _get_open_accounts(session, workspace_id, account_ids)# Compute snapshot at each date pointtrend: list[ReportDataPoint] = []for point in points:- dp = await _net_worth_at(session, workspace_id, point, primary_currency, account_ids, asset_group_ids)+ dp = await _net_worth_at(+ session, workspace_id, point, primary_currency, account_ids, asset_group_ids,+ accounts=accounts,+ )dp.date = _format_date_label(point, interval)dp.change = round(dp.value - trend[-1].value, 2) if trend else Nonetrend.append(dp)@@ -319,7 +343,17 @@ async def get_net_worth_report(current = trend[-1] if trend else ReportDataPoint(date="", value=0, breakdowns={"accounts": 0, "assets": 0, "liabilities": 0})- baseline = await _net_worth_at(session, workspace_id, start, primary_currency, account_ids, asset_group_ids)+ # The first trend point's *actual* cutoff (`points[0]`, before its `.date`+ # was overwritten with a formatted label) equals `start` for every+ # interval except monthly, which snaps to month-end. Only reuse it then —+ # an approximate match would silently swap in the wrong day's snapshot.+ if trend and points[0] == start:+ baseline = trend[0]+ else:+ baseline = await _net_worth_at(+ session, workspace_id, start, primary_currency, account_ids, asset_group_ids,+ accounts=accounts,+ )previous = baseline if trend else currentchange_amount = current.value - previous.value@@ -362,8 +396,8 @@ async def get_net_worth_report(interval=interval,)- # The last trend point is always today — reuse its per-item composition for- # the response-level `composition` field (current snapshot for the donut).+ # Reuse the selected end date's per-item composition for the response-level+ # `composition` field (final snapshot for the donut).composition = trend[-1].composition if trend else []return ReportResponse(summary=summary, trend=trend, meta=meta, composition=composition)@@ -397,17 +431,21 @@ async def get_income_expenses_report(period: str | None = None,days: int | None = None,financial_year_start_month: int = 1,+ start_date: date | None = None,+ end_date: date | None = None,) -> ReportResponse:- """Build a ReportResponse for income vs expenses over time."""+ """Build income/expenses; explicit custom windows include actuals only."""filtered = account_ids is not Noneacct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []- today = date.today()+ real_today = date.today()+ axis_end = end_date or real_todaystart = _report_start_date(- today,+ axis_end,months,period=period,days=days,financial_year_start_month=financial_year_start_month,+ start_date=start_date,)# Get user's primary currency + global reporting mode@@ -432,7 +470,7 @@ async def get_income_expenses_report(Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= start,- report_date <= today,+ report_date <= axis_end,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -492,7 +530,7 @@ async def get_income_expenses_report(Transaction.workspace_id == workspace_id,_TS_.group_member_id.notin_(own_member_ids_sq),report_date >= start,- report_date <= today,+ report_date <= axis_end,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -556,7 +594,7 @@ async def get_income_expenses_report(Transaction.user_id != user_id,Transaction.workspace_id != workspace_id,report_date >= start,- report_date <= today,+ report_date <= axis_end,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -584,13 +622,16 @@ async def get_income_expenses_report(existing_expenses + share_expenses_pri,)+ # Custom windows report only actuals, including when they end today.+ # Presets retain their existing full-month estimates.+ include_forecasts = start_date is None and end_date is Noneforecast_map: dict[str, tuple[float, float]] = {}# Add recurring projections for each month in the range (consistent with dashboard)from app.services.dashboard_service import _month_range, _get_recurring_projectionscursor = start- while cursor <= today:+ while include_forecasts and cursor <= real_today:m_start, m_end = _month_range(cursor)# A day-window range can start mid-month: only project occurrences that# fall inside the requested window.@@ -664,7 +705,7 @@ async def get_income_expenses_report(cursor = date(cursor.year, cursor.month + 1, 1)# Generate all expected date points and map to results- points = _date_points(start, today, interval)+ points = _date_points(start, axis_end, interval)trend: list[ReportDataPoint] = []total_income = 0.0total_expenses = 0.0@@ -686,7 +727,7 @@ async def get_income_expenses_report(},))- # A daily report's visible axis ends today, but the monthly forecast query+ # A daily preset's visible axis ends today, but the monthly forecast query# can still contain future installments/generate-ahead rows in the current# month. Keep those rows in the projected summary even when they have no# historical point to render yet.@@ -766,7 +807,7 @@ async def get_income_expenses_report(Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= start,- report_date <= today,+ report_date <= axis_end,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -795,7 +836,7 @@ async def get_income_expenses_report(# owner_split_offset_by_category is debit-only). Keeps the report's# composition consistent with summary totals under share-only model.full_range_offset = {} if filtered else await owner_split_offset_by_category(- session, user_id, start, today + timedelta(days=1),+ session, user_id, start, axis_end + timedelta(days=1),use_effective_date=accounting_mode == "accrual",primary_currency=primary_currency,)@@ -829,7 +870,7 @@ async def get_income_expenses_report(Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= start,- report_date <= today,+ report_date <= axis_end,Transaction.source != "opening_balance",Transaction.type == "debit",Transaction.status == "posted",@@ -869,7 +910,7 @@ async def get_income_expenses_report(Transaction.workspace_id == workspace_id,Account.is_closed == False,report_date >= start,- report_date <= today,+ report_date <= axis_end,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -917,7 +958,7 @@ async def get_income_expenses_report(Transaction.type == "debit",_TS_.group_member_id.notin_(own_member_ids_sq),report_date >= start,- report_date <= today,+ report_date <= axis_end,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -948,7 +989,7 @@ async def get_income_expenses_report(# Add recurring projections to composition and category trendcat_cache: dict[str, dict] = {}cursor2 = start- while cursor2 <= today:+ while include_forecasts and cursor2 <= real_today:m_start, m_end = _month_range(cursor2)projections = await _get_recurring_projections(session, workspace_id, m_start, m_end, account_ids)period_label = _format_date_label(cursor2, interval)diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.pyindex bc062452..30dd27a5 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -23,6 +23,7 @@ from app.schemas.report import ()from app.services import report_servicefrom app.api.reports import (+ _add_years,_financial_year_start_month,_reject_unsupported_fiscal_year_report,)@@ -389,6 +390,26 @@ async def test_net_worth_report_ytd_starts_at_current_year(assert all(point.date.startswith(str(date.today().year)) for point in report.trend)[email protected]("interval", ["daily", "weekly", "monthly", "yearly"])+async def test_net_worth_report_custom_range_pins_window(+ session: AsyncSession, test_user, test_workspace, interval+):+ """Explicit start_date/end_date override the preset window."""+ start = date(2022, 3, 1)+ end = date(2022, 6, 30)+ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id,+ months=6, interval=interval,+ start_date=start, end_date=end,+ )++ expected = [_format_date_label(point, interval)+ for point in _date_points(start, end, interval)]+ assert [point.date for point in report.trend] == expected+ assert report.trend[-1].date == _format_date_label(end, interval)++# ---------------------------------------------------------------------------# API-level tests: /reports/net-worth# ---------------------------------------------------------------------------@@ -574,6 +595,7 @@ async def test_income_expenses_api_accepts_ytd_period(client, auth_headers, monkasync def fake_report(session, workspace_id, user_id, months, interval, currency,account_ids=None, period=None, days=None, financial_year_start_month=1,+ start_date=None, end_date=None,):assert months == 12assert interval == "monthly"@@ -616,6 +638,7 @@ async def test_income_expenses_api_forwards_days_window(client, auth_headers, moasync def fake_report(session, workspace_id, user_id, months, interval, currency,account_ids=None, period=None, days=None, financial_year_start_month=1,+ start_date=None, end_date=None,):seen["days"] = daysreturn ReportResponse(@@ -654,6 +677,60 @@ async def test_income_expenses_api_forwards_days_window(client, auth_headers, moassert resp.status_code == 422+async def test_income_expenses_api_forwards_custom_range(client, auth_headers, monkeypatch):+ """start_date/end_date override presets and reach the service."""+ seen: dict = {}++ async def fake_report(+ session, workspace_id, user_id, months, interval, currency,+ account_ids=None, period=None, days=None, financial_year_start_month=1,+ start_date=None, end_date=None,+ ):+ seen["start"] = start_date+ seen["end"] = end_date+ return ReportResponse(+ summary=ReportSummary(primary_value=0, change_amount=0, change_percent=None, breakdowns=[]),+ trend=[],+ meta=ReportMeta(type="income_expenses", series_keys=[], currency=currency, interval=interval),+ composition=[],+ category_trend=[],+ )++ monkeypatch.setattr(report_service, "get_income_expenses_report", fake_report)++ resp = await client.get(+ "/api/reports/income-expenses",+ params={"start_date": "2022-01-01", "end_date": "2022-06-30"},+ headers=auth_headers,+ )+ assert resp.status_code == 200+ assert seen["start"] == date(2022, 1, 1)+ assert seen["end"] == date(2022, 6, 30)+++async def test_income_expenses_api_rejects_partial_custom_range(client, auth_headers):+ """Both start_date and end_date must be provided together."""+ resp = await client.get(+ "/api/reports/income-expenses",+ params={"start_date": "2022-01-01"},+ headers=auth_headers,+ )+ assert resp.status_code == 422+++async def test_income_expenses_api_rejects_reversed_custom_range(client, auth_headers):+ """end_date must be on or after start_date."""+ resp = await client.get(+ "/api/reports/income-expenses",+ params={"start_date": "2022-06-30", "end_date": "2022-01-01"},+ headers=auth_headers,+ )+ assert resp.status_code == 422++def test_financial_year_start_month_uses_india_jurisdiction():assert _financial_year_start_month("IN") == 4assert _financial_year_start_month("in") == 4@@ -2666,3 +2743,99 @@ async def test_cash_flow_chart_includes_past_history(delta_days = (today - first_date).days# _PAST_HISTORY_MONTHS = 1 (28–31 days depending on month).assert 27 <= delta_days <= 32+++def test_add_years_clamps_leap_day():+ """Feb 29 + N years clamps to Feb 28 when the target year isn't leap."""+ assert _add_years(date(2016, 2, 29), 10) == date(2026, 2, 28)+ # Target year is also a leap year, so Feb 29 survives untouched.+ assert _add_years(date(2020, 2, 29), 4) == date(2024, 2, 29)+ assert _add_years(date(2016, 9, 12), 10) == date(2026, 9, 12)++[email protected]('endpoint,service_name', [+ ('net-worth', 'get_net_worth_report'),+ ('income-expenses', 'get_income_expenses_report'),+])[email protected]('start_offset,end_offset,status', [+ # FixedDate.today() is 2026-09-12; -3652 days is exactly 2016-09-12, the+ # 10-calendar-year anniversary. One day further back crosses it, even+ # though the day-count difference (3653 vs. 3652) understates the effect+ # of the two leap days (2020, 2024) inside the window.+ (-1, 1, 422), (0, 0, 200), (-3652, 0, 200), (-3653, 0, 422),+ (None, 0, 422), (-1, None, 422), (0, -1, 422),+])+async def test_historical_api_custom_range_boundaries(+ client, auth_headers, monkeypatch, endpoint, service_name,+ start_offset, end_offset, status,+):+ from app.api import reports as reports_api++ class FixedDate(date):+ @classmethod+ def today(cls):+ return cls(2026, 9, 12)++ monkeypatch.setattr(reports_api, 'date', FixedDate)+ report = ReportResponse(+ summary=ReportSummary(primary_value=0, change_amount=0, change_percent=None,+ breakdowns=[]),+ trend=[], meta=ReportMeta(type=endpoint, series_keys=[], currency='USD',+ interval='monthly'),+ composition=[], category_trend=[],+ )+ service = AsyncMock(return_value=report)+ monkeypatch.setattr(report_service, service_name, service)+ params = {}+ for name, offset in [('start_date', start_offset), ('end_date', end_offset)]:+ if offset is not None:+ params[name] = (FixedDate.today() + timedelta(days=offset)).isoformat()+ response = await client.get(f'/api/reports/{endpoint}', params=params, headers=auth_headers)+ assert response.status_code == status, response.text+ if status == 200:+ service.assert_awaited_once()+ assert service.call_args.kwargs['start_date'].isoformat() == params['start_date']+ assert service.call_args.kwargs['end_date'].isoformat() == params['end_date']+ else:+ service.assert_not_awaited()+ assert isinstance(response.json()['detail'], str)++[email protected]('endpoint,service_name', [+ ('net-worth', 'get_net_worth_report'),+ ('income-expenses', 'get_income_expenses_report'),+])+async def test_custom_dates_override_indian_yearly_ytd(+ client, auth_headers, monkeypatch, endpoint, service_name,+):+ context = SimpleNamespace(+ workspace=SimpleNamespace(id=uuid.uuid4(), tax_jurisdiction='IN'),+ user_id=uuid.uuid4(), user=SimpleNamespace(primary_currency='INR'),+ )++ async def override_workspace():+ return context++ report = ReportResponse(+ summary=ReportSummary(primary_value=0, change_amount=0, change_percent=None,+ breakdowns=[]),+ trend=[], meta=ReportMeta(type=endpoint, series_keys=[], currency='INR',+ interval='yearly'), composition=[], category_trend=[],+ )+ service = AsyncMock(return_value=report)+ monkeypatch.setattr(report_service, service_name, service)+ app.dependency_overrides[current_workspace] = override_workspace+ try:+ params = {'period': 'ytd', 'interval': 'yearly'}+ rejected = await client.get(f'/api/reports/{endpoint}', params=params,+ headers=auth_headers)+ assert rejected.status_code == 422+ service.assert_not_awaited()+ params.update(start_date='2022-03-10', end_date='2022-06-15')+ accepted = await client.get(f'/api/reports/{endpoint}', params=params,+ headers=auth_headers)+ assert accepted.status_code == 200, accepted.text+ assert service.call_args.kwargs['period'] is None+ assert service.call_args.kwargs['financial_year_start_month'] == 4+ finally:+ app.dependency_overrides.pop(current_workspace, None)diff --git a/backend/tests/test_report_service_coverage.py b/backend/tests/test_report_service_coverage.pyindex 85798e44..32dab5d7 100644--- a/backend/tests/test_report_service_coverage.py+++ b/backend/tests/test_report_service_coverage.py@@ -781,3 +781,66 @@ async def test_cash_flow_accrual_mode_pending_cc(session, test_user, test_worksp)assert report.meta.type == "cash_flow"assert len(report.trend) > 0++[email protected]('interval', ['daily', 'monthly', 'yearly'])[email protected]('end', [date(2022, 3, 20), date(2026, 9, 12)])+async def test_custom_income_expenses_only_include_in_range_actuals(+ session, test_user, test_workspace, monkeypatch, interval, end,+):+ from app.models.invoice import Invoice+ from app.services import report_service++ class FixedDate(date):+ @classmethod+ def today(cls):+ return cls(2026, 9, 12)++ monkeypatch.setattr(report_service, 'date', FixedDate)+ start = end.replace(day=10)+ currency = test_user.primary_currency+ account = await _make_account(session, test_user.id, 'Custom actuals', currency=currency)+ category = await _make_category(session, test_user.id, 'Actual category')+ for amount, kind, day, status in [+ (100, 'credit', start, 'posted'),+ (-30, 'debit', end, 'posted'),+ (500, 'credit', start - timedelta(days=1), 'posted'),+ (-700, 'debit', end + timedelta(days=1), 'posted'),+ (900, 'credit', start, 'pending'),+ (-800, 'debit', end, 'pending'),+ ]:+ await _add_txn(session, test_user.id, account.id, amount, kind, day,+ status=status, category_id=category.id, currency=currency)+ recurring = await _make_recurring(+ session, test_user.id, account.id, 600, 'credit',+ next_occurrence=start, category_id=category.id, currency=currency,+ )+ recurring.start_date = start+ session.add(Invoice(+ workspace_id=test_workspace.id, user_id=test_user.id, status='open',+ issue_date=start, due_date=start, currency=currency, total=Decimal('1100'),+ direction='receivable', number=1, series='TEST',+ ))+ await session.commit()++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, interval=interval,+ start_date=start, end_date=end,+ )+ totals = {item.key: item.value for item in report.summary.breakdowns}+ assert totals['income'] == 100+ assert totals['expenses'] == 30+ assert totals['projectedIncome'] == totals['projectedExpenses'] == 0+ assert report.summary.primary_value == 70+ assert sum(point.breakdowns['income'] for point in report.trend) == 100+ assert sum(point.breakdowns['expenses'] for point in report.trend) == 30+ assert all(point.breakdowns['projectedIncome'] == 0 and+ point.breakdowns['projectedExpenses'] == 0 for point in report.trend)+ assert {item.group: item.value for item in report.composition} == {+ 'income': 100, 'expenses': 30,+ }+ assert {item.group: item.total for item in report.category_trend} == {+ 'income': 100, 'expenses': 30,+ }+ for item in report.category_trend:+ assert sum(point.value for point in item.series) == item.totaldiff --git a/frontend/src/components/transactions-filter-bar.tsx b/frontend/src/components/transactions-filter-bar.tsxindex cf21313d..09f3bf96 100644--- a/frontend/src/components/transactions-filter-bar.tsx+++ b/frontend/src/components/transactions-filter-bar.tsx@@ -42,6 +42,7 @@ import { Calendar } from '@/components/ui/calendar'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'import { localDateString } from '@/lib/date-utils'+import { formatDateRange } from '@/lib/date-range-format'import { resolveDateFnsLocale } from '@/lib/date-fns-locale'import { CategoryFilterContent } from '@/components/category-filter-content'import {@@ -231,14 +232,7 @@ export function TransactionsFilterBar({const dateLabel = useMemo(() => {if (!filterFrom && !filterTo) return null- const fmt = (iso: string) =>- new Date(iso + 'T00:00:00').toLocaleDateString(dateLocale, {- day: '2-digit',- month: 'short',- })- if (filterFrom && filterTo) return `${fmt(filterFrom)} — ${fmt(filterTo)}`- if (filterFrom) return `≥ ${fmt(filterFrom)}`- return `≤ ${fmt(filterTo)}`+ return formatDateRange(filterFrom, filterTo, dateLocale, { compact: true })}, [filterFrom, filterTo, dateLocale])const amountLabel = useMemo(() => {@@ -1130,7 +1124,7 @@ export function TransactionsFilterBar({</p><p className="mt-0.5 text-[11px] text-muted-foreground/70">{draftFrom || draftTo- ? formatRange(draftFrom, draftTo, dateLocale)+ ? formatDateRange(draftFrom, draftTo, dateLocale): t('transactions.filtersBar.pickRange')}</p></div>@@ -1212,18 +1206,6 @@ export function TransactionsFilterBar({)}-function formatRange(from: string, to: string, locale: string): string {- const fmt = (iso: string) =>- new Date(iso + 'T00:00:00').toLocaleDateString(locale, {- day: '2-digit',- month: 'short',- year: 'numeric',- })- if (from && to) return `${fmt(from)} — ${fmt(to)}`- if (from) return `≥ ${fmt(from)}`- return `≤ ${fmt(to)}`-}-interface FilterChipProps {icon: React.ReactNodelabel: stringdiff --git a/frontend/src/components/ui/date-range-picker.test.tsx b/frontend/src/components/ui/date-range-picker.test.tsxnew file mode 100644index 00000000..e14c89c3--- /dev/null+++ b/frontend/src/components/ui/date-range-picker.test.tsx@@ -0,0 +1,361 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { DateRangePicker } from '@/components/ui/date-range-picker'+import { renderWithProviders, t } from '@/test/utils'++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++// The segment variant's active label drops the year — same compact form the+// transactions filter bar's applied-range chip uses.+function fmtCompact(iso: string): string {+ return new Date(`${iso}T00:00:00`).toLocaleDateString('en-US', {+ day: '2-digit',+ month: 'short',+ })+}++describe('DateRangePicker — segment variant', () => {+ it('shows the plain label while inactive, even if a range is already stored', () => {+ renderWithProviders(+ <DateRangePicker+ variant="segment"+ active={false}+ from="2026-02-01"+ to="2026-02-10"+ onChange={vi.fn()}+ label="Custom"+ />,+ )++ // The picked dates only surface once the segment is the active range —+ // otherwise it reads exactly like the other preset segments beside it.+ expect(screen.getByRole('button', { name: 'Custom' })).toHaveTextContent('Custom')+ })++ it('shows the compact, year-less range once active', () => {+ renderWithProviders(+ <DateRangePicker+ variant="segment"+ active+ from="2026-03-01"+ to="2026-03-10"+ onChange={vi.fn()}+ label="Custom"+ />,+ )++ // aria-label stays the fixed "Custom" (same as every other preset+ // segment); it's the visible text that swaps to the picked dates, in+ // the same compact (no-year) form as the transactions filter bar's+ // applied-range chip.+ const trigger = screen.getByRole('button', { name: 'Custom' })+ expect(trigger).toHaveTextContent(`${fmtCompact('2026-03-01')} - ${fmtCompact('2026-03-10')}`)+ expect(trigger).not.toHaveTextContent('2026')+ })++ it('keeps the compact form even when the range crosses a year boundary', () => {+ renderWithProviders(+ <DateRangePicker+ variant="segment"+ active+ from="2025-09-26"+ to="2026-01-30"+ onChange={vi.fn()}+ label="Custom"+ />,+ )++ // Crossing a year boundary is exactly the case a year-inclusive format+ // would need to disambiguate — the segment still drops it, since the+ // year is visible while the calendar itself is open.+ expect(screen.getByRole('button', { name: 'Custom' })).toHaveTextContent(+ `${fmtCompact('2025-09-26')} - ${fmtCompact('2026-01-30')}`,+ )+ })++ it('seeds drafts on open and commits defaults only on Apply', async () => {+ const onOpen = vi.fn()+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker+ variant="segment"+ active={false}+ from=""+ to=""+ defaultFrom="2026-01-01"+ defaultTo="2026-12-31"+ onOpen={onOpen}+ onChange={onChange}+ label="Custom"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Custom' }))++ expect(onOpen).toHaveBeenCalledTimes(1)+ expect(onChange).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-01-01', '2026-12-31')++ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })++ it('does not overwrite an already-picked range when reopened', async () => {+ const onOpen = vi.fn()+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker+ variant="segment"+ active+ from="2026-02-01"+ to="2026-02-10"+ defaultFrom="2026-01-01"+ defaultTo="2026-12-31"+ onOpen={onOpen}+ onChange={onChange}+ label="Custom"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Custom' }))++ expect(onOpen).toHaveBeenCalledTimes(1)+ // A range is already set, so the default seed must not clobber it.+ expect(onChange).not.toHaveBeenCalled()+ expect(await screen.findByText(t('transactions.filtersBar.fromLabel'))).toBeInTheDocument()+ })+})++describe('DateRangePicker — standalone button variant (regression)', () => {+ it('still renders as a bordered button with a placeholder when unset', () => {+ renderWithProviders(+ <DateRangePicker+ from=""+ to=""+ onChange={vi.fn()}+ label="Custom range"+ placeholder="Pick a range"+ />,+ )++ const trigger = screen.getByRole('button', { name: 'Custom range' })+ expect(trigger).toHaveTextContent('Pick a range')+ })++ it('confirms a picked range through Apply', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker+ from="2026-05-01"+ to="2026-05-15"+ onChange={onChange}+ label="Custom range"+ />,+ )++ await user.click(screen.getByRole('button', { name: 'Custom range' }))+ await user.click(await screen.findByRole('button', { name: t('transactions.filtersBar.apply') }))++ expect(onChange).toHaveBeenCalledWith('2026-05-01', '2026-05-15')+ })+})+++describe('DateRangePicker — draft lifecycle', () => {+ it('keeps calendar selections in draft state until Apply', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2026-05-01" to="2026-05-15"+ onChange={onChange} label="Custom" />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ // getByRole's `name` matches the whole accessible name exactly by+ // default, so no `exact` option is needed (and this type doesn't have one).+ await user.click(screen.getAllByRole('button', { name: '12' })[0])+ await user.click(screen.getAllByRole('button', { name: '8' })[1])+ expect(onChange).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-05-08', '2026-05-12')+ })++ it.each(['Cancel', 'Escape', 'outside'] as const)(+ '%s discards edits and restores committed dates on reopening', async (dismiss) => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2026-05-01" to="2026-05-15"+ onChange={onChange} label="Custom" />,+ )+ const trigger = screen.getByRole('button', { name: 'Custom' })+ await user.click(trigger)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.reset') }))+ if (dismiss === 'Cancel') {+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.cancel') }))+ } else if (dismiss === 'Escape') {+ await user.keyboard('{Escape}')+ } else {+ await user.click(document.body)+ }+ expect(onChange).not.toHaveBeenCalled()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await user.click(trigger)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-05-01', '2026-05-15')+ },+ )++ it('Reset only clears drafts; Apply commits the empty range', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2026-05-01" to="2026-05-15"+ onChange={onChange} label="Custom" />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.reset') }))+ expect(onChange).not.toHaveBeenCalled()+ const apply = screen.getByRole('button', { name: t('transactions.filtersBar.apply') })+ expect(apply).toBeEnabled()+ await user.click(apply)+ expect(onChange).toHaveBeenCalledExactlyOnceWith('', '')+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })++ it.each([+ ['2026-05-15', '2026-05-01', '2026-05-01', '2026-05-15'],+ ['2026-05-15', '', '2026-05-15', '2026-05-15'],+ ['', '2026-05-15', '2026-05-15', '2026-05-15'],+ ])('normalizes %s → %s on Apply', async (from, to, expectedFrom, expectedTo) => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from={from} to={to} onChange={onChange} label="Custom" />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ expect(onChange).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith(expectedFrom, expectedTo)+ })+})++describe('DateRangePicker — draft validation', () => {+ beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(new Date(2026, 5, 15)) // June 15, 2026+ })+ afterEach(() => vi.useRealTimers())++ it('rejects a range ending after today and disables Apply', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2026-06-01" to="2026-06-16"+ onChange={onChange} label="Custom" disallowFuture />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ expect(screen.getByText(t('transactions.filtersBar.futureDateError'))).toBeInTheDocument()+ const apply = screen.getByRole('button', { name: t('transactions.filtersBar.apply') })+ expect(apply).toBeDisabled()+ await user.click(apply)+ expect(onChange).not.toHaveBeenCalled()+ })++ it('allows a range ending exactly today', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2026-06-01" to="2026-06-15"+ onChange={onChange} label="Custom" disallowFuture />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ expect(screen.queryByText(t('transactions.filtersBar.futureDateError'))).not.toBeInTheDocument()+ const apply = screen.getByRole('button', { name: t('transactions.filtersBar.apply') })+ expect(apply).toBeEnabled()+ await user.click(apply)+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-06-01', '2026-06-15')+ })++ it('accepts the inclusive maxRangeYears boundary (the calendar-year anniversary)', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2016-01-01" to="2026-01-01"+ onChange={onChange} label="Custom" maxRangeYears={10} />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ expect(+ screen.queryByText(t('transactions.filtersBar.rangeTooWideError', { years: 10 })),+ ).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2016-01-01', '2026-01-01')+ })++ it('rejects a range one day past the maxRangeYears anniversary and disables Apply', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2016-01-01" to="2026-01-02"+ onChange={onChange} label="Custom" maxRangeYears={10} />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ expect(+ screen.getByText(t('transactions.filtersBar.rangeTooWideError', { years: 10 })),+ ).toBeInTheDocument()+ const apply = screen.getByRole('button', { name: t('transactions.filtersBar.apply') })+ expect(apply).toBeDisabled()+ await user.click(apply)+ expect(onChange).not.toHaveBeenCalled()+ })++ it('accepts a leap-day start date through its clamped (Feb 28) anniversary', async () => {+ const onChange = vi.fn()+ // date-fns's addYears clamps Feb 29 + 10y to Feb 28 (2026 isn't a leap+ // year), matching the backend's _add_years helper exactly.+ const { user } = renderWithProviders(+ <DateRangePicker from="2016-02-29" to="2026-02-28"+ onChange={onChange} label="Custom" maxRangeYears={10} />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ expect(+ screen.queryByText(t('transactions.filtersBar.rangeTooWideError', { years: 10 })),+ ).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: t('transactions.filtersBar.apply') })).toBeEnabled()+ })++ it('rejects a leap-day start date one day past its clamped anniversary', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2016-02-29" to="2026-03-01"+ onChange={onChange} label="Custom" maxRangeYears={10} />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ expect(+ screen.getByText(t('transactions.filtersBar.rangeTooWideError', { years: 10 })),+ ).toBeInTheDocument()+ expect(screen.getByRole('button', { name: t('transactions.filtersBar.apply') })).toBeDisabled()+ })++ it('normalizes a reversed draft before validating and applying', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2026-06-10" to="2026-06-01"+ onChange={onChange} label="Custom" disallowFuture maxRangeYears={5} />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ const apply = screen.getByRole('button', { name: t('transactions.filtersBar.apply') })+ expect(apply).toBeEnabled()+ await user.click(apply)+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-06-01', '2026-06-10')+ })++ it('keeps an empty draft applicable for clearing even with validation props set', async () => {+ const onChange = vi.fn()+ const { user } = renderWithProviders(+ <DateRangePicker from="2026-06-01" to="2026-06-10"+ onChange={onChange} label="Custom" disallowFuture maxRangeYears={5} />,+ )+ await user.click(screen.getByRole('button', { name: 'Custom' }))+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.reset') }))+ const apply = screen.getByRole('button', { name: t('transactions.filtersBar.apply') })+ expect(apply).toBeEnabled()+ await user.click(apply)+ expect(onChange).toHaveBeenCalledExactlyOnceWith('', '')+ })+})diff --git a/frontend/src/components/ui/date-range-picker.tsx b/frontend/src/components/ui/date-range-picker.tsxnew file mode 100644index 00000000..d6bd28ab--- /dev/null+++ b/frontend/src/components/ui/date-range-picker.tsx@@ -0,0 +1,285 @@+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { AlertCircle, Calendar as CalendarIcon } from 'lucide-react'+import { addYears } from 'date-fns'++import { Button } from '@/components/ui/button'+import { Calendar } from '@/components/ui/calendar'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'+import { cn } from '@/lib/utils'+import { localDateString } from '@/lib/date-utils'+import { formatDateRange } from '@/lib/date-range-format'+import { resolveDateFnsLocale } from '@/lib/date-fns-locale'+import { useDisplayLocale } from '@/hooks/use-display-locale'++export interface DateRangePickerProps {+ /** Inclusive start date as YYYY-MM-DD, or empty string when unset. */+ from: string+ /** Inclusive end date as YYYY-MM-DD, or empty string when unset. */+ to: string+ /** Fired when the user confirms a new range. Empty strings clear it. */+ onChange: (from: string, to: string) => void+ /** Optional label used in the trigger and popover header. */+ label?: string+ /** Extra classes applied to the trigger button. */+ className?: string+ /** Compact styling suitable for report toolbars. */+ size?: 'default' | 'sm'+ /** Trigger content when nothing is selected. */+ placeholder?: string+ /**+ * 'segment' renders the trigger as a plain segment cell (no border/icon of+ * its own) so it can sit inside a segmented control, e.g. a range-preset+ * button group, instead of appearing as a separate floating control.+ */+ variant?: 'button' | 'segment'+ /** Segment highlight state; ignored for variant 'button'. */+ active?: boolean+ /**+ * Fired as soon as the popover starts opening — before the calendar is+ * shown. This is a notification only; committed values change on Apply.+ */+ onOpen?: () => void+ /**+ * Seed the drafts when the picker opens with no committed selection.+ * Defaults are committed only when the user clicks Apply.+ */+ defaultFrom?: string+ defaultTo?: string+ /** Reject a candidate range whose (normalized) end date is after today. */+ disallowFuture?: boolean+ /**+ * Reject a candidate range whose end date is more than this many calendar+ * years after the start date (the 10-year anniversary, not a fixed day+ * count — leap days inside the window would otherwise let a day-count cap+ * drift past the intended boundary).+ */+ maxRangeYears?: number+}++/**+ * A self-contained "from → to" date picker, mirroring the popover the+ * transactions filter bar uses. Isolated so multiple pages (Reports, Assets,+ * …) can share the same interaction without duplicating state juggling.+ *+ * Deliberately independent of the transactions filter bar's rich chip UI:+ * this variant is a single trigger + popover, which is what report toolbars+ * actually need.+ */+export function DateRangePicker({+ from,+ to,+ onChange,+ label,+ className,+ size = 'sm',+ placeholder,+ variant = 'button',+ active = false,+ onOpen,+ defaultFrom,+ defaultTo,+ disallowFuture = false,+ maxRangeYears,+}: DateRangePickerProps) {+ const { t, i18n } = useTranslation()+ const dateLocale = useDisplayLocale()+ const dateFnsLocale = resolveDateFnsLocale(i18n.resolvedLanguage ?? i18n.language)+ const [open, setOpen] = useState(false)+ const [draftFrom, setDraftFrom] = useState(from)+ const [draftTo, setDraftTo] = useState(to)++ // Mirrors the Apply-time normalization (a one-sided pick mirrors into the+ // other bound; a reversed pick swaps) so validation always judges the same+ // range Apply would actually commit.+ const normalizeDraft = (f: string, toDate: string): { from: string; to: string } => {+ const nextFrom = f || toDate+ const nextTo = toDate || f+ return nextFrom && nextTo && nextFrom > nextTo+ ? { from: nextTo, to: nextFrom }+ : { from: nextFrom, to: nextTo }+ }+ const normalizedDraft = normalizeDraft(draftFrom, draftTo)++ // An empty draft is always valid — it's how Apply clears a saved range.+ const draftError = (() => {+ const { from: draftStart, to: draftEnd } = normalizedDraft+ if (!draftStart && !draftEnd) return null+ if (disallowFuture && draftEnd > localDateString()) {+ return t('transactions.filtersBar.futureDateError')+ }+ if (maxRangeYears && draftStart && draftEnd) {+ // Compare against the calendar-year anniversary of the start date,+ // not a fixed day count — a day count would let leap days inside the+ // window push the effective cap past the intended N years.+ const maxEnd = addYears(new Date(draftStart + 'T00:00:00'), maxRangeYears)+ if (new Date(draftEnd + 'T00:00:00') > maxEnd) {+ return t('transactions.filtersBar.rangeTooWideError', { years: maxRangeYears })+ }+ }+ return null+ })()++ // Reset the drafts every time the popover opens so a preset switch above+ // the picker (which mutates the controlled `from`/`to` props) doesn't+ // surface stale values the next time the user opens it. Done via the+ // Popover callback rather than an effect on props to avoid the cascading+ // renders that react-hooks/set-state-in-effect flags.+ const handleOpenChange = (next: boolean) => {+ if (next) {+ onOpen?.()+ // Seed only drafts; closing without Apply leaves the controlled range intact.+ const seedFrom = from || to ? from : defaultFrom ?? from+ const seedTo = from || to ? to : defaultTo ?? to+ setDraftFrom(seedFrom)+ setDraftTo(seedTo)+ }+ setOpen(next)+ }++ const headerLabel = label ?? t('transactions.filtersBar.customRange')+ const emptyLabel =+ placeholder ?? t('transactions.filtersBar.pickRange')+ const triggerLabel =+ from || to ? formatDateRange(from, to, dateLocale) : emptyLabel+ // Segment mode sits inline among short preset labels (6M, 1Y, …), so it+ // drops the year even across a year boundary — the same compact form the+ // transactions filter bar's applied-range chip uses. The year is still+ // visible while the calendar is open, which is the only place picking it+ // actually matters.+ const compactLabel =+ from || to ? formatDateRange(from, to, dateLocale, { compact: true }) : emptyLabel++ return (+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger asChild>+ {variant === 'segment' ? (+ <button+ type="button"+ className={cn(+ 'px-3 py-1.5 text-xs font-semibold whitespace-nowrap transition-colors',+ active+ ? 'bg-primary text-primary-foreground'+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50',+ className,+ )}+ aria-label={headerLabel}+ >+ {active ? compactLabel : (label ?? emptyLabel)}+ </button>+ ) : (+ <Button+ type="button"+ variant="outline"+ size={size}+ className={cn(+ 'gap-1.5 whitespace-nowrap font-normal',+ !(from || to) && 'text-muted-foreground',+ className,+ )}+ aria-label={headerLabel}+ >+ <CalendarIcon size={14} />+ {triggerLabel}+ </Button>+ )}+ </PopoverTrigger>+ <PopoverContent+ align="end"+ sideOffset={8}+ className="w-auto p-0"+ onOpenAutoFocus={(e) => e.preventDefault()}+ >+ <div className="border-b border-border/70 px-4 py-3">+ <p className="text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">+ {headerLabel}+ </p>+ <p className="mt-0.5 text-[11px] text-muted-foreground/70">+ {draftFrom || draftTo+ ? formatDateRange(draftFrom, draftTo, dateLocale)+ : emptyLabel}+ </p>+ </div>+ <div className="flex flex-col gap-4 p-3 sm:flex-row sm:gap-0">+ <div className="sm:border-r sm:border-border/60 sm:pr-2">+ <p className="px-2 pb-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80">+ {t('transactions.filtersBar.fromLabel')}+ </p>+ <Calendar+ selected={draftFrom ? new Date(draftFrom + 'T00:00:00') : undefined}+ defaultMonth={+ draftFrom ? new Date(draftFrom + 'T00:00:00') : new Date()+ }+ locale={dateFnsLocale}+ onSelect={(d) => setDraftFrom(d ? localDateString(d) : '')}+ />+ </div>+ <div className="sm:pl-2">+ <p className="px-2 pb-1 text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground/80">+ {t('transactions.filtersBar.toLabel')}+ </p>+ <Calendar+ selected={draftTo ? new Date(draftTo + 'T00:00:00') : undefined}+ defaultMonth={+ draftTo+ ? new Date(draftTo + 'T00:00:00')+ : draftFrom+ ? new Date(draftFrom + 'T00:00:00')+ : new Date()+ }+ locale={dateFnsLocale}+ onSelect={(d) => setDraftTo(d ? localDateString(d) : '')}+ />+ </div>+ </div>+ {draftError && (+ <div className="flex items-center gap-1.5 px-3 pb-2 text-[11px] text-rose-600 dark:text-rose-400">+ <AlertCircle size={12} className="shrink-0" />+ <span>{draftError}</span>+ </div>+ )}+ <div className="flex items-center justify-between gap-2 border-t border-border/70 px-3 py-2">+ <button+ type="button"+ onClick={() => {+ setDraftFrom('')+ setDraftTo('')+ }}+ className="text-[12px] font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ {t('transactions.filtersBar.reset')}+ </button>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={() => {+ setDraftFrom(from)+ setDraftTo(to)+ setOpen(false)+ }}+ >+ {t('transactions.filtersBar.cancel')}+ </Button>+ <Button+ type="button"+ size="sm"+ disabled={!!draftError}+ onClick={() => {+ onChange(normalizedDraft.from, normalizedDraft.to)+ setOpen(false)+ }}+ >+ {t('transactions.filtersBar.apply')}+ </Button>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ )+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 25ad3657..6e39d496 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1389,11 +1389,20 @@ export const collections = {// Reportsexport const reports = {- netWorth: async (months = 12, interval = 'monthly', accountIds?: string[], assetGroupIds?: string[], period?: 'ytd'): Promise<ReportResponse> => {+ netWorth: async (+ months = 12,+ interval = 'monthly',+ accountIds?: string[],+ assetGroupIds?: string[],+ period?: 'ytd',+ startDate?: string,+ endDate?: string,+ ): Promise<ReportResponse> => {const hasFilter = (accountIds && accountIds.length > 0) || (assetGroupIds && assetGroupIds.length > 0)const { data } = await api.get('/reports/net-worth', {params: {months, interval, period,+ ...(startDate && endDate ? { start_date: startDate, end_date: endDate } : {}),...(accountIds && accountIds.length > 0 ? { account_ids: accountIds } : {}),...(assetGroupIds && assetGroupIds.length > 0 ? { asset_group_ids: assetGroupIds } : {}),},@@ -1402,10 +1411,27 @@ export const reports = {return data},// `days` requests an exact rolling window ending today, instead of the- // month-aligned window `months` produces.- incomeExpenses: async (months = 12, interval = 'monthly', accountIds?: string[], period?: 'ytd', days?: number): Promise<ReportResponse> => {+ // month-aligned window `months` produces. `startDate`/`endDate` (both+ // required together) pin the window to an explicit calendar range and+ // override the preset selectors on the backend.+ incomeExpenses: async (+ months = 12,+ interval = 'monthly',+ accountIds?: string[],+ period?: 'ytd',+ days?: number,+ startDate?: string,+ endDate?: string,+ ): Promise<ReportResponse> => {const extra = acctIdsParam(accountIds)- const { data } = await api.get('/reports/income-expenses', { params: { months, interval, period, days, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })+ const { data } = await api.get('/reports/income-expenses', {+ params: {+ months, interval, period, days,+ ...(startDate && endDate ? { start_date: startDate, end_date: endDate } : {}),+ ...(extra.params ?? {}),+ },+ ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}),+ })return data},cashFlow: async (months = 6, interval = 'daily', baseline = false, accountIds?: string[]): Promise<ReportResponse> => {diff --git a/frontend/src/lib/date-range-format.test.ts b/frontend/src/lib/date-range-format.test.tsnew file mode 100644index 00000000..636b7026--- /dev/null+++ b/frontend/src/lib/date-range-format.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest'++import { formatDateRange } from './date-range-format'++describe('formatDateRange', () => {+ it('formats a closed range with the year by default', () => {+ expect(formatDateRange('2025-09-26', '2026-01-30', 'en-US')).toBe('Sep 26, 2025 - Jan 30, 2026')+ })++ it('drops the year in compact mode, even across a year boundary', () => {+ expect(formatDateRange('2025-09-26', '2026-01-30', 'en-US', { compact: true })).toBe(+ 'Sep 26 - Jan 30',+ )+ })++ it('formats a from-only lower bound', () => {+ expect(formatDateRange('2026-03-01', '', 'en-US')).toBe('≥ Mar 01, 2026')+ expect(formatDateRange('2026-03-01', '', 'en-US', { compact: true })).toBe('≥ Mar 01')+ })++ it('formats a to-only upper bound', () => {+ expect(formatDateRange('', '2026-03-10', 'en-US')).toBe('≤ Mar 10, 2026')+ expect(formatDateRange('', '2026-03-10', 'en-US', { compact: true })).toBe('≤ Mar 10')+ })++ it('localizes month names for the requested locale', () => {+ expect(formatDateRange('2026-03-01', '2026-03-10', 'es-ES')).toMatch(/mar\.?/i)+ })+})diff --git a/frontend/src/lib/date-range-format.ts b/frontend/src/lib/date-range-format.tsnew file mode 100644index 00000000..7da46a97--- /dev/null+++ b/frontend/src/lib/date-range-format.ts@@ -0,0 +1,29 @@+/**+ * Shared "from → to" range formatting for the transactions filter bar+ * (chip and picker trigger) and the Reports custom date-range picker. Both+ * need the same three shapes — a closed range, and each one-sided bound —+ * differing only in whether the year is shown: the full form for a trigger+ * label with room to spare, the compact form for a tight chip or an active+ * segment where the year would just add noise.+ *+ * Callers are expected to guard the fully-empty case themselves (there is no+ * sensible range label for `from === '' && to === ''`), matching how the+ * transactions filter bar and date-range picker already gate on it before+ * calling in.+ */+export function formatDateRange(+ from: string,+ to: string,+ locale: string,+ { compact = false }: { compact?: boolean } = {},+): string {+ const fmt = (iso: string) =>+ new Date(iso + 'T00:00:00').toLocaleDateString(locale, {+ day: '2-digit',+ month: 'short',+ ...(compact ? {} : { year: 'numeric' as const }),+ })+ if (from && to) return `${fmt(from)} - ${fmt(to)}`+ if (from) return `≥ ${fmt(from)}`+ return `≤ ${fmt(to)}`+}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 2f18745f..2940a990 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -781,7 +781,9 @@"thisMonth": "Diesen Monat","last90": "Letzte 90 Tage","thisYear": "Dieses Jahr"- }+ },+ "futureDateError": "Enddatum darf nicht in der Zukunft liegen",+ "rangeTooWideError": "Zeitraum ist zu groß (max. {{years}} Jahre)"},"listView": "Liste","calendarView": "Kalender",@@ -1639,7 +1641,10 @@"amount": "Betrag","investments": "Investitionen","moneyMap": "Geld-Karte",- "range30d": "30T"+ "range30d": "30T",+ "customRange": "Benutzerdefinierter Zeitraum",+ "pickCustomRange": "Start- und Enddatum wählen",+ "loadError": "Bericht konnte nicht geladen werden"},"payees": {"addFavorite": "Zu Favoriten hinzufügen",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex 9836782d..840074fe 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -959,7 +959,9 @@"thisMonth": "Αυτόν τον μήνα","last90": "Τελευταίες 90 ημέρες","thisYear": "Αυτό το έτος"- }+ },+ "futureDateError": "Η ημερομηνία λήξης δεν μπορεί να είναι μετά από σήμερα",+ "rangeTooWideError": "Το εύρος είναι πολύ μεγάλο (έως {{years}} χρόνια)"},"listView": "Λίστα","calendarView": "Ημερολόγιο",@@ -1693,7 +1695,10 @@"amount": "Ποσό","investments": "Επενδύσεις","moneyMap": "Χάρτης χρημάτων",- "range30d": "30Η"+ "range30d": "30Η",+ "customRange": "Προσαρμοσμένο εύρος",+ "pickCustomRange": "Επιλέξτε ημερομηνία έναρξης και λήξης",+ "loadError": "Αποτυχία φόρτωσης αναφοράς"},"fiscal": {"kind": {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex d51db3f2..bcfd3a13 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -781,7 +781,9 @@"thisMonth": "This month","last90": "Last 90 days","thisYear": "This year"- }+ },+ "futureDateError": "End date can't be after today",+ "rangeTooWideError": "Range is too wide (max {{years}} years)"},"listView": "List","calendarView": "Calendar",@@ -1638,7 +1640,10 @@"amount": "Amount","investments": "Investments","moneyMap": "Money Map",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Custom range",+ "pickCustomRange": "Pick a start and end date",+ "loadError": "Failed to load report"},"payees": {"addFavorite": "Add to favorites",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 3480afd2..1e58aea7 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -777,7 +777,9 @@"thisMonth": "Este mes","last90": "Últimos 90 días","thisYear": "Este año"- }+ },+ "futureDateError": "La fecha de fin no puede ser posterior a hoy",+ "rangeTooWideError": "El rango es demasiado amplio (máx. {{years}} años)"},"bulkAddTags": "Añadir etiquetas","bulkRemoveTags": "Eliminar etiquetas",@@ -1639,7 +1641,10 @@"amount": "Importe","investments": "Inversiones","moneyMap": "Mapa del Dinero",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Rango personalizado",+ "pickCustomRange": "Elige una fecha de inicio y fin",+ "loadError": "No se pudo cargar el informe"},"payees": {"addFavorite": "Añadir a favoritos",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex d72897cb..fc10f3cb 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -781,7 +781,9 @@"thisMonth": "Ce mois-ci","last90": "90 derniers jours","thisYear": "Cette année"- }+ },+ "futureDateError": "La date de fin ne peut pas être postérieure à aujourd'hui",+ "rangeTooWideError": "La période est trop large (max. {{years}} ans)"},"listView": "Liste","calendarView": "Calendrier",@@ -1639,7 +1641,10 @@"amount": "Montant","investments": "Investissements","moneyMap": "Carte de l'argent",- "range30d": "30J"+ "range30d": "30J",+ "customRange": "Plage personnalisée",+ "pickCustomRange": "Choisir une date de début et de fin",+ "loadError": "Échec du chargement du rapport"},"payees": {"addFavorite": "Ajouter aux favoris",diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex 87cd4e9c..c8f9a878 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -781,7 +781,9 @@"thisMonth": "इस महीने","last90": "पिछले 90 दिन","thisYear": "इस साल"- }+ },+ "futureDateError": "समाप्ति तिथि आज के बाद नहीं हो सकती",+ "rangeTooWideError": "सीमा बहुत बड़ी है (अधिकतम {{years}} वर्ष)"},"listView": "सूची","calendarView": "कैलेंडर",@@ -1638,7 +1640,10 @@"amount": "राशि","investments": "निवेश","moneyMap": "मनी मैप",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "कस्टम सीमा",+ "pickCustomRange": "प्रारंभ और समाप्ति तिथि चुनें",+ "loadError": "रिपोर्ट लोड करने में विफल"},"payees": {"addFavorite": "पसंदीदा में जोड़ें",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 1b1efdd4..15798eba 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -777,7 +777,9 @@"thisMonth": "Questo mese","last90": "Ultimi 90 giorni","thisYear": "Quest'anno"- }+ },+ "futureDateError": "La data di fine non può essere successiva a oggi",+ "rangeTooWideError": "L'intervallo è troppo ampio (max {{years}} anni)"},"bulkAddTags": "Aggiungi tag","bulkRemoveTags": "Rimuovi tag",@@ -1639,7 +1641,10 @@"amount": "Importo","investments": "Investimenti","moneyMap": "Mappa del Denaro",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Intervallo personalizzato",+ "pickCustomRange": "Scegli una data di inizio e fine",+ "loadError": "Impossibile caricare il report"},"payees": {"addFavorite": "Aggiungi ai preferiti",diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex 046853c6..f929202a 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -781,7 +781,9 @@"thisMonth": "今月","last90": "過去90日間","thisYear": "今年"- }+ },+ "futureDateError": "終了日は今日より後の日付にできません",+ "rangeTooWideError": "範囲が広すぎます(最大{{years}}年)"},"listView": "リスト","calendarView": "カレンダー",@@ -1638,7 +1640,10 @@"amount": "金額","investments": "投資","moneyMap": "マネーマップ",- "range30d": "30日"+ "range30d": "30日",+ "customRange": "期間を指定",+ "pickCustomRange": "開始日と終了日を選択",+ "loadError": "レポートの読み込みに失敗しました"},"payees": {"addFavorite": "お気に入りに追加",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex c3266613..6d346935 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -781,7 +781,9 @@"thisMonth": "Deze maand","last90": "Laatste 90 dagen","thisYear": "Dit jaar"- }+ },+ "futureDateError": "Einddatum mag niet na vandaag liggen",+ "rangeTooWideError": "Bereik is te breed (max. {{years}} jaar)"},"listView": "Lijst","calendarView": "Kalender",@@ -1640,7 +1642,10 @@"amount": "Bedrag","investments": "Investeringen","moneyMap": "Geld kaart",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Aangepast bereik",+ "pickCustomRange": "Kies een start- en einddatum",+ "loadError": "Rapport laden mislukt"},"payees": {"addFavorite": "Toevoegen aan favorieten",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 6dff588d..b98b128f 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -814,7 +814,9 @@"thisMonth": "Bieżący miesiąc","last90": "Ostatnie 90 dni","thisYear": "Bieżący rok"- }+ },+ "futureDateError": "Data końcowa nie może przypadać po dzisiejszej dacie",+ "rangeTooWideError": "Zakres jest zbyt szeroki (maks. {{years}} lat)"},"bulkAddTags": "Dodaj tagi","bulkRemoveTags": "Usuń tagi",@@ -1723,7 +1725,10 @@"amount": "Kwota","investments": "Inwestycje","moneyMap": "Mapa Pieniędzy",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Zakres niestandardowy",+ "pickCustomRange": "Wybierz datę początkową i końcową",+ "loadError": "Nie udało się załadować raportu"},"payees": {"addFavorite": "Dodaj do ulubionych",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex afccb735..ea26f4d5 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -777,7 +777,9 @@"thisMonth": "Este mês","last90": "Últimos 90 dias","thisYear": "Este ano"- }+ },+ "futureDateError": "A data final não pode ser posterior a hoje",+ "rangeTooWideError": "O intervalo é muito amplo (máx. {{years}} anos)"},"bulkAddTags": "Adicionar tags","bulkRemoveTags": "Remover tags",@@ -1639,7 +1641,10 @@"amount": "Valor","investments": "Investimentos","moneyMap": "Mapa do Dinheiro",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Período personalizado",+ "pickCustomRange": "Escolha uma data inicial e final",+ "loadError": "Falha ao carregar o relatório"},"payees": {"addFavorite": "Adicionar aos favoritos",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex fbf1bb29..553a9049 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -777,7 +777,9 @@"thisMonth": "Este mês","last90": "Últimos 90 dias","thisYear": "Este ano"- }+ },+ "futureDateError": "A data final não pode ser posterior a hoje",+ "rangeTooWideError": "O intervalo é demasiado amplo (máx. {{years}} anos)"},"listView": "Lista","calendarView": "Calendário",@@ -1639,7 +1641,10 @@"amount": "Valor","investments": "Investimentos","moneyMap": "Mapa do Dinheiro",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Período personalizado",+ "pickCustomRange": "Escolha uma data inicial e final",+ "loadError": "Falha ao carregar o relatório"},"payees": {"addFavorite": "Adicionar aos favoritos",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 4fb290a2..138575ac 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -791,7 +791,9 @@"thisMonth": "Этот месяц","last90": "Последние 90 дней","thisYear": "Этот год"- }+ },+ "futureDateError": "Дата окончания не может быть позже сегодняшнего дня",+ "rangeTooWideError": "Диапазон слишком широкий (макс. {{years}} лет)"},"listView": "Список","calendarView": "Календарь",@@ -1651,7 +1653,10 @@"amount": "Сумма","investments": "Инвестиции","moneyMap": "Money Map",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Произвольный диапазон",+ "pickCustomRange": "Выберите дату начала и конца",+ "loadError": "Не удалось загрузить отчёт"},"payees": {"addFavorite": "Добавить в избранное",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 16e625b9..6b7314a4 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -829,7 +829,9 @@"thisMonth": "Tento mesiac","last90": "Posledných 90 dní","thisYear": "Tento rok"- }+ },+ "futureDateError": "Dátum konca nemôže byť neskôr ako dnes",+ "rangeTooWideError": "Rozsah je príliš široký (max. {{years}} rokov)"},"listView": "Zoznam","calendarView": "Kalendár",@@ -1750,7 +1752,10 @@"amount": "Suma","investments": "Investície","moneyMap": "Mapa peňazí",- "range30d": "30D"+ "range30d": "30D",+ "customRange": "Vlastný rozsah",+ "pickCustomRange": "Vyberte dátum začiatku a konca",+ "loadError": "Nepodarilo sa načítať prehľad"},"payees": {"addFavorite": "Pridať do obľúbených",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 92be82f3..1561c2b1 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -791,7 +791,9 @@"thisMonth": "Цей місяць","last90": "Останні 90 днів","thisYear": "Цей рік"- }+ },+ "futureDateError": "Дата завершення не може бути пізніше сьогодні",+ "rangeTooWideError": "Діапазон надто широкий (макс. {{years}} років)"},"listView": "Список","calendarView": "Календар",@@ -1651,7 +1653,10 @@"amount": "Сума","investments": "Інвестиції","moneyMap": "Money Map",- "range30d": "30Д"+ "range30d": "30Д",+ "customRange": "Довільний діапазон",+ "pickCustomRange": "Виберіть дату початку та кінця",+ "loadError": "Не вдалося завантажити звіт"},"payees": {"addFavorite": "Додати до обраного",diff --git a/frontend/src/pages/reports.test.tsx b/frontend/src/pages/reports.test.tsxnew file mode 100644index 00000000..9ece384f--- /dev/null+++ b/frontend/src/pages/reports.test.tsx@@ -0,0 +1,240 @@+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'+import { screen, waitFor } from '@testing-library/react'++import ReportsPage from '@/pages/reports'+import { renderWithProviders, t } from '@/test/utils'+import type { ReportResponse } from '@/types'++const api = vi.hoisted(() => ({+ reports: {+ netWorth: vi.fn(),+ incomeExpenses: vi.fn(),+ cashFlow: vi.fn(),+ },+}))++vi.mock('@/lib/api', () => ({ reports: api.reports }))++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++vi.mock('@/contexts/auth-context', () => ({+ useAuth: () => ({ user: { preferences: { currency_display: 'USD' } } }),+}))++vi.mock('@/contexts/collection-filter-context', () => ({+ useCollectionFilter: () => ({ activeAccountIds: null, activeWalletIds: null }),+}))++vi.mock('@/hooks/use-privacy-mode', () => ({+ usePrivacyMode: () => ({ mask: (value: string) => value, privacyMode: false, MASK: '••••' }),+}))++function emptyReport(type: string): ReportResponse {+ return {+ summary: { primary_value: 1000, change_amount: 100, change_percent: 5, breakdowns: [] },+ trend: [{ date: '2026-01-01', value: 1000, breakdowns: {}, change: null }],+ meta: { type, series_keys: [], currency: 'USD', interval: 'monthly' },+ composition: [],+ category_trend: [],+ }+}++beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(new Date(2026, 8, 12, 12))+ vi.clearAllMocks()+ api.reports.netWorth.mockResolvedValue(emptyReport('net_worth'))+ api.reports.incomeExpenses.mockResolvedValue(emptyReport('income_expenses'))+ api.reports.cashFlow.mockResolvedValue(emptyReport('cash_flow'))+})++afterEach(() => vi.useRealTimers())++describe('Reports page — Custom range segment', () => {+ it('loads the Net Worth tab with the 1Y preset by default', async () => {+ renderWithProviders(<ReportsPage />)++ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalled())+ const [, , , , , startDate, endDate] = api.reports.netWorth.mock.calls[0]+ expect(startDate).toBeUndefined()+ expect(endDate).toBeUndefined()+ })++ it('opening Custom waits for Apply before querying January 1 through today', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalledTimes(1))++ await user.click(screen.getByRole('button', { name: t('reports.customRange') }))++ expect(api.reports.netWorth).toHaveBeenCalledTimes(1)+ expect(screen.getByRole('button', { name: t('reports.range1y') })).toHaveClass('bg-primary')+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ const year = 2026+ await waitFor(() => {+ const last = api.reports.netWorth.mock.calls.at(-1)!+ expect(last[5]).toBe(`${year}-01-01`)+ expect(last[6]).toBe('2026-09-12')+ })++ // The segment itself now displays the picked range instead of "Custom+ // range" — in the same compact, year-less form as the transactions+ // filter bar's applied-range chip.+ const fmt = (iso: string) =>+ new Date(`${iso}T00:00:00`).toLocaleDateString('en-US', {+ day: '2-digit',+ month: 'short',+ })+ expect(+ screen.getByRole('button', { name: t('reports.customRange') }),+ ).toHaveTextContent(`${fmt(`${year}-01-01`)} - ${fmt('2026-09-12')}`)+ })++ it('is not offered on the Cash Flow tab', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalled())++ await user.click(screen.getByRole('button', { name: t('reports.cashFlow') }))++ await waitFor(() => expect(api.reports.cashFlow).toHaveBeenCalled())+ expect(screen.queryByRole('button', { name: t('reports.customRange') })).not.toBeInTheDocument()+ })+})+++it.each(['Cancel', 'Escape', 'outside'] as const)(+ '6M → Custom → %s leaves the preset and query unchanged', async (dismiss) => {+ const { user } = renderWithProviders(<ReportsPage />)+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalledTimes(1))+ const preset = screen.getByRole('button', { name: t('reports.range6m') })+ await user.click(preset)+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalledTimes(2))+ await user.click(screen.getByRole('button', { name: t('reports.customRange') }))+ if (dismiss === 'Cancel') {+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.cancel') }))+ } else if (dismiss === 'Escape') {+ await user.keyboard('{Escape}')+ } else {+ await user.click(document.body)+ }+ expect(preset).toHaveClass('bg-primary')+ expect(api.reports.netWorth).toHaveBeenCalledTimes(2)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: t('reports.customRange') }))+ expect(api.reports.netWorth).toHaveBeenCalledTimes(2)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalledTimes(3))+ },+)++it.each([+ ['reports.netWorth', 'reports.range1y', 12],+ ['reports.incomeExpenses', 'reports.range1y', 12],+ ['reports.moneyMap', 'reports.range3m', 3],+] as const)('Reset then Apply restores the fallback for %s', async (tab, fallback, months) => {+ const { user } = renderWithProviders(<ReportsPage />)+ if (tab !== 'reports.netWorth') {+ await user.click(screen.getByRole('button', { name: t(tab) }))+ }+ const custom = screen.getByRole('button', { name: t('reports.customRange') })+ await user.click(custom)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ const reportApi = tab === 'reports.netWorth' ? api.reports.netWorth : api.reports.incomeExpenses+ await waitFor(() => expect(reportApi.mock.calls.at(-1)?.slice(-2)).toEqual([+ '2026-01-01', '2026-09-12',+ ]))+ await user.click(custom)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.reset') }))+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ await waitFor(() => {+ expect(screen.getByRole('button', { name: t(fallback) })).toHaveClass('bg-primary')+ expect(reportApi.mock.calls.at(-1)?.[0]).toBe(months)+ expect(reportApi.mock.calls.at(-1)?.slice(-2)).toEqual([undefined, undefined])+ })+ expect(custom).toHaveTextContent(t('reports.customRange'))+})++it('preserves saved custom dates across supported tabs and preset dismissal', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ const custom = screen.getByRole('button', { name: t('reports.customRange') })+ await user.click(custom)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ for (const tab of ['reports.incomeExpenses', 'reports.moneyMap']) {+ await user.click(screen.getByRole('button', { name: t(tab) }))+ await waitFor(() => expect(api.reports.incomeExpenses.mock.calls.at(-1)?.slice(-2))+ .toEqual(['2026-01-01', '2026-09-12']))+ expect(custom).toHaveClass('bg-primary')+ }+ await user.click(screen.getByRole('button', { name: t('reports.range6m') }))+ await waitFor(() => expect(api.reports.incomeExpenses.mock.calls.at(-1)?.slice(-2))+ .toEqual([undefined, undefined]))+ const count = api.reports.incomeExpenses.mock.calls.length+ await user.click(custom)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.reset') }))+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.cancel') }))+ expect(api.reports.incomeExpenses).toHaveBeenCalledTimes(count)+ expect(screen.getByRole('button', { name: t('reports.range6m') })).toHaveClass('bg-primary')+ await user.click(custom)+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ await waitFor(() => expect(api.reports.incomeExpenses.mock.calls.at(-1)?.slice(-2))+ .toEqual(['2026-01-01', '2026-09-12']))+ await user.click(screen.getByRole('button', { name: t('reports.cashFlow') }))+ await waitFor(() => expect(api.reports.cashFlow).toHaveBeenCalled())+ expect(screen.queryByRole('button', { name: t('reports.customRange') })).not.toBeInTheDocument()+ expect(api.reports.cashFlow.mock.calls.at(-1)?.[0]).toBe(6)+ await user.click(screen.getByRole('button', { name: t('reports.netWorth') }))+ await user.click(screen.getByRole('button', { name: t('reports.customRange') }))+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ await waitFor(() => expect(api.reports.netWorth.mock.calls.at(-1)?.slice(-2))+ .toEqual(['2026-01-01', '2026-09-12']))+})++describe('Reports page — query failure', () => {+ it('surfaces a rejected custom range instead of showing stale numbers', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalledTimes(1))++ api.reports.netWorth.mockRejectedValueOnce({+ response: { data: { detail: 'Custom range is too wide (max 10 years)' } },+ })+ await user.click(screen.getByRole('button', { name: t('reports.customRange') }))+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))++ expect(await screen.findByText('Custom range is too wide (max 10 years)')).toBeInTheDocument()+ // The prior successful report must not linger under the error.+ expect(screen.queryByText(t('reports.trend'), { exact: false })).not.toBeInTheDocument()+ // Tabs and range controls stay usable so the user can correct the request.+ expect(screen.getByRole('button', { name: t('reports.range1y') })).toBeInTheDocument()+ })++ it('shows a generic fallback for a network failure and recovers via Retry', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalledTimes(1))++ api.reports.netWorth.mockRejectedValueOnce(new Error('network error'))+ await user.click(screen.getByRole('button', { name: t('reports.range6m') }))++ expect(await screen.findByText(t('reports.loadError'))).toBeInTheDocument()++ api.reports.netWorth.mockResolvedValueOnce(emptyReport('net_worth'))+ await user.click(screen.getByRole('button', { name: t('common.retry') }))++ await waitFor(() => expect(screen.queryByText(t('reports.loadError'))).not.toBeInTheDocument())+ })++ it('recovers by changing the range after a rejected selection', async () => {+ const { user } = renderWithProviders(<ReportsPage />)+ await waitFor(() => expect(api.reports.netWorth).toHaveBeenCalledTimes(1))++ api.reports.netWorth.mockRejectedValueOnce({ response: { data: { detail: 'end_date must be on or before today' } } })+ await user.click(screen.getByRole('button', { name: t('reports.customRange') }))+ await user.click(screen.getByRole('button', { name: t('transactions.filtersBar.apply') }))+ expect(await screen.findByText('end_date must be on or before today')).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: t('reports.range6m') }))+ await waitFor(() => expect(screen.queryByText('end_date must be on or before today')).not.toBeInTheDocument())+ expect(screen.getByRole('button', { name: t('reports.range6m') })).toHaveClass('bg-primary')+ })+})diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex 9b713df5..35ff1753 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -18,10 +18,12 @@ import {ReferenceLine,ResponsiveContainer,} from 'recharts'-import { HelpCircle, X } from 'lucide-react'+import { AlertCircle, HelpCircle, X } from 'lucide-react'import { reports } from '@/lib/api'+import { extractApiError } from '@/lib/api-errors'import { Skeleton } from '@/components/ui/skeleton'import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'+import { DateRangePicker } from '@/components/ui/date-range-picker'import { PageHeader } from '@/components/page-header'import { CashflowSankey } from '@/components/reports/CashflowSankey'import { usePrivacyMode } from '@/hooks/use-privacy-mode'@@ -29,6 +31,7 @@ import { useAuth } from '@/contexts/auth-context'import { useCollectionFilter } from '@/contexts/collection-filter-context'import type { ReportResponse, CategoryTrendItem } from '@/types'import { formatCurrency } from '@/lib/format'+import { localDateString } from '@/lib/date-utils'// A small qualitative palette of well-separated hues for the composition// detail ring. Capped to a handful of slices, distinct colours make each@@ -116,19 +119,60 @@ const RANGE_LABELS: Record<string, string> = {ytd: 'rangeYtd','12m': 'range12m','2y': 'range2y',+ custom: 'customRange',+}++// Sentinel key for the "custom range" preset. Kept out of the preset arrays+// above so we can decide per-tab whether it's actually offered (cash flow,+// which is a forecast, still uses forward-only presets).+const CUSTOM_RANGE_KEY = 'custom'++// Mirrors the backend's `_MAX_CUSTOM_RANGE_YEARS` (backend/app/api/reports.py)+// so a too-wide pick is rejected in the picker instead of round-tripping to+// the API for the same 422. A calendar-year anniversary, not a fixed day+// count, so leap days inside the window can't push the cap past 10 years.+const CUSTOM_RANGE_MAX_YEARS = 10++// Seed a historical draft from January 1 through today; Apply commits it.+function defaultCustomRange(): { from: string; to: string } {+ const today = new Date()+ return { from: `${today.getFullYear()}-01-01`, to: localDateString(today) }}interface ReportTab {key: stringlabelKey: stringenabled: boolean+ rangeOptions: readonly RangeOption[]+ intervalOptions: readonly { key: string; value: string }[]+ /** Cash flow is a forward-only forecast, so it's the only tab that can't offer a past-only calendar range. */+ supportsCustomRange: boolean+ /** Preset selected when switching to this tab drops the current preset, or when Reset+Apply clears a custom range on it. */+ fallbackRangeKey: string+ fallbackInterval: string}const REPORT_TABS: ReportTab[] = [- { key: 'net_worth', labelKey: 'reports.netWorth', enabled: true },- { key: 'income_expenses', labelKey: 'reports.incomeExpenses', enabled: true },- { key: 'cash_flow', labelKey: 'reports.cashFlow', enabled: true },- { key: 'money_map', labelKey: 'reports.moneyMap', enabled: true },+ {+ key: 'net_worth', labelKey: 'reports.netWorth', enabled: true,+ rangeOptions: HISTORICAL_RANGE_OPTIONS, intervalOptions: HISTORICAL_INTERVAL_OPTIONS,+ supportsCustomRange: true, fallbackRangeKey: '1y', fallbackInterval: 'monthly',+ },+ {+ key: 'income_expenses', labelKey: 'reports.incomeExpenses', enabled: true,+ rangeOptions: HISTORICAL_RANGE_OPTIONS, intervalOptions: HISTORICAL_INTERVAL_OPTIONS,+ supportsCustomRange: true, fallbackRangeKey: '1y', fallbackInterval: 'monthly',+ },+ {+ key: 'cash_flow', labelKey: 'reports.cashFlow', enabled: true,+ rangeOptions: FORWARD_RANGE_OPTIONS, intervalOptions: CASH_FLOW_INTERVAL_OPTIONS,+ supportsCustomRange: false, fallbackRangeKey: '6m', fallbackInterval: 'daily',+ },+ {+ key: 'money_map', labelKey: 'reports.moneyMap', enabled: true,+ rangeOptions: MONEY_MAP_RANGE_OPTIONS, intervalOptions: HISTORICAL_INTERVAL_OPTIONS,+ supportsCustomRange: true, fallbackRangeKey: '3m', fallbackInterval: 'monthly',+ },]export default function ReportsPage() {@@ -138,8 +182,15 @@ export default function ReportsPage() {const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = useDisplayLocale()+ const customDefaults = defaultCustomRange()const [rangeKey, setRangeKey] = useState('1y')const [interval, setInterval] = useState('monthly')+ // 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 [compositionView, setCompositionView] = useState<string>('netWorth')const [sparklineView, setSparklineView] = useState<'byExpenses' | 'byIncome'>('byExpenses')@@ -162,46 +213,65 @@ export default function ReportsPage() {// The Money Map (Sankey) tab is driven by the same income/expenses// composition, aggregated over the selected historical range.const isMoneyMap = activeTab === 'money_map'- const rangeOptions = isCashFlow- ? FORWARD_RANGE_OPTIONS- : isMoneyMap- ? MONEY_MAP_RANGE_OPTIONS- : HISTORICAL_RANGE_OPTIONS- const intervalOptions = isCashFlow ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONS+ const rangeOptions = currentTab.rangeOptions+ // Cash flow's forecast presets don't make sense with a past-only calendar+ // range, so custom is only offered for the historical tabs (Net Worth,+ // Income vs Expenses, Money Map).+ const supportsCustomRange = currentTab.supportsCustomRange+ const intervalOptions = currentTab.intervalOptions+ const isCustomRange = supportsCustomRange && rangeKey === CUSTOM_RANGE_KEY+ const hasCustomRange = isCustomRange && !!customFrom && !!customToconst selectedRange = rangeOptions.find((r) => r.key === rangeKey) ?? rangeOptions[0]- const months = selectedRange.months- const period = selectedRange.period- const days = selectedRange.days+ // 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.+ const customMonths = hasCustomRange+ ? Math.max(+ 1,+ Math.min(+ 24,+ Math.ceil(+ (new Date(customTo + 'T00:00:00').getTime() -+ new Date(customFrom + 'T00:00:00').getTime()) /+ (1000 * 60 * 60 * 24 * 30),+ ),+ ),+ )+ : 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 : undefinedconst handleSelectTab = (key: string) => {+ const nextTab = REPORT_TABS.find((tab) => tab.key === key) ?? REPORT_TABS[0]setActiveTab(key)setCompositionView(key === 'net_worth' ? 'netWorth' : 'net')setSparklinePage(0)setSelectedDate(null)- // Clamp months/interval to options supported by the new tab- const nextRanges = key === 'cash_flow'- ? FORWARD_RANGE_OPTIONS- : key === 'money_map'- ? MONEY_MAP_RANGE_OPTIONS- : HISTORICAL_RANGE_OPTIONS- if (!nextRanges.some((r) => r.key === rangeKey)) {- setRangeKey(key === 'cash_flow' ? '6m' : key === 'money_map' ? '3m' : '1y')+ // Clamp the range/interval preset to what the new tab supports.+ const stillValid =+ (rangeKey === CUSTOM_RANGE_KEY && nextTab.supportsCustomRange) ||+ nextTab.rangeOptions.some((r) => r.key === rangeKey)+ if (!stillValid) {+ setRangeKey(nextTab.fallbackRangeKey)}- const nextIntervals = key === 'cash_flow' ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONS- if (!nextIntervals.some((i) => i.value === interval)) {- setInterval(key === 'cash_flow' ? 'daily' : 'monthly')+ if (!nextTab.intervalOptions.some((i) => i.value === interval)) {+ setInterval(nextTab.fallbackInterval)}}- const { data, isLoading } = useQuery<ReportResponse>({- queryKey: ['reports', activeTab, rangeKey, months, period ?? null, days ?? null, interval, isCashFlow ? cashFlowBaseline : false, activeAccountIds, activeWalletIds],+ 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: () =>isCashFlow? reports.cashFlow(months, interval, cashFlowBaseline, acctIds): activeTab === 'income_expenses' || isMoneyMap- ? reports.incomeExpenses(months, interval, acctIds, period, days)- : reports.netWorth(months, interval, acctIds, walletIds, period),- enabled: currentTab.enabled && !(noAccounts && activeTab !== 'net_worth'),+ ? reports.incomeExpenses(months, interval, acctIds, period, days, apiStart, apiEnd)+ : reports.netWorth(months, interval, acctIds, walletIds, period, apiStart, apiEnd),+ // Only request a custom report with both committed endpoints.+ enabled: currentTab.enabled && !(noAccounts && activeTab !== 'net_worth') && (!isCustomRange || hasCustomRange),})const summary = data?.summary@@ -510,6 +580,26 @@ export default function ReportsPage() {{t(`reports.${RANGE_LABELS[opt.key]}`)}</button>))}+ {supportsCustomRange && (+ <DateRangePicker+ variant="segment"+ active={isCustomRange}+ from={customFrom}+ to={customTo}+ defaultFrom={customDefaults.from}+ defaultTo={customDefaults.to}+ disallowFuture+ maxRangeYears={CUSTOM_RANGE_MAX_YEARS}+ onChange={(f, to) => {+ setCustomFrom(f)+ setCustomTo(to)+ setRangeKey(f && to ? CUSTOM_RANGE_KEY : currentTab.fallbackRangeKey)+ setSelectedDate(null)+ }}+ label={t('reports.customRange')}+ placeholder={t('reports.pickCustomRange')}+ />+ )}</div><div className={`flex items-center rounded-lg border border-border bg-card overflow-hidden ${isMoneyMap ? 'hidden' : ''}`}>{intervalOptions.map((opt) => (@@ -558,6 +648,26 @@ export default function ReportsPage() {))}</div>+ {isError && (+ <div className="flex items-center justify-between gap-3 bg-rose-50 dark:bg-rose-500/10 border border-rose-200 dark:border-rose-500/30 rounded-lg px-4 py-2.5 mb-5">+ <div className="flex items-center gap-2.5 min-w-0">+ <AlertCircle size={16} className="shrink-0 text-rose-600 dark:text-rose-400" />+ <span className="text-sm text-rose-900 dark:text-rose-200 truncate">+ {extractApiError(error, t('reports.loadError'))}+ </span>+ </div>+ <button+ type="button"+ onClick={() => refetch()}+ className="shrink-0 text-sm font-semibold text-rose-600 dark:text-rose-400 hover:underline"+ >+ {t('common.retry')}+ </button>+ </div>+ )}++ {!isError && (+ <>{/* Hero Card */}<div className="bg-card rounded-xl border border-border shadow-sm mb-5"><div className="px-5 py-4">@@ -1456,6 +1566,8 @@ export default function ReportsPage() {</div></>)}+ </>+ )}</div>)}