Open-source personal finance manager. Self-hosted, privacy-first.
Feat/networth evolution composition link (#335)
Geovane Pereira69d5b7a84e28
diff --git a/backend/app/schemas/report.py b/backend/app/schemas/report.pyindex 0c99f4f4..0d9604bf 100644--- a/backend/app/schemas/report.py+++ b/backend/app/schemas/report.py@@ -15,11 +15,20 @@ class ReportSummary(BaseModel):breakdowns: list[ReportBreakdown]+class ReportCompositionItem(BaseModel):+ key: str+ label: str+ value: float+ color: str+ group: str++class ReportDataPoint(BaseModel):date: strvalue: floatbreakdowns: dict[str, float]change: float | None = None+ composition: list[ReportCompositionItem] = []class ReportMeta(BaseModel):@@ -32,14 +41,6 @@ class ReportMeta(BaseModel):baseline_lookback_days: int | None = None-class ReportCompositionItem(BaseModel):- key: str- label: str- value: float- color: str- group: str--class CategoryTrendItem(BaseModel):key: strlabel: strdiff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 99a83d83..0c878829 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -32,11 +32,25 @@ from app.schemas.report import (ReportResponse,ReportSummary,)-from app.services.asset_service import get_asset_values_atfrom app.services.dashboard_service import _get_open_accounts, _account_balance_atCATEGORY_TREND_TOP_N = 11+_ACCOUNT_TYPE_COLORS: dict[str, str] = {+ "checking": "#6366F1",+ "savings": "#3B82F6",+ "credit_card": "#F43F5E",+ "investment": "#8B5CF6",+ "wallet": "#F59E0B",+}+_ASSET_TYPE_COLORS: dict[str, str] = {+ "real_estate": "#0EA5E9",+ "vehicle": "#14B8A6",+ "valuable": "#F59E0B",+ "investment": "#8B5CF6",+ "other": "#6B7280",+}+def _report_start_date(today: date, months: int, period: str | None = None) -> date:"""Resolve historical report start date."""@@ -53,11 +67,36 @@ async def _asset_value_at(group_ids: Optional[list[uuid.UUID]] = None,) -> float:"""Sum of all active asset values at a given date, converted to primary currency."""- _, total = await get_asset_values_at(- session, workspace_id, as_of_date=cutoff,- primary_currency=primary_currency, by_workspace=True,- group_ids=group_ids,+ asset_stmt = select(Asset).where(+ Asset.workspace_id == workspace_id,+ Asset.is_archived == False,+ Asset.sell_date.is_(None),)+ if group_ids is not None:+ asset_stmt = asset_stmt.where(Asset.group_id.in_(group_ids))+ asset_result = await session.execute(asset_stmt)+ total = 0.0+ for asset in asset_result.scalars().all():+ val_result = await session.execute(+ select(AssetValue.amount)+ .where(AssetValue.asset_id == asset.id, AssetValue.date <= cutoff)+ .order_by(desc(AssetValue.date), desc(AssetValue.id))+ .limit(1)+ )+ val = val_result.scalar_one_or_none()+ if val is not None:+ amount = float(val)+ elif asset.purchase_price is not None and (+ asset.purchase_date is None or asset.purchase_date <= cutoff+ ):+ amount = float(asset.purchase_price)+ else:+ amount = 0.0+ if amount > 0:+ converted, _ = await convert(+ session, Decimal(str(amount)), asset.currency, primary_currency, cutoff+ )+ total += float(converted)return total@@ -76,23 +115,76 @@ async def _net_worth_at(accounts_total = 0.0liabilities_total = 0.0+ composition: list[ReportCompositionItem] = []for account in accounts:bal = await _account_balance_at(session, account, cutoff)- # Convert to primary currencyconverted, _ = await convert(session, Decimal(str(abs(bal))), account.currency, primary_currency, cutoff)converted_val = float(converted)if account.type == "credit_card" or bal < 0:liabilities_total += converted_val+ if converted_val > 0:+ composition.append(ReportCompositionItem(+ key=str(account.id),+ label=get_account_name(account),+ value=round(converted_val, 2),+ color=_ACCOUNT_TYPE_COLORS.get(account.type, "#6B7280"),+ group="liabilities",+ ))else:accounts_total += converted_val+ if converted_val > 0:+ composition.append(ReportCompositionItem(+ key=str(account.id),+ label=get_account_name(account),+ value=round(converted_val, 2),+ color=_ACCOUNT_TYPE_COLORS.get(account.type, "#6B7280"),+ group="accounts",+ ))- assets_total = await _asset_value_at(- session, workspace_id, cutoff, primary_currency,- group_ids=(asset_group_ids or []) if account_ids is not None else None,+ # Per-asset composition at the cutoff date+ filtered = account_ids is not None+ asset_stmt = select(Asset).where(+ Asset.workspace_id == workspace_id,+ Asset.is_archived == False,+ Asset.sell_date.is_(None),)+ if filtered:+ asset_stmt = asset_stmt.where(Asset.group_id.in_(asset_group_ids or []))+ asset_result = await session.execute(asset_stmt)+ assets_total = 0.0+ for asset in asset_result.scalars().all():+ val_result = await session.execute(+ select(AssetValue.amount)+ .where(AssetValue.asset_id == asset.id, AssetValue.date <= cutoff)+ .order_by(desc(AssetValue.date), desc(AssetValue.id))+ .limit(1)+ )+ val = val_result.scalar_one_or_none()+ if val is not None:+ amount = float(val)+ elif asset.purchase_price is not None and (+ asset.purchase_date is None or asset.purchase_date <= cutoff+ ):+ amount = float(asset.purchase_price)+ else:+ amount = 0.0+ if amount > 0:+ converted, _ = await convert(+ session, Decimal(str(amount)), asset.currency, primary_currency, cutoff+ )+ converted_val = round(float(converted), 2)+ assets_total += converted_val+ composition.append(ReportCompositionItem(+ key=str(asset.id),+ label=asset.name,+ value=converted_val,+ color=_ASSET_TYPE_COLORS.get(asset.type, "#6B7280"),+ group="assets",+ ))+net_worth = accounts_total + assets_total - liabilities_totalreturn ReportDataPoint(@@ -103,6 +195,7 @@ async def _net_worth_at("assets": round(assets_total, 2),"liabilities": round(liabilities_total, 2),},+ composition=composition,)@@ -180,7 +273,6 @@ async def get_net_worth_report(# A wallet-only collection (wallets, no accounts) still filters.if asset_group_ids is not None and account_ids is None:account_ids = []- filtered = account_ids is not Nonetoday = date.today()start = _report_start_date(today, months, period)@@ -245,92 +337,9 @@ async def get_net_worth_report(interval=interval,)- # Build per-item composition from current snapshot- account_type_colors = {- "checking": "#6366F1",- "savings": "#3B82F6",- "credit_card": "#F43F5E",- "investment": "#8B5CF6",- "wallet": "#F59E0B",- }- asset_type_colors = {- "real_estate": "#0EA5E9",- "vehicle": "#14B8A6",- "valuable": "#F59E0B",- "investment": "#8B5CF6",- "other": "#6B7280",- }- composition: list[ReportCompositionItem] = []- accounts = await _get_open_accounts(session, workspace_id, account_ids)- for account in accounts:- bal = await _account_balance_at(session, account, today)- converted, _ = await convert(- session, Decimal(str(abs(bal))), account.currency, primary_currency, today- )- converted_val = float(converted)- if account.type == "credit_card":- composition.append(ReportCompositionItem(- key=str(account.id),- label=get_account_name(account),- value=round(converted_val, 2),- color=account_type_colors.get(account.type, "#6B7280"),- group="liabilities",- ))- else:- if bal > 0:- composition.append(ReportCompositionItem(- key=str(account.id),- label=get_account_name(account),- value=round(converted_val, 2),- color=account_type_colors.get(account.type, "#6B7280"),- group="accounts",- ))- elif bal < 0:- composition.append(ReportCompositionItem(- key=str(account.id),- label=get_account_name(account),- value=round(converted_val, 2),- color="#F43F5E",- group="liabilities",- ))-- # Assets — scoped to workspace, or (under a collection filter) to the- # assets in the collection's wallets. An empty wallet set → no assets.- asset_stmt = select(Asset).where(- Asset.workspace_id == workspace_id,- Asset.is_archived == False,- Asset.sell_date.is_(None),- )- if filtered:- asset_stmt = asset_stmt.where(Asset.group_id.in_(asset_group_ids or []))- asset_result = await session.execute(asset_stmt)- for asset in asset_result.scalars().all():- val_result = await session.execute(- select(AssetValue.amount)- .where(AssetValue.asset_id == asset.id, AssetValue.date <= today)- .order_by(desc(AssetValue.date), desc(AssetValue.id))- .limit(1)- )- val = val_result.scalar_one_or_none()- if val is not None:- amount = float(val)- elif asset.purchase_price is not None and (- asset.purchase_date is None or asset.purchase_date <= today- ):- amount = float(asset.purchase_price)- else:- amount = 0.0- if amount > 0:- converted, _ = await convert(- session, Decimal(str(amount)), asset.currency, primary_currency, today- )- composition.append(ReportCompositionItem(- key=str(asset.id),- label=asset.name,- value=round(float(converted), 2),- color=asset_type_colors.get(asset.type, "#6B7280"),- group="assets",- ))+ # The last trend point is always today — reuse its per-item composition for+ # the response-level `composition` field (current snapshot for the donut).+ composition = trend[-1].composition if trend else []return ReportResponse(summary=summary, trend=trend, meta=meta, composition=composition)@@ -945,6 +954,20 @@ async def get_income_expenses_report(series=series,))+ # Populate each trend point's composition from the per-period category data,+ # so the frontend can show a per-period donut when a bar is clicked.+ for dp in trend:+ for (cat_key, group), info in cat_trend_map.items():+ v = info["periods"].get(dp.date, 0.0)+ if v > 0:+ dp.composition.append(ReportCompositionItem(+ key=cat_key,+ label=info["label"],+ value=round(v, 2),+ color=info["color"],+ group=group,+ ))+return ReportResponse(summary=summary, trend=trend, meta=meta,composition=composition, category_trend=category_trend,diff --git a/backend/scripts/seed_perf.py b/backend/scripts/seed_perf.pyindex 278e0a89..f67503c3 100644--- a/backend/scripts/seed_perf.py+++ b/backend/scripts/seed_perf.py@@ -12,7 +12,8 @@ Options:--start-date YYYY-MM-DD Earliest date for seeded data (default: 2024-01-01)At scale=1.0 seeds:- 5 accounts · 30 categories · 100 000 transactions · 15 assets w/ daily values+ 8 accounts (4 credit cards) · 30 categories · 100 000 transactions+ 3 asset wallet groups · 15 assets w/ daily values (10 grouped into wallets)FX rates for EUR + BRL · 20 recurring transactions(date range: --start-date through today)"""@@ -35,6 +36,7 @@ from app.core.auth import UserManagerfrom app.core.database import async_session_makerfrom app.models.account import Accountfrom app.models.asset import Asset+from app.models.asset_group import AssetGroupfrom app.models.asset_value import AssetValuefrom app.models.category import Categoryfrom app.models.fx_rate import FxRate@@ -54,8 +56,11 @@ ACCOUNT_TEMPLATES = [{"name": "Main Checking", "type": "checking", "currency": "USD", "balance": Decimal("5000.00")},{"name": "Savings", "type": "savings", "currency": "USD", "balance": Decimal("25000.00")},{"name": "Visa Credit", "type": "credit_card", "currency": "USD", "balance": Decimal("0.00"), "credit_limit": Decimal("10000.00")},+ {"name": "Mastercard Platinum", "type": "credit_card", "currency": "USD", "balance": Decimal("0.00"), "credit_limit": Decimal("15000.00")},+ {"name": "Amex Gold", "type": "credit_card", "currency": "USD", "balance": Decimal("0.00"), "credit_limit": Decimal("20000.00")},{"name": "Euro Account", "type": "checking", "currency": "EUR", "balance": Decimal("3000.00")},{"name": "BRL Account", "type": "checking", "currency": "BRL", "balance": Decimal("15000.00")},+ {"name": "Euro Visa", "type": "credit_card", "currency": "EUR", "balance": Decimal("0.00"), "credit_limit": Decimal("8000.00")},]# (name, color, icon) — first 22 are debit, last 8 are credit@@ -103,22 +108,29 @@ PAYEES = ["PG&E", "Comcast", "AT&T", "Verizon", "State Farm", "Geico",]+# Wallet groups to create. Each asset below can reference one by the "group" key.+ASSET_GROUP_TEMPLATES = [+ {"name": "Stock Portfolio", "icon": "trending-up", "color": "#22c55e"},+ {"name": "Real Estate", "icon": "home", "color": "#f97316"},+ {"name": "Collectibles", "icon": "gem", "color": "#a855f7"},+]+ASSET_TEMPLATES = [- {"name": "Primary Residence", "type": "real_estate", "currency": "USD", "purchase": Decimal("450000"), "base": Decimal("520000"), "daily_pct": Decimal("0.00110")},- {"name": "Investment Property", "type": "real_estate", "currency": "USD", "purchase": Decimal("280000"), "base": Decimal("310000"), "daily_pct": Decimal("0.00082")},+ {"name": "Primary Residence", "type": "real_estate", "currency": "USD", "purchase": Decimal("450000"), "base": Decimal("520000"), "daily_pct": Decimal("0.00110"), "group": "Real Estate"},+ {"name": "Investment Property", "type": "real_estate", "currency": "USD", "purchase": Decimal("280000"), "base": Decimal("310000"), "daily_pct": Decimal("0.00082"), "group": "Real Estate"},{"name": "Tesla Model 3", "type": "vehicle", "currency": "USD", "purchase": Decimal("45000"), "base": Decimal("28000"), "daily_pct": Decimal("-0.00219")},- {"name": "Rolex Watch", "type": "valuable", "currency": "USD", "purchase": Decimal("8000"), "base": Decimal("9500"), "daily_pct": Decimal("0.00055")},- {"name": "S&P 500 Index", "type": "investment", "currency": "USD", "purchase": Decimal("50000"), "base": Decimal("75000"), "daily_pct": Decimal("0.00219")},- {"name": "Tech Stock Portfolio","type": "investment", "currency": "USD", "purchase": Decimal("30000"), "base": Decimal("42000"), "daily_pct": Decimal("0.00274")},- {"name": "Bond Portfolio", "type": "investment", "currency": "USD", "purchase": Decimal("20000"), "base": Decimal("22000"), "daily_pct": Decimal("0.00082")},+ {"name": "Rolex Watch", "type": "valuable", "currency": "USD", "purchase": Decimal("8000"), "base": Decimal("9500"), "daily_pct": Decimal("0.00055"), "group": "Collectibles"},+ {"name": "S&P 500 Index", "type": "investment", "currency": "USD", "purchase": Decimal("50000"), "base": Decimal("75000"), "daily_pct": Decimal("0.00219"), "group": "Stock Portfolio"},+ {"name": "Tech Stock Portfolio","type": "investment", "currency": "USD", "purchase": Decimal("30000"), "base": Decimal("42000"), "daily_pct": Decimal("0.00274"), "group": "Stock Portfolio"},+ {"name": "Bond Portfolio", "type": "investment", "currency": "USD", "purchase": Decimal("20000"), "base": Decimal("22000"), "daily_pct": Decimal("0.00082"), "group": "Stock Portfolio"},{"name": "Crypto Portfolio", "type": "investment", "currency": "USD", "purchase": Decimal("10000"), "base": Decimal("15000"), "daily_pct": Decimal("0.00548")},- {"name": "Vacation Cabin", "type": "real_estate", "currency": "USD", "purchase": Decimal("180000"), "base": Decimal("210000"), "daily_pct": Decimal("0.00137")},+ {"name": "Vacation Cabin", "type": "real_estate", "currency": "USD", "purchase": Decimal("180000"), "base": Decimal("210000"), "daily_pct": Decimal("0.00137"), "group": "Real Estate"},{"name": "BMW 5 Series", "type": "vehicle", "currency": "USD", "purchase": Decimal("55000"), "base": Decimal("35000"), "daily_pct": Decimal("-0.00247")},- {"name": "Art Collection", "type": "valuable", "currency": "USD", "purchase": Decimal("15000"), "base": Decimal("18000"), "daily_pct": Decimal("0.00082")},- {"name": "Gold Bars", "type": "valuable", "currency": "USD", "purchase": Decimal("25000"), "base": Decimal("30000"), "daily_pct": Decimal("0.00110")},- {"name": "EU Real Estate", "type": "real_estate", "currency": "EUR", "purchase": Decimal("300000"), "base": Decimal("340000"), "daily_pct": Decimal("0.00110")},- {"name": "Emerging Markets ETF","type": "investment", "currency": "USD", "purchase": Decimal("15000"), "base": Decimal("18000"), "daily_pct": Decimal("0.00164")},- {"name": "Private Equity Fund", "type": "investment", "currency": "USD", "purchase": Decimal("100000"), "base": Decimal("125000"), "daily_pct": Decimal("0.00192")},+ {"name": "Art Collection", "type": "valuable", "currency": "USD", "purchase": Decimal("15000"), "base": Decimal("18000"), "daily_pct": Decimal("0.00082"), "group": "Collectibles"},+ {"name": "Gold Bars", "type": "valuable", "currency": "USD", "purchase": Decimal("25000"), "base": Decimal("30000"), "daily_pct": Decimal("0.00110"), "group": "Collectibles"},+ {"name": "EU Real Estate", "type": "real_estate", "currency": "EUR", "purchase": Decimal("300000"), "base": Decimal("340000"), "daily_pct": Decimal("0.00110"), "group": "Real Estate"},+ {"name": "Emerging Markets ETF","type": "investment", "currency": "USD", "purchase": Decimal("15000"), "base": Decimal("18000"), "daily_pct": Decimal("0.00164"), "group": "Stock Portfolio"},+ {"name": "Private Equity Fund", "type": "investment", "currency": "USD", "purchase": Decimal("100000"), "base": Decimal("125000"), "daily_pct": Decimal("0.00192"), "group": "Stock Portfolio"},]RECURRING_DESCRIPTIONS = [@@ -146,6 +158,7 @@ async def _wipe_user_data(session, user_id: uuid.UUID) -> None:))await session.execute(delete(Asset).where(Asset.user_id == user_id))+ await session.execute(delete(AssetGroup).where(AssetGroup.user_id == user_id))await session.execute(delete(Transaction).where(Transaction.user_id == user_id))await session.execute(delete(Category).where(Category.user_id == user_id))await session.execute(delete(Account).where(Account.user_id == user_id))@@ -309,11 +322,30 @@ async def seed(await session.commit()print(f" {n_tx:,} transactions done ")- # ── 6. Assets + AssetValues ──────────────────────────────────────────+ # ── 6. Asset Groups (wallets) ────────────────────────────────────────+ print("Creating asset groups (wallets) …")+ asset_groups: dict[str, AssetGroup] = {}+ for i, gtmpl in enumerate(ASSET_GROUP_TEMPLATES):+ grp = AssetGroup(+ user_id=uid,+ workspace_id=wid,+ name=gtmpl["name"],+ icon=gtmpl["icon"],+ color=gtmpl["color"],+ position=i,+ source="manual",+ )+ session.add(grp)+ asset_groups[gtmpl["name"]] = grp+ await session.flush()+ print(f" {len(asset_groups)} asset groups")++ # ── 7. Assets + AssetValues ──────────────────────────────────────────print(f"Creating {len(ASSET_TEMPLATES[:n_assets])} assets with {n_days + 1} daily values each …")asset_days = _make_date_range(n_days)for tmpl in ASSET_TEMPLATES[:n_assets]:+ grp = asset_groups.get(tmpl.get("group", ""))asset = Asset(user_id=uid,workspace_id=wid,@@ -323,6 +355,7 @@ async def seed(purchase_price=tmpl["purchase"],purchase_date=asset_days[0],valuation_method="manual",+ group_id=grp.id if grp else None,)session.add(asset)await session.flush()@@ -354,7 +387,7 @@ async def seed(total_av = len(ASSET_TEMPLATES[:n_assets]) * (n_days + 1)print(f" {len(ASSET_TEMPLATES)} assets, {total_av:,} asset values")- # ── 7. Recurring transactions ────────────────────────────────────────+ # ── 8. Recurring transactions ────────────────────────────────────────n_rec = max(1, int(20 * scale))print(f"Creating {n_rec} recurring transactions …")for i, desc in enumerate(RECURRING_DESCRIPTIONS[:n_rec]):diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.pyindex 41c84963..ac7e110a 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -912,6 +912,26 @@ async def test_net_worth_composition_uses_display_name(session: AsyncSession, teassert "Provider Name" not in comp_labels+async def test_net_worth_intermediate_trend_points_have_composition(+ session: AsyncSession, test_user, test_workspace: User+):+ """Non-last trend points carry per-item composition, not just the current snapshot."""+ acct = await _make_manual_account(session, test_user.id, "History Acct")+ # 135 days back lands before the first monthly cutoff (end of month-4),+ # so the first trend point carries this account in composition.+ await _add_txn(session, test_user.id, acct.id, 8000, "credit", date.today() - timedelta(days=135))++ report = await get_net_worth_report(+ session, test_workspace.id, test_user.id, months=4, interval="monthly"+ )+ assert len(report.trend) >= 2+ # The first trend point predates today and must still have composition populated+ first = report.trend[0]+ assert len(first.composition) > 0+ assert any(c.label == "History Acct" for c in first.composition)++@pytest.mark.asyncioasync def test_net_worth_weekly_interval(session: AsyncSession, test_user, test_workspace: User):acct = await _make_manual_account(session, test_user.id, "Weekly Test")diff --git a/backend/tests/test_report_service_coverage.py b/backend/tests/test_report_service_coverage.pyindex 10d2afc7..2b2c9cb9 100644--- a/backend/tests/test_report_service_coverage.py+++ b/backend/tests/test_report_service_coverage.py@@ -585,6 +585,31 @@ async def test_income_expenses_owner_split_offset(session, test_user, test_worksassert dinner.value == pytest.approx(600.0)+async def test_income_expenses_trend_points_have_per_period_composition(session, test_user, test_workspace):+ """Each income/expenses trend DataPoint carries per-period composition items."""+ cat_wages = await _make_category(session, test_user.id, "Wages", color="#0E0")+ cat_groceries = await _make_category(session, test_user.id, "Groceries", color="#E00")+ acct = await _make_account(session, test_user.id, "IE Trend Acct")+ today = date.today()++ await _add_txn(session, test_user.id, acct.id, 4000, "credit", today, category_id=cat_wages.id)+ await _add_txn(session, test_user.id, acct.id, 900, "debit", today, category_id=cat_groceries.id)++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=2, interval="monthly"+ )++ # The last trend point always covers the current period where transactions landed+ current_dp = report.trend[-1]+ assert len(current_dp.composition) > 0+ groups = {c.group for c in current_dp.composition}+ assert "income" in groups+ assert "expenses" in groups+ labels = {c.label for c in current_dp.composition}+ assert "Wages" in labels+ assert "Groceries" in labels++async def test_net_worth_composition_positive_checking_in_accounts_group(session, test_user, test_workspace):"""A manual checking account with positive balance lands in the accounts group."""acct = await _make_account(session, test_user.id, "NW Pos Checking")diff --git a/frontend/src/index.css b/frontend/src/index.cssindex e1f2c8ea..107bdbeb 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -131,6 +131,18 @@}}+/* Recharts focuses its wrapper/surface on click; on macOS this draws a+ browser focus ring around the whole chart. Suppress it — the chart conveys+ selection via bar opacity, not a focus outline. */+.recharts-wrapper:focus,+.recharts-wrapper:focus-visible,+.recharts-surface:focus,+.recharts-surface:focus-visible,+.recharts-wrapper *:focus,+.recharts-wrapper *:focus-visible {+ outline: none;+}+@keyframes securo-highlight-flash {0% {background-color: color-mix(in srgb, var(--primary) 22%, transparent);diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex e208ef1a..c7dba952 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1062,6 +1062,7 @@"cashFlow": "Cash Flow","comingSoon": "(coming soon)","composition": "Composition",+ "asOf": "as of {{date}}","evolution": "Evolution","income": "Income","expenses": "Expenses",@@ -1074,6 +1075,8 @@"assetsAndAccounts": "Assets & Accounts","youOwn": "You Own","youOwe": "You Owe",+ "youOwned": "You Owned",+ "youOwed": "You Owed","other": "Other","otherAccounts": "Other Accounts","otherAssets": "Other Assets",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 324c31fd..0946e547 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1062,6 +1062,7 @@"cashFlow": "Flujo de caja","comingSoon": "(próximamente)","composition": "Composición",+ "asOf": "a fecha de {{date}}","evolution": "Evolución","income": "Ingresos","expenses": "Gastos",@@ -1074,6 +1075,8 @@"assetsAndAccounts": "Activos y Cuentas","youOwn": "Lo que tienes","youOwe": "Lo que debes",+ "youOwned": "Lo que tenías",+ "youOwed": "Lo que debías","other": "Otro","otherAccounts": "Otras Cuentas","otherAssets": "Otros Activos",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 5ab24c14..fdadb4dd 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1062,6 +1062,7 @@"cashFlow": "Flusso di cassa","comingSoon": "(prossimamente)","composition": "Composizione",+ "asOf": "al {{date}}","evolution": "Evoluzione","income": "Entrate","expenses": "Spese",@@ -1074,6 +1075,8 @@"assetsAndAccounts": "Attività e Conti","youOwn": "Hai","youOwe": "Devi",+ "youOwned": "Avevi",+ "youOwed": "Dovevi","other": "Altro","otherAccounts": "Altri Conti","otherAssets": "Altre Attività",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 534357f6..99d18ac9 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1131,6 +1131,7 @@"cashFlow": "Przepływy pieniężne","comingSoon": "(wkrótce)","composition": "Struktura",+ "asOf": "na dzień {{date}}","evolution": "Zmiana w czasie","income": "Przychody","expenses": "Wydatki",@@ -1143,6 +1144,8 @@"assetsAndAccounts": "Aktywa i Konta","youOwn": "Posiadasz","youOwe": "Jesteś winien",+ "youOwned": "Posiadałeś",+ "youOwed": "Byłeś winien","other": "Inne","otherAccounts": "Inne Konta","otherAssets": "Inne Aktywa",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 4d1ab646..febe008a 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1062,6 +1062,7 @@"cashFlow": "Fluxo de Caixa","comingSoon": "(em breve)","composition": "Composição",+ "asOf": "em {{date}}","evolution": "Evolução","income": "Receitas","expenses": "Despesas",@@ -1074,6 +1075,8 @@"assetsAndAccounts": "Ativos e Contas","youOwn": "Você Tem","youOwe": "Você Deve",+ "youOwned": "Você Tinha",+ "youOwed": "Você Devia","other": "Outros","otherAccounts": "Outras Contas","otherAssets": "Outros Ativos",diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex c0c9d8a4..eb366168 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -18,7 +18,7 @@ import {ReferenceLine,ResponsiveContainer,} from 'recharts'-import { HelpCircle } from 'lucide-react'+import { HelpCircle, X } from 'lucide-react'import { reports } from '@/lib/api'import { Skeleton } from '@/components/ui/skeleton'import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popover'@@ -44,6 +44,8 @@ const SLICE_COLORS = ['#14B8A6', // teal'#84CC16', // lime'#D946EF', // fuchsia+ '#F43F5E', // rose+ '#06B6D4', // cyan]const OTHER_SLICE_COLOR = '#9CA3AF'@@ -144,6 +146,7 @@ export default function ReportsPage() {const [sparklineView, setSparklineView] = useState<'byExpenses' | 'byIncome'>('byExpenses')const [sparklinePage, setSparklinePage] = useState(0)const [cashFlowBaseline, setCashFlowBaseline] = useState(false)+ const [selectedDate, setSelectedDate] = useState<string | null>(null)// Active Collection filter (issue #105): scope all report tabs to its// accounts; net worth also includes the collection's wallets' assets.const { activeAccountIds, activeWalletIds } = useCollectionFilter()@@ -174,6 +177,7 @@ export default function ReportsPage() {setActiveTab(key)setCompositionView(key === 'net_worth' ? 'netWorth' : 'net')setSparklinePage(0)+ setSelectedDate(null)// Clamp months/interval to options supported by the new tabconst nextRanges = key === 'cash_flow'? FORWARD_RANGE_OPTIONS@@ -235,6 +239,29 @@ export default function ReportsPage() {colorMap[b.key] = b.color}+ const snapshotTrendPoint = selectedDate+ ? (trend.find((dp) => dp.date === selectedDate) ?? null)+ : null+ const isHistoricalSnapshot =+ snapshotTrendPoint !== null &&+ selectedDate !== trend[trend.length - 1]?.date++ const snapshotBreakdownData = snapshotTrendPoint+ ? Object.entries(snapshotTrendPoint.breakdowns)+ .map(([key, rawValue]) => {+ const orig = allBreakdowns.find((b) => b.key === key)+ return {+ key,+ label: orig?.label ?? key,+ value: Math.abs(rawValue as number),+ color: orig?.color ?? '#6366F1',+ }+ })+ .filter((b) => b.value > 0)+ : null++ const compositionBreakdownData = snapshotBreakdownData ?? breakdownData+const changePrefix = (summary?.change_amount ?? 0) >= 0 ? '+' : ''const changeColor = (summary?.change_amount ?? 0) >= 0 ? 'text-emerald-600' : 'text-rose-500'@@ -277,7 +304,7 @@ export default function ReportsPage() {// Inner ring — summary view (high-level breakdown), filtered by toggle state for net_worthconst innerDonutData = (() => {const excludedKeys = new Set(['netIncome', 'startingBalance', 'endingBalance'])- return breakdownData+ return compositionBreakdownData.filter((b) => !excludedKeys.has(b.key) && (!activeCompositionGroups || activeCompositionGroups.has(groupOf(b.key)))).map((b) => ({name: t(`reports.${b.key}`, { defaultValue: b.label }),@@ -286,16 +313,40 @@ export default function ReportsPage() {}))})()+ const activeComposition = snapshotTrendPoint?.composition ?? composition++ // Build a stable key → color map from the full composition range (never the+ // snapshot), sorted the same way compositionDetail sorts, so colors don't+ // shift when switching between dates.+ const netWorthColorMap = (() => {+ const excludedKeys = new Set(['netIncome', 'startingBalance', 'endingBalance'])+ const groupOrder = breakdownData+ .filter((b) => !excludedKeys.has(b.key) && (!activeCompositionGroups || activeCompositionGroups.has(groupOf(b.key))))+ .map((b) => groupOf(b.key))+ const activeGroups = new Set(groupOrder)+ const sorted = [...composition]+ .filter((c) => activeGroups.has(c.group))+ .sort((a, b) => {+ const ga = groupOrder.indexOf(a.group)+ const gb = groupOrder.indexOf(b.group)+ if (ga !== gb) return ga - gb+ return b.value - a.value+ })+ const map = new Map<string, string>()+ sorted.forEach((c, i) => map.set(c.key, SLICE_COLORS[i % SLICE_COLORS.length]))+ return map+ })()+// Full detail — every holding in the active group(s), largest first, labelled// and coloured. The donut draws only the top slice of this; the legend popover// lists all of it. Net worth items get a distinct palette (the long tail falls// back to the neutral colour); income/expense items keep the user's category colour.const compositionDetail = (() => {- if (composition.length === 0) return []+ if (activeComposition.length === 0) return []const excludedKeys = new Set(['netIncome', 'startingBalance', 'endingBalance'])const activeGroups = new Set(- breakdownData+ compositionBreakdownData.filter((b) => !excludedKeys.has(b.key) && (!activeCompositionGroups || activeCompositionGroups.has(groupOf(b.key)))).map((b) => groupOf(b.key)))@@ -313,33 +364,88 @@ export default function ReportsPage() {return c.label}- return composition+ const groupOrder = compositionBreakdownData+ .filter((b) => !excludedKeys.has(b.key) && (!activeCompositionGroups || activeCompositionGroups.has(groupOf(b.key))))+ .map((b) => groupOf(b.key))++ return activeComposition.filter((c) => activeGroups.has(c.group))- .sort((a, b) => b.value - a.value)- .map((c, i) => ({+ .sort((a, b) => {+ const ga = groupOrder.indexOf(a.group)+ const gb = groupOrder.indexOf(b.group)+ if (ga !== gb) return ga - gb+ return b.value - a.value+ })+ .map((c) => ({name: itemLabel(c),value: c.value,- color: activeTab === 'net_worth' ? (SLICE_COLORS[i] ?? OTHER_SLICE_COLOR) : c.color,+ color: activeTab === 'net_worth' ? (netWorthColorMap.get(c.key) ?? OTHER_SLICE_COLOR) : c.color,+ group: c.group,}))})()- // Outer ring — the top slices individually, with the long tail folded into a- // single "Other". Capping the slice count is what keeps them tellable apart;- // the full breakdown stays one click away in the legend's "+N more" popover.+ // Outer ring — items above 3 % of total get their own slice; everything else+ // per group folds into one "Other <Group>" slice. Outer arcs are anchored to+ // inner ring values so per-item rounding never misaligns the two rings.const outerDonutData = (() => {if (compositionDetail.length === 0) return []- const LIMIT = SLICE_COLORS.length- const top = compositionDetail.slice(0, LIMIT)- const rest = compositionDetail.slice(LIMIT)- const result: { name: string; value: number; color: string }[] =- top.map((d) => ({ name: d.name, value: d.value, color: d.color }))- if (rest.length > 0) {- result.push({- name: t('reports.other'),- value: Math.round(rest.reduce((s, d) => s + d.value, 0) * 100) / 100,- color: OTHER_SLICE_COLOR,- })++ const excludedKeys = new Set(['netIncome', 'startingBalance', 'endingBalance'])+ const innerGroups = [+ ...new Set(+ compositionBreakdownData+ .filter((b) => !excludedKeys.has(b.key) && (!activeCompositionGroups || activeCompositionGroups.has(groupOf(b.key))))+ .map((b) => groupOf(b.key))+ ),+ ]++ const innerGroupValue = new Map<string, number>()+ for (const b of compositionBreakdownData) {+ if (!excludedKeys.has(b.key) && (!activeCompositionGroups || activeCompositionGroups.has(groupOf(b.key)))) {+ const g = groupOf(b.key)+ innerGroupValue.set(g, (innerGroupValue.get(g) ?? 0) + b.value)+ }+ }++ const totalValue = [...innerGroupValue.values()].reduce((s, v) => s + v, 0)++ const otherLabel = (g: string) =>+ g === 'accounts' ? t('reports.otherAccounts')+ : g === 'assets' ? t('reports.otherAssets')+ : g === 'liabilities' ? t('reports.otherLiabilities')+ : g === 'income' ? t('reports.otherIncome')+ : g === 'expenses' ? t('reports.otherExpenses')+ : t('reports.other')++ const byGroup = new Map<string, typeof compositionDetail>()+ for (const g of innerGroups) byGroup.set(g, [])+ for (const item of compositionDetail) byGroup.get(item.group)?.push(item)++ const result: {+ name: string+ value: number+ color: string+ children?: { name: string; value: number; color: string }[]+ }[] = []++ for (const g of innerGroups) {+ const all = byGroup.get(g) ?? []+ const significant = all.filter((item) => totalValue > 0 && item.value / totalValue >= 0.03)+ const rest = all.filter((item) => totalValue <= 0 || item.value / totalValue < 0.03)+ const topSum = significant.reduce((s, d) => s + d.value, 0)+ const innerTotal = innerGroupValue.get(g) ?? topSum+ const otherValue = Math.round((innerTotal - topSum) * 100) / 100+ for (const item of significant) result.push(item)+ if (otherValue > 0.005) {+ result.push({+ name: otherLabel(g),+ value: otherValue,+ color: OTHER_SLICE_COLOR,+ children: rest.length > 0 ? rest : undefined,+ })+ }}+return result})()@@ -390,7 +496,7 @@ export default function ReportsPage() {{rangeOptions.map((opt) => (<buttonkey={opt.key}- onClick={() => setRangeKey(opt.key)}+ onClick={() => { setRangeKey(opt.key); setSelectedDate(null) }}className={`px-3 py-1.5 text-xs font-semibold transition-colors ${rangeKey === opt.key? 'bg-primary text-primary-foreground'@@ -405,7 +511,7 @@ export default function ReportsPage() {{intervalOptions.map((opt) => (<buttonkey={opt.key}- onClick={() => setInterval(opt.value)}+ onClick={() => { setInterval(opt.value); setSelectedDate(null) }}className={`px-2.5 py-1.5 text-xs font-semibold transition-colors ${interval === opt.value? 'bg-primary text-primary-foreground'@@ -822,16 +928,21 @@ export default function ReportsPage() {{/* Breakdown: Donut + Grouped Bar */}<div className="grid grid-cols-1 lg:grid-cols-3 gap-5 items-start">{/* Composition widget — summary ring + ranked, labelled detail bars */}- <div className="bg-card rounded-xl border border-border shadow-sm">- <div className="px-5 pt-4 pb-2 flex items-center justify-between gap-2">- <p className="text-sm font-semibold text-foreground shrink-0">{t('reports.composition')}</p>- <div className="flex items-stretch rounded-lg border border-border bg-muted/30 overflow-hidden">+ <div className={`rounded-xl border shadow-sm transition-colors ${selectedDate ? 'bg-primary/5 border-primary/50' : 'bg-card border-border'}`}>+ <div className="px-5 pt-4 pb-2 flex flex-col gap-2 min-[635px]:flex-row min-[635px]:items-start min-[635px]:justify-between lg:flex-col lg:items-start xl:flex-row xl:items-start xl:justify-between">+ <div className="flex flex-col">+ <p className="text-sm font-semibold text-foreground">{t('reports.composition')}</p>+ {selectedDate && (+ <span className="text-xs text-primary font-medium">{t('reports.asOf', { date: selectedDate })}</span>+ )}+ </div>+ <div className="flex items-stretch rounded-lg border border-border bg-muted/30 overflow-hidden w-fit">{compositionOptions.map((opt) => (<buttonkey={opt}type="button"onClick={() => setCompositionView(opt)}- className={`px-2 py-1 text-[11px] font-semibold text-center whitespace-nowrap transition-colors ${+ className={`px-2 py-1 text-[11px] font-semibold text-center transition-colors ${compositionView === opt? 'bg-primary text-primary-foreground': 'text-muted-foreground hover:text-foreground hover:bg-muted/50'@@ -912,56 +1023,78 @@ export default function ReportsPage() {const pct = donutTotal > 0 ? ((v / donutTotal) * 100).toFixed(1) : '0'const rawName = (entry.name as string) ?? ''const displayName = rawName.length > 50 ? rawName.slice(0, 47) + '…' : rawName+ const children = (entry.payload as { children?: { name: string; value: number; color: string }[] }).childrenreturn (- <div style={{ ...tooltipStyle, padding: '8px 12px', zIndex: 10 }}>+ <div style={{ ...tooltipStyle, padding: '8px 12px', zIndex: 10, maxWidth: 256 }}><p className="text-xs font-semibold mb-1">{displayName}</p><p className="text-xs">{privacyMode ? MASK : `${formatCurrency(v, userCurrency, locale)} (${pct}%)`}</p>+ {children && children.length > 0 && (+ <div className="mt-1.5 border-t border-border/50 pt-1.5 flex flex-col gap-0.5" style={{ maxHeight: 180, overflowY: 'auto', paddingRight: '0.5rem' }}>+ {children.map((child, i) => {+ const childPct = donutTotal > 0 ? ((child.value / donutTotal) * 100).toFixed(1) : '0'+ return (+ <div key={i} className="flex items-center justify-between gap-3">+ <div className="flex items-center gap-1.5 min-w-0">+ <div className="w-1.5 h-1.5 rounded-full shrink-0" style={{ backgroundColor: child.color }} />+ <span className="text-xs text-muted-foreground truncate">+ {child.name.length > 25 ? child.name.slice(0, 22) + '…' : child.name}+ </span>+ </div>+ <span className="text-xs text-muted-foreground shrink-0">+ {privacyMode ? MASK : `${formatCurrency(child.value, userCurrency, locale)} (${childPct}%)`}+ </span>+ </div>+ )+ })}+ </div>+ )}</div>)}}- wrapperStyle={{ zIndex: 10 }}+ wrapperStyle={{ zIndex: 10, pointerEvents: 'auto' }}offset={20}/></PieChart><div className="absolute inset-0 flex flex-col items-center justify-center pointer-events-none" style={{ zIndex: 0 }}><span className="text-[10px] text-muted-foreground">- {compositionView === 'assetsAndAccounts' ? t('reports.youOwn', { defaultValue: 'You Own' })- : compositionView === 'liabilities' ? t('reports.youOwe', { defaultValue: 'You Owe' })- : compositionView === 'byIncome' ? t('reports.income')- : compositionView === 'byExpenses' ? t('reports.expenses')- : meta?.type === 'income_expenses' ? t('reports.netIncome')- : t(currentTab.labelKey)}+ {compositionView === 'assetsAndAccounts'+ ? t(isHistoricalSnapshot ? 'reports.youOwned' : 'reports.youOwn', { defaultValue: isHistoricalSnapshot ? 'You Owned' : 'You Own' })+ : compositionView === 'liabilities'+ ? t(isHistoricalSnapshot ? 'reports.youOwed' : 'reports.youOwe', { defaultValue: isHistoricalSnapshot ? 'You Owed' : 'You Owe' })+ : compositionView === 'byIncome' ? t('reports.income')+ : compositionView === 'byExpenses' ? t('reports.expenses')+ : meta?.type === 'income_expenses' ? t('reports.netIncome')+ : t(currentTab.labelKey)}</span><span className="text-base font-bold text-foreground tabular-nums">{mask(formatCompact(- compositionView === 'netWorth' || compositionView === 'net' || !compositionView- ? meta?.type === 'cash_flow'- ? (summary?.change_amount ?? 0)- : (summary?.primary_value ?? 0)- : innerDonutData.reduce((s, d) => s + d.value, 0),+ snapshotTrendPoint+ ? compositionView === 'netWorth' || compositionView === 'net' || !compositionView+ ? snapshotTrendPoint.value+ : innerDonutData.reduce((s, d) => s + d.value, 0)+ : compositionView === 'netWorth' || compositionView === 'net' || !compositionView+ ? meta?.type === 'cash_flow'+ ? (summary?.change_amount ?? 0)+ : (summary?.primary_value ?? 0)+ : innerDonutData.reduce((s, d) => s + d.value, 0),userCurrency, locale))}</span></div></div><div key={compositionView} className="flex flex-col items-center gap-1 px-3 mt-1 w-full">- {/* Inner-ring (summary) legend only when there is no detailed- outer ring — otherwise the toggle + center label already- name it, and the detailed legend below carries the colours. */}- {!hasOuter && (- <div className="flex flex-wrap justify-center gap-x-3 gap-y-1">- {innerDonutData.map((d, i) => (- <div key={`${i}-${d.name}`} className="flex items-center gap-1.5">- <div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: d.color }} />- <span className="text-[11px] text-muted-foreground whitespace-nowrap">- {d.name.length > 30 ? d.name.slice(0, 27) + '…' : d.name}- </span>- </div>- ))}- </div>- )}+ <div className="flex flex-wrap justify-center gap-x-3 gap-y-1">+ {innerDonutData.map((d, i) => (+ <div key={`${i}-${d.name}`} className="flex items-center gap-1.5">+ <div className="w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: d.color }} />+ <span className="text-[11px] text-muted-foreground whitespace-nowrap">+ {d.name.length > 30 ? d.name.slice(0, 27) + '…' : d.name}+ </span>+ </div>+ ))}+ </div>{hasOuter && (() => {const visible = outerDonutData.slice(0, 6)const hiddenCount = compositionDetail.length - visible.length@@ -998,9 +1131,8 @@ export default function ReportsPage() {<span className="text-[11px] text-muted-foreground flex-1 truncate">{d.name.length > 25 ? d.name.slice(0, 22) + '…' : d.name}</span>- <span className="text-[11px] tabular-nums text-foreground whitespace-nowrap">- {mask(formatCompact(d.value, userCurrency, locale))}- <span className="text-muted-foreground ml-1">({pct}%)</span>+ <span className="text-xs text-muted-foreground shrink-0">+ {privacyMode ? MASK : `${formatCurrency(d.value, userCurrency, locale)} (${pct}%)`}</span></div>)@@ -1024,15 +1156,27 @@ export default function ReportsPage() {</div>{/* Evolution / Category Sparklines */}- <div className="lg:col-span-2 bg-card rounded-xl border border-border shadow-sm">+ <div className={`lg:col-span-2 rounded-xl border shadow-sm transition-colors ${selectedDate && meta?.type !== 'income_expenses' ? 'bg-primary/5 border-primary/50' : 'bg-card border-border'}`}><div className="px-5 pt-5 pb-2 flex items-center justify-between">- <p className="text-sm font-semibold text-foreground">- {meta?.type === 'income_expenses'- ? t('reports.categoryTrends')- : meta?.type === 'cash_flow'- ? t('reports.inflowOutflow')- : t('reports.evolution')}- </p>+ <div className="flex items-center gap-2">+ <p className="text-sm font-semibold text-foreground">+ {meta?.type === 'income_expenses'+ ? t('reports.categoryTrends')+ : meta?.type === 'cash_flow'+ ? t('reports.inflowOutflow')+ : t('reports.evolution')}+ </p>+ {selectedDate && (+ <button+ type="button"+ onClick={() => setSelectedDate(null)}+ className="flex items-center gap-1 rounded-full bg-primary/10 border border-primary/30 px-2 py-0.5 text-[11px] font-semibold text-primary transition-colors hover:bg-primary/20 whitespace-nowrap"+ >+ {selectedDate}+ <X className="h-3 w-3" />+ </button>+ )}+ </div>{meta?.type === 'income_expenses' && (() => {const groupKey = sparklineView === 'byIncome' ? 'income' : 'expenses'const allItems = (data?.category_trend ?? []).filter((c) => c.group === groupKey)@@ -1181,7 +1325,17 @@ export default function ReportsPage() {</div>) : chartData.length > 0 && meta ? (<ResponsiveContainer width="100%" height="100%">- <ComposedChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }} stackOffset="sign">+ <ComposedChart+ data={chartData}+ margin={{ top: 8, right: 16, left: 0, bottom: 0 }}+ stackOffset="sign"+ onClick={(payload) => {+ const date = payload?.activeLabel as string | undefined+ if (!date) return+ setSelectedDate((prev) => (prev === date ? null : date))+ }}+ style={{ cursor: 'pointer' }}+ ><XAxisdataKey="date"tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}@@ -1256,7 +1410,15 @@ export default function ReportsPage() {fill={color}radius={radius}maxBarSize={32}- />+ >+ {selectedDate && chartData.map((d) => (+ <Cell+ key={d.date}+ fill={color}+ fillOpacity={d.date === selectedDate ? 1 : 0.4}+ />+ ))}+ </Bar>)})})()}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 9fcffdc3..8b7b1125 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -676,6 +676,7 @@ export interface ReportDataPoint {value: numberbreakdowns: Record<string, number>change: number | null+ composition?: ReportCompositionItem[]}export interface ReportMeta {