Skip to content

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

feat(dashboard): compare balance evolution against selectable months (#1155)

Christian Segercrantz073a6a3ea1fa
diff --git a/backend/app/api/dashboard.py b/backend/app/api/dashboard.py
index e19c22a7..ae7bb379 100644
--- a/backend/app/api/dashboard.py
+++ b/backend/app/api/dashboard.py
@@ -2,7 +2,7 @@ import uuid
from datetime import date
from typing import Optional
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_async_session
@@ -55,12 +55,27 @@ async def get_monthly_trend(
@router.get("/balance-history", response_model=BalanceHistory)
async def get_balance_history(
month: Optional[date] = Query(None),
+ account_ids: Optional[list[uuid.UUID]] = Query(None),
+ comparison_months: Optional[list[date]] = Query(None),
+ ctx: WorkspaceContext = Depends(current_workspace),
+ session: AsyncSession = Depends(get_async_session),
+) -> BalanceHistory:
+ try:
+ return await dashboard_service.get_balance_history(
+ session, ctx.workspace.id, ctx.user_id, month, account_ids, comparison_months
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
+
+
[email protected]("/balance-history/months", response_model=list[str])
+async def get_balance_history_months(
account_ids: Optional[list[uuid.UUID]] = Query(None),
ctx: WorkspaceContext = Depends(current_workspace),
session: AsyncSession = Depends(get_async_session),
):
- return await dashboard_service.get_balance_history(
- session, ctx.workspace.id, ctx.user_id, month, account_ids
+ return await dashboard_service.get_balance_history_months(
+ session, ctx.workspace.id, account_ids
)
diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.py
index 16e8a675..786a97f2 100644
--- a/backend/app/schemas/dashboard.py
+++ b/backend/app/schemas/dashboard.py
@@ -6,7 +6,9 @@ from pydantic import BaseModel, Field
class DashboardSummary(BaseModel):
total_balance: dict[str, float] # currency -> amount
total_balance_primary: float = 0.0 # consolidated in primary currency
- projected_balance: dict[str, float] = Field(default_factory=dict) # current balance plus forecast rows
+ projected_balance: dict[str, float] = Field(
+ default_factory=dict
+ ) # current balance plus forecast rows
projected_balance_primary: float = 0.0 # consolidated projected balance
balance_date: str # ISO date string, e.g. "2026-03-02"
monthly_income: float
@@ -58,9 +60,20 @@ class DailyBalance(BaseModel):
balance: Optional[float] # None for future days beyond cutoff
+class DailyBaseline(BaseModel):
+ day: int
+ median: Optional[float] = None # None when fewer than 2 months contribute
+ lower_quartile: Optional[float] = None # None when fewer than 3 contribute
+ upper_quartile: Optional[float] = None # None when fewer than 3 contribute
+
+
class BalanceHistory(BaseModel):
current: list[DailyBalance]
- previous: list[DailyBalance]
+ opening_balance: float
+ baseline: list[DailyBaseline] # cumulative change since month opening
+ comparison: Optional[list[DailyBalance]] = None
+ comparison_month: Optional[str] = None
+ comparison_opening_balance: Optional[float] = None
class ProjectedTransaction(BaseModel):
diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py
index 35281348..1638f0fb 100644
--- a/backend/app/services/dashboard_service.py
+++ b/backend/app/services/dashboard_service.py
@@ -3,7 +3,7 @@ from datetime import date, timedelta
from decimal import Decimal
from typing import Optional
-from sqlalchemy import select, func, case, or_
+from sqlalchemy import and_, select, func, case, extract, or_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
@@ -14,7 +14,7 @@ from app.models.bank_connection import BankConnection
from app.models.transaction import Transaction
from app.models.category import Category
from app.models.recurring_transaction import RecurringTransaction
-from app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, DailyBalance, BalanceHistory
+from app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, DailyBalance, DailyBaseline, BalanceHistory
from app.services._query_filters import (
counts_as_user_pnl,
owner_split_offset_by_category,
@@ -30,6 +30,10 @@ from app.services.asset_service import get_asset_values_at
from app.services.fx_rate_service import _resolve_rate, convert
from app.models.user import User
+BASELINE_MONTHS = 12
+BASELINE_MIN_MONTHS = 3
+_TAIL_ANCHOR = 27
+
def _month_range(month: date) -> tuple[date, date]:
"""Return (month_start, month_end) for a given date."""
@@ -1521,6 +1525,8 @@ async def _daily_balance_deltas_by_date(
primary_currency_hint: Optional[str] = None,
account_ids: Optional[list[uuid.UUID]] = None,
include_pending: bool = False,
+ exclude_opening_balance: bool = False,
+ month_starts: Optional[list[date]] = None,
) -> dict[date, float]:
"""Get daily balance deltas for a date range [start, end), keyed by date.
@@ -1538,6 +1544,22 @@ async def _daily_balance_deltas_by_date(
else_=-effective,
)
status_filter = [] if include_pending else [Transaction.status == "posted"]
+ if month_starts is not None and not month_starts:
+ return {}
+
+ date_filters = (
+ [
+ or_(*[
+ and_(
+ Transaction.date >= month_start.replace(day=1),
+ Transaction.date < _month_range(month_start)[1],
+ )
+ for month_start in month_starts
+ ])
+ ]
+ if month_starts is not None
+ else [Transaction.date >= start, Transaction.date < end]
+ )
result = await session.execute(
select(
Transaction.date,
@@ -1549,11 +1571,11 @@ async def _daily_balance_deltas_by_date(
.where(
Transaction.workspace_id == workspace_id,
Account.is_closed == False,
- Transaction.date >= start,
- Transaction.date < end,
+ *date_filters,
Transaction.date <= app_today(),
Transaction.is_ignored == False,
*status_filter,
+ *([Transaction.source != "opening_balance"] if exclude_opening_balance else []),
or_(
Transaction.category_id.is_(None),
Category.is_ignored == False,
@@ -1583,6 +1605,7 @@ async def _daily_deltas(
primary_currency_hint: Optional[str] = None,
account_ids: Optional[list[uuid.UUID]] = None,
include_pending: bool = False,
+ exclude_opening_balance: bool = False,
) -> dict[int, float]:
"""Get daily balance deltas for a date range [start, end), keyed by day-of-month."""
by_date = await _daily_balance_deltas_by_date(
@@ -1593,31 +1616,156 @@ async def _daily_deltas(
primary_currency_hint=primary_currency_hint,
account_ids=account_ids,
include_pending=include_pending,
+ exclude_opening_balance=exclude_opening_balance,
)
return {tx_date.day: amount for tx_date, amount in by_date.items()}
+def _baseline_from_deltas(
+ deltas: dict[date, float],
+ month_starts: list[date],
+ target_days: int,
+ today: date,
+) -> list[DailyBaseline]:
+ """Per-day median and P25/P75 of cumulative change across months with data."""
+ by_day: dict[int, list[float]] = {}
+ for month_start in month_starts:
+ month_start = month_start.replace(day=1)
+ month_end = _month_range(month_start)[1]
+ days = (month_end - month_start).days
+ if any(month_start <= d < month_end for d in deltas):
+ cumulative = []
+ running = 0.0
+ for day in range(1, days + 1):
+ running += deltas.get(month_start.replace(day=day), 0.0)
+ cumulative.append(running)
+ for day in range(1, target_days + 1):
+ source_day = _source_day(day, target_days, days)
+ # Days after today have no data yet; don't carry the balance flat.
+ if month_start.replace(day=source_day) > today:
+ continue
+ by_day.setdefault(day, []).append(cumulative[source_day - 1])
+
+ baseline = []
+ for day in range(1, target_days + 1):
+ values = sorted(by_day.get(day, []))
+ if len(values) < 2:
+ baseline.append(DailyBaseline(day=day))
+ continue
+ baseline.append(DailyBaseline(
+ day=day,
+ median=round(_percentile(values, 0.5), 2),
+ lower_quartile=(
+ round(_percentile(values, 0.25), 2)
+ if len(values) >= BASELINE_MIN_MONTHS else None
+ ),
+ upper_quartile=(
+ round(_percentile(values, 0.75), 2)
+ if len(values) >= BASELINE_MIN_MONTHS else None
+ ),
+ ))
+ return baseline
+
+def _source_day(day: int, target_days: int, source_days: int) -> int:
+ """Map a day of the target month onto a source month of a different length.
+
+ Days up to the anchor match by calendar day; the tail is stretched linearly so
+ the last day always maps to the last day (month-end income lines up).
+ """
+ if day <= _TAIL_ANCHOR or target_days == source_days:
+ return min(day, source_days)
+ frac = (day - _TAIL_ANCHOR) / (target_days - _TAIL_ANCHOR)
+ return min(source_days, round(_TAIL_ANCHOR + frac * (source_days - _TAIL_ANCHOR)))
+
+
+def _percentile(sorted_values: list[float], q: float) -> float:
+ """Linear-interpolated percentile of a non-empty sorted list, q in [0, 1]."""
+ pos = (len(sorted_values) - 1) * q
+ lo = int(pos)
+ hi = min(lo + 1, len(sorted_values) - 1)
+ return sorted_values[lo] + (sorted_values[hi] - sorted_values[lo]) * (pos - lo)
+
+
+def _months_before(month: date, count: int) -> list[date]:
+ months = []
+ cursor = month.replace(day=1)
+ for _ in range(count):
+ cursor = (cursor - timedelta(days=1)).replace(day=1)
+ months.append(cursor)
+ return list(reversed(months))
+
+
+def _normalize_comparison_months(
+ comparison_months: Optional[list[date]], viewed_month: date
+) -> list[date]:
+ if comparison_months is None:
+ return _months_before(viewed_month, BASELINE_MONTHS)
+ if not comparison_months:
+ raise ValueError("At least one comparison month is required")
+
+ months = sorted({month.replace(day=1) for month in comparison_months})
+ if len(months) > 24:
+ raise ValueError("A maximum of 24 comparison months is allowed")
+ if any(month >= viewed_month for month in months):
+ raise ValueError("Comparison months must be before the viewed month")
+ return months
+
+
+async def get_balance_history_months(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ account_ids: Optional[list[uuid.UUID]] = None,
+) -> list[str]:
+ if account_ids is not None and not account_ids:
+ return []
+
+ tx_year = extract("year", Transaction.date)
+ tx_month = extract("month", Transaction.date)
+ result = await session.execute(
+ select(tx_year, tx_month)
+ .join(Account, Transaction.account_id == Account.id)
+ .outerjoin(Category, Transaction.category_id == Category.id)
+ .where(
+ Transaction.workspace_id == workspace_id,
+ Account.is_closed == False,
+ Account.type != "loan",
+ Transaction.date <= app_today(),
+ Transaction.status == "posted",
+ Transaction.is_ignored == False,
+ Transaction.source != "opening_balance",
+ or_(
+ Transaction.category_id.is_(None),
+ Category.is_ignored == False,
+ ),
+ *([Transaction.account_id.in_(account_ids)] if account_ids is not None else []),
+ )
+ .group_by(tx_year, tx_month)
+ .order_by(tx_year, tx_month)
+ )
+ return [f"{int(year):04d}-{int(month):02d}" for year, month in result.all()]
+
+
async def get_balance_history(
session: AsyncSession,
workspace_id: uuid.UUID,
user_id: uuid.UUID,
month: Optional[date] = None,
account_ids: Optional[list[uuid.UUID]] = None,
+ comparison_months: Optional[list[date]] = None,
) -> BalanceHistory:
if not month:
month = app_today().replace(day=1)
month_start, month_end = _month_range(month)
- prev_month_start = (month_start - timedelta(days=1)).replace(day=1)
- prev_month_end = month_start
+ selected_comparison_months = _normalize_comparison_months(
+ comparison_months, month_start
+ )
today = app_today()
is_current = month_start.year == today.year and month_start.month == today.month
days_in_month = (month_end - month_start).days
cutoff_day = today.day if is_current else days_in_month
- prev_days_in_month = (prev_month_end - prev_month_start).days
-
# Look up the user's primary currency once so the helpers can avoid
# re-querying.
user = await session.get(User, user_id)
@@ -1642,20 +1790,62 @@ async def get_balance_history(
session, workspace_id, month_start - timedelta(days=1),
primary_currency_hint=primary_currency, account_ids=balance_account_ids,
)
- prev_start = await _balance_at(
- session, workspace_id, prev_month_start - timedelta(days=1),
- primary_currency_hint=primary_currency, account_ids=balance_account_ids,
- )
# Daily deltas from real transactions
current_deltas = await _daily_deltas(
session, workspace_id, month_start, month_end,
primary_currency_hint=primary_currency, account_ids=balance_account_ids,
+ exclude_opening_balance=True,
)
- prev_deltas = await _daily_deltas(
- session, workspace_id, prev_month_start, prev_month_end,
- primary_currency_hint=primary_currency, account_ids=balance_account_ids,
- )
+
+ comparison = None
+ comparison_month = None
+ comparison_opening_balance = None
+ baseline: list[DailyBaseline] = []
+ if len(selected_comparison_months) == 1:
+ comparison_month = selected_comparison_months[0]
+ comparison_start, comparison_end = _month_range(comparison_month)
+ comparison_opening_balance = await _balance_at(
+ session,
+ workspace_id,
+ comparison_start - timedelta(days=1),
+ primary_currency_hint=primary_currency,
+ account_ids=balance_account_ids,
+ )
+ comparison_deltas = await _daily_deltas(
+ session,
+ workspace_id,
+ comparison_start,
+ comparison_end,
+ primary_currency_hint=primary_currency,
+ account_ids=balance_account_ids,
+ exclude_opening_balance=True,
+ )
+ if comparison_deltas:
+ comparison = []
+ comparison_balance = comparison_opening_balance
+ comparison_days = (comparison_end - comparison_start).days
+ for day in range(1, comparison_days + 1):
+ comparison_balance += comparison_deltas.get(day, 0.0)
+ is_future = comparison_start.replace(day=day) > today
+ comparison.append(DailyBalance(
+ day=day,
+ balance=None if is_future else round(comparison_balance, 2),
+ ))
+ else:
+ baseline_deltas = await _daily_balance_deltas_by_date(
+ session,
+ workspace_id,
+ selected_comparison_months[0],
+ _month_range(selected_comparison_months[-1])[1],
+ primary_currency_hint=primary_currency,
+ account_ids=balance_account_ids,
+ exclude_opening_balance=True,
+ month_starts=selected_comparison_months,
+ )
+ baseline = _baseline_from_deltas(
+ baseline_deltas, selected_comparison_months, days_in_month, today
+ )
# Recurring projections for future days of current month (converted to primary currency)
proj_deltas: dict[int, float] = {}
@@ -1724,11 +1914,16 @@ async def get_balance_history(
balance=round(balance, 2) if day <= cutoff_day else None,
))
- # Build previous month daily balances
- prev_daily = []
- balance = prev_start
- for day in range(1, prev_days_in_month + 1):
- balance += prev_deltas.get(day, 0)
- prev_daily.append(DailyBalance(day=day, balance=round(balance, 2)))
-
- return BalanceHistory(current=current_daily, previous=prev_daily)
+ return BalanceHistory(
+ current=current_daily,
+ opening_balance=round(current_start, 2),
+ baseline=baseline,
+ comparison=comparison,
+ comparison_month=(
+ comparison_month.strftime("%Y-%m") if comparison_month else None
+ ),
+ comparison_opening_balance=(
+ round(comparison_opening_balance, 2)
+ if comparison_opening_balance is not None else None
+ ),
+ )
diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.json
index 4bc335ac..245c3dec 100644
--- a/backend/tests/api_contract/baseline.json
+++ b/backend/tests/api_contract/baseline.json
@@ -95,6 +95,7 @@
"GET /api/connections/{provider}/institutions": 401,
"GET /api/currencies": 200,
"GET /api/dashboard/balance-history": 401,
+ "GET /api/dashboard/balance-history/months": 401,
"GET /api/dashboard/monthly-trend": 401,
"GET /api/dashboard/projected-transactions": 401,
"GET /api/dashboard/spending-by-category": 401,
@@ -484,6 +485,7 @@
"GET /api/connections/{provider}/institutions": 400,
"GET /api/currencies": 200,
"GET /api/dashboard/balance-history": 200,
+ "GET /api/dashboard/balance-history/months": 200,
"GET /api/dashboard/projected-transactions": 200,
"GET /api/dashboard/spending-by-category": 200,
"GET /api/dashboard/summary": 200,
diff --git a/backend/tests/test_api_extended.py b/backend/tests/test_api_extended.py
index 2f32502b..38021564 100644
--- a/backend/tests/test_api_extended.py
+++ b/backend/tests/test_api_extended.py
@@ -504,7 +504,7 @@ async def test_dashboard_projected_transactions(
@pytest.mark.asyncio
async def test_dashboard_balance_history(client: AsyncClient, auth_headers):
- """GET /api/dashboard/balance-history returns current/previous month data."""
+ """GET /api/dashboard/balance-history returns current month and baseline data."""
# Create an account first
await client.post(
"/api/accounts",
@@ -518,9 +518,52 @@ async def test_dashboard_balance_history(client: AsyncClient, auth_headers):
assert response.status_code == 200
data = response.json()
assert "current" in data
- assert "previous" in data
+ assert "opening_balance" in data
+ assert "baseline" in data
assert isinstance(data["current"], list)
- assert isinstance(data["previous"], list)
+ assert len(data["baseline"]) == len(data["current"])
+
+
+async def test_dashboard_balance_history_accepts_comparison_months(
+ client: AsyncClient, auth_headers
+):
+ response = await client.get(
+ "/api/dashboard/balance-history",
+ params=[
+ ("month", "2026-04-01"),
+ ("comparison_months", "2026-01-01"),
+ ("comparison_months", "2026-03-01"),
+ ],
+ headers=auth_headers,
+ )
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["comparison"] is None
+ assert len(data["baseline"]) == len(data["current"])
+
+ months_response = await client.get(
+ "/api/dashboard/balance-history/months", headers=auth_headers
+ )
+ assert months_response.status_code == 200
+ assert isinstance(months_response.json(), list)
+
+
+async def test_dashboard_balance_history_rejects_non_prior_comparison_month(
+ client: AsyncClient, auth_headers
+):
+ response = await client.get(
+ "/api/dashboard/balance-history",
+ params=[
+ ("month", "2026-04-01"),
+ ("comparison_months", "2026-04-01"),
+ ],
+ headers=auth_headers,
+ )
+
+ assert response.status_code == 422
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_dashboard_service.py b/backend/tests/test_dashboard_service.py
index 92756b12..fe45c544 100644
--- a/backend/tests/test_dashboard_service.py
+++ b/backend/tests/test_dashboard_service.py
@@ -13,17 +13,20 @@ from app.models.transaction import Transaction
from app.models.bank_connection import BankConnection
from app.services.dashboard_service import (
_balance_at,
+ _baseline_from_deltas,
_get_recurring_projections,
_month_range,
_get_open_accounts,
_account_balance_at,
_total_balance_by_currency,
get_balance_history,
+ get_balance_history_months,
get_monthly_trend,
get_summary,
get_spending_by_category,
get_projected_transactions,
)
+
from app.services.transaction_service import get_transactions
@@ -1104,7 +1107,291 @@ async def test_balance_history_basic(session, test_user, test_workspace):
history = await get_balance_history(session, test_workspace.id, test_user.id)
assert len(history.current) > 0
- assert len(history.previous) > 0
+ assert 28 <= len(history.baseline) <= 31
+
+
+async def test_balance_history_single_comparison_reuses_month_daily_balances(
+ session: AsyncSession, test_user, test_workspace
+):
+ account = await _make_account(session, test_user.id, "Single comparison")
+ account.workspace_id = test_workspace.id
+ await session.commit()
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit", date(2026, 1, 1),
+ source="opening_balance",
+ )
+ await _add_txn(session, test_user.id, account.id, 50, "credit", date(2026, 2, 5))
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit", date(2026, 2, 10),
+ source="opening_balance",
+ )
+ await _add_txn(session, test_user.id, account.id, 5, "debit", date(2026, 2, 20))
+
+ history = await get_balance_history(
+ session,
+ test_workspace.id,
+ test_user.id,
+ month=date(2026, 4, 1),
+ account_ids=[account.id],
+ comparison_months=[date(2026, 2, 1)],
+ )
+
+ assert history.comparison_month == "2026-02"
+ assert history.comparison_opening_balance == 1000.0
+ assert history.comparison is not None
+ assert len(history.comparison) == 28
+ assert history.comparison[0].balance == 1000.0
+ assert history.comparison[4].balance == 1050.0
+ assert history.comparison[9].balance == 1050.0
+ assert history.comparison[5].balance == 1050.0
+ assert history.comparison[19].balance == 1045.0
+ assert history.baseline == []
+
+
+async def test_midmonth_opening_balances_are_excluded_from_current_and_baseline(
+ session: AsyncSession, test_user, test_workspace
+):
+ account = await _make_account(session, test_user.id, "Opening balance consistency")
+ account.workspace_id = test_workspace.id
+ await session.commit()
+
+ for month, amount in ((1, 10), (2, 20), (3, 30), (4, 40)):
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit", date(2026, month, 15),
+ source="opening_balance",
+ )
+ await _add_txn(
+ session, test_user.id, account.id, amount, "credit", date(2026, month, 20)
+ )
+
+ history = await get_balance_history(
+ session,
+ test_workspace.id,
+ test_user.id,
+ month=date(2026, 4, 1),
+ account_ids=[account.id],
+ comparison_months=[date(2026, month, 1) for month in (1, 2, 3)],
+ )
+
+ current_change = [
+ point.balance - history.opening_balance
+ for point in history.current
+ if point.balance is not None
+ ]
+ assert current_change[14] == 0.0
+ assert current_change[19] == 40.0
+ assert history.baseline[14].median == 0.0
+ assert history.baseline[19].median == 20.0
+
+
+async def test_balance_history_single_comparison_stops_at_today(
+ session: AsyncSession, test_user, test_workspace, monkeypatch
+):
+ monkeypatch.setattr(
+ "app.services.dashboard_service.app_today", lambda: date(2026, 10, 18)
+ )
+ account = await _make_account(session, test_user.id, "In-progress comparison")
+ account.workspace_id = test_workspace.id
+ await session.commit()
+ await _add_txn(session, test_user.id, account.id, 50, "credit", date(2026, 10, 5))
+
+ history = await get_balance_history(
+ session,
+ test_workspace.id,
+ test_user.id,
+ month=date(2026, 11, 1),
+ account_ids=[account.id],
+ comparison_months=[date(2026, 10, 1)],
+ )
+
+ assert history.comparison is not None
+ assert len(history.comparison) == 31
+ assert history.comparison[17].balance is not None
+ assert all(point.balance is None for point in history.comparison[18:])
+
+
+async def test_balance_history_sparse_month_selection_excludes_gap_month(
+ session: AsyncSession, test_user, test_workspace
+):
+ account = await _make_account(session, test_user.id, "Sparse comparisons")
+ account.workspace_id = test_workspace.id
+ await session.commit()
+ await _add_txn(session, test_user.id, account.id, 10, "credit", date(2026, 1, 1))
+ await _add_txn(session, test_user.id, account.id, 1000, "credit", date(2026, 2, 1))
+ await _add_txn(session, test_user.id, account.id, 30, "credit", date(2026, 3, 1))
+
+ history = await get_balance_history(
+ session,
+ test_workspace.id,
+ test_user.id,
+ month=date(2026, 4, 1),
+ account_ids=[account.id],
+ comparison_months=[date(2026, 3, 1), date(2026, 1, 1)],
+ )
+
+ assert history.comparison is None
+ assert history.baseline[0].median == 20.0
+ assert history.baseline[0].lower_quartile is None
+ assert history.baseline[0].upper_quartile is None
+
+
+async def test_balance_history_month_options_are_scoped_and_exclude_openings(
+ session: AsyncSession, test_user, test_workspace
+):
+ first = await _make_account(session, test_user.id, "Month options one")
+ second = await _make_account(session, test_user.id, "Month options two")
+ first.workspace_id = test_workspace.id
+ second.workspace_id = test_workspace.id
+ await session.commit()
+ await _add_txn(
+ session, test_user.id, first.id, 500, "credit", date(2026, 1, 1),
+ source="opening_balance",
+ )
+ await _add_txn(session, test_user.id, first.id, 25, "credit", date(2026, 2, 1))
+ await _add_txn(session, test_user.id, second.id, 75, "credit", date(2026, 3, 1))
+
+ all_months = await get_balance_history_months(session, test_workspace.id)
+ first_account_months = await get_balance_history_months(
+ session, test_workspace.id, [first.id]
+ )
+
+ assert all_months == ["2026-02", "2026-03"]
+ assert first_account_months == ["2026-02"]
+
+
+async def test_balance_history_month_options_exclude_loans(
+ session: AsyncSession, test_user, test_workspace
+):
+ # Loans are left out of the balance curve, so their months have no data to plot.
+ checking = await _make_account(session, test_user.id, "Months checking")
+ loan = await _make_account(session, test_user.id, "Months loan", acc_type="loan")
+ checking.workspace_id = test_workspace.id
+ loan.workspace_id = test_workspace.id
+ await session.commit()
+ await _add_txn(session, test_user.id, checking.id, 25, "credit", date(2026, 2, 1))
+ await _add_txn(session, test_user.id, loan.id, 300, "debit", date(2026, 3, 1))
+
+ assert await get_balance_history_months(session, test_workspace.id) == ["2026-02"]
+ assert await get_balance_history_months(
+ session, test_workspace.id, [checking.id, loan.id]
+ ) == ["2026-02"]
+
+
+def test_baseline_from_deltas_median_and_quartiles():
+
+ # Four months; day-1 changes are -10, -20, -30, -40.
+ deltas = {
+ date(2026, 1, 1): -10.0,
+ date(2026, 2, 1): -20.0,
+ date(2026, 3, 1): -30.0,
+ date(2026, 4, 1): -40.0,
+ }
+ month_starts = [date(2026, month, 1) for month in range(1, 5)]
+ baseline = _baseline_from_deltas(deltas, month_starts, 31, date.max)
+ assert len(baseline) == 31
+ day1 = baseline[0]
+ assert day1.median == -25.0
+ assert day1.lower_quartile == -32.5
+ assert day1.upper_quartile == -17.5
+ assert baseline[1].median == -25.0
+
+
+def test_baseline_three_contributors_include_quartiles():
+ deltas = {
+ date(2026, 1, 1): 10.0,
+ date(2026, 2, 1): 20.0,
+ date(2026, 3, 1): 30.0,
+ }
+
+ baseline = _baseline_from_deltas(
+ deltas,
+ [date(2026, 1, 1), date(2026, 2, 1), date(2026, 3, 1)],
+ 30,
+ date.max,
+ )
+
+ assert baseline[0].median == 20.0
+ assert baseline[0].lower_quartile == 15.0
+ assert baseline[0].upper_quartile == 25.0
+
+
+def test_normalize_comparison_months_defaults_and_deduplicates():
+ from app.services.dashboard_service import _normalize_comparison_months
+
+ default = _normalize_comparison_months(None, date(2026, 10, 1))
+ selected = _normalize_comparison_months(
+ [date(2026, 3, 15), date(2026, 1, 1), date(2026, 3, 1)],
+ date(2026, 10, 1),
+ )
+
+ assert len(default) == 12
+ assert selected == [date(2026, 1, 1), date(2026, 3, 1)]
+
+
+ "months",
+ [
+ pytest.param([], id="empty"),
+ pytest.param([date(2026, 10, 1)], id="not-before-viewed-month"),
+ pytest.param(
+ [date(2024 + index // 12, index % 12 + 1, 1) for index in range(25)],
+ id="more-than-24-months",
+ ),
+ ],
+)
+def test_normalize_comparison_months_rejects_invalid_selections(months):
+ from app.services.dashboard_service import _normalize_comparison_months
+
+ with pytest.raises(ValueError):
+ _normalize_comparison_months(months, date(2026, 10, 1))
+
+
+def test_baseline_aligns_month_end_income():
+ # Salary of +100 on the last day of Jan (31), Feb (28), Mar (31), Apr (30).
+ deltas = {
+ date(2026, 1, 31): 100.0,
+ date(2026, 2, 28): 100.0,
+ date(2026, 3, 31): 100.0,
+ date(2026, 4, 30): 100.0,
+ }
+ for target_days in (28, 30, 31):
+ month_starts = [date(2026, month, 1) for month in range(1, 5)]
+ baseline = _baseline_from_deltas(deltas, month_starts, target_days, date.max)
+ assert len(baseline) == target_days
+ assert baseline[-1].median == 100.0
+ assert baseline[0].median == 0.0
+
+
+def test_baseline_two_months_has_median_without_quartiles():
+ deltas = {date(2026, 1, 5): 10.0, date(2026, 2, 5): 20.0}
+ month_starts = [date(2026, month, 1) for month in range(1, 13)]
+ baseline = _baseline_from_deltas(deltas, month_starts, 30, date.max)
+ assert baseline[4].median == 15.0
+ assert baseline[4].lower_quartile is None
+ assert baseline[4].upper_quartile is None
+
+
+def test_baseline_omits_source_days_after_today():
+ # Viewing a future month: the in-progress month must not carry its
+ # balance flat past today and drag the median.
+ deltas = {
+ date(2026, 8, 1): 10.0,
+ date(2026, 9, 1): 20.0,
+ date(2026, 10, 1): 30.0,
+ date(2026, 10, 20): 1000.0,
+ }
+ month_starts = [date(2026, 8, 1), date(2026, 9, 1), date(2026, 10, 1)]
+ baseline = _baseline_from_deltas(deltas, month_starts, 30, date(2026, 10, 18))
+
+ assert baseline[17].median == 20.0 # day 18: Aug, Sep, Oct all count
+ assert baseline[18].median == 15.0 # day 19: only Aug and Sep
+ assert baseline[18].lower_quartile is None
@pytest.mark.asyncio
diff --git a/backend/tests/test_dashboard_service_coverage.py b/backend/tests/test_dashboard_service_coverage.py
index 9379c9c0..12f08207 100644
--- a/backend/tests/test_dashboard_service_coverage.py
+++ b/backend/tests/test_dashboard_service_coverage.py
@@ -414,7 +414,7 @@ async def test_balance_history_with_future_projections(
history = await get_balance_history(session, test_workspace.id, test_user.id, month=month_start)
assert len(history.current) > 0
- assert len(history.previous) > 0
+ assert len(history.baseline) == len(history.current)
def test_signed_expr_helpers_smoke():
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 6396df77..7437e731 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1352,9 +1352,28 @@ export const dashboard = {
const { data } = await api.get('/dashboard/projected-transactions', { params })
return data
},
- balanceHistory: async (month?: string, accountIds?: string[]): Promise<BalanceHistory> => {
+ balanceHistory: async (
+ month?: string,
+ accountIds?: string[],
+ comparisonMonths?: string[],
+ ): Promise<BalanceHistory> => {
const extra = acctIdsParam(accountIds)
- const { data } = await api.get('/dashboard/balance-history', { params: { month, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })
+ const { data } = await api.get('/dashboard/balance-history', {
+ params: {
+ month,
+ ...(extra.params ?? {}),
+ ...(comparisonMonths?.length ? { comparison_months: comparisonMonths } : {}),
+ },
+ paramsSerializer: { indexes: null },
+ })
+ return data
+ },
+ balanceHistoryMonths: async (accountIds?: string[]): Promise<string[]> => {
+ const extra = acctIdsParam(accountIds)
+ const { data } = await api.get('/dashboard/balance-history/months', {
+ params: extra.params,
+ ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}),
+ })
return data
},
}
diff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.json
index 565ef9d4..0810706b 100644
--- a/frontend/src/locales/cs.json
+++ b/frontend/src/locales/cs.json
@@ -866,10 +866,14 @@
"monthlyTrend": "Měsíční trend",
"budgetVsActual": "Rozpočet vs. skutečnost",
"balanceFlow": "Vývoj zůstatku",
- "balanceFlowVsPrev": "{{month}}, den {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "Den {{day}}: {{delta}} oproti obvyklému stavu ({{median}})",
+ "balanceFlowVsMonth": "Den {{day}}: {{delta}} oproti {{month}}",
+ "balanceMedianLegend": "Medián vybraných měsíců",
+ "compareMonths": "Porovnat měsíce",
+ "selectComparisonMonths": "Vyberte měsíce k porovnání",
+ "balanceRangeLegend": "Prostředních 50 %",
"balancePeriodVariation": "Změna za období",
"balanceCurrentMonthLegend": "Aktuální měsíc",
- "balancePreviousMonthLegend": "Předchozí měsíc",
"day": "Den {{day}}",
"noData": "Žádná data",
"noTransactions": "V tomto období nejsou žádné transakce",
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 9cd14a51..013dcbbd 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -842,10 +842,14 @@
"monthlyTrend": "Monatstrend",
"budgetVsActual": "Budget vs. Istwert",
"balanceFlow": "Saldo-Verlauf",
- "balanceFlowVsPrev": "In {{month}} am Tag {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "Am Tag {{day}}: {{delta}} ggü. dem Üblichen ({{median}})",
+ "balanceFlowVsMonth": "Am Tag {{day}}: {{delta}} gegenüber {{month}}",
+ "balanceMedianLegend": "Median der ausgewählten Monate",
+ "compareMonths": "Monate vergleichen",
+ "selectComparisonMonths": "Vergleichsmonate auswählen",
+ "balanceRangeLegend": "Mittlere 50 %",
"balancePeriodVariation": "Veränderung im Zeitraum",
"balanceCurrentMonthLegend": "Aktueller Monat",
- "balancePreviousMonthLegend": "Vormonat",
"day": "Tag {{day}}",
"noData": "Keine Daten verfügbar",
"noTransactions": "Keine Transaktionen in diesem Zeitraum",
diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.json
index 72a74e26..024f1553 100644
--- a/frontend/src/locales/el.json
+++ b/frontend/src/locales/el.json
@@ -842,10 +842,14 @@
"monthlyTrend": "Μηνιαία τάση",
"budgetVsActual": "Προϋπολογισμός έναντι Πραγματικού",
"balanceFlow": "Εξέλιξη υπολοίπου",
- "balanceFlowVsPrev": "Τον μήνα {{month}} την ημέρα {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "Την ημέρα {{day}}: {{delta}} έναντι του τυπικού ({{median}})",
+ "balanceFlowVsMonth": "Την ημέρα {{day}}: {{delta}} σε σύγκριση με τον μήνα {{month}}",
+ "balanceMedianLegend": "Διάμεσος επιλεγμένων μηνών",
+ "compareMonths": "Σύγκριση μηνών",
+ "selectComparisonMonths": "Επιλέξτε μήνες σύγκρισης",
+ "balanceRangeLegend": "Κεντρικό 50%",
"balancePeriodVariation": "Μεταβολή περιόδου",
"balanceCurrentMonthLegend": "Τρέχων μήνας",
- "balancePreviousMonthLegend": "Προηγούμενος μήνας",
"day": "Ημέρα {{day}}",
"noData": "Δεν υπάρχουν διαθέσιμα δεδομένα",
"noTransactions": "Δεν υπάρχουν συναλλαγές σε αυτήν την περίοδο",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 8e816418..6566144b 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -842,10 +842,14 @@
"monthlyTrend": "Monthly Trend",
"budgetVsActual": "Budget vs Actual",
"balanceFlow": "Balance Evolution",
- "balanceFlowVsPrev": "In {{month}} on day {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "On day {{day}}: {{delta}} vs typical ({{median}})",
+ "balanceFlowVsMonth": "On day {{day}}: {{delta}} vs {{month}}",
+ "balanceMedianLegend": "Selected-month median",
+ "compareMonths": "Compare months",
+ "selectComparisonMonths": "Select comparison months",
+ "balanceRangeLegend": "Middle 50% range",
"balancePeriodVariation": "Period change",
"balanceCurrentMonthLegend": "Current month",
- "balancePreviousMonthLegend": "Previous month",
"day": "Day {{day}}",
"noData": "No data available",
"noTransactions": "No transactions in this period",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 69db973b..1ad5c72c 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -844,10 +844,14 @@
"monthlyTrend": "Tendencia mensual",
"budgetVsActual": "Presupuesto vs Real",
"balanceFlow": "Evolución del saldo",
- "balanceFlowVsPrev": "En {{month}} día {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "El día {{day}}: {{delta}} frente a lo habitual ({{median}})",
+ "balanceFlowVsMonth": "El día {{day}}: {{delta}} frente a {{month}}",
+ "balanceMedianLegend": "Mediana de los meses seleccionados",
+ "compareMonths": "Comparar meses",
+ "selectComparisonMonths": "Seleccionar meses de comparación",
+ "balanceRangeLegend": "Rango central del 50 %",
"balancePeriodVariation": "Variación del período",
"balanceCurrentMonthLegend": "Mes actual",
- "balancePreviousMonthLegend": "Mes anterior",
"day": "Día {{day}}",
"noData": "No hay datos disponibles",
"noTransactions": "No hay transacciones en este periodo",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index edc34a6d..e76b5fbc 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -844,10 +844,14 @@
"monthlyTrend": "Tendance mensuelle",
"budgetVsActual": "Budget vs réel",
"balanceFlow": "Évolution du solde",
- "balanceFlowVsPrev": "En {{month}} le jour {{day}} : {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "Le jour {{day}} : {{delta}} par rapport à la normale ({{median}})",
+ "balanceFlowVsMonth": "Le jour {{day}} : {{delta}} par rapport à {{month}}",
+ "balanceMedianLegend": "Médiane des mois sélectionnés",
+ "compareMonths": "Comparer les mois",
+ "selectComparisonMonths": "Sélectionner les mois à comparer",
+ "balanceRangeLegend": "50 % central",
"balancePeriodVariation": "Variation de la période",
"balanceCurrentMonthLegend": "Mois en cours",
- "balancePreviousMonthLegend": "Mois précédent",
"day": "Jour {{day}}",
"noData": "Aucune donnée disponible",
"noTransactions": "Aucune transaction sur cette période",
diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.json
index 04276065..ad6c235a 100644
--- a/frontend/src/locales/hi.json
+++ b/frontend/src/locales/hi.json
@@ -842,10 +842,14 @@
"monthlyTrend": "मासिक रुझान",
"budgetVsActual": "बजट बनाम वास्तविक",
"balanceFlow": "शेष राशि का रुझान",
- "balanceFlowVsPrev": "{{month}} में दिन {{day}} को: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "दिन {{day}} पर: सामान्य ({{median}}) की तुलना में {{delta}}",
+ "balanceFlowVsMonth": "दिन {{day}} पर: {{month}} की तुलना में {{delta}}",
+ "balanceMedianLegend": "चुने गए महीनों की माध्यिका",
+ "compareMonths": "महीनों की तुलना करें",
+ "selectComparisonMonths": "तुलना के महीने चुनें",
+ "balanceRangeLegend": "मध्य 50% सीमा",
"balancePeriodVariation": "अवधि में बदलाव",
"balanceCurrentMonthLegend": "मौजूदा महीना",
- "balancePreviousMonthLegend": "पिछला महीना",
"day": "दिन {{day}}",
"noData": "कोई डेटा उपलब्ध नहीं",
"noTransactions": "इस अवधि में कोई लेन-देन नहीं",
diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.json
index 3f878b98..6383819f 100644
--- a/frontend/src/locales/hu.json
+++ b/frontend/src/locales/hu.json
@@ -842,10 +842,14 @@
"monthlyTrend": "Havi trend",
"budgetVsActual": "Költségkeret és tény",
"balanceFlow": "Egyenleg alakulása",
- "balanceFlowVsPrev": "{{month}}, {{day}}. nap: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "{{day}}. nap: {{delta}} a szokásoshoz képest ({{median}})",
+ "balanceFlowVsMonth": "{{day}}. nap: {{delta}} ehhez képest: {{month}}",
+ "balanceMedianLegend": "A kiválasztott hónapok mediánja",
+ "compareMonths": "Hónapok összehasonlítása",
+ "selectComparisonMonths": "Összehasonlítandó hónapok kiválasztása",
+ "balanceRangeLegend": "Középső 50%",
"balancePeriodVariation": "Változás az időszakban",
"balanceCurrentMonthLegend": "Aktuális hónap",
- "balancePreviousMonthLegend": "Előző hónap",
"day": "{{day}}. nap",
"noData": "Nincs elérhető adat",
"noTransactions": "Ebben az időszakban nincs tranzakció",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 792ed303..0f43da28 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -844,10 +844,14 @@
"monthlyTrend": "Andamento mensile",
"budgetVsActual": "Budget vs Effettivo",
"balanceFlow": "Andamento del saldo",
- "balanceFlowVsPrev": "In {{month}} il giorno {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "Il giorno {{day}}: {{delta}} rispetto al tipico ({{median}})",
+ "balanceFlowVsMonth": "Il giorno {{day}}: {{delta}} rispetto a {{month}}",
+ "balanceMedianLegend": "Mediana dei mesi selezionati",
+ "compareMonths": "Confronta mesi",
+ "selectComparisonMonths": "Seleziona i mesi da confrontare",
+ "balanceRangeLegend": "Intervallo centrale del 50%",
"balancePeriodVariation": "Variazione del periodo",
"balanceCurrentMonthLegend": "Mese corrente",
- "balancePreviousMonthLegend": "Mese precedente",
"day": "Giorno {{day}}",
"noData": "Nessun dato disponibile",
"noTransactions": "Nessuna transazione in questo periodo",
diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json
index b6197db0..84795257 100644
--- a/frontend/src/locales/ja.json
+++ b/frontend/src/locales/ja.json
@@ -842,10 +842,14 @@
"monthlyTrend": "月間推移",
"budgetVsActual": "予算と実績",
"balanceFlow": "残高推移",
- "balanceFlowVsPrev": "{{month}}の{{day}}日目: {{amount}}({{delta}})",
+ "balanceFlowVsMedian": "{{day}}日目: 通常({{median}})との差 {{delta}}",
+ "balanceFlowVsMonth": "{{day}}日目: {{month}}との差 {{delta}}",
+ "balanceMedianLegend": "選択した月の中央値",
+ "compareMonths": "月を比較",
+ "selectComparisonMonths": "比較する月を選択",
+ "balanceRangeLegend": "中央50%の範囲",
"balancePeriodVariation": "期間の変化",
"balanceCurrentMonthLegend": "今月",
- "balancePreviousMonthLegend": "前月",
"day": "{{day}}日",
"noData": "データがありません",
"noTransactions": "この期間の取引はありません",
diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json
index 5b624cb0..cf64670d 100644
--- a/frontend/src/locales/nl.json
+++ b/frontend/src/locales/nl.json
@@ -842,10 +842,14 @@
"monthlyTrend": "Maandelijkse trend",
"budgetVsActual": "Budget versus Werkelijk",
"balanceFlow": "Saldoverloop",
- "balanceFlowVsPrev": "In {{month}} op dag {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "Op dag {{day}}: {{delta}} t.o.v. gebruikelijk ({{median}})",
+ "balanceFlowVsMonth": "Op dag {{day}}: {{delta}} vergeleken met {{month}}",
+ "balanceMedianLegend": "Mediaan van geselecteerde maanden",
+ "compareMonths": "Maanden vergelijken",
+ "selectComparisonMonths": "Vergelijkingsmaanden selecteren",
+ "balanceRangeLegend": "Middelste 50%",
"balancePeriodVariation": "Wijziging in de periode",
"balanceCurrentMonthLegend": "Huidige maand",
- "balancePreviousMonthLegend": "Vorige maand",
"day": "Dag {{day}}",
"noData": "Geen gegevens beschikbaar",
"noTransactions": "Geen transacties in deze periode",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 38e0cbb5..7b6e5503 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -850,10 +850,14 @@
"monthlyTrend": "Trend miesięczny",
"budgetVsActual": "Budżet a realizacja",
"balanceFlow": "Ewolucja salda",
- "balanceFlowVsPrev": "W {{month}} w dniu {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "W dniu {{day}}: {{delta}} względem typowego ({{median}})",
+ "balanceFlowVsMonth": "W dniu {{day}}: {{delta}} względem {{month}}",
+ "balanceMedianLegend": "Mediana wybranych miesięcy",
+ "compareMonths": "Porównaj miesiące",
+ "selectComparisonMonths": "Wybierz miesiące do porównania",
+ "balanceRangeLegend": "Środkowe 50%",
"balancePeriodVariation": "Zmiana w okresie",
"balanceCurrentMonthLegend": "Bieżący miesiąc",
- "balancePreviousMonthLegend": "Poprzedni miesiąc",
"day": "Dzień {{day}}",
"noData": "Brak dostępnych danych",
"noTransactions": "Brak transakcji w tym okresie",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 69019dc0..f2006076 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -844,10 +844,14 @@
"monthlyTrend": "Tendência Mensal",
"budgetVsActual": "Orçamento vs Realizado",
"balanceFlow": "Evolução do Saldo",
- "balanceFlowVsPrev": "Em {{month}} no dia {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "No dia {{day}}: {{delta}} vs o típico ({{median}})",
+ "balanceFlowVsMonth": "No dia {{day}}: {{delta}} em relação a {{month}}",
+ "balanceMedianLegend": "Mediana dos meses selecionados",
+ "compareMonths": "Comparar meses",
+ "selectComparisonMonths": "Selecionar meses para comparação",
+ "balanceRangeLegend": "Faixa central de 50%",
"balancePeriodVariation": "Variação do período",
"balanceCurrentMonthLegend": "Mês atual",
- "balancePreviousMonthLegend": "Mês anterior",
"day": "Dia {{day}}",
"noData": "Nenhum dado disponível",
"noTransactions": "Nenhuma transação no período",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index d02ea1dd..2a412fd7 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -844,10 +844,14 @@
"monthlyTrend": "Tendência Mensal",
"budgetVsActual": "Orçamento vs Realizado",
"balanceFlow": "Evolução do Saldo",
- "balanceFlowVsPrev": "Em {{month}} no dia {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "No dia {{day}}: {{delta}} vs o típico ({{median}})",
+ "balanceFlowVsMonth": "No dia {{day}}: {{delta}} em relação a {{month}}",
+ "balanceMedianLegend": "Mediana dos meses selecionados",
+ "compareMonths": "Comparar meses",
+ "selectComparisonMonths": "Selecionar meses para comparação",
+ "balanceRangeLegend": "Intervalo central de 50%",
"balancePeriodVariation": "Variação do período",
"balanceCurrentMonthLegend": "Mês atual",
- "balancePreviousMonthLegend": "Mês anterior",
"day": "Dia {{day}}",
"noData": "Nenhum dado disponível",
"noTransactions": "Nenhuma transação no período",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 165c5ed1..956a2acf 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -850,10 +850,14 @@
"monthlyTrend": "Месячная динамика",
"budgetVsActual": "Бюджет vs Факт",
"balanceFlow": "Динамика баланса",
- "balanceFlowVsPrev": "В {{month}} на {{day}} день: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "На {{day}} день: {{delta}} относительно обычного ({{median}})",
+ "balanceFlowVsMonth": "На {{day}} день: {{delta}} по сравнению с {{month}}",
+ "balanceMedianLegend": "Медиана выбранных месяцев",
+ "compareMonths": "Сравнить месяцы",
+ "selectComparisonMonths": "Выберите месяцы для сравнения",
+ "balanceRangeLegend": "Средние 50%",
"balancePeriodVariation": "Изменение за период",
"balanceCurrentMonthLegend": "Текущий месяц",
- "balancePreviousMonthLegend": "Предыдущий месяц",
"day": "День {{day}}",
"noData": "Нет данных",
"noTransactions": "Нет транзакций за этот период",
diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.json
index 95daf776..428923a2 100644
--- a/frontend/src/locales/sk.json
+++ b/frontend/src/locales/sk.json
@@ -850,10 +850,14 @@
"monthlyTrend": "Mesačný trend",
"budgetVsActual": "Rozpočet vs. skutočnosť",
"balanceFlow": "Vývoj zostatku",
- "balanceFlowVsPrev": "{{month}}, deň {{day}}: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "V deň {{day}}: {{delta}} oproti typickému ({{median}})",
+ "balanceFlowVsMonth": "V deň {{day}}: {{delta}} v porovnaní s {{month}}",
+ "balanceMedianLegend": "Medián vybraných mesiacov",
+ "compareMonths": "Porovnať mesiace",
+ "selectComparisonMonths": "Vyberte mesiace na porovnanie",
+ "balanceRangeLegend": "Stredných 50 %",
"balancePeriodVariation": "Zmena za obdobie",
"balanceCurrentMonthLegend": "Aktuálny mesiac",
- "balancePreviousMonthLegend": "Predchádzajúci mesiac",
"day": "Deň {{day}}",
"noData": "Žiadne údaje",
"noTransactions": "V tomto období nie sú žiadne transakcie",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 487c4847..3bf59088 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -850,10 +850,14 @@
"monthlyTrend": "Місячна динаміка",
"budgetVsActual": "Бюджет vs Факт",
"balanceFlow": "Динаміка балансу",
- "balanceFlowVsPrev": "У {{month}} на {{day}} день: {{amount}} ({{delta}})",
+ "balanceFlowVsMedian": "На {{day}} день: {{delta}} відносно звичайного ({{median}})",
+ "balanceFlowVsMonth": "На {{day}} день: {{delta}} порівняно з {{month}}",
+ "balanceMedianLegend": "Медіана вибраних місяців",
+ "compareMonths": "Порівняти місяці",
+ "selectComparisonMonths": "Виберіть місяці для порівняння",
+ "balanceRangeLegend": "Середні 50%",
"balancePeriodVariation": "Зміна за період",
"balanceCurrentMonthLegend": "Поточний місяць",
- "balancePreviousMonthLegend": "Попередній місяць",
"day": "День {{day}}",
"noData": "Немає даних",
"noTransactions": "Немає транзакцій за цей період",
diff --git a/frontend/src/pages/dashboard.test.tsx b/frontend/src/pages/dashboard.test.tsx
index 61682bde..eb3c9027 100644
--- a/frontend/src/pages/dashboard.test.tsx
+++ b/frontend/src/pages/dashboard.test.tsx
@@ -1,9 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { screen, within } from '@testing-library/react'
+import { act, screen, waitFor, within } from '@testing-library/react'
+import { useLocation, useNavigate } from 'react-router-dom'
import DashboardPage from '@/pages/dashboard'
import { TooltipProvider } from '@/components/ui/tooltip'
import { formatCurrency } from '@/lib/format'
+import { monthLabel } from '@/lib/month-utils'
import { renderWithProviders, t } from '@/test/utils'
import type { Account, DashboardSummary } from '@/types'
@@ -12,6 +14,7 @@ const api = vi.hoisted(() => ({
summary: vi.fn(),
spendingByCategory: vi.fn(),
balanceHistory: vi.fn(),
+ balanceHistoryMonths: vi.fn(),
projectedTransactions: vi.fn(),
},
transactions: { list: vi.fn(), calendar: vi.fn() },
@@ -77,6 +80,22 @@ function account(overrides: Partial<Account>): Account {
}
}
+function DashboardRouteNavigation() {
+ const navigate = useNavigate()
+ return (
+ <>
+ <button onClick={() => navigate('/?month=2026-03&comparison_month=2026-02')}>Navigate to March</button>
+ <button onClick={() => navigate('/?month=2026-04&comparison_month=2026-02')}>Navigate to April</button>
+ <button onClick={() => navigate('/?month=2026-04&comparison_month=2026-03')}>Compare April with March</button>
+ </>
+ )
+}
+
+function LocationProbe() {
+ const location = useLocation()
+ return <output data-testid="location-search">{location.search}</output>
+}
+
// Two cards on one shared credit line both report the line's full -300.
const accounts = [
account({ id: 'checking', name: 'Checking', current_balance: 1000 }),
@@ -108,7 +127,15 @@ beforeEach(() => {
vi.clearAllMocks()
api.dashboard.summary.mockResolvedValue(summary)
api.dashboard.spendingByCategory.mockResolvedValue([])
- api.dashboard.balanceHistory.mockResolvedValue({ current: [], previous: [] })
+ api.dashboard.balanceHistory.mockResolvedValue({
+ current: [],
+ opening_balance: 0,
+ baseline: [],
+ comparison: null,
+ comparison_month: null,
+ comparison_opening_balance: null,
+ })
+ api.dashboard.balanceHistoryMonths.mockResolvedValue([])
api.dashboard.projectedTransactions.mockResolvedValue([])
api.transactions.list.mockResolvedValue({ items: [], total: 0 })
api.budgets.comparison.mockResolvedValue([])
@@ -185,6 +212,248 @@ describe('Dashboard available balance without an FX rate', () => {
})
})
+describe('Dashboard balance comparisons', () => {
+ const month = (value: string) => monthLabel(value, 'en')
+ const money = (value: number) => formatCurrency(value, 'USD', 'en-US')
+ const signed = (value: number) => `${value >= 0 ? '+' : ''}${money(value)}`
+
+ function renderDashboard(route: string) {
+ return renderWithProviders(
+ <TooltipProvider delayDuration={0}>
+ <DashboardPage />
+ </TooltipProvider>,
+ { route },
+ )
+ }
+
+ const selectorButton = (singleMonth?: string) => screen.findByRole('button', {
+ name: singleMonth
+ ? month(singleMonth)
+ : (name) => name === t('dashboard.compareMonths')
+ || name.startsWith(`${t('dashboard.compareMonths')} (`),
+ })
+
+ function mockHistory(overrides: Record<string, unknown>) {
+ api.dashboard.balanceHistory.mockResolvedValue({
+ current: [{ day: 1, balance: 1100 }],
+ opening_balance: 1000,
+ baseline: [],
+ comparison: null,
+ comparison_month: null,
+ comparison_opening_balance: null,
+ ...overrides,
+ })
+ }
+
+ it('labels a single comparison month in the selector, legend and footer', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+ // Current month is +100 since its opening, February was +50: 50 ahead.
+ mockHistory({
+ comparison: [{ day: 1, balance: 1950 }, { day: 2, balance: 1950 }],
+ comparison_month: '2026-02',
+ comparison_opening_balance: 1900,
+ })
+
+ renderDashboard('/?month=2026-04&comparison_month=2026-02')
+
+ expect(await screen.findByText(
+ t('dashboard.balanceFlowVsMonth', { day: 1, month: month('2026-02'), delta: signed(50) }),
+ )).toBeInTheDocument()
+ expect(await selectorButton('2026-02')).toHaveTextContent(month('2026-02'))
+ // The legend shows the month itself, not the median wording.
+ expect(screen.getAllByText(month('2026-02')).some((el) => !el.closest('button'))).toBe(true)
+ expect(screen.queryByText(t('dashboard.balanceMedianLegend'))).not.toBeInTheDocument()
+ expect(api.dashboard.balanceHistory).toHaveBeenCalledWith('2026-04-01', undefined, ['2026-02-01'])
+ })
+
+ it('does not carry a comparison month past its last known day', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+ // The comparison month is still in progress: days after today come back null.
+ mockHistory({
+ current: [{ day: 1, balance: 1100 }, { day: 2, balance: 1100 }],
+ comparison: [{ day: 1, balance: 1950 }, { day: 2, balance: null }],
+ comparison_month: '2026-03',
+ comparison_opening_balance: 1900,
+ })
+
+ renderDashboard('/?month=2026-04&comparison_month=2026-03')
+
+ await waitFor(async () => expect(await selectorButton('2026-03')).toHaveTextContent(month('2026-03')))
+ expect(await screen.findAllByText(month('2026-03'))).not.toHaveLength(0)
+ // Day 2 has no comparison value, so there is no footer delta to show.
+ expect(screen.queryByText(
+ t('dashboard.balanceFlowVsMonth', { day: 2, month: month('2026-03'), delta: signed(50) }),
+ )).not.toBeInTheDocument()
+ })
+
+ it('keeps the URL selection when the month options fail to load', async () => {
+ api.dashboard.balanceHistoryMonths.mockRejectedValue(new Error('network'))
+
+ renderWithProviders(
+ <TooltipProvider delayDuration={0}>
+ <LocationProbe />
+ <DashboardPage />
+ </TooltipProvider>,
+ { route: '/?month=2026-04&comparison_month=2026-02' },
+ )
+
+ expect(await screen.findByRole('heading', { name: 'April 2026' })).toBeInTheDocument()
+ // History waits for the month options, so once it is requested the failed request has settled.
+ await waitFor(() => expect(api.dashboard.balanceHistory).toHaveBeenCalled())
+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)))
+ expect(screen.getByTestId('location-search')).toHaveTextContent('comparison_month=2026-02')
+ })
+
+ it('shows the median and the range with three months, compared against the median', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+ mockHistory({
+ baseline: [{ day: 1, median: 40, lower_quartile: 20, upper_quartile: 60 }],
+ })
+
+ renderDashboard('/?month=2026-04&comparison_month=2026-01&comparison_month=2026-02&comparison_month=2026-03')
+
+ expect(await screen.findByText(
+ t('dashboard.balanceFlowVsMedian', { day: 1, median: money(40), delta: signed(60) }),
+ )).toBeInTheDocument()
+ expect(screen.getByText(t('dashboard.balanceMedianLegend'))).toBeInTheDocument()
+ expect(screen.getByText(t('dashboard.balanceRangeLegend'))).toBeInTheDocument()
+ expect(await selectorButton()).toHaveTextContent(`${t('dashboard.compareMonths')} (3)`)
+ })
+
+ it('shows the median but no range when only two months contribute', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+ mockHistory({
+ baseline: [{ day: 1, median: 40, lower_quartile: null, upper_quartile: null }],
+ })
+
+ renderDashboard('/?month=2026-04&comparison_month=2026-02&comparison_month=2026-03')
+
+ expect(await screen.findByText(t('dashboard.balanceMedianLegend'))).toBeInTheDocument()
+ expect(screen.queryByText(t('dashboard.balanceRangeLegend'))).not.toBeInTheDocument()
+ })
+
+ it('defaults to the active months of the previous 12 when the URL has no selection', async () => {
+ // 2025-03 is more than 12 months before April 2026, 2026-05 is after it.
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2025-03', '2025-06', '2026-03', '2026-05'])
+
+ renderDashboard('/?month=2026-04')
+
+ // The options load after first paint, so the label settles asynchronously.
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: (name) => name.startsWith(t('dashboard.compareMonths')) }))
+ .toHaveTextContent(`${t('dashboard.compareMonths')} (2)`)
+ })
+ await waitFor(() => {
+ expect(api.dashboard.balanceHistory).toHaveBeenCalledWith(
+ '2026-04-01',
+ undefined,
+ ['2025-06-01', '2026-03-01'],
+ )
+ })
+ })
+
+ it('follows back and forward navigation between viewed months', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+
+ const { user } = renderWithProviders(
+ <TooltipProvider delayDuration={0}>
+ <DashboardRouteNavigation />
+ <DashboardPage />
+ </TooltipProvider>,
+ { route: '/?month=2026-04&comparison_month=2026-02' },
+ )
+
+ expect(await screen.findByRole('heading', { name: 'April 2026' })).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Navigate to March' }))
+ expect(await screen.findByRole('heading', { name: 'March 2026' })).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'Navigate to April' }))
+ expect(await screen.findByRole('heading', { name: 'April 2026' })).toBeInTheDocument()
+ })
+
+ it('keeps a comparison month that is only valid for the month being navigated to', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+
+ const { user } = renderWithProviders(
+ <TooltipProvider delayDuration={0}>
+ <LocationProbe />
+ <DashboardRouteNavigation />
+ <DashboardPage />
+ </TooltipProvider>,
+ { route: '/?month=2026-03&comparison_month=2026-02' },
+ )
+
+ expect(await screen.findByRole('heading', { name: 'March 2026' })).toBeInTheDocument()
+ await waitFor(() => expect(api.dashboard.balanceHistory).toHaveBeenCalled())
+ // March is not an earlier month while March is still shown, but it is for April.
+ await user.click(screen.getByRole('button', { name: 'Compare April with March' }))
+
+ expect(await screen.findByRole('heading', { name: 'April 2026' })).toBeInTheDocument()
+ await waitFor(() => expect(api.dashboard.balanceHistory).toHaveBeenCalledWith('2026-04-01', undefined, ['2026-03-01']))
+ expect(screen.getByTestId('location-search')).toHaveTextContent('comparison_month=2026-03')
+ })
+
+ it('offers only earlier months, newest first, and keeps the last selected month checked', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03', '2026-04', '2026-05'])
+
+ const { user } = renderDashboard('/?month=2026-04&comparison_month=2026-02')
+ await user.click(await selectorButton('2026-02'))
+
+ const boxes = await screen.findAllByRole('checkbox')
+ expect(boxes.map((box) => box.closest('label')?.textContent)).toEqual([
+ month('2026-03'),
+ month('2026-02'),
+ month('2026-01'),
+ ])
+ expect(screen.getByRole('checkbox', { name: month('2026-03') })).not.toBeChecked()
+ expect(screen.getByRole('checkbox', { name: month('2026-01') })).not.toBeChecked()
+ // The only selected month cannot be removed.
+ expect(screen.getByRole('checkbox', { name: month('2026-02') })).toBeChecked()
+ expect(screen.getByRole('checkbox', { name: month('2026-02') })).toBeDisabled()
+ })
+
+ it('adds a month to the comparison when it is checked', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+
+ const { user } = renderDashboard('/?month=2026-04&comparison_month=2026-02')
+ await user.click(await selectorButton('2026-02'))
+ await user.click(await screen.findByRole('checkbox', { name: month('2026-03') }))
+
+ await waitFor(() => {
+ expect(api.dashboard.balanceHistory).toHaveBeenLastCalledWith(
+ '2026-04-01',
+ undefined,
+ ['2026-02-01', '2026-03-01'],
+ )
+ })
+ expect(await selectorButton()).toHaveTextContent(`${t('dashboard.compareMonths')} (2)`)
+ })
+
+ it('removes a month from the comparison when it is unchecked', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-01', '2026-02', '2026-03'])
+
+ const { user } = renderDashboard('/?month=2026-04&comparison_month=2026-02&comparison_month=2026-03')
+ await user.click(await selectorButton())
+ await user.click(await screen.findByRole('checkbox', { name: month('2026-03') }))
+
+ await waitFor(() => {
+ expect(api.dashboard.balanceHistory).toHaveBeenLastCalledWith(
+ '2026-04-01',
+ undefined,
+ ['2026-02-01'],
+ )
+ })
+ expect(await selectorButton('2026-02')).toHaveTextContent(month('2026-02'))
+ })
+
+ it('disables the selector when there are no earlier months to compare with', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue([])
+
+ renderDashboard('/?month=2026-04')
+
+ expect(await selectorButton()).toBeDisabled()
+ })
+})
+
describe('Dashboard net worth without an FX rate', () => {
const renderDashboard = () => renderWithProviders(
<TooltipProvider delayDuration={0}>
@@ -225,4 +494,32 @@ describe('Dashboard refresh button', () => {
// Only the queries on screen: a refresh must not refetch every page visited earlier.
expect(refetch).toHaveBeenCalledWith({ type: 'active' })
})
+
+ it('refreshes comparison data without losing the selected months', async () => {
+ api.dashboard.balanceHistoryMonths.mockResolvedValue(['2026-02', '2026-03'])
+ const { user } = renderWithProviders(
+ <TooltipProvider delayDuration={0}>
+ <LocationProbe />
+ <DashboardPage />
+ </TooltipProvider>,
+ { route: '/?month=2026-04&comparison_month=2026-02' },
+ )
+
+ await waitFor(() => expect(api.dashboard.balanceHistory).toHaveBeenLastCalledWith(
+ '2026-04-01', undefined, ['2026-02-01'],
+ ))
+ const historyCalls = api.dashboard.balanceHistory.mock.calls.length
+ const monthOptionsCalls = api.dashboard.balanceHistoryMonths.mock.calls.length
+
+ await user.click(screen.getByRole('button', { name: 'Refresh' }))
+
+ await waitFor(() => {
+ expect(api.dashboard.balanceHistory.mock.calls.length).toBeGreaterThan(historyCalls)
+ expect(api.dashboard.balanceHistoryMonths.mock.calls.length).toBeGreaterThan(monthOptionsCalls)
+ })
+ expect(api.dashboard.balanceHistory).toHaveBeenLastCalledWith(
+ '2026-04-01', undefined, ['2026-02-01'],
+ )
+ expect(screen.getByTestId('location-search')).toHaveTextContent('comparison_month=2026-02')
+ })
})
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index c4052727..9917f8f3 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -38,7 +38,7 @@ import {
Tooltip as RechartsTooltip,
ResponsiveContainer,
} from 'recharts'
-import { CheckCircle2, CalendarIcon, Clock, Paperclip, Target, ArrowUpDown, HelpCircle, EyeClosed, AlertCircle } from 'lucide-react'
+import { CheckCircle2, CalendarIcon, ChevronDown, Clock, Paperclip, Target, ArrowUpDown, HelpCircle, EyeClosed, AlertCircle } from 'lucide-react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { ICON_MAP } from '@/lib/category-icons'
import { PageHeader } from '@/components/page-header'
@@ -72,6 +72,8 @@ function parseHashtags(notes: string | null): string[] {
const MONTH_REGEX = /^\d{4}-\d{2}$/
const MONTH_STRING_LENGTH = 7
+const COMPARISON_MONTH_PARAM = 'comparison_month'
+const EMPTY_COMPARISON_MONTHS: string[] = []
function parseMonthFromParams(params: URLSearchParams): string | null {
const monthParam = params.get('month')
@@ -90,6 +92,21 @@ function parseMonthFromParams(params: URLSearchParams): string | null {
return null
}
+function normalizeComparisonMonths(months: string[], availableMonths: string[], viewedMonth: string): string[] {
+ const available = new Set(availableMonths)
+ return [...new Set(months)]
+ .filter((month) => MONTH_REGEX.test(month) && month < viewedMonth && available.has(month))
+ .sort()
+ .slice(-24)
+}
+
+function defaultComparisonMonths(availableMonths: string[], viewedMonth: string): string[] {
+ const firstMonth = shiftMonth(viewedMonth, -12)
+ return availableMonths
+ .filter((month) => MONTH_REGEX.test(month) && month >= firstMonth && month < viewedMonth)
+ .sort()
+}
+
export default function DashboardPage() {
const { t, i18n } = useTranslation()
@@ -121,6 +138,8 @@ export default function DashboardPage() {
const [calendarSelectedDate, setCalendarSelectedDate] = useState<string>(() => searchParams.get('day') ?? '')
const prevSearchRef = useRef<string | null>(null)
+ const searchParamsRef = useRef(searchParams)
+ searchParamsRef.current = searchParams
// Sync state from URL when navigating (e.g. back/forward button)
useEffect(() => {
@@ -141,7 +160,7 @@ export default function DashboardPage() {
// Sync selectedMonth and the transactions view back to URL
useEffect(() => {
- const params = new URLSearchParams(window.location.search)
+ const params = new URLSearchParams(searchParamsRef.current.toString())
if (selectedMonth) {
params.set('month', selectedMonth)
params.delete('from')
@@ -167,6 +186,7 @@ export default function DashboardPage() {
const [createRuleInitialData, setCreateRuleInitialData] = useState<RuleDialogInitialData | undefined>(undefined)
const queryClient = useQueryClient()
const [headerCalOpen, setHeaderCalOpen] = useState(false)
+ const [comparisonPickerOpen, setComparisonPickerOpen] = useState(false)
const [hoveredDay, setHoveredDay] = useState<number | null>(null)
const dateFnsLocale = resolveDateFnsLocale(i18n.resolvedLanguage ?? i18n.language)
const { from: monthStart, to: monthEnd } = monthRange(selectedMonth)
@@ -176,7 +196,7 @@ export default function DashboardPage() {
const handleMonthChange = (newMonth: string) => {
setSelectedMonth(newMonth)
-}
+ }
// Active Collection filter (issue #105): scope dashboard cards to its
// accounts. undefined when "All accounts".
@@ -188,6 +208,71 @@ export default function DashboardPage() {
// silently falling back to "all accounts".
const noAccounts = activeAccountIds !== null && activeAccountIds.length === 0
+ const { data: comparisonMonthOptions, isLoading: comparisonMonthsLoading } = useQuery({
+ queryKey: ['dashboard', 'balance-history-months', activeAccountIds],
+ queryFn: () => dashboard.balanceHistoryMonths(acctIds),
+ enabled: !noAccounts,
+ staleTime: 60_000,
+ })
+ const availableComparisonMonths = comparisonMonthOptions ?? EMPTY_COMPARISON_MONTHS
+ const defaultMonths = useMemo(
+ () => defaultComparisonMonths(availableComparisonMonths, selectedMonth),
+ [availableComparisonMonths, selectedMonth],
+ )
+ const requestedComparisonMonths = useMemo(
+ () => searchParams.getAll(COMPARISON_MONTH_PARAM),
+ [searchParams],
+ )
+ const validComparisonMonths = useMemo(
+ () => normalizeComparisonMonths(
+ requestedComparisonMonths,
+ availableComparisonMonths,
+ selectedMonth,
+ ),
+ [requestedComparisonMonths, availableComparisonMonths, selectedMonth],
+ )
+ const comparisonMonths = validComparisonMonths.length > 0 ? validComparisonMonths : defaultMonths
+
+ useEffect(() => {
+ // Only prune once the options have loaded; a failed request must not drop a shared selection.
+ if (comparisonMonthsLoading || !comparisonMonthOptions || requestedComparisonMonths.length === 0) return
+ // After navigation the URL is ahead of selectedMonth for one render; validate against the month it asks for.
+ const urlMonth = parseMonthFromParams(searchParams)
+ if (urlMonth && urlMonth !== selectedMonth) return
+ if (
+ requestedComparisonMonths.length === validComparisonMonths.length &&
+ requestedComparisonMonths.every((month, index) => month === validComparisonMonths[index])
+ ) return
+
+ const params = new URLSearchParams(searchParams.toString())
+ params.delete(COMPARISON_MONTH_PARAM)
+ validComparisonMonths.forEach((month) => params.append(COMPARISON_MONTH_PARAM, month))
+ setSearchParams(params, { replace: true })
+ }, [
+ comparisonMonthsLoading,
+ comparisonMonthOptions,
+ requestedComparisonMonths,
+ validComparisonMonths,
+ selectedMonth,
+ searchParams,
+ setSearchParams,
+ ])
+
+ const toggleComparisonMonth = (month: string, checked: boolean) => {
+ const nextMonths = checked
+ ? [...comparisonMonths, month]
+ : comparisonMonths.filter((selected) => selected !== month)
+ if (nextMonths.length === 0 || nextMonths.length > 24) return
+
+ const params = new URLSearchParams(searchParams.toString())
+ params.delete(COMPARISON_MONTH_PARAM)
+ const orderedMonths = [...new Set(nextMonths)].sort()
+ orderedMonths.forEach((selected) => {
+ params.append(COMPARISON_MONTH_PARAM, selected)
+ })
+ setSearchParams(params)
+ }
+
const { data: summary, isLoading: summaryLoading, isFetching: summaryFetching } = useQuery({
queryKey: ['dashboard', 'summary', selectedMonth, activeAccountIds, activeWalletIds],
queryFn: () => dashboard.summary(monthParam, undefined, acctIds, walletIds),
@@ -199,12 +284,15 @@ export default function DashboardPage() {
enabled: !noAccounts,
})
- const prevMonth = shiftMonth(selectedMonth, -1)
const { data: balanceHistory, isLoading: balanceHistoryLoading } = useQuery({
- queryKey: ['dashboard', 'balance-history', selectedMonth, activeAccountIds],
- queryFn: () => dashboard.balanceHistory(monthParam, acctIds),
- enabled: !noAccounts,
+ queryKey: ['dashboard', 'balance-history', selectedMonth, activeAccountIds, comparisonMonths],
+ queryFn: () => dashboard.balanceHistory(
+ monthParam,
+ acctIds,
+ comparisonMonths.length > 0 ? comparisonMonths.map((value) => `${value}-01`) : undefined,
+ ),
+ enabled: !noAccounts && !comparisonMonthsLoading,
})
const { data: currentMonthTxs, isLoading: currentTxLoading } = useQuery({
@@ -365,18 +453,32 @@ export default function DashboardPage() {
const cumulativeData = useMemo(() => {
if (!balanceHistory) return []
const daysInMonth = monthLastDay(selectedMonth)
- const result: { day: number; current: number | null; previous: number }[] = []
- let lastPrevBalance = 0
+ const opening = balanceHistory.opening_balance
+ const result: {
+ day: number
+ current: number | null
+ comparison: number | null
+ median: number | null
+ band: [number, number] | null
+ }[] = []
+ let lastComparison: number | null = null
for (let day = 1; day <= daysInMonth; day++) {
const cur = balanceHistory.current.find(d => d.day === day)
- const prev = balanceHistory.previous.find(d => d.day === day)
- if (prev?.balance != null) {
- lastPrevBalance = prev.balance
+ const comparisonPoint = balanceHistory.comparison?.find(d => d.day === day)
+ if (comparisonPoint?.balance != null && balanceHistory.comparison_opening_balance != null) {
+ lastComparison = comparisonPoint.balance - balanceHistory.comparison_opening_balance
+ } else if (comparisonPoint) {
+ // A null balance is a day after today; only carry over days the comparison month lacks.
+ lastComparison = null
}
+ const base = balanceHistory.baseline.find(d => d.day === day)
+ const hasBand = base?.lower_quartile != null && base?.upper_quartile != null
result.push({
day,
- current: cur?.balance ?? null,
- previous: prev?.balance ?? lastPrevBalance,
+ current: cur?.balance != null ? cur.balance - opening : null,
+ comparison: lastComparison,
+ median: base?.median ?? null,
+ band: hasBand ? [base!.lower_quartile!, base!.upper_quartile!] : null,
})
}
return result
@@ -384,9 +486,7 @@ export default function DashboardPage() {
const lastCurrentPoint = [...cumulativeData].reverse().find(d => d.current !== null)
const lastDay = lastCurrentPoint?.day ?? 0
- const currentStartBalance = balanceHistory?.current.find(d => d.day === 1)?.balance ?? 0
- const currentLatestBalance = lastCurrentPoint?.current ?? 0
- const monthVariation = currentLatestBalance - currentStartBalance
+ const monthVariation = lastCurrentPoint?.current ?? 0
const primaryCurrency = summary?.primary_currency ?? userCurrency
const totalBalance = summary?.total_balance_primary ?? Object.values(summary?.total_balance ?? {}).reduce((a, b) => a + Number(b), 0)
@@ -732,13 +832,13 @@ export default function DashboardPage() {
<p className="text-xs tabular-nums mt-2.5 inline-block cursor-help text-muted-foreground underline decoration-dotted underline-offset-2">
{summary.pending_shares_net < 0
? t('dashboard.pendingSharesOwe', {
- net: mask(formatCurrency(availableBalance + summary.pending_shares_net, primaryCurrency, locale)),
- owed: mask(formatCurrency(Math.abs(summary.pending_shares_net), primaryCurrency, locale)),
- })
+ net: mask(formatCurrency(availableBalance + summary.pending_shares_net, primaryCurrency, locale)),
+ owed: mask(formatCurrency(Math.abs(summary.pending_shares_net), primaryCurrency, locale)),
+ })
: t('dashboard.pendingSharesOwed', {
- net: mask(formatCurrency(availableBalance + summary.pending_shares_net, primaryCurrency, locale)),
- owed: mask(formatCurrency(summary.pending_shares_net, primaryCurrency, locale)),
- })}
+ net: mask(formatCurrency(availableBalance + summary.pending_shares_net, primaryCurrency, locale)),
+ owed: mask(formatCurrency(summary.pending_shares_net, primaryCurrency, locale)),
+ })}
</p>
</TooltipTrigger>
<TooltipContent>{t('dashboard.pendingSharesTooltip')}</TooltipContent>
@@ -987,9 +1087,8 @@ export default function DashboardPage() {
<div className="flex items-center gap-2 shrink-0">
<span className="text-sm font-bold tabular-nums text-foreground">{mask(formatCurrency(item.actual, userCurrency, locale))}</span>
{item.momPct !== null && (
- <span className={`inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-bold tabular-nums ${
- item.momPct > 0 ? 'bg-rose-100 text-rose-600 dark:bg-rose-500/20 dark:text-rose-400' : item.momPct < 0 ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400' : 'bg-muted text-muted-foreground'
- }`}>
+ <span className={`inline-flex items-center px-1.5 py-0.5 rounded-full text-[10px] font-bold tabular-nums ${item.momPct > 0 ? 'bg-rose-100 text-rose-600 dark:bg-rose-500/20 dark:text-rose-400' : item.momPct < 0 ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-500/20 dark:text-emerald-400' : 'bg-muted text-muted-foreground'
+ }`}>
{item.momPct > 0 ? '\u2191' : item.momPct < 0 ? '\u2193' : '='}{Math.abs(item.momPct).toFixed(0)}%
</span>
)}
@@ -1003,9 +1102,8 @@ export default function DashboardPage() {
style={{ width: `${Math.min(pct!, 100)}%` }}
/>
</div>
- <span className={`text-[11px] tabular-nums font-medium shrink-0 ${
- pct! > 100 ? 'text-rose-500' : pct! >= 80 ? 'text-amber-500' : 'text-muted-foreground'
- }`}>
+ <span className={`text-[11px] tabular-nums font-medium shrink-0 ${pct! > 100 ? 'text-rose-500' : pct! >= 80 ? 'text-amber-500' : 'text-muted-foreground'
+ }`}>
{mask(t('dashboard.ofBudget', { budget: formatCurrency(item.budget_amount!, userCurrency, locale) }))}
</span>
</div>
@@ -1027,7 +1125,63 @@ export default function DashboardPage() {
<div className="px-5 pt-5 pb-3 shrink-0">
<div className="flex items-start justify-between mb-0.5">
<div>
- <p className="text-base font-bold text-foreground">{t('dashboard.balanceFlow')}</p>
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="text-base font-bold text-foreground">{t('dashboard.balanceFlow')}</p>
+ <Popover open={comparisonPickerOpen} onOpenChange={setComparisonPickerOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ disabled={availableComparisonMonths.filter((month) => month < selectedMonth).length === 0}
+ aria-label={comparisonMonths.length === 1
+ ? monthLabel(comparisonMonths[0], uiLocale)
+ : `${t('dashboard.compareMonths')} (${comparisonMonths.length})`}
+ className="h-7 gap-1.5 px-2 text-[11px] font-medium"
+ >
+ <CalendarIcon className="size-3.5" />
+ {comparisonMonths.length === 1
+ ? monthLabel(comparisonMonths[0], uiLocale)
+ : `${t('dashboard.compareMonths')} (${comparisonMonths.length})`}
+ <ChevronDown className="size-3" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-64 p-2">
+ <p className="px-2 pb-2 text-xs font-semibold text-foreground">
+ {t('dashboard.selectComparisonMonths')}
+ </p>
+ <div className="max-h-64 overflow-y-auto">
+ {availableComparisonMonths
+ .filter((month) => month < selectedMonth)
+ .slice()
+ .reverse()
+ .map((month) => {
+ const checked = comparisonMonths.includes(month)
+ return (
+ <label
+ key={month}
+ className="flex cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-xs hover:bg-muted"
+ >
+ <input
+ type="checkbox"
+ checked={checked}
+ disabled={
+ (checked && comparisonMonths.length === 1) ||
+ (!checked && comparisonMonths.length >= 24)
+ }
+ onChange={(event) => toggleComparisonMonth(month, event.target.checked)}
+ />
+ <span>{monthLabel(month, uiLocale)}</span>
+ </label>
+ )
+ })}
+ </div>
+ {availableComparisonMonths.filter((month) => month < selectedMonth).length === 0 && (
+ <p className="px-2 py-2 text-xs text-muted-foreground">{t('dashboard.noData')}</p>
+ )}
+ </PopoverContent>
+ </Popover>
+ </div>
<p className="text-xs text-muted-foreground mt-0.5">
{new Date(`${selectedMonth}-01T00:00:00`).toLocaleDateString(dateLocale)} → {new Date(`${selectedMonth}-${String(lastCurrentPoint?.day ?? monthLastDay(selectedMonth)).padStart(2, '0')}T00:00:00`).toLocaleDateString(dateLocale)}
</p>
@@ -1046,10 +1200,25 @@ export default function DashboardPage() {
<span className="inline-block w-3 h-0.5 rounded-full bg-emerald-500" />
{t('dashboard.balanceCurrentMonthLegend')}
</span>
- <span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
- <span className="inline-block w-3 border-t-2 border-dashed border-slate-400" />
- {t('dashboard.balancePreviousMonthLegend')}
- </span>
+ {comparisonMonths.length === 1 ? (
+ <span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ <span className="inline-block w-3 border-t-2 border-dashed border-slate-400" />
+ {monthLabel(comparisonMonths[0], uiLocale)}
+ </span>
+ ) : (
+ <>
+ <span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ <span className="inline-block w-3 h-0.5 rounded-full bg-slate-400" />
+ {t('dashboard.balanceMedianLegend')}
+ </span>
+ {cumulativeData.some((point) => point.band !== null) && (
+ <span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ <span className="inline-block w-3 h-2 rounded-sm bg-slate-400/25" />
+ {t('dashboard.balanceRangeLegend')}
+ </span>
+ )}
+ </>
+ )}
</div>
</div>
<div className="px-1 pb-4 flex-1 min-h-0">
@@ -1109,15 +1278,28 @@ export default function DashboardPage() {
width={56}
tickCount={5}
domain={[
- (dataMin: number) => dataMin < 0 ? Math.floor(dataMin / 100) * 100 : 0,
- (dataMax: number) => Math.ceil(dataMax / 100) * 100,
+ (dataMin: number) => Math.min(0, Math.floor(dataMin / 100) * 100),
+ (dataMax: number) => Math.max(0, Math.ceil(dataMax / 100) * 100),
]}
/>
<RechartsTooltip
- formatter={(value, name) => [
- value !== null ? (privacyMode ? MASK : formatCurrency(Number(value), userCurrency, locale)) : '\u2014',
- name === 'current' ? monthLabel(selectedMonth, uiLocale).split(' ')[0] : monthLabel(prevMonth, uiLocale).split(' ')[0],
- ]}
+ formatter={(value, name) => {
+ const fmt = (v: number) => (privacyMode ? MASK : formatCurrency(v, userCurrency, locale))
+ if (name === 'band') {
+ const range = value as [number, number] | null
+ return [range ? `${fmt(range[0])} – ${fmt(range[1])}` : '\u2014', t('dashboard.balanceRangeLegend')]
+ }
+ if (name === 'comparison') {
+ return [
+ value !== null ? fmt(Number(value)) : '\u2014',
+ monthLabel(comparisonMonths[0], uiLocale),
+ ]
+ }
+ return [
+ value !== null ? fmt(Number(value)) : '\u2014',
+ name === 'current' ? monthLabel(selectedMonth, uiLocale).split(' ')[0] : t('dashboard.balanceMedianLegend'),
+ ]
+ }}
labelFormatter={(day) => t('dashboard.day', { day })}
contentStyle={{
background: 'var(--card)',
@@ -1128,6 +1310,16 @@ export default function DashboardPage() {
fontSize: '12px',
}}
/>
+ <Area
+ type="monotone"
+ dataKey="band"
+ stroke="none"
+ fill="#94A3B8"
+ fillOpacity={0.22}
+ dot={false}
+ activeDot={false}
+ connectNulls={false}
+ />
<Area
type="monotone"
dataKey="current"
@@ -1140,12 +1332,13 @@ export default function DashboardPage() {
/>
<Line
type="monotone"
- dataKey="previous"
+ dataKey={comparisonMonths.length === 1 ? 'comparison' : 'median'}
stroke="#94A3B8"
strokeWidth={2}
- strokeDasharray="5 3"
+ strokeDasharray={comparisonMonths.length === 1 ? '5 3' : undefined}
dot={false}
activeDot={{ r: 3, fill: '#94A3B8' }}
+ connectNulls={false}
/>
</ComposedChart>
</ResponsiveContainer>
@@ -1155,22 +1348,34 @@ export default function DashboardPage() {
</div>
{!balanceHistoryLoading && lastCurrentPoint && (() => {
const footerDay = hoveredDay ?? lastDay
- const footerPrev = balanceHistory?.previous.find(d => d.day === footerDay)?.balance ?? 0
- const footerCurrent = cumulativeData.find(d => d.day === footerDay)?.current ?? totalBalance
- const footerPct = footerPrev !== 0 ? ((footerCurrent - footerPrev) / Math.abs(footerPrev)) * 100 : null
- if (footerPrev === 0 || footerPct === null) return null
+ const point = cumulativeData.find(d => d.day === footerDay)
+ const comparisonValue = comparisonMonths.length === 1 ? point?.comparison : point?.median
+ if (!point || comparisonValue == null || point.current == null) return null
+ const footerDelta = point.current - comparisonValue
+ if (comparisonMonths.length === 1) {
+ return (
+ <div className="px-5 pb-4 pt-0 shrink-0">
+ <p className="text-xs text-muted-foreground">
+ {t('dashboard.balanceFlowVsMonth', {
+ day: footerDay,
+ month: monthLabel(comparisonMonths[0], uiLocale),
+ delta: mask(`${footerDelta >= 0 ? '+' : ''}${formatCurrency(footerDelta, userCurrency, locale)}`),
+ })}
+ </p>
+ </div>
+ )
+ }
return (
<div className="px-5 pb-4 pt-0 shrink-0">
<p className="text-xs text-muted-foreground">
- {t('dashboard.balanceFlowVsPrev', {
- month: monthLabel(prevMonth, uiLocale).split(' ')[0],
+ {t('dashboard.balanceFlowVsMedian', {
day: footerDay,
- amount: mask(formatCurrency(footerPrev, userCurrency, locale)),
- delta: `${footerPct >= 0 ? '+' : ''}${footerPct.toFixed(1)}%`,
+ median: mask(formatCurrency(point.median, userCurrency, locale)),
+ delta: mask(`${footerDelta >= 0 ? '+' : ''}${formatCurrency(footerDelta, userCurrency, locale)}`),
})}
{' '}
- <span className={footerPct >= 0 ? 'text-emerald-600' : 'text-rose-500'}>
- {footerPct >= 0 ? '\u25B2' : '\u25BC'}
+ <span className={footerDelta >= 0 ? 'text-emerald-600' : 'text-rose-500'}>
+ {footerDelta >= 0 ? '\u25B2' : '\u25BC'}
</span>
</p>
</div>
@@ -1290,300 +1495,298 @@ export default function DashboardPage() {
)}
{txViewMode === 'list' && (
- <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
- {txListLoading ? (
- <div className="p-5 space-y-3">
- {Array.from({ length: 5 }).map((_, i) => (
- <Skeleton key={i} className="h-10 w-full" />
- ))}
- </div>
- ) : pagedRows.length > 0 ? (
- <>
- {isMobile ? (
- <div>
- {pagedRows.map((row) => (
- <div
- key={row.key}
- className={`flex items-center gap-3 pl-3 pr-3 py-3 border-b border-border last:border-0 bg-card ${
- row.isProjected ? '' : 'cursor-pointer active:bg-muted/60'
- }`}
- onClick={() => {
- if (row.isProjected) return
- if (row.isShared) {
- if (row.groupId) navigate(`/groups/${row.groupId}`)
- return
- }
- const tx = currentMonthTxs?.items.find((t) => t.id === row.key)
- if (tx) { setEditingTx(tx); setDialogOpen(true) }
- }}
- >
- {/* Category Icon */}
- <div className="shrink-0">
- <CategoryIcon icon={row.categoryIcon} color={row.categoryColor} size="md" />
- </div>
+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
+ {txListLoading ? (
+ <div className="p-5 space-y-3">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-10 w-full" />
+ ))}
+ </div>
+ ) : pagedRows.length > 0 ? (
+ <>
+ {isMobile ? (
+ <div>
+ {pagedRows.map((row) => (
+ <div
+ key={row.key}
+ className={`flex items-center gap-3 pl-3 pr-3 py-3 border-b border-border last:border-0 bg-card ${row.isProjected ? '' : 'cursor-pointer active:bg-muted/60'
+ }`}
+ onClick={() => {
+ if (row.isProjected) return
+ if (row.isShared) {
+ if (row.groupId) navigate(`/groups/${row.groupId}`)
+ return
+ }
+ const tx = currentMonthTxs?.items.find((t) => t.id === row.key)
+ if (tx) { setEditingTx(tx); setDialogOpen(true) }
+ }}
+ >
+ {/* Category Icon */}
+ <div className="shrink-0">
+ <CategoryIcon icon={row.categoryIcon} color={row.categoryColor} size="md" />
+ </div>
- {/* Content */}
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-1.5">
- <p className="text-sm font-semibold text-foreground truncate leading-tight">{row.description}</p>
- {row.groupId && (
- <span className="inline-flex items-center text-[9px] font-semibold uppercase tracking-wide text-violet-700 bg-violet-50 border border-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:border-violet-900 px-1 py-0.5 rounded-full shrink-0">
- {row.isShared && row.parentOwnerName
- ? t('splitGroups.sharedShortBadgeAuthor', { author: row.parentOwnerName })
- : row.groupName ?? t('splitGroups.sharedShortBadge')}
- </span>
- )}
- {row.isProjected && (
- <ProjectedTransactionBadge />
- )}
- {row.installmentNumber != null && row.totalInstallments != null && (
- <span className="inline-flex items-center text-[9px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1 py-0.5 rounded-full shrink-0">
- {row.installmentNumber}/{row.totalInstallments}
- </span>
+ {/* Content */}
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <p className="text-sm font-semibold text-foreground truncate leading-tight">{row.description}</p>
+ {row.groupId && (
+ <span className="inline-flex items-center text-[9px] font-semibold uppercase tracking-wide text-violet-700 bg-violet-50 border border-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:border-violet-900 px-1 py-0.5 rounded-full shrink-0">
+ {row.isShared && row.parentOwnerName
+ ? t('splitGroups.sharedShortBadgeAuthor', { author: row.parentOwnerName })
+ : row.groupName ?? t('splitGroups.sharedShortBadge')}
+ </span>
+ )}
+ {row.isProjected && (
+ <ProjectedTransactionBadge />
+ )}
+ {row.installmentNumber != null && row.totalInstallments != null && (
+ <span className="inline-flex items-center text-[9px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1 py-0.5 rounded-full shrink-0">
+ {row.installmentNumber}/{row.totalInstallments}
+ </span>
+ )}
+ {row.showPendingBadge && (
+ <span
+ title={t('transactions.pending')}
+ className="shrink-0 inline-flex items-center justify-center rounded-full border border-amber-200 bg-amber-50 p-0.5 dark:border-amber-500/30 dark:bg-amber-500/10"
+ >
+ <Clock size={12} className="text-amber-500" role="img" aria-label={t('transactions.pending')} />
+ </span>
+ )}
+ {row.isIgnored && (
+ <EyeClosed className="h-3 w-3 text-gray-500 shrink-0" />
+ )}
+ {row.attachmentCount > 0 && (
+ <Paperclip size={11} className="text-muted-foreground shrink-0" />
+ )}
+ </div>
+ {row.accountId && (() => {
+ const acc = accountsList?.find((a) => a.id === row.accountId)
+ if (!acc) return null
+ return (
+ <div className="flex items-center gap-1.5 mt-0.5">
+ <AccountIcon account={acc} size="xs" />
+ <span className="text-xs text-muted-foreground truncate">{getAccountName(acc)}</span>
+ </div>
+ )
+ })()}
+ {!row.accountId && (
+ <p className="text-xs text-muted-foreground mt-0.5">{formatDate(row.date, dateLocale)}</p>
)}
- {row.showPendingBadge && (
- <span
- title={t('transactions.pending')}
- className="shrink-0 inline-flex items-center justify-center rounded-full border border-amber-200 bg-amber-50 p-0.5 dark:border-amber-500/30 dark:bg-amber-500/10"
- >
- <Clock size={12} className="text-amber-500" role="img" aria-label={t('transactions.pending')} />
- </span>
+ </div>
+
+ {/* Amount */}
+ <div className="shrink-0 text-right">
+ <span className={`text-sm font-bold tabular-nums ${row.isIgnored ? 'text-gray-500' : row.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>
+ {mask(`${row.isIgnored ? ' ' : row.type === 'credit' ? '+' : '\u2212'}${formatCurrency(Math.abs(row.amount), row.currency, locale)}`)}
+ </span>
+ {row.isShared && row.parentTotal != null && (
+ <div className="text-[10px] text-muted-foreground tabular-nums mt-0.5">
+ {t('splitGroups.sharedRowParent', {
+ total: formatCurrency(Math.abs(row.parentTotal), row.currency, locale),
+ })}
+ </div>
)}
- {row.isIgnored && (
- <EyeClosed className="h-3 w-3 text-gray-500 shrink-0" />
+ {!row.isShared && row.ownerShare != null && (
+ <div className="text-[10px] text-muted-foreground tabular-nums mt-0.5">
+ {t('splitGroups.ownerRowYourShare', {
+ share: formatCurrency(Math.abs(row.ownerShare), row.currency, locale),
+ })}
+ </div>
)}
- {row.attachmentCount > 0 && (
- <Paperclip size={11} className="text-muted-foreground shrink-0" />
+ {!row.isShared && row.currency !== userCurrency && row.amountPrimary != null && (
+ <div className="text-[10px] text-muted-foreground tabular-nums mt-0.5">
+ {mask(formatCurrency(Math.abs(row.amountPrimary), userCurrency, locale))}
+ </div>
)}
</div>
- {row.accountId && (() => {
- const acc = accountsList?.find((a) => a.id === row.accountId)
- if (!acc) return null
- return (
- <div className="flex items-center gap-1.5 mt-0.5">
- <AccountIcon account={acc} size="xs" />
- <span className="text-xs text-muted-foreground truncate">{getAccountName(acc)}</span>
- </div>
- )
- })()}
- {!row.accountId && (
- <p className="text-xs text-muted-foreground mt-0.5">{formatDate(row.date, dateLocale)}</p>
- )}
- </div>
-
- {/* Amount */}
- <div className="shrink-0 text-right">
- <span className={`text-sm font-bold tabular-nums ${row.isIgnored ? 'text-gray-500' : row.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>
- {mask(`${row.isIgnored ? ' ' : row.type === 'credit' ? '+' : '\u2212'}${formatCurrency(Math.abs(row.amount), row.currency, locale)}`)}
- </span>
- {row.isShared && row.parentTotal != null && (
- <div className="text-[10px] text-muted-foreground tabular-nums mt-0.5">
- {t('splitGroups.sharedRowParent', {
- total: formatCurrency(Math.abs(row.parentTotal), row.currency, locale),
- })}
- </div>
- )}
- {!row.isShared && row.ownerShare != null && (
- <div className="text-[10px] text-muted-foreground tabular-nums mt-0.5">
- {t('splitGroups.ownerRowYourShare', {
- share: formatCurrency(Math.abs(row.ownerShare), row.currency, locale),
- })}
- </div>
- )}
- {!row.isShared && row.currency !== userCurrency && row.amountPrimary != null && (
- <div className="text-[10px] text-muted-foreground tabular-nums mt-0.5">
- {mask(formatCurrency(Math.abs(row.amountPrimary), userCurrency, locale))}
- </div>
- )}
</div>
- </div>
- ))}
- </div>
- ) : (
- <Table>
- <TableHeader>
- <TableRow className="border-b border-border hover:bg-transparent">
- <TableHead className="pl-5 text-xs font-medium text-muted-foreground hidden sm:table-cell">{t('transactions.date')}</TableHead>
- <TableHead className="text-xs font-medium text-muted-foreground">{t('transactions.description')}</TableHead>
- <TableHead className="text-xs font-medium text-muted-foreground hidden sm:table-cell">{t('transactions.account')}</TableHead>
- <TableHead className="pr-5 text-right text-xs font-medium text-muted-foreground">{t('transactions.amount')}</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {pagedRows.map((row) => (
- <TableRow
- key={row.key}
- className={`border-b border-border last:border-0 ${
- row.isProjected
- ? ''
- : row.isShared
- ? 'cursor-pointer hover:bg-muted'
- : 'cursor-pointer hover:bg-muted'
- }`}
- onClick={() => {
- if (row.isProjected) return
- if (row.isShared) {
- // Shared rows belong to another user — open the
- // group instead of the (locked) edit dialog.
- if (row.groupId) navigate(`/groups/${row.groupId}`)
- return
- }
- const tx = currentMonthTxs?.items.find((t) => t.id === row.key)
- if (tx) { setEditingTx(tx); setDialogOpen(true) }
- }}
- >
- <TableCell className="py-2.5 pl-5 text-sm text-muted-foreground tabular-nums whitespace-nowrap hidden sm:table-cell">
- {formatDate(row.date, dateLocale)}
- </TableCell>
- <TableCell className="py-2.5 pl-5 sm:pl-0">
- <div className="flex items-center gap-3">
- <CategoryIcon icon={row.categoryIcon} color={row.categoryColor} size="lg" />
- <div className="min-w-0">
- <div className="flex items-center gap-2">
- <p className="text-sm font-semibold text-foreground truncate">{row.description}</p>
- {row.groupId && (
- <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold bg-violet-100 text-violet-700 dark:bg-violet-950/40 dark:text-violet-300 shrink-0 uppercase tracking-wide">
- {row.isShared && row.parentOwnerName
- ? t('splitGroups.sharedShortBadgeAuthor', { author: row.parentOwnerName })
- : row.groupName ?? t('splitGroups.sharedShortBadge')}
- </span>
- )}
- {row.isProjected && (
- <ProjectedTransactionBadge />
- )}
- {row.installmentNumber != null && row.totalInstallments != null && (
- <span className="inline-flex items-center text-[10px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1.5 py-0.5 rounded-full shrink-0">
- {row.installmentNumber}/{row.totalInstallments}
- </span>
- )}
- {row.showPendingBadge && (
- <span
- title={t('transactions.pending')}
- className="shrink-0 inline-flex items-center justify-center rounded-full border border-amber-200 bg-amber-50 p-0.5 dark:border-amber-500/30 dark:bg-amber-500/10"
- >
- <Clock size={12} className="text-amber-500" role="img" aria-label={t('transactions.pending')} />
- </span>
- )}
- {row.isIgnored && (
- <span className="ml-2 inline-flex items-center gap-1 text-xs text-gray-600 font-normal bg-gray-100 border border-gray-200 rounded px-1.5 py-0.5">
- <EyeClosed className="h-3 w-3" />
- {t('transactions.ignored')}
- <span title={t('transactions.ignoreTransferHint')}><HelpCircle className="h-3 w-3 text-blue-400" /></span>
- </span>
- )}
- {row.attachmentCount > 0 && (
- <Paperclip size={12} className="text-muted-foreground shrink-0" />
- )}
+ ))}
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow className="border-b border-border hover:bg-transparent">
+ <TableHead className="pl-5 text-xs font-medium text-muted-foreground hidden sm:table-cell">{t('transactions.date')}</TableHead>
+ <TableHead className="text-xs font-medium text-muted-foreground">{t('transactions.description')}</TableHead>
+ <TableHead className="text-xs font-medium text-muted-foreground hidden sm:table-cell">{t('transactions.account')}</TableHead>
+ <TableHead className="pr-5 text-right text-xs font-medium text-muted-foreground">{t('transactions.amount')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {pagedRows.map((row) => (
+ <TableRow
+ key={row.key}
+ className={`border-b border-border last:border-0 ${row.isProjected
+ ? ''
+ : row.isShared
+ ? 'cursor-pointer hover:bg-muted'
+ : 'cursor-pointer hover:bg-muted'
+ }`}
+ onClick={() => {
+ if (row.isProjected) return
+ if (row.isShared) {
+ // Shared rows belong to another user — open the
+ // group instead of the (locked) edit dialog.
+ if (row.groupId) navigate(`/groups/${row.groupId}`)
+ return
+ }
+ const tx = currentMonthTxs?.items.find((t) => t.id === row.key)
+ if (tx) { setEditingTx(tx); setDialogOpen(true) }
+ }}
+ >
+ <TableCell className="py-2.5 pl-5 text-sm text-muted-foreground tabular-nums whitespace-nowrap hidden sm:table-cell">
+ {formatDate(row.date, dateLocale)}
+ </TableCell>
+ <TableCell className="py-2.5 pl-5 sm:pl-0">
+ <div className="flex items-center gap-3">
+ <CategoryIcon icon={row.categoryIcon} color={row.categoryColor} size="lg" />
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <p className="text-sm font-semibold text-foreground truncate">{row.description}</p>
+ {row.groupId && (
+ <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold bg-violet-100 text-violet-700 dark:bg-violet-950/40 dark:text-violet-300 shrink-0 uppercase tracking-wide">
+ {row.isShared && row.parentOwnerName
+ ? t('splitGroups.sharedShortBadgeAuthor', { author: row.parentOwnerName })
+ : row.groupName ?? t('splitGroups.sharedShortBadge')}
+ </span>
+ )}
+ {row.isProjected && (
+ <ProjectedTransactionBadge />
+ )}
+ {row.installmentNumber != null && row.totalInstallments != null && (
+ <span className="inline-flex items-center text-[10px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1.5 py-0.5 rounded-full shrink-0">
+ {row.installmentNumber}/{row.totalInstallments}
+ </span>
+ )}
+ {row.showPendingBadge && (
+ <span
+ title={t('transactions.pending')}
+ className="shrink-0 inline-flex items-center justify-center rounded-full border border-amber-200 bg-amber-50 p-0.5 dark:border-amber-500/30 dark:bg-amber-500/10"
+ >
+ <Clock size={12} className="text-amber-500" role="img" aria-label={t('transactions.pending')} />
+ </span>
+ )}
+ {row.isIgnored && (
+ <span className="ml-2 inline-flex items-center gap-1 text-xs text-gray-600 font-normal bg-gray-100 border border-gray-200 rounded px-1.5 py-0.5">
+ <EyeClosed className="h-3 w-3" />
+ {t('transactions.ignored')}
+ <span title={t('transactions.ignoreTransferHint')}><HelpCircle className="h-3 w-3 text-blue-400" /></span>
+ </span>
+ )}
+ {row.attachmentCount > 0 && (
+ <Paperclip size={12} className="text-muted-foreground shrink-0" />
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground sm:hidden">{formatDate(row.date, dateLocale)}</p>
+ </div>
</div>
- <p className="text-xs text-muted-foreground sm:hidden">{formatDate(row.date, dateLocale)}</p>
- </div>
- </div>
- </TableCell>
- <TableCell className="py-2.5 text-sm text-muted-foreground hidden sm:table-cell">
- {(() => {
- const acc = row.accountId
- ? accountsList?.find((a) => a.id === row.accountId)
- : undefined
- if (!acc) return <span className="text-muted-foreground">—</span>
- return (
- <span className="flex items-center gap-2 min-w-0">
- <AccountIcon account={acc} size="sm" />
- <span className="truncate">{getAccountName(acc)}</span>
+ </TableCell>
+ <TableCell className="py-2.5 text-sm text-muted-foreground hidden sm:table-cell">
+ {(() => {
+ const acc = row.accountId
+ ? accountsList?.find((a) => a.id === row.accountId)
+ : undefined
+ if (!acc) return <span className="text-muted-foreground">—</span>
+ return (
+ <span className="flex items-center gap-2 min-w-0">
+ <AccountIcon account={acc} size="sm" />
+ <span className="truncate">{getAccountName(acc)}</span>
+ </span>
+ )
+ })()}
+ </TableCell>
+ <TableCell className="py-2.5 pr-5 text-right">
+ <span className={`text-sm font-semibold tabular-nums ${row.isIgnored ? 'text-gray-500' : row.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>
+ {mask(`${row.isIgnored ? ' ' : row.type === 'credit' ? '+' : '-'}${formatCurrency(Math.abs(row.amount), row.currency, locale)}`)}
</span>
- )
- })()}
- </TableCell>
- <TableCell className="py-2.5 pr-5 text-right">
- <span className={`text-sm font-semibold tabular-nums ${row.isIgnored ? 'text-gray-500' : row.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>
- {mask(`${row.isIgnored ? ' ' : row.type === 'credit' ? '+' : '-'}${formatCurrency(Math.abs(row.amount), row.currency, locale)}`)}
+ {row.isShared && row.parentTotal != null && (
+ <span className="block text-[10px] text-muted-foreground tabular-nums">
+ {t('splitGroups.sharedRowParent', {
+ total: formatCurrency(Math.abs(row.parentTotal), row.currency, locale),
+ })}
+ </span>
+ )}
+ {!row.isShared && row.ownerShare != null && (
+ <span className="block text-[10px] text-muted-foreground tabular-nums">
+ {t('splitGroups.ownerRowYourShare', {
+ share: formatCurrency(Math.abs(row.ownerShare), row.currency, locale),
+ })}
+ </span>
+ )}
+ {!row.isShared && row.currency !== userCurrency && row.amountPrimary != null && (
+ <span className="block text-[10px] text-muted-foreground tabular-nums">
+ {mask(formatCurrency(Math.abs(row.amountPrimary), userCurrency, locale))}
+ </span>
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ {allDisplayRows.length > 10 && (
+ <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-5 py-4 border-t border-border">
+ <div className="hidden sm:block w-32" />
+ {txTotalPages > 1 ? (
+ <div className="flex items-center justify-center gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={txPage <= 1}
+ onClick={() => setTxPage(txPage - 1)}
+ >
+ {t('dashboard.previous')}
+ </Button>
+ <span className="text-sm text-muted-foreground">
+ {txPage} / {txTotalPages}
</span>
- {row.isShared && row.parentTotal != null && (
- <span className="block text-[10px] text-muted-foreground tabular-nums">
- {t('splitGroups.sharedRowParent', {
- total: formatCurrency(Math.abs(row.parentTotal), row.currency, locale),
- })}
- </span>
- )}
- {!row.isShared && row.ownerShare != null && (
- <span className="block text-[10px] text-muted-foreground tabular-nums">
- {t('splitGroups.ownerRowYourShare', {
- share: formatCurrency(Math.abs(row.ownerShare), row.currency, locale),
- })}
- </span>
- )}
- {!row.isShared && row.currency !== userCurrency && row.amountPrimary != null && (
- <span className="block text-[10px] text-muted-foreground tabular-nums">
- {mask(formatCurrency(Math.abs(row.amountPrimary), userCurrency, locale))}
- </span>
- )}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- )}
- {allDisplayRows.length > 10 && (
- <div className="flex flex-col sm:flex-row items-center justify-between gap-4 px-5 py-4 border-t border-border">
- <div className="hidden sm:block w-32" />
- {txTotalPages > 1 ? (
- <div className="flex items-center justify-center gap-2">
- <Button
- variant="outline"
- size="sm"
- disabled={txPage <= 1}
- onClick={() => setTxPage(txPage - 1)}
- >
- {t('dashboard.previous')}
- </Button>
- <span className="text-sm text-muted-foreground">
- {txPage} / {txTotalPages}
- </span>
- <Button
- variant="outline"
- size="sm"
- disabled={txPage >= txTotalPages}
- onClick={() => setTxPage(txPage + 1)}
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={txPage >= txTotalPages}
+ onClick={() => setTxPage(txPage + 1)}
+ >
+ {t('dashboard.next')}
+ </Button>
+ </div>
+ ) : (
+ <div className="hidden sm:block" />
+ )}
+
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-muted-foreground">{t('common.rowsPerPage', 'Rows per page')}</span>
+ <Select
+ value={String(txPerPage)}
+ onValueChange={(val) => {
+ const nextLimit = Number(val)
+ setTxPerPage(nextLimit)
+ setTxPage(1)
+ try {
+ localStorage.setItem('securo.dashboard.pageSize', String(nextLimit))
+ } catch {
+ // ignored
+ }
+ }}
>
- {t('dashboard.next')}
- </Button>
+ <SelectTrigger className="w-[70px] h-8 text-xs">
+ <SelectValue placeholder={txPerPage} />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="10">10</SelectItem>
+ <SelectItem value="20">20</SelectItem>
+ <SelectItem value="50">50</SelectItem>
+ <SelectItem value="100">100</SelectItem>
+ </SelectContent>
+ </Select>
</div>
- ) : (
- <div className="hidden sm:block" />
- )}
-
- <div className="flex items-center gap-2">
- <span className="text-xs text-muted-foreground">{t('common.rowsPerPage', 'Rows per page')}</span>
- <Select
- value={String(txPerPage)}
- onValueChange={(val) => {
- const nextLimit = Number(val)
- setTxPerPage(nextLimit)
- setTxPage(1)
- try {
- localStorage.setItem('securo.dashboard.pageSize', String(nextLimit))
- } catch {
- // ignored
- }
- }}
- >
- <SelectTrigger className="w-[70px] h-8 text-xs">
- <SelectValue placeholder={txPerPage} />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="10">10</SelectItem>
- <SelectItem value="20">20</SelectItem>
- <SelectItem value="50">50</SelectItem>
- <SelectItem value="100">100</SelectItem>
- </SelectContent>
- </Select>
</div>
- </div>
- )}
- </>
- ) : (
- <p className="text-muted-foreground text-sm text-center py-8">{t('dashboard.noTransactions')}</p>
- )}
- </div>
+ )}
+ </>
+ ) : (
+ <p className="text-muted-foreground text-sm text-center py-8">{t('dashboard.noTransactions')}</p>
+ )}
+ </div>
)}
</div>
@@ -1591,12 +1794,12 @@ export default function DashboardPage() {
filter={
drillDown
? {
- ...drillDown,
- // Keep drill-downs consistent with the collection-scoped cards
- // they open from (e.g. "Categorize now").
- account_ids:
- drillDown.account_ids ?? (acctIds && acctIds.length > 0 ? acctIds : undefined),
- }
+ ...drillDown,
+ // Keep drill-downs consistent with the collection-scoped cards
+ // they open from (e.g. "Categorize now").
+ account_ids:
+ drillDown.account_ids ?? (acctIds && acctIds.length > 0 ? acctIds : undefined),
+ }
: null
}
onClose={() => setDrillDown(null)}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index c36edc73..65317a09 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -780,6 +780,13 @@ export interface DailyBalance {
balance: number | null
}
+export interface DailyBaseline {
+ day: number
+ median: number | null
+ lower_quartile: number | null
+ upper_quartile: number | null
+}
+
/** End-of-day balance of one account, one point per day (#1202). */
export interface AccountRunningBalancePoint {
date: string
@@ -789,7 +796,11 @@ export interface AccountRunningBalancePoint {
export interface BalanceHistory {
current: DailyBalance[]
- previous: DailyBalance[]
+ opening_balance: number
+ baseline: DailyBaseline[]
+ comparison: DailyBalance[] | null
+ comparison_month: string | null
+ comparison_opening_balance: number | null
}
export interface Budget {