Skip to content

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

feat: add reports module with category sparklines and README updates

Tássio Noronhaecd354211e0c
diff --git a/README.md b/README.md
index ed5b0d34..cf2b0350 100644
--- a/README.md
+++ b/README.md
@@ -5,6 +5,8 @@
<p align="center">
<a href="https://github.com/securo-finance/securo/actions/workflows/ci.yml"><img src="https://github.com/securo-finance/securo/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
<a href="https://www.gnu.org/licenses/agpl-3.0"><img src="https://img.shields.io/badge/License-AGPL--3.0-blue.svg" alt="License: AGPL-3.0" /></a>
+ <br />
+ <a href="https://usesecuro.com/">Website</a> · <a href="https://github.com/orgs/securo-finance/projects/2">Roadmap</a>
</p>
<h3 align="center">Finance apps want your data. This one doesn't.</h3>
@@ -41,6 +43,8 @@ Open [http://localhost:3000](http://localhost:3000) and create an account. That'
- File import (OFX, QIF, CAMT, CSV)
- Auto-categorization rules engine
- Recurring transactions and budgets
+- Asset management with valuation tracking and growth rules
+- Reports: Net Worth and Income vs Expenses with category sparklines
- Dashboard with spending analytics and projections
- Bank sync via providers (Pluggy supported, extensible)
- Dark/light theme, multi-language support, privacy mode
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.py
new file mode 100644
index 00000000..a17a0659
--- /dev/null
+++ b/backend/app/api/reports.py
@@ -0,0 +1,44 @@
+from fastapi import APIRouter, Depends, Query
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.auth import current_active_user
+from app.core.database import get_async_session
+from app.models.user import User
+from app.schemas.report import ReportResponse
+from app.services import report_service
+
+router = APIRouter(prefix="/api/reports", tags=["reports"])
+
+
[email protected]("/net-worth", response_model=ReportResponse)
+async def get_net_worth(
+ months: int = Query(12, ge=1, le=24),
+ interval: str = Query("monthly", pattern="^(daily|weekly|monthly|yearly)$"),
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ currency = getattr(user, "preferences", None)
+ currency_display = "BRL"
+ if currency and isinstance(currency, dict):
+ currency_display = currency.get("currency_display", "BRL")
+
+ return await report_service.get_net_worth_report(
+ session, user.id, months, interval, currency_display
+ )
+
+
[email protected]("/income-expenses", response_model=ReportResponse)
+async def get_income_expenses(
+ months: int = Query(12, ge=1, le=24),
+ interval: str = Query("monthly", pattern="^(daily|weekly|monthly|yearly)$"),
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ currency = getattr(user, "preferences", None)
+ currency_display = "BRL"
+ if currency and isinstance(currency, dict):
+ currency_display = currency.get("currency_display", "BRL")
+
+ return await report_service.get_income_expenses_report(
+ session, user.id, months, interval, currency_display
+ )
diff --git a/backend/app/main.py b/backend/app/main.py
index 94956779..da3b9a45 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -15,6 +15,7 @@ from app.api.import_transactions import router as import_router
from app.api.recurring_transactions import router as recurring_router
from app.api.rules import router as rules_router
from app.api.assets import router as assets_router
+from app.api.reports import router as reports_router
from app.api.setup import router as setup_router
from app.api.transactions import router as transactions_router
from app.core.auth import auth_backend, fastapi_users
@@ -88,6 +89,7 @@ app.include_router(recurring_router)
app.include_router(budgets_router)
app.include_router(assets_router)
app.include_router(dashboard_router)
+app.include_router(reports_router)
app.include_router(setup_router)
diff --git a/backend/app/schemas/report.py b/backend/app/schemas/report.py
new file mode 100644
index 00000000..2626e540
--- /dev/null
+++ b/backend/app/schemas/report.py
@@ -0,0 +1,53 @@
+from pydantic import BaseModel
+
+
+class ReportBreakdown(BaseModel):
+ key: str
+ label: str
+ value: float
+ color: str
+
+
+class ReportSummary(BaseModel):
+ primary_value: float
+ change_amount: float
+ change_percent: float | None
+ breakdowns: list[ReportBreakdown]
+
+
+class ReportDataPoint(BaseModel):
+ date: str
+ value: float
+ breakdowns: dict[str, float]
+
+
+class ReportMeta(BaseModel):
+ type: str
+ series_keys: list[str]
+ currency: str
+ interval: str
+
+
+class ReportCompositionItem(BaseModel):
+ key: str
+ label: str
+ value: float
+ color: str
+ group: str
+
+
+class CategoryTrendItem(BaseModel):
+ key: str
+ label: str
+ color: str
+ total: float
+ group: str
+ series: list[ReportDataPoint]
+
+
+class ReportResponse(BaseModel):
+ summary: ReportSummary
+ trend: list[ReportDataPoint]
+ meta: ReportMeta
+ composition: list[ReportCompositionItem] = []
+ category_trend: list[CategoryTrendItem] = []
diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py
index 3e31154f..9ef5b376 100644
--- a/backend/app/services/dashboard_service.py
+++ b/backend/app/services/dashboard_service.py
@@ -396,6 +396,7 @@ async def _account_balance_at(
)
return current_bal - float(delta_after or 0)
else:
+ # Manual: sum signed transactions up to cutoff
result = await session.scalar(
select(func.coalesce(func.sum(_signed_balance_expr()), 0))
.where(
@@ -403,7 +404,26 @@ async def _account_balance_at(
Transaction.date <= cutoff,
)
)
- return float(result or 0)
+ bal = float(result or 0)
+
+ # If zero and no transactions exist before cutoff, carry opening balance back.
+ # This handles the common case where a user starts tracking an existing account.
+ if bal == 0.0:
+ first_txn_date = await session.scalar(
+ select(func.min(Transaction.date))
+ .where(Transaction.account_id == account.id)
+ )
+ if first_txn_date is not None and first_txn_date > cutoff:
+ opening_bal = await session.scalar(
+ select(func.coalesce(func.sum(_signed_balance_expr()), 0))
+ .where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ bal = float(opening_bal or 0)
+
+ return bal
async def _total_balance_by_currency(
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.py
new file mode 100644
index 00000000..23c84772
--- /dev/null
+++ b/backend/app/services/report_service.py
@@ -0,0 +1,557 @@
+import uuid
+from datetime import date, timedelta
+
+from sqlalchemy import String, select, desc, func, case
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.asset import Asset
+from app.models.asset_value import AssetValue
+from app.models.transaction import Transaction
+from app.models.category import Category
+from app.schemas.report import (
+ CategoryTrendItem,
+ ReportBreakdown,
+ ReportCompositionItem,
+ ReportDataPoint,
+ ReportMeta,
+ ReportResponse,
+ ReportSummary,
+)
+from app.services.dashboard_service import _get_open_accounts, _account_balance_at
+
+
+async def _asset_value_at(
+ session: AsyncSession, user_id: uuid.UUID, cutoff: date
+) -> float:
+ """Sum of all active (non-archived, non-sold) asset values at a given date.
+
+ For each asset, finds the most recent AssetValue with date <= cutoff.
+ Falls back to purchase_price if no value entries exist before the cutoff
+ (but only if purchase_date <= cutoff or purchase_date is None).
+ """
+ result = await session.execute(
+ select(Asset).where(
+ Asset.user_id == user_id,
+ Asset.is_archived == False,
+ Asset.sell_date.is_(None),
+ )
+ )
+ assets = list(result.scalars().all())
+
+ total = 0.0
+ for asset in assets:
+ # Find most recent value entry at or before the cutoff
+ 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)
+ )
+ row = val_result.scalar_one_or_none()
+ if row is not None:
+ total += float(row)
+ elif asset.purchase_price is not None:
+ # Fall back to purchase_price if the asset existed by cutoff
+ if asset.purchase_date is None or asset.purchase_date <= cutoff:
+ total += float(asset.purchase_price)
+
+ return total
+
+
+async def _net_worth_at(
+ session: AsyncSession, user_id: uuid.UUID, cutoff: date
+) -> ReportDataPoint:
+ """Compute a single net worth snapshot at a given date."""
+ accounts = await _get_open_accounts(session, user_id)
+
+ accounts_total = 0.0
+ liabilities_total = 0.0
+
+ for account in accounts:
+ bal = await _account_balance_at(session, account, cutoff)
+ if account.type == "credit_card":
+ # _account_balance_at already negates credit_card; show as positive liability
+ liabilities_total += abs(bal)
+ else:
+ accounts_total += bal
+
+ assets_total = await _asset_value_at(session, user_id, cutoff)
+ net_worth = accounts_total + assets_total - liabilities_total
+
+ return ReportDataPoint(
+ date=cutoff.isoformat(),
+ value=round(net_worth, 2),
+ breakdowns={
+ "accounts": round(accounts_total, 2),
+ "assets": round(assets_total, 2),
+ "liabilities": round(liabilities_total, 2),
+ },
+ )
+
+
+def _format_date_label(d: date, interval: str) -> str:
+ """Format a date point based on interval granularity."""
+ if interval == "daily":
+ return d.isoformat()
+ elif interval == "weekly":
+ iso_year, iso_week, _ = d.isocalendar()
+ return f"{iso_year}-W{iso_week:02d}"
+ elif interval == "monthly":
+ return f"{d.year}-{d.month:02d}"
+ elif interval == "yearly":
+ return str(d.year)
+ return d.isoformat()
+
+
+def _date_points(
+ start: date, end: date, interval: str
+) -> list[date]:
+ """Generate date points between start and end for the given interval."""
+ points: list[date] = []
+ current = start
+
+ if interval == "daily":
+ while current <= end:
+ points.append(current)
+ current += timedelta(days=1)
+ elif interval == "weekly":
+ while current <= end:
+ points.append(current)
+ current += timedelta(weeks=1)
+ elif interval == "monthly":
+ while current <= end:
+ points.append(current)
+ # Advance by one month
+ month = current.month + 1
+ year = current.year
+ if month > 12:
+ month = 1
+ year += 1
+ day = min(current.day, 28)
+ current = date(year, month, day)
+ elif interval == "yearly":
+ while current <= end:
+ points.append(current)
+ current = date(current.year + 1, current.month, current.day)
+ else:
+ # Default to monthly
+ return _date_points(start, end, "monthly")
+
+ # Ensure the last point uses `end` so the final snapshot reflects today's data.
+ # If the last generated point is in the same period as `end`, replace it;
+ # otherwise append `end` as a new point.
+ if points and points[-1] < end:
+ if _format_date_label(points[-1], interval) == _format_date_label(end, interval):
+ points[-1] = end # same label, use today's cutoff
+ else:
+ points.append(end)
+
+ return points
+
+
+async def get_net_worth_report(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ months: int = 12,
+ interval: str = "monthly",
+ currency: str = "BRL",
+) -> ReportResponse:
+ """Build a full ReportResponse for net worth over time."""
+ today = date.today()
+ start = date(today.year, today.month, 1) - timedelta(days=months * 30)
+ start = start.replace(day=1) # Align to month start
+
+ points = _date_points(start, today, interval)
+
+ # Compute snapshot at each date point
+ trend: list[ReportDataPoint] = []
+ for point in points:
+ dp = await _net_worth_at(session, user_id, point)
+ dp.date = _format_date_label(point, interval)
+ trend.append(dp)
+
+ # Current snapshot (last point) and previous (first point) for summary
+ current = trend[-1] if trend else ReportDataPoint(
+ date="", value=0, breakdowns={"accounts": 0, "assets": 0, "liabilities": 0}
+ )
+ previous = trend[0] if len(trend) > 1 else current
+
+ change_amount = current.value - previous.value
+ change_percent = (
+ (change_amount / abs(previous.value) * 100)
+ if previous.value != 0
+ else None
+ )
+
+ summary = ReportSummary(
+ primary_value=current.value,
+ change_amount=round(change_amount, 2),
+ change_percent=round(change_percent, 2) if change_percent is not None else None,
+ breakdowns=[
+ ReportBreakdown(
+ key="accounts",
+ label="Accounts",
+ value=current.breakdowns.get("accounts", 0),
+ color="#6366F1",
+ ),
+ ReportBreakdown(
+ key="assets",
+ label="Assets",
+ value=current.breakdowns.get("assets", 0),
+ color="#F59E0B",
+ ),
+ ReportBreakdown(
+ key="liabilities",
+ label="Liabilities",
+ value=current.breakdowns.get("liabilities", 0),
+ color="#F43F5E",
+ ),
+ ],
+ )
+
+ meta = ReportMeta(
+ type="net_worth",
+ series_keys=["accounts", "assets", "liabilities"],
+ currency=currency,
+ 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, user_id)
+ for account in accounts:
+ bal = await _account_balance_at(session, account, today)
+ if account.type == "credit_card":
+ composition.append(ReportCompositionItem(
+ key=str(account.id),
+ label=account.name,
+ value=round(abs(bal), 2),
+ color=account_type_colors.get(account.type, "#6B7280"),
+ group="liabilities",
+ ))
+ else:
+ if bal > 0:
+ composition.append(ReportCompositionItem(
+ key=str(account.id),
+ label=account.name,
+ value=round(bal, 2),
+ color=account_type_colors.get(account.type, "#6B7280"),
+ group="accounts",
+ ))
+
+ # Assets
+ asset_result = await session.execute(
+ select(Asset).where(
+ Asset.user_id == user_id,
+ Asset.is_archived == False,
+ Asset.sell_date.is_(None),
+ )
+ )
+ 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:
+ composition.append(ReportCompositionItem(
+ key=str(asset.id),
+ label=asset.name,
+ value=round(amount, 2),
+ color=asset_type_colors.get(asset.type, "#6B7280"),
+ group="assets",
+ ))
+
+ return ReportResponse(summary=summary, trend=trend, meta=meta, composition=composition)
+
+
+def _interval_label_expr(interval: str):
+ """SQL expression that groups transaction dates into interval buckets."""
+ if interval == "daily":
+ return func.to_char(Transaction.date, 'YYYY-MM-DD')
+ elif interval == "weekly":
+ return func.concat(
+ func.extract('isoyear', Transaction.date).cast(String),
+ '-W',
+ func.lpad(func.extract('week', Transaction.date).cast(String), 2, '0'),
+ )
+ elif interval == "yearly":
+ return func.to_char(Transaction.date, 'YYYY')
+ else: # monthly (default)
+ return func.to_char(Transaction.date, 'YYYY-MM')
+
+
+async def get_income_expenses_report(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ months: int = 12,
+ interval: str = "monthly",
+ currency: str = "BRL",
+) -> ReportResponse:
+ """Build a ReportResponse for income vs expenses over time."""
+ today = date.today()
+ start = date(today.year, today.month, 1) - timedelta(days=months * 30)
+ start = start.replace(day=1)
+
+ label_expr = _interval_label_expr(interval).label('period')
+
+ result = await session.execute(
+ select(
+ label_expr,
+ func.sum(case((Transaction.type == "credit", Transaction.amount), else_=0)),
+ func.sum(case((Transaction.type == "debit", Transaction.amount), else_=0)),
+ )
+ .join(Account, Transaction.account_id == Account.id)
+ .where(
+ Transaction.user_id == user_id,
+ Account.is_closed == False,
+ Transaction.date >= start,
+ Transaction.date <= today,
+ Transaction.source != "opening_balance",
+ Transaction.transfer_pair_id.is_(None),
+ )
+ .group_by(label_expr)
+ .order_by(label_expr)
+ )
+
+ # Build data map from query results
+ data_map: dict[str, tuple[float, float]] = {}
+ for row in result.all():
+ income = float(row[1] or 0)
+ expenses = abs(float(row[2] or 0))
+ data_map[row[0]] = (income, expenses)
+
+ # Generate all expected date points and map to results
+ points = _date_points(start, today, interval)
+ trend: list[ReportDataPoint] = []
+ total_income = 0.0
+ total_expenses = 0.0
+
+ for point in points:
+ label = _format_date_label(point, interval)
+ income, expenses = data_map.get(label, (0.0, 0.0))
+ net = round(income - expenses, 2)
+ total_income += income
+ total_expenses += expenses
+ trend.append(ReportDataPoint(
+ date=label,
+ value=net,
+ breakdowns={
+ "income": round(income, 2),
+ "expenses": round(expenses, 2),
+ },
+ ))
+
+ total_net = round(total_income - total_expenses, 2)
+
+ # Compare last point vs first point net income
+ current_net = trend[-1].value if trend else 0.0
+ previous_net = trend[0].value if len(trend) > 1 else 0.0
+ change_amount = current_net - previous_net
+ change_percent = (
+ (change_amount / abs(previous_net) * 100)
+ if previous_net != 0
+ else None
+ )
+
+ summary = ReportSummary(
+ primary_value=total_net,
+ change_amount=round(change_amount, 2),
+ change_percent=round(change_percent, 2) if change_percent is not None else None,
+ breakdowns=[
+ ReportBreakdown(
+ key="income",
+ label="Income",
+ value=round(total_income, 2),
+ color="#10B981",
+ ),
+ ReportBreakdown(
+ key="expenses",
+ label="Expenses",
+ value=round(total_expenses, 2),
+ color="#F43F5E",
+ ),
+ ReportBreakdown(
+ key="netIncome",
+ label="Net Income",
+ value=total_net,
+ color="#6366F1",
+ ),
+ ],
+ )
+
+ meta = ReportMeta(
+ type="income_expenses",
+ series_keys=["income", "expenses"],
+ currency=currency,
+ interval=interval,
+ )
+
+ # Build per-category composition for the full date range
+ cat_result = await session.execute(
+ select(
+ Category.id,
+ Category.name,
+ Category.color,
+ Transaction.type,
+ func.sum(Transaction.amount),
+ )
+ .select_from(Transaction)
+ .join(Account, Transaction.account_id == Account.id)
+ .outerjoin(Category, Transaction.category_id == Category.id)
+ .where(
+ Transaction.user_id == user_id,
+ Account.is_closed == False,
+ Transaction.date >= start,
+ Transaction.date <= today,
+ Transaction.source != "opening_balance",
+ Transaction.transfer_pair_id.is_(None),
+ )
+ .group_by(Category.id, Category.name, Category.color, Transaction.type)
+ )
+ composition: list[ReportCompositionItem] = []
+ for row in cat_result.all():
+ cat_id, cat_name, cat_color, txn_type, total_amount = row
+ amount = abs(float(total_amount or 0))
+ if amount <= 0:
+ continue
+ composition.append(ReportCompositionItem(
+ key=str(cat_id) if cat_id else "uncategorized",
+ label=cat_name if cat_name else "Uncategorized",
+ value=round(amount, 2),
+ color=cat_color if cat_color else "#6B7280",
+ group="income" if txn_type == "credit" else "expenses",
+ ))
+
+ # Build per-category trend (sparklines) for the full date range
+ cat_trend_result = await session.execute(
+ select(
+ label_expr,
+ Category.id,
+ Category.name,
+ Category.color,
+ Transaction.type,
+ func.sum(Transaction.amount),
+ )
+ .select_from(Transaction)
+ .join(Account, Transaction.account_id == Account.id)
+ .outerjoin(Category, Transaction.category_id == Category.id)
+ .where(
+ Transaction.user_id == user_id,
+ Account.is_closed == False,
+ Transaction.date >= start,
+ Transaction.date <= today,
+ Transaction.source != "opening_balance",
+ Transaction.transfer_pair_id.is_(None),
+ )
+ .group_by(label_expr, Category.id, Category.name, Category.color, Transaction.type)
+ )
+
+ # Collect into dict[(cat_key, group)] -> {label, color, total, periods}
+ cat_trend_map: dict[tuple[str, str], dict] = {}
+ for row in cat_trend_result.all():
+ period_label, cat_id, cat_name, cat_color, txn_type, total_amount = row
+ amount = abs(float(total_amount or 0))
+ if amount <= 0:
+ continue
+ cat_key = str(cat_id) if cat_id else "uncategorized"
+ group = "income" if txn_type == "credit" else "expenses"
+ map_key = (cat_key, group)
+ if map_key not in cat_trend_map:
+ cat_trend_map[map_key] = {
+ "label": cat_name if cat_name else "Uncategorized",
+ "color": cat_color if cat_color else "#6B7280",
+ "total": 0.0,
+ "periods": {},
+ }
+ cat_trend_map[map_key]["total"] += amount
+ cat_trend_map[map_key]["periods"][period_label] = (
+ cat_trend_map[map_key]["periods"].get(period_label, 0.0) + amount
+ )
+
+ # Build period labels from the same points used by the trend
+ period_labels = [_format_date_label(p, interval) for p in points]
+
+ # Top 6 + Other per group
+ category_trend: list[CategoryTrendItem] = []
+ for group in ("expenses", "income"):
+ group_items = [
+ (k, v) for (k, g), v in cat_trend_map.items() if g == group
+ ]
+ group_items.sort(key=lambda x: x[1]["total"], reverse=True)
+ top = group_items[:6]
+ rest = group_items[6:]
+
+ for cat_key, info in top:
+ series = [
+ ReportDataPoint(
+ date=pl,
+ value=round(info["periods"].get(pl, 0.0), 2),
+ breakdowns={},
+ )
+ for pl in period_labels
+ ]
+ category_trend.append(CategoryTrendItem(
+ key=cat_key,
+ label=info["label"],
+ color=info["color"],
+ total=round(info["total"], 2),
+ group=group,
+ series=series,
+ ))
+
+ if rest:
+ other_total = sum(v["total"] for _, v in rest)
+ other_periods: dict[str, float] = {}
+ for _, v in rest:
+ for pl, amt in v["periods"].items():
+ other_periods[pl] = other_periods.get(pl, 0.0) + amt
+ series = [
+ ReportDataPoint(
+ date=pl,
+ value=round(other_periods.get(pl, 0.0), 2),
+ breakdowns={},
+ )
+ for pl in period_labels
+ ]
+ category_trend.append(CategoryTrendItem(
+ key="other",
+ label="Other",
+ color="#6B7280",
+ total=round(other_total, 2),
+ group=group,
+ series=series,
+ ))
+
+ return ReportResponse(
+ summary=summary, trend=trend, meta=meta,
+ composition=composition, category_trend=category_trend,
+ )
diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.py
new file mode 100644
index 00000000..11f136c8
--- /dev/null
+++ b/backend/tests/test_report_service.py
@@ -0,0 +1,536 @@
+"""Tests for report service and API endpoints."""
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.transaction import Transaction
+from app.schemas.report import CategoryTrendItem, ReportDataPoint, ReportResponse
+from app.services.report_service import (
+ _date_points,
+ _format_date_label,
+ get_net_worth_report,
+)
+
+
+# ---------------------------------------------------------------------------
+# Pure-function tests: _format_date_label
+# ---------------------------------------------------------------------------
+
+
+def test_format_date_label_daily():
+ assert _format_date_label(date(2025, 6, 15), "daily") == "2025-06-15"
+
+
+def test_format_date_label_weekly():
+ # 2025-06-16 is a Monday in ISO week 25
+ assert _format_date_label(date(2025, 6, 16), "weekly") == "2025-W25"
+
+
+def test_format_date_label_monthly():
+ assert _format_date_label(date(2025, 1, 20), "monthly") == "2025-01"
+
+
+def test_format_date_label_yearly():
+ assert _format_date_label(date(2025, 3, 1), "yearly") == "2025"
+
+
+def test_format_date_label_unknown_falls_back_to_iso():
+ assert _format_date_label(date(2025, 3, 1), "unknown") == "2025-03-01"
+
+
+# ---------------------------------------------------------------------------
+# Pure-function tests: _date_points
+# ---------------------------------------------------------------------------
+
+
+def test_date_points_daily():
+ start = date(2025, 1, 1)
+ end = date(2025, 1, 5)
+ points = _date_points(start, end, "daily")
+ assert len(points) == 5
+ assert points[0] == start
+ assert points[-1] == end
+
+
+def test_date_points_weekly():
+ start = date(2025, 1, 1)
+ end = date(2025, 1, 22)
+ points = _date_points(start, end, "weekly")
+ # 1st, 8th, 15th, 22nd = 4 points
+ assert len(points) == 4
+ assert points[0] == start
+ assert points[-1] == end
+
+
+def test_date_points_monthly():
+ start = date(2025, 1, 1)
+ end = date(2025, 6, 15)
+ points = _date_points(start, end, "monthly")
+ assert points[0] == start
+ # Last point should be end (June 15), not June 1
+ assert points[-1] == end
+
+
+def test_date_points_yearly():
+ start = date(2023, 1, 1)
+ end = date(2025, 6, 15)
+ points = _date_points(start, end, "yearly")
+ assert points[0] == start
+ assert points[-1] == end
+
+
+def test_date_points_empty_range():
+ """Start after end returns single point."""
+ start = date(2025, 1, 1)
+ end = date(2025, 1, 1)
+ points = _date_points(start, end, "daily")
+ assert len(points) == 1
+
+
+def test_date_points_unknown_interval_defaults_to_monthly():
+ start = date(2025, 1, 1)
+ end = date(2025, 3, 15)
+ points = _date_points(start, end, "something_else")
+ monthly = _date_points(start, end, "monthly")
+ assert points == monthly
+
+
+def test_date_points_last_point_replaces_same_period():
+ """When end falls in the same period as the last generated point, replace it."""
+ start = date(2025, 1, 1)
+ end = date(2025, 3, 15)
+ points = _date_points(start, end, "monthly")
+ # March 1 and March 15 share "2025-03" label, so March 15 replaces March 1
+ assert points[-1] == end
+ labels = [_format_date_label(p, "monthly") for p in points]
+ # No duplicates
+ assert len(labels) == len(set(labels))
+
+
+# ---------------------------------------------------------------------------
+# Service-level tests: get_net_worth_report (works with SQLite)
+# ---------------------------------------------------------------------------
+
+
+async def _create_manual_account(
+ session: AsyncSession, user_id: uuid.UUID, name: str, balance: float = 0
+) -> Account:
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ name=name,
+ type="checking",
+ balance=Decimal(str(balance)),
+ currency="BRL",
+ is_closed=False,
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+async def _create_transaction(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ account_id: uuid.UUID,
+ amount: float,
+ txn_type: str,
+ txn_date: date,
+ source: str = "manual",
+) -> Transaction:
+ from datetime import datetime, timezone
+
+ txn = Transaction(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ account_id=account_id,
+ description=f"Test {txn_type} {amount}",
+ amount=Decimal(str(amount)),
+ date=txn_date,
+ type=txn_type,
+ source=source,
+ currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+ await session.refresh(txn)
+ return txn
+
+
+async def test_net_worth_report_structure(session: AsyncSession, test_user):
+ """Net worth report returns correct ReportResponse structure."""
+ account = await _create_manual_account(session, test_user.id, "NW Test")
+ await _create_transaction(
+ session, test_user.id, account.id, 5000, "credit", date.today(), source="opening_balance"
+ )
+
+ report = await get_net_worth_report(session, test_user.id, months=6, interval="monthly")
+
+ assert report.meta.type == "net_worth"
+ assert report.meta.series_keys == ["accounts", "assets", "liabilities"]
+ assert report.meta.currency == "BRL"
+ assert report.meta.interval == "monthly"
+ assert report.summary.primary_value is not None
+ assert len(report.summary.breakdowns) == 3
+ assert len(report.trend) > 0
+
+ # Each trend point has the expected breakdown keys
+ for dp in report.trend:
+ assert "accounts" in dp.breakdowns
+ assert "assets" in dp.breakdowns
+ assert "liabilities" in dp.breakdowns
+
+
+async def test_net_worth_report_reflects_balance(session: AsyncSession, test_user):
+ """Net worth report reflects actual account balance."""
+ account = await _create_manual_account(session, test_user.id, "NW Balance Test")
+ await _create_transaction(
+ session, test_user.id, account.id, 10000, "credit", date.today(), source="opening_balance"
+ )
+ await _create_transaction(
+ session, test_user.id, account.id, 3000, "debit", date.today()
+ )
+
+ report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")
+
+ # Current net worth should be 10000 - 3000 = 7000
+ assert report.summary.primary_value == 7000.0
+ assert report.summary.breakdowns[0].key == "accounts"
+ assert report.summary.breakdowns[0].value == 7000.0
+
+
+async def test_net_worth_report_change_amount(session: AsyncSession, test_user):
+ """Net worth report computes change between first and last trend points."""
+ account = await _create_manual_account(session, test_user.id, "NW Change Test")
+
+ # Add a transaction 3 months ago
+ three_months_ago = date.today() - timedelta(days=90)
+ await _create_transaction(
+ session, test_user.id, account.id, 1000, "credit", three_months_ago, source="opening_balance"
+ )
+ # Add more income recently
+ await _create_transaction(
+ session, test_user.id, account.id, 2000, "credit", date.today()
+ )
+
+ report = await get_net_worth_report(session, test_user.id, months=6, interval="monthly")
+
+ # change_amount = last.value - first.value; should be positive
+ assert report.summary.change_amount >= 0
+
+
+async def test_net_worth_report_excludes_closed_accounts(session: AsyncSession, test_user):
+ """Closed accounts are excluded from net worth."""
+ # Open account with 5000
+ open_acct = await _create_manual_account(session, test_user.id, "NW Open")
+ await _create_transaction(
+ session, test_user.id, open_acct.id, 5000, "credit", date.today(), source="opening_balance"
+ )
+
+ # Closed account with 3000
+ closed_acct = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ name="NW Closed",
+ type="checking",
+ balance=Decimal("3000.00"),
+ currency="BRL",
+ is_closed=True,
+ )
+ session.add(closed_acct)
+ await session.commit()
+ await _create_transaction(
+ session, test_user.id, closed_acct.id, 3000, "credit", date.today(), source="opening_balance"
+ )
+
+ report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")
+
+ # Should only include the open account
+ assert report.summary.primary_value == 5000.0
+
+
+async def test_net_worth_report_intervals(session: AsyncSession, test_user):
+ """Net worth report works with different interval options."""
+ account = await _create_manual_account(session, test_user.id, "NW Interval Test")
+ await _create_transaction(
+ session, test_user.id, account.id, 1000, "credit", date.today(), source="opening_balance"
+ )
+
+ for interval in ["daily", "weekly", "monthly", "yearly"]:
+ report = await get_net_worth_report(session, test_user.id, months=6, interval=interval)
+ assert report.meta.interval == interval
+ assert len(report.trend) > 0
+
+
+# ---------------------------------------------------------------------------
+# API-level tests: /reports/net-worth
+# ---------------------------------------------------------------------------
+
+
+async def test_net_worth_api_endpoint(client, auth_headers, test_transactions):
+ """GET /reports/net-worth returns valid response."""
+ response = await client.get(
+ "/api/reports/net-worth",
+ params={"months": 6, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ assert data["meta"]["type"] == "net_worth"
+ assert "summary" in data
+ assert "trend" in data
+ assert isinstance(data["summary"]["primary_value"], (int, float))
+ assert isinstance(data["trend"], list)
+
+
+async def test_net_worth_api_validation(client, auth_headers):
+ """GET /reports/net-worth validates query params."""
+ # Invalid interval
+ resp = await client.get(
+ "/api/reports/net-worth",
+ params={"interval": "invalid"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+ # Months out of range
+ resp = await client.get(
+ "/api/reports/net-worth",
+ params={"months": 0},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+
+async def test_net_worth_api_requires_auth(client):
+ """GET /reports/net-worth requires authentication."""
+ resp = await client.get("/api/reports/net-worth")
+ assert resp.status_code == 401
+
+
+# ---------------------------------------------------------------------------
+# API-level tests: /reports/income-expenses
+# ---------------------------------------------------------------------------
+
+
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
+async def test_income_expenses_api_endpoint(client, auth_headers, test_transactions):
+ """GET /reports/income-expenses returns valid response."""
+ response = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 12, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ assert data["meta"]["type"] == "income_expenses"
+ assert data["meta"]["series_keys"] == ["income", "expenses"]
+ assert "summary" in data
+ assert "trend" in data
+
+ # Summary should have income, expenses, netIncome breakdowns
+ breakdown_keys = [b["key"] for b in data["summary"]["breakdowns"]]
+ assert "income" in breakdown_keys
+ assert "expenses" in breakdown_keys
+ assert "netIncome" in breakdown_keys
+
+ # Verify math: net income = income - expenses
+ breakdowns = {b["key"]: b["value"] for b in data["summary"]["breakdowns"]}
+ assert abs(breakdowns["netIncome"] - (breakdowns["income"] - breakdowns["expenses"])) < 0.01
+
+ # Each trend point has income/expenses breakdowns
+ for dp in data["trend"]:
+ assert "income" in dp["breakdowns"]
+ assert "expenses" in dp["breakdowns"]
+ # value = net income = income - expenses
+ expected_net = dp["breakdowns"]["income"] - dp["breakdowns"]["expenses"]
+ assert abs(dp["value"] - expected_net) < 0.01
+
+
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
+async def test_income_expenses_excludes_opening_balance(client, auth_headers):
+ """Income expenses report excludes opening balance transactions."""
+ # Create account with opening balance
+ acc_resp = await client.post(
+ "/api/accounts",
+ json={"name": "IE Test", "type": "checking", "balance": 10000.00, "currency": "BRL"},
+ headers=auth_headers,
+ )
+ assert acc_resp.status_code == 201
+
+ response = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 1, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ # Opening balance should NOT appear as income
+ breakdowns = {b["key"]: b["value"] for b in data["summary"]["breakdowns"]}
+ assert breakdowns["income"] == 0.0
+
+
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
+async def test_income_expenses_excludes_transfers(client, auth_headers):
+ """Income expenses report excludes transfer pair transactions."""
+ response = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 12, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ # Just verify the endpoint works — transfer exclusion is enforced by the SQL filter
+
+
+async def test_income_expenses_api_validation(client, auth_headers):
+ """GET /reports/income-expenses validates query params."""
+ resp = await client.get(
+ "/api/reports/income-expenses",
+ params={"interval": "invalid"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+ resp = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 25},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+
+async def test_income_expenses_api_requires_auth(client):
+ """GET /reports/income-expenses requires authentication."""
+ resp = await client.get("/api/reports/income-expenses")
+ assert resp.status_code == 401
+
+
+# ---------------------------------------------------------------------------
+# Schema tests: CategoryTrendItem & category_trend on ReportResponse
+# ---------------------------------------------------------------------------
+
+
+def test_category_trend_item_schema():
+ """CategoryTrendItem can be constructed with valid data."""
+ item = CategoryTrendItem(
+ key="cat-1",
+ label="Groceries",
+ color="#10B981",
+ total=1500.0,
+ group="expenses",
+ series=[
+ ReportDataPoint(date="2025-01", value=500.0, breakdowns={}),
+ ReportDataPoint(date="2025-02", value=450.0, breakdowns={}),
+ ReportDataPoint(date="2025-03", value=550.0, breakdowns={}),
+ ],
+ )
+ assert item.key == "cat-1"
+ assert item.group == "expenses"
+ assert len(item.series) == 3
+ assert item.total == 1500.0
+
+
+def test_report_response_includes_category_trend():
+ """ReportResponse includes category_trend field, defaulting to empty."""
+ from app.schemas.report import ReportMeta, ReportSummary, ReportBreakdown
+
+ response = ReportResponse(
+ summary=ReportSummary(
+ primary_value=1000.0,
+ change_amount=100.0,
+ change_percent=10.0,
+ breakdowns=[ReportBreakdown(key="a", label="A", value=1000.0, color="#000")],
+ ),
+ trend=[ReportDataPoint(date="2025-01", value=1000.0, breakdowns={})],
+ meta=ReportMeta(type="test", series_keys=["a"], currency="BRL", interval="monthly"),
+ )
+ # Default is empty list
+ assert response.category_trend == []
+
+ # Can also be set explicitly
+ item = CategoryTrendItem(
+ key="cat-1", label="Food", color="#F00", total=500.0,
+ group="expenses", series=[],
+ )
+ response2 = ReportResponse(
+ summary=response.summary,
+ trend=response.trend,
+ meta=response.meta,
+ category_trend=[item],
+ )
+ assert len(response2.category_trend) == 1
+ assert response2.category_trend[0].label == "Food"
+
+
+# ---------------------------------------------------------------------------
+# Service-level test: net_worth returns empty category_trend
+# ---------------------------------------------------------------------------
+
+
+async def test_net_worth_report_has_empty_category_trend(session: AsyncSession, test_user):
+ """Net worth report returns empty category_trend (only used by income_expenses)."""
+ account = await _create_manual_account(session, test_user.id, "NW CatTrend Test")
+ await _create_transaction(
+ session, test_user.id, account.id, 1000, "credit", date.today(), source="opening_balance"
+ )
+
+ report = await get_net_worth_report(session, test_user.id, months=3, interval="monthly")
+ assert report.category_trend == []
+
+
+# ---------------------------------------------------------------------------
+# API-level test: income-expenses includes category_trend
+# ---------------------------------------------------------------------------
+
+
[email protected](reason="to_char() is PostgreSQL-specific; tests use SQLite")
+async def test_income_expenses_has_category_trend(client, auth_headers, test_transactions):
+ """GET /reports/income-expenses response includes category_trend array."""
+ response = await client.get(
+ "/api/reports/income-expenses",
+ params={"months": 12, "interval": "monthly"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ assert "category_trend" in data
+ assert isinstance(data["category_trend"], list)
+
+ # Each item should have the expected shape
+ for item in data["category_trend"]:
+ assert "key" in item
+ assert "label" in item
+ assert "color" in item
+ assert "total" in item
+ assert "group" in item
+ assert item["group"] in ("income", "expenses")
+ assert "series" in item
+ assert isinstance(item["series"], list)
+ for point in item["series"]:
+ assert "date" in point
+ assert "value" in point
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d087aeba..02b6b040 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -20,6 +20,7 @@ const CategoriesPage = lazy(() => import('@/pages/categories'))
const BudgetsPage = lazy(() => import('@/pages/budgets'))
const RecurringPage = lazy(() => import('@/pages/recurring'))
const AssetsPage = lazy(() => import('@/pages/assets'))
+const ReportsPage = lazy(() => import('@/pages/reports'))
const queryClient = new QueryClient({
defaultOptions: {
@@ -66,6 +67,7 @@ function App() {
<Route path="/budgets" element={<BudgetsPage />} />
<Route path="/recurring" element={<RecurringPage />} />
<Route path="/assets" element={<AssetsPage />} />
+ <Route path="/reports" element={<ReportsPage />} />
</Route>
</Routes>
</Suspense>
diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsx
index e35de8dd..f415b95b 100644
--- a/frontend/src/components/app-layout.tsx
+++ b/frontend/src/components/app-layout.tsx
@@ -32,6 +32,7 @@ import {
EyeOff,
Repeat,
Landmark,
+ BarChart3,
Sun,
Moon,
} from 'lucide-react'
@@ -44,6 +45,7 @@ const navItems = [
{ key: 'categories', path: '/categories', icon: Tag },
{ key: 'budgets', path: '/budgets', icon: PiggyBank },
{ key: 'assets', path: '/assets', icon: Landmark },
+ { key: 'reports', path: '/reports', icon: BarChart3 },
{ key: 'recurring', path: '/recurring', icon: Repeat },
{ key: 'rules', path: '/rules', icon: SlidersHorizontal },
{ key: 'import', path: '/import', icon: Upload },
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 78c753c6..54caf6be 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -21,6 +21,7 @@ import type {
MonthlyTrend,
BalanceHistory,
PaginatedResponse,
+ ReportResponse,
} from '@/types'
const api = axios.create({
@@ -426,6 +427,18 @@ export const assets = {
},
}
+// Reports
+export const reports = {
+ netWorth: async (months = 12, interval = 'monthly'): Promise<ReportResponse> => {
+ const { data } = await api.get('/reports/net-worth', { params: { months, interval } })
+ return data
+ },
+ incomeExpenses: async (months = 12, interval = 'monthly'): Promise<ReportResponse> => {
+ const { data } = await api.get('/reports/income-expenses', { params: { months, interval } })
+ return data
+ },
+}
+
// Import Logs
export const importLogs = {
list: async (): Promise<ImportLog[]> => {
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index a026bfac..361aa4e8 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -12,7 +12,8 @@
"budgets": "Budgets",
"settings": "Settings",
"recurring": "Recurring",
- "assets": "Assets"
+ "assets": "Assets",
+ "reports": "Reports"
},
"auth": {
"login": "Login",
@@ -415,6 +416,39 @@
"confirmRegenerate": "Growth parameters changed. All automatically generated values will be deleted and recalculated. Manual values will be kept.",
"regenerate": "Regenerate"
},
+ "reports": {
+ "section": "Analytics",
+ "netWorth": "Net Worth",
+ "trend": "Over Time",
+ "breakdown": "Breakdown",
+ "noData": "No data available for this period",
+ "range6m": "6M",
+ "range1y": "1Y",
+ "range2y": "2Y",
+ "intervalDaily": "D",
+ "intervalWeekly": "W",
+ "intervalMonthly": "M",
+ "intervalYearly": "Y",
+ "accounts": "Accounts",
+ "assets": "Assets",
+ "liabilities": "Liabilities",
+ "vsStart": "vs start of period",
+ "incomeExpenses": "Income vs Expenses",
+ "cashFlow": "Cash Flow",
+ "comingSoon": "(coming soon)",
+ "composition": "Composition",
+ "evolution": "Evolution",
+ "income": "Income",
+ "expenses": "Expenses",
+ "netIncome": "Net Income",
+ "summary": "Summary",
+ "detailed": "Detailed",
+ "byIncome": "By Income",
+ "byExpenses": "By Expenses",
+ "other": "Other",
+ "uncategorized": "Uncategorized",
+ "categoryTrends": "Category Trends"
+ },
"common": {
"save": "Save",
"cancel": "Cancel",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index fc376287..1fcb93fa 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -12,7 +12,8 @@
"budgets": "Orçamentos",
"settings": "Configurações",
"recurring": "Recorrentes",
- "assets": "Patrimônio"
+ "assets": "Patrimônio",
+ "reports": "Relatórios"
},
"auth": {
"login": "Entrar",
@@ -415,6 +416,39 @@
"confirmRegenerate": "Os parâmetros de crescimento foram alterados. Todos os valores gerados automaticamente serão excluídos e recalculados. Valores manuais serão mantidos.",
"regenerate": "Regenerar"
},
+ "reports": {
+ "section": "Análises",
+ "netWorth": "Patrimônio Líquido",
+ "trend": "Ao Longo do Tempo",
+ "breakdown": "Composição",
+ "noData": "Nenhum dado disponível para este período",
+ "range6m": "6M",
+ "range1y": "1A",
+ "range2y": "2A",
+ "intervalDaily": "D",
+ "intervalWeekly": "S",
+ "intervalMonthly": "M",
+ "intervalYearly": "A",
+ "accounts": "Contas",
+ "assets": "Ativos",
+ "liabilities": "Passivos",
+ "vsStart": "vs início do período",
+ "incomeExpenses": "Receitas vs Despesas",
+ "cashFlow": "Fluxo de Caixa",
+ "comingSoon": "(em breve)",
+ "composition": "Composição",
+ "evolution": "Evolução",
+ "income": "Receitas",
+ "expenses": "Despesas",
+ "netIncome": "Resultado Líquido",
+ "summary": "Resumo",
+ "detailed": "Detalhado",
+ "byIncome": "Por Receita",
+ "byExpenses": "Por Despesa",
+ "other": "Outros",
+ "uncategorized": "Sem categoria",
+ "categoryTrends": "Tendência por Categoria"
+ },
"common": {
"save": "Salvar",
"cancel": "Cancelar",
diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsx
new file mode 100644
index 00000000..e6dd5aae
--- /dev/null
+++ b/frontend/src/pages/reports.tsx
@@ -0,0 +1,769 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery } from '@tanstack/react-query'
+import {
+ AreaChart,
+ Area,
+ BarChart,
+ Bar,
+ ComposedChart,
+ Line,
+ PieChart,
+ Pie,
+ Cell,
+ XAxis,
+ YAxis,
+ Tooltip,
+ Legend,
+ ReferenceLine,
+ ResponsiveContainer,
+} from 'recharts'
+import { reports } from '@/lib/api'
+import { Skeleton } from '@/components/ui/skeleton'
+import { PageHeader } from '@/components/page-header'
+import { usePrivacyMode } from '@/hooks/use-privacy-mode'
+import { useAuth } from '@/contexts/auth-context'
+import type { ReportResponse, CategoryTrendItem } from '@/types'
+
+function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {
+ return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)
+}
+
+function formatCompact(value: number, currency = 'BRL', locale = 'pt-BR') {
+ return new Intl.NumberFormat(locale, {
+ style: 'currency',
+ currency,
+ notation: 'compact',
+ maximumFractionDigits: 1,
+ }).format(value)
+}
+
+const RANGE_OPTIONS = [
+ { key: '6m', months: 6 },
+ { key: '1y', months: 12 },
+ { key: '2y', months: 24 },
+] as const
+
+const INTERVAL_OPTIONS = [
+ { key: 'daily', value: 'daily' },
+ { key: 'weekly', value: 'weekly' },
+ { key: 'monthly', value: 'monthly' },
+ { key: 'yearly', value: 'yearly' },
+] as const
+
+const INTERVAL_LABELS: Record<string, string> = {
+ daily: 'intervalDaily',
+ weekly: 'intervalWeekly',
+ monthly: 'intervalMonthly',
+ yearly: 'intervalYearly',
+}
+
+const RANGE_LABELS: Record<string, string> = {
+ '6m': 'range6m',
+ '1y': 'range1y',
+ '2y': 'range2y',
+}
+
+interface ReportTab {
+ key: string
+ labelKey: string
+ fetch: (months: number, interval: string) => Promise<ReportResponse>
+ enabled: boolean
+}
+
+const REPORT_TABS: ReportTab[] = [
+ { key: 'net_worth', labelKey: 'reports.netWorth', fetch: (m, i) => reports.netWorth(m, i), enabled: true },
+ { key: 'income_expenses', labelKey: 'reports.incomeExpenses', fetch: (m, i) => reports.incomeExpenses(m, i), enabled: true },
+ { key: 'cash_flow', labelKey: 'reports.cashFlow', fetch: () => Promise.reject(), enabled: false },
+]
+
+export default function ReportsPage() {
+ const { t, i18n } = useTranslation()
+ const { mask, privacyMode, MASK } = usePrivacyMode()
+ const { user } = useAuth()
+ const userCurrency = user?.preferences?.currency_display ?? 'BRL'
+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language
+
+ const [months, setMonths] = useState(12)
+ const [interval, setInterval] = useState('monthly')
+ const [activeTab, setActiveTab] = useState('net_worth')
+ const [compositionView, setCompositionView] = useState<string>('summary')
+ const [sparklineView, setSparklineView] = useState<'byExpenses' | 'byIncome'>('byExpenses')
+ const [sparklinePage, setSparklinePage] = useState(0)
+
+ const currentTab = REPORT_TABS.find((tab) => tab.key === activeTab) ?? REPORT_TABS[0]
+
+ const { data, isLoading } = useQuery<ReportResponse>({
+ queryKey: ['reports', activeTab, months, interval],
+ queryFn: () => currentTab.fetch(months, interval),
+ enabled: currentTab.enabled,
+ })
+
+ const summary = data?.summary
+ const trend = data?.trend ?? []
+ const meta = data?.meta
+
+ const chartData = trend.map((dp) => ({
+ date: dp.date,
+ value: dp.value,
+ ...dp.breakdowns,
+ } as Record<string, string | number>))
+
+ const allBreakdowns = summary?.breakdowns ?? []
+ const breakdownData = allBreakdowns.filter((b) => b.value > 0)
+
+ const colorMap: Record<string, string> = {}
+ for (const b of allBreakdowns) {
+ colorMap[b.key] = b.color
+ }
+
+ const changePrefix = (summary?.change_amount ?? 0) >= 0 ? '+' : ''
+ const changeColor = (summary?.change_amount ?? 0) >= 0 ? 'text-emerald-600' : 'text-rose-500'
+
+ const tooltipStyle = {
+ background: 'var(--card)',
+ color: 'var(--foreground)',
+ border: '1px solid var(--border)',
+ borderRadius: '0.75rem',
+ boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
+ fontSize: '12px',
+ }
+
+ // Composition view options per report type
+ const compositionOptions = meta?.type === 'income_expenses'
+ ? ['summary', 'byIncome', 'byExpenses'] as const
+ : ['summary', 'detailed'] as const
+
+ // Build donut data based on composition view
+ const composition = data?.composition ?? []
+
+ const donutData = (() => {
+ if (compositionView === 'summary' || composition.length === 0) {
+ return breakdownData
+ .filter((b) => b.value > 0 && b.key !== 'netIncome')
+ .map((b) => ({
+ name: t(`reports.${b.key}`, { defaultValue: b.label }),
+ value: b.value,
+ color: b.color,
+ }))
+ }
+
+ let items = composition
+ if (compositionView === 'byIncome') {
+ items = composition.filter((c) => c.group === 'income')
+ } else if (compositionView === 'byExpenses') {
+ items = composition.filter((c) => c.group === 'expenses')
+ }
+
+ // Sort descending, take top 6, bucket the rest into "Other"
+ const sorted = [...items].sort((a, b) => b.value - a.value)
+ const top = sorted.slice(0, 6)
+ const rest = sorted.slice(6)
+ const otherValue = rest.reduce((sum, c) => sum + c.value, 0)
+
+ const result = top.map((c) => ({
+ name: c.key === 'uncategorized' ? t('reports.uncategorized') : c.label,
+ value: c.value,
+ color: c.color,
+ }))
+ if (otherValue > 0) {
+ result.push({ name: t('reports.other'), value: Math.round(otherValue * 100) / 100, color: '#6B7280' })
+ }
+ return result
+ })()
+
+ return (
+ <div>
+ <PageHeader
+ section={t('reports.section')}
+ title={t(currentTab.labelKey)}
+ action={
+ <div className="flex items-center gap-2">
+ <div className="flex items-center rounded-lg border border-border bg-card overflow-hidden">
+ {RANGE_OPTIONS.map((opt) => (
+ <button
+ key={opt.key}
+ onClick={() => setMonths(opt.months)}
+ className={`px-3 py-1.5 text-xs font-semibold transition-colors ${
+ months === opt.months
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
+ }`}
+ >
+ {t(`reports.${RANGE_LABELS[opt.key]}`)}
+ </button>
+ ))}
+ </div>
+ <div className="flex items-center rounded-lg border border-border bg-card overflow-hidden">
+ {INTERVAL_OPTIONS.map((opt) => (
+ <button
+ key={opt.key}
+ onClick={() => setInterval(opt.value)}
+ className={`px-2.5 py-1.5 text-xs font-semibold transition-colors ${
+ interval === opt.value
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
+ }`}
+ >
+ {t(`reports.${INTERVAL_LABELS[opt.key]}`)}
+ </button>
+ ))}
+ </div>
+ </div>
+ }
+ />
+
+ {/* Tab Bar */}
+ <div className="flex items-center gap-1 mb-5 border-b border-border">
+ {REPORT_TABS.map((tab) => (
+ <button
+ key={tab.key}
+ onClick={() => { if (tab.enabled) { setActiveTab(tab.key); setCompositionView('summary') } }}
+ disabled={!tab.enabled}
+ className={`relative px-4 py-2.5 text-sm font-medium transition-colors ${
+ activeTab === tab.key
+ ? 'text-foreground'
+ : tab.enabled
+ ? 'text-muted-foreground hover:text-foreground'
+ : 'text-muted-foreground/50 cursor-not-allowed'
+ }`}
+ >
+ {t(tab.labelKey)}
+ {!tab.enabled && (
+ <span className="ml-1.5 text-[10px] text-muted-foreground/50">
+ {t('reports.comingSoon')}
+ </span>
+ )}
+ {activeTab === tab.key && (
+ <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-full" />
+ )}
+ </button>
+ ))}
+ </div>
+
+ {/* Hero Card */}
+ <div className="bg-card rounded-xl border border-border shadow-sm mb-5">
+ <div className="px-5 py-4">
+ {isLoading ? (
+ <div className="flex items-center gap-8">
+ <Skeleton className="h-16 w-48" />
+ <div className="flex gap-6">
+ <Skeleton className="h-12 w-28" />
+ <Skeleton className="h-12 w-28" />
+ <Skeleton className="h-12 w-28" />
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
+ <div>
+ <p className="text-xs font-medium text-muted-foreground mb-0.5 uppercase tracking-wider">
+ {t(currentTab.labelKey)}
+ </p>
+ <div className="flex items-baseline gap-3">
+ <p className="text-3xl font-bold tabular-nums text-foreground">
+ {mask(formatCurrency(summary?.primary_value ?? 0, userCurrency, locale))}
+ </p>
+ {summary?.change_percent !== null && summary?.change_percent !== undefined && (
+ <span className={`text-sm font-semibold tabular-nums ${changeColor}`}>
+ {changePrefix}{summary.change_percent.toFixed(1)}%
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {mask(`${changePrefix}${formatCurrency(summary?.change_amount ?? 0, userCurrency, locale)}`)}
+ {' '}{t('reports.vsStart')}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-6">
+ {breakdownData.map((b) => (
+ <div key={b.key} className="min-w-0">
+ <div className="flex items-center gap-1.5 mb-0.5">
+ <div
+ className="w-2.5 h-2.5 rounded-full shrink-0"
+ style={{ backgroundColor: b.color }}
+ />
+ <p className="text-xs font-medium text-muted-foreground">
+ {t(`reports.${b.key}`, { defaultValue: b.label })}
+ </p>
+ </div>
+ <p className="text-lg font-bold tabular-nums text-foreground">
+ {mask(formatCurrency(b.value, userCurrency, locale))}
+ </p>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {/* Main Trend Chart */}
+ <div className="bg-card rounded-xl border border-border shadow-sm mb-5">
+ <div className="px-5 pt-5 pb-2 flex items-center justify-between">
+ <p className="text-sm font-semibold text-foreground">
+ {t(currentTab.labelKey)} · {t('reports.trend')}
+ </p>
+ {meta && (
+ <div className="flex items-center gap-3">
+ {meta.series_keys.map((key) => (
+ <div key={key} className="flex items-center gap-1.5">
+ <div
+ className="w-2 h-2 rounded-full"
+ style={{ backgroundColor: colorMap[key] || '#6366F1' }}
+ />
+ <span className="text-[11px] text-muted-foreground">
+ {t(`reports.${key}`, { defaultValue: key })}
+ </span>
+ </div>
+ ))}
+ {meta.type === 'income_expenses' && (
+ <div className="flex items-center gap-1.5">
+ <div className="w-3 h-0 border-t-2 border-dashed" style={{ borderColor: '#6366F1' }} />
+ <span className="text-[11px] text-muted-foreground">
+ {t('reports.netIncome')}
+ </span>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ <div className="px-1 pb-4" style={{ height: 320 }}>
+ {isLoading ? (
+ <div className="px-4">
+ <Skeleton className="h-full w-full" />
+ </div>
+ ) : chartData.length > 0 ? (
+ meta?.type === 'income_expenses' ? (
+ <ResponsiveContainer width="100%" height="100%">
+ <ComposedChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
+ <XAxis
+ dataKey="date"
+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
+ axisLine={false}
+ tickLine={false}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ tickFormatter={(v) => {
+ if (privacyMode) return ''
+ if (v === 0) return '0'
+ return formatCompact(v, userCurrency, locale)
+ }}
+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
+ axisLine={false}
+ tickLine={false}
+ width={64}
+ tickCount={5}
+ />
+ <Tooltip
+ formatter={(value?: number, name?: string) => [
+ privacyMode ? MASK : formatCurrency(value ?? 0, userCurrency, locale),
+ name === 'value'
+ ? t('reports.netIncome')
+ : t(`reports.${name ?? ''}`, { defaultValue: name ?? '' }),
+ ]}
+ labelFormatter={(label) => label}
+ contentStyle={tooltipStyle}
+ />
+ <ReferenceLine y={0} stroke="var(--border)" strokeDasharray="3 3" />
+ <Bar dataKey="income" fill="#10B981" radius={[4, 4, 0, 0]} maxBarSize={24} />
+ <Bar dataKey="expenses" fill="#F43F5E" radius={[4, 4, 0, 0]} maxBarSize={24} />
+ <Line
+ type="monotone"
+ dataKey="value"
+ stroke="#6366F1"
+ strokeWidth={2}
+ strokeDasharray="6 3"
+ dot={false}
+ activeDot={{ r: 4, fill: '#6366F1' }}
+ />
+ </ComposedChart>
+ </ResponsiveContainer>
+ ) : (
+ <ResponsiveContainer width="100%" height="100%">
+ <AreaChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id="netWorthGrad" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor="#6366F1" stopOpacity={0.2} />
+ <stop offset="95%" stopColor="#6366F1" stopOpacity={0.02} />
+ </linearGradient>
+ </defs>
+ <XAxis
+ dataKey="date"
+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
+ axisLine={false}
+ tickLine={false}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ tickFormatter={(v) => {
+ if (privacyMode) return ''
+ if (v === 0) return '0'
+ return formatCompact(v, userCurrency, locale)
+ }}
+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
+ axisLine={false}
+ tickLine={false}
+ width={64}
+ tickCount={5}
+ />
+ <Tooltip
+ formatter={(value?: number, name?: string) => [
+ privacyMode ? MASK : formatCurrency(value ?? 0, userCurrency, locale),
+ name === 'value'
+ ? t(currentTab.labelKey)
+ : t(`reports.${name ?? ''}`, { defaultValue: name ?? '' }),
+ ]}
+ labelFormatter={(label) => label}
+ contentStyle={tooltipStyle}
+ />
+ <Area
+ type="monotone"
+ dataKey="value"
+ stroke="#6366F1"
+ strokeWidth={2.5}
+ fill="url(#netWorthGrad)"
+ dot={false}
+ activeDot={{ r: 4, fill: '#6366F1' }}
+ />
+ </AreaChart>
+ </ResponsiveContainer>
+ )
+ ) : (
+ <p className="text-muted-foreground text-sm text-center py-16">
+ {t('reports.noData')}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Breakdown: Donut + Grouped Bar */}
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-5">
+ {/* Donut Chart — Current Composition */}
+ <div className="bg-card rounded-xl border border-border shadow-sm">
+ <div className="px-5 pt-4 pb-2 flex items-center justify-between">
+ <p className="text-sm font-semibold text-foreground">{t('reports.composition')}</p>
+ <div className="flex items-center rounded-lg border border-border bg-muted/30 overflow-hidden">
+ {compositionOptions.map((opt) => (
+ <button
+ key={opt}
+ onClick={() => setCompositionView(opt)}
+ className={`px-2.5 py-1 text-[11px] font-semibold transition-colors ${
+ compositionView === opt
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
+ }`}
+ >
+ {t(`reports.${opt}`)}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="px-1 pb-4">
+ {isLoading ? (
+ <div className="px-4" style={{ height: 200 }}>
+ <Skeleton className="h-full w-full" />
+ </div>
+ ) : donutData.length > 0 ? (
+ (() => {
+ const donutTotal = donutData.reduce((s, d) => s + d.value, 0)
+ const centerLabel = compositionView === 'byIncome'
+ ? t('reports.income')
+ : compositionView === 'byExpenses'
+ ? t('reports.expenses')
+ : meta?.type === 'income_expenses'
+ ? t('reports.netIncome')
+ : t(currentTab.labelKey)
+ const centerValue = compositionView === 'byIncome'
+ ? (summary?.breakdowns.find((b) => b.key === 'income')?.value ?? 0)
+ : compositionView === 'byExpenses'
+ ? (summary?.breakdowns.find((b) => b.key === 'expenses')?.value ?? 0)
+ : (summary?.primary_value ?? 0)
+ return (
+ <div className="flex flex-col items-center">
+ <div className="relative" style={{ width: 200, height: 200 }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <PieChart>
+ <Pie
+ data={donutData}
+ cx="50%"
+ cy="50%"
+ innerRadius={55}
+ outerRadius={85}
+ paddingAngle={3}
+ dataKey="value"
+ strokeWidth={0}
+ >
+ {donutData.map((entry, idx) => (
+ <Cell key={idx} fill={entry.color} />
+ ))}
+ </Pie>
+ <Tooltip
+ formatter={(value?: number, name?: string) => {
+ const v = value ?? 0
+ const pct = donutTotal > 0 ? ((v / donutTotal) * 100).toFixed(1) : '0'
+ return [
+ privacyMode ? MASK : `${formatCurrency(v, userCurrency, locale)} (${pct}%)`,
+ name,
+ ]
+ }}
+ contentStyle={{ ...tooltipStyle, zIndex: 10 }}
+ wrapperStyle={{ zIndex: 10 }}
+ offset={20}
+ />
+ </PieChart>
+ </ResponsiveContainer>
+ {/* Center label — positioned absolutely over the SVG */}
+ <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">{centerLabel}</span>
+ <span className="text-base font-bold text-foreground tabular-nums">
+ {mask(formatCompact(centerValue, userCurrency, locale))}
+ </span>
+ </div>
+ </div>
+ {/* Custom legend */}
+ <div className="flex flex-wrap justify-center gap-x-3 gap-y-1 px-3 mt-1">
+ {donutData.map((d) => (
+ <div key={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}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+ })()
+ ) : (
+ <p className="text-muted-foreground text-sm text-center py-16">
+ {t('reports.noData')}
+ </p>
+ )}
+ </div>
+ </div>
+
+ {/* Evolution / Category Sparklines */}
+ <div className="lg:col-span-2 bg-card rounded-xl border border-border shadow-sm">
+ <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') : t('reports.evolution')}
+ </p>
+ {meta?.type === 'income_expenses' && (() => {
+ const groupKey = sparklineView === 'byIncome' ? 'income' : 'expenses'
+ const allItems = (data?.category_trend ?? []).filter((c) => c.group === groupKey)
+ const totalPages = Math.ceil(allItems.length / 6)
+ const hasPagination = totalPages > 1
+ return (
+ <div className="flex items-center gap-2">
+ {hasPagination && (
+ <div className="flex items-center gap-0.5">
+ <button
+ onClick={() => setSparklinePage((p) => Math.max(0, p - 1))}
+ disabled={sparklinePage === 0}
+ className="p-1 rounded text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
+ >
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6" /></svg>
+ </button>
+ <button
+ onClick={() => setSparklinePage((p) => Math.min(totalPages - 1, p + 1))}
+ disabled={sparklinePage >= totalPages - 1}
+ className="p-1 rounded text-muted-foreground hover:text-foreground disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
+ >
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6" /></svg>
+ </button>
+ </div>
+ )}
+ <div className="flex items-center rounded-lg border border-border bg-muted/30 overflow-hidden">
+ {(['byExpenses', 'byIncome'] as const).map((opt) => (
+ <button
+ key={opt}
+ onClick={() => { setSparklineView(opt); setSparklinePage(0) }}
+ className={`px-2.5 py-1 text-[11px] font-semibold transition-colors ${
+ sparklineView === opt
+ ? 'bg-primary text-primary-foreground'
+ : 'text-muted-foreground hover:text-foreground hover:bg-muted/50'
+ }`}
+ >
+ {t(`reports.${opt}`)}
+ </button>
+ ))}
+ </div>
+ </div>
+ )
+ })()}
+ </div>
+ {meta?.type === 'income_expenses' ? (
+ <div className="pb-4 overflow-hidden">
+ {isLoading ? (
+ <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 px-4">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-20 w-full" />
+ ))}
+ </div>
+ ) : (() => {
+ const groupKey = sparklineView === 'byIncome' ? 'income' : 'expenses'
+ const allGroupItems: CategoryTrendItem[] = (data?.category_trend ?? []).filter(
+ (c) => c.group === groupKey
+ )
+ if (allGroupItems.length === 0) {
+ return (
+ <p className="text-muted-foreground text-sm text-center py-16">
+ {t('reports.noData')}
+ </p>
+ )
+ }
+ const totalPages = Math.ceil(allGroupItems.length / 6)
+ const pages = Array.from({ length: totalPages }, (_, i) =>
+ allGroupItems.slice(i * 6, i * 6 + 6)
+ )
+ return (
+ <div
+ className="flex"
+ style={{
+ transform: `translateX(-${sparklinePage * 100}%)`,
+ transition: 'transform 300ms cubic-bezier(0.4, 0, 0.2, 1)',
+ }}
+ >
+ {pages.map((pageItems, pageIdx) => (
+ <div
+ key={pageIdx}
+ className="grid grid-cols-2 sm:grid-cols-3 gap-3 w-full shrink-0 px-4"
+ >
+ {pageItems.map((item) => {
+ const sparkData = item.series.map((s) => ({ date: s.date, v: s.value }))
+ const gradId = `grad-${item.key}-${item.group}-p${pageIdx}`
+ return (
+ <div
+ key={`${item.key}-${item.group}`}
+ className="rounded-lg border border-border/50 bg-muted/20 px-3 py-2"
+ >
+ <div className="flex items-center gap-1.5 mb-0.5">
+ <div
+ className="w-2 h-2 rounded-full shrink-0"
+ style={{ backgroundColor: item.color }}
+ />
+ <span className="text-[11px] text-muted-foreground truncate">
+ {item.key === 'uncategorized' ? t('reports.uncategorized') : item.key === 'other' ? t('reports.other') : item.label}
+ </span>
+ </div>
+ <p className="text-xs font-bold tabular-nums text-foreground mb-1">
+ {mask(formatCompact(item.total, userCurrency, locale))}
+ </p>
+ <div style={{ height: 48 }}>
+ <ResponsiveContainer width="100%" height="100%">
+ <AreaChart data={sparkData} margin={{ top: 2, right: 0, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id={gradId} x1="0" y1="0" x2="0" y2="1">
+ <stop offset="5%" stopColor={item.color} stopOpacity={0.3} />
+ <stop offset="95%" stopColor={item.color} stopOpacity={0.02} />
+ </linearGradient>
+ </defs>
+ <XAxis dataKey="date" hide />
+ <Tooltip
+ formatter={(value?: number) => [
+ privacyMode ? MASK : formatCurrency(value ?? 0, userCurrency, locale),
+ item.label,
+ ]}
+ labelFormatter={(label) => label}
+ contentStyle={{ ...tooltipStyle, padding: '4px 8px' }}
+ />
+ <Area
+ type="monotone"
+ dataKey="v"
+ stroke={item.color}
+ strokeWidth={1.5}
+ fill={`url(#${gradId})`}
+ dot={false}
+ activeDot={{ r: 2, fill: item.color }}
+ />
+ </AreaChart>
+ </ResponsiveContainer>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ ))}
+ </div>
+ )
+ })()}
+ </div>
+ ) : (
+ <div className="px-1 pb-4" style={{ height: 280 }}>
+ {isLoading ? (
+ <div className="px-4">
+ <Skeleton className="h-full w-full" />
+ </div>
+ ) : chartData.length > 0 && meta ? (
+ <ResponsiveContainer width="100%" height="100%">
+ <BarChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
+ <XAxis
+ dataKey="date"
+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
+ axisLine={false}
+ tickLine={false}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ tickFormatter={(v) => {
+ if (privacyMode) return ''
+ if (v === 0) return '0'
+ return formatCompact(v, userCurrency, locale)
+ }}
+ tick={{ fontSize: 10, fill: 'var(--muted-foreground)' }}
+ axisLine={false}
+ tickLine={false}
+ width={64}
+ tickCount={5}
+ />
+ <Tooltip
+ content={({ active, payload, label }) => {
+ if (!active || !payload) return null
+ const items = payload.filter((p) => (p.value as number) > 0)
+ if (items.length === 0) return null
+ return (
+ <div style={tooltipStyle} className="px-3 py-2">
+ <p className="text-xs font-medium mb-1">{label}</p>
+ {items.map((p) => (
+ <p key={p.dataKey as string} className="text-xs" style={{ color: p.color }}>
+ {t(`reports.${p.dataKey}`, { defaultValue: p.name })}:{' '}
+ {privacyMode ? MASK : formatCurrency(p.value as number, userCurrency, locale)}
+ </p>
+ ))}
+ </div>
+ )
+ }}
+ />
+ <Legend
+ iconType="circle"
+ iconSize={8}
+ wrapperStyle={{ fontSize: '12px', paddingTop: '8px' }}
+ formatter={(value: string) => t(`reports.${value}`, { defaultValue: value })}
+ />
+ {meta.series_keys
+ .filter((key) => chartData.some((d) => (d[key] as number) > 0))
+ .map((key, idx, arr) => (
+ <Bar
+ key={key}
+ dataKey={key}
+ stackId="stack"
+ fill={colorMap[key] || '#6366F1'}
+ radius={idx === arr.length - 1 ? [4, 4, 0, 0] : [0, 0, 0, 0]}
+ maxBarSize={32}
+ />
+ ))}
+ </BarChart>
+ </ResponsiveContainer>
+ ) : (
+ <p className="text-muted-foreground text-sm text-center py-16">
+ {t('reports.noData')}
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index b5d7d9d1..3ebf7595 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -253,3 +253,56 @@ export interface PaginatedResponse<T> {
page: number
limit: number
}
+
+// Reports (universal schema for all report types)
+export interface ReportBreakdown {
+ key: string
+ label: string
+ value: number
+ color: string
+}
+
+export interface ReportSummary {
+ primary_value: number
+ change_amount: number
+ change_percent: number | null
+ breakdowns: ReportBreakdown[]
+}
+
+export interface ReportDataPoint {
+ date: string
+ value: number
+ breakdowns: Record<string, number>
+}
+
+export interface ReportMeta {
+ type: string
+ series_keys: string[]
+ currency: string
+ interval: string
+}
+
+export interface ReportCompositionItem {
+ key: string
+ label: string
+ value: number
+ color: string
+ group: string
+}
+
+export interface CategoryTrendItem {
+ key: string
+ label: string
+ color: string
+ total: number
+ group: string
+ series: ReportDataPoint[]
+}
+
+export interface ReportResponse {
+ summary: ReportSummary
+ trend: ReportDataPoint[]
+ meta: ReportMeta
+ composition: ReportCompositionItem[]
+ category_trend: CategoryTrendItem[]
+}