Skip to content

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

Adding cash flow report (#102) (#137)

Tássio Noronha6af055f1bcfd
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.py
index 312f0ba1..e860fd08 100644
--- a/backend/app/api/reports.py
+++ b/backend/app/api/reports.py
@@ -32,3 +32,15 @@ async def get_income_expenses(
return await report_service.get_income_expenses_report(
session, user.id, months, interval, user.primary_currency
)
+
+
[email protected]("/cash-flow", response_model=ReportResponse)
+async def get_cash_flow(
+ months: int = Query(6, ge=1, le=12),
+ interval: str = Query("daily", pattern="^(daily|weekly|monthly)$"),
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ return await report_service.get_cash_flow_report(
+ session, user.id, months, interval, user.primary_currency
+ )
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.py
index 2abe054d..abf38903 100644
--- a/backend/app/services/report_service.py
+++ b/backend/app/services/report_service.py
@@ -1,3 +1,4 @@
+import calendar
import uuid
from datetime import date, timedelta
from decimal import Decimal
@@ -705,3 +706,310 @@ async def get_income_expenses_report(
summary=summary, trend=trend, meta=meta,
composition=composition, category_trend=category_trend,
)
+
+
+def _add_months(d: date, months: int) -> date:
+ """Advance a date by N months, clamping the day to the target month's length."""
+ new_month = d.month + months
+ new_year = d.year + (new_month - 1) // 12
+ new_month = ((new_month - 1) % 12) + 1
+ last_day = calendar.monthrange(new_year, new_month)[1]
+ new_day = min(d.day, last_day)
+ return date(new_year, new_month, new_day)
+
+
+async def get_cash_flow_report(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ months: int = 6,
+ interval: str = "daily",
+ currency: str = "USD",
+) -> ReportResponse:
+ """Forward-looking cash flow projection.
+
+ Starts from today's total balance (across all open accounts, converted to
+ the user's primary currency) and walks forward, applying:
+ - already-booked transactions whose cash impact is in the future,
+ - virtual recurring-transaction occurrences (the bulk of the projection).
+
+ Respects the global ``credit_card_accounting_mode`` setting:
+ - **cash**: future flows queried by ``Transaction.date``. CC purchases
+ impact balance on purchase date.
+ - **accrual**: future flows queried by ``Transaction.effective_date`` so
+ a CC purchase shows up as cash leaving on its bill due date. The
+ starting balance is also adjusted to add back any pending CC
+ purchases (purchase date <= today, due date > today) so they're not
+ double-counted (the CC liability already reduced ``_balance_at``).
+
+ Aggregates the resulting day-by-day running balance into the requested
+ interval and returns a ReportResponse compatible with the existing report
+ chart on the frontend.
+ """
+ from app.services.dashboard_service import _balance_at, _get_recurring_projections
+ from app.services.fx_rate_service import get_rate
+
+ today = date.today()
+ end = _add_months(today, months)
+
+ user = await session.get(User, user_id)
+ primary_currency = user.primary_currency if user else get_settings().default_currency
+
+ accounting_mode = await get_credit_card_accounting_mode(session)
+ accrual = accounting_mode == "accrual"
+
+ starting_balance = await _balance_at(session, user_id, today)
+
+ # FX rate cache: currency -> rate to primary_currency (using today's rate;
+ # future rates are unknown so we project at today's rate).
+ rate_cache: dict[str, Decimal] = {primary_currency: Decimal("1")}
+
+ async def _to_primary(amount: Decimal, ccy: str) -> float:
+ if ccy == primary_currency:
+ return float(amount)
+ rate = rate_cache.get(ccy)
+ if rate is None:
+ rate = await get_rate(session, ccy, primary_currency)
+ rate_cache[ccy] = rate
+ return float((amount * rate).quantize(Decimal("0.01")))
+
+ # Per-day flow accumulator: date -> {"inflow": float, "outflow": float}
+ flows: dict[date, dict[str, float]] = {}
+
+ def _add_flow(d: date, amount: float, is_credit: bool) -> None:
+ bucket = flows.setdefault(d, {"inflow": 0.0, "outflow": 0.0})
+ if is_credit:
+ bucket["inflow"] += amount
+ else:
+ bucket["outflow"] += amount
+
+ # 1. Already-booked transactions whose CASH impact is in the future.
+ # - cash mode: filter on Transaction.date.
+ # - accrual mode: filter on Transaction.effective_date so CC purchases
+ # hit their bill due date instead of purchase date.
+ flow_date_col = Transaction.effective_date if accrual else Transaction.date
+ booked_result = await session.execute(
+ select(
+ flow_date_col,
+ Transaction.type,
+ Transaction.amount,
+ Transaction.amount_primary,
+ Transaction.currency,
+ )
+ .join(Account, Transaction.account_id == Account.id)
+ .where(
+ Transaction.user_id == user_id,
+ Account.is_closed == False,
+ flow_date_col > today,
+ flow_date_col <= end,
+ Transaction.source != "opening_balance",
+ counts_as_pnl(),
+ )
+ )
+ for row in booked_result.all():
+ flow_date, tx_type, amt, amt_primary, ccy = row
+ if amt_primary is not None:
+ amount_primary = float(amt_primary)
+ else:
+ amount_primary = await _to_primary(Decimal(str(amt or 0)), ccy)
+ if amount_primary == 0:
+ continue
+ _add_flow(flow_date, abs(amount_primary), tx_type == "credit")
+
+ # 2. Accrual mode only: undo the impact of pending CC purchases on the
+ # starting balance. _balance_at already deducted them via the CC
+ # account's debt (Transaction.date <= today), but in accrual mode we
+ # project them as outflows on their effective_date — so add them back
+ # here to avoid double-counting.
+ if accrual:
+ pending_cc = await session.execute(
+ select(
+ Transaction.type,
+ Transaction.amount,
+ Transaction.amount_primary,
+ Transaction.currency,
+ )
+ .join(Account, Transaction.account_id == Account.id)
+ .where(
+ Transaction.user_id == user_id,
+ Account.is_closed == False,
+ Account.type == "credit_card",
+ Transaction.date <= today,
+ Transaction.effective_date > today,
+ Transaction.effective_date <= end,
+ Transaction.source != "opening_balance",
+ counts_as_pnl(),
+ )
+ )
+ for tx_type, amt, amt_primary, ccy in pending_cc.all():
+ if amt_primary is not None:
+ amount_primary = float(amt_primary)
+ else:
+ amount_primary = await _to_primary(Decimal(str(amt or 0)), ccy)
+ if amount_primary == 0:
+ continue
+ # On a CC account: a debit (purchase) reduced total balance via
+ # extra debt; add it back. A credit (refund/payment) raised total;
+ # subtract it back.
+ if tx_type == "debit":
+ starting_balance += abs(amount_primary)
+ else:
+ starting_balance -= abs(amount_primary)
+
+ # 2. Recurring projections — single call for the whole forward window
+ # (range_end is exclusive in get_occurrences_in_range, so use end+1).
+ cat_totals: dict[tuple[str, str], dict] = {}
+ cat_cache: dict[str, dict] = {}
+
+ projections = await _get_recurring_projections(
+ session, user_id, today + timedelta(days=1), end + timedelta(days=1),
+ )
+ for proj in projections:
+ d = proj["date"]
+ if d <= today or d > end:
+ continue
+ amount_primary = await _to_primary(
+ Decimal(str(proj["amount"])), proj["currency"]
+ )
+ if amount_primary == 0:
+ continue
+ _add_flow(d, amount_primary, proj["type"] == "credit")
+
+ # Track category contributions for the composition donut
+ cat_id = proj["category_id"]
+ cat_id_str = str(cat_id) if cat_id else "uncategorized"
+ group = "income" if proj["type"] == "credit" else "expenses"
+ if cat_id and cat_id_str not in cat_cache:
+ cat_row = await session.execute(
+ select(Category.name, Category.color).where(Category.id == cat_id)
+ )
+ row = cat_row.one_or_none()
+ cat_cache[cat_id_str] = {
+ "label": row[0] if row else "Uncategorized",
+ "color": row[1] if row else "#6B7280",
+ }
+ info = cat_cache.get(cat_id_str, {"label": "Uncategorized", "color": "#6B7280"})
+ key = (cat_id_str, group)
+ if key not in cat_totals:
+ cat_totals[key] = {"label": info["label"], "color": info["color"], "value": 0.0}
+ cat_totals[key]["value"] += amount_primary
+
+ # Walk day-by-day from today to end, building per-day running balance.
+ daily_balance: dict[date, float] = {today: starting_balance}
+ daily_inflow: dict[date, float] = {today: 0.0}
+ daily_outflow: dict[date, float] = {today: 0.0}
+ running = starting_balance
+ cursor_d = today
+ while cursor_d < end:
+ cursor_d = cursor_d + timedelta(days=1)
+ bucket = flows.get(cursor_d, {"inflow": 0.0, "outflow": 0.0})
+ running += bucket["inflow"] - bucket["outflow"]
+ daily_balance[cursor_d] = running
+ daily_inflow[cursor_d] = bucket["inflow"]
+ daily_outflow[cursor_d] = bucket["outflow"]
+
+ # Aggregate to interval. For each interval label, take the running balance
+ # at the last day in the bucket; sum inflow/outflow over the bucket.
+ points = _date_points(today, end, interval)
+ trend: list[ReportDataPoint] = []
+
+ if interval == "daily":
+ for p in points:
+ bal = daily_balance.get(p, running)
+ inf = daily_inflow.get(p, 0.0)
+ outf = daily_outflow.get(p, 0.0)
+ trend.append(ReportDataPoint(
+ date=_format_date_label(p, "daily"),
+ value=round(bal, 2),
+ breakdowns={"inflow": round(inf, 2), "outflow": round(outf, 2)},
+ ))
+ else:
+ # Build per-bucket aggregates by walking all daily points in order
+ groups: dict[str, dict] = {}
+ cur = today
+ while cur <= end:
+ label = _format_date_label(cur, interval)
+ g = groups.setdefault(
+ label, {"balance": daily_balance[cur], "last_d": cur, "inflow": 0.0, "outflow": 0.0}
+ )
+ if cur >= g["last_d"]:
+ g["balance"] = daily_balance[cur]
+ g["last_d"] = cur
+ g["inflow"] += daily_inflow.get(cur, 0.0)
+ g["outflow"] += daily_outflow.get(cur, 0.0)
+ cur = cur + timedelta(days=1)
+
+ # Emit trend points in the order produced by _date_points
+ seen: set[str] = set()
+ for p in points:
+ label = _format_date_label(p, interval)
+ if label in seen:
+ continue
+ seen.add(label)
+ g = groups.get(label)
+ if g is None:
+ continue
+ trend.append(ReportDataPoint(
+ date=label,
+ value=round(g["balance"], 2),
+ breakdowns={
+ "inflow": round(g["inflow"], 2),
+ "outflow": round(g["outflow"], 2),
+ },
+ ))
+
+ # Summary
+ ending_balance = trend[-1].value if trend else round(starting_balance, 2)
+ total_inflow = round(sum(p.breakdowns.get("inflow", 0.0) for p in trend), 2)
+ total_outflow = round(sum(p.breakdowns.get("outflow", 0.0) for p in trend), 2)
+ change_amount = round(ending_balance - starting_balance, 2)
+ change_percent = (
+ (change_amount / abs(starting_balance) * 100) if starting_balance != 0 else None
+ )
+
+ summary = ReportSummary(
+ primary_value=ending_balance,
+ change_amount=change_amount,
+ change_percent=round(change_percent, 2) if change_percent is not None else None,
+ breakdowns=[
+ ReportBreakdown(
+ key="startingBalance", label="Starting Balance",
+ value=round(starting_balance, 2), color="#6366F1",
+ ),
+ ReportBreakdown(
+ key="projectedIncome", label="Projected Income",
+ value=total_inflow, color="#10B981",
+ ),
+ ReportBreakdown(
+ key="projectedExpenses", label="Projected Expenses",
+ value=total_outflow, color="#F43F5E",
+ ),
+ ReportBreakdown(
+ key="endingBalance", label="Ending Balance",
+ value=ending_balance, color="#8B5CF6",
+ ),
+ ],
+ )
+
+ meta = ReportMeta(
+ type="cash_flow",
+ series_keys=["balance"],
+ currency=primary_currency,
+ interval=interval,
+ )
+
+ composition: list[ReportCompositionItem] = []
+ for (cat_key, group), info in cat_totals.items():
+ if info["value"] <= 0:
+ continue
+ composition.append(ReportCompositionItem(
+ key=cat_key,
+ label=info["label"],
+ value=round(info["value"], 2),
+ color=info["color"],
+ group=group,
+ ))
+
+ return ReportResponse(
+ summary=summary, trend=trend, meta=meta,
+ composition=composition, category_trend=[],
+ )
diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.py
index 9a7fa524..82e8f5a5 100644
--- a/backend/tests/test_report_service.py
+++ b/backend/tests/test_report_service.py
@@ -13,12 +13,15 @@ from app.models.transaction import Transaction
from app.models.user import User
from app.schemas.report import CategoryTrendItem, ReportDataPoint, ReportResponse
from app.services.report_service import (
+ _add_months,
_asset_value_at,
_date_points,
_format_date_label,
_net_worth_at,
+ get_cash_flow_report,
get_net_worth_report,
)
+from app.models.recurring_transaction import RecurringTransaction
# ---------------------------------------------------------------------------
@@ -783,3 +786,1282 @@ async def test_net_worth_change_percent_zero_previous(session: AsyncSession, tes
report = await get_net_worth_report(session, test_user.id, months=1, interval="monthly")
if report.summary.primary_value == 0:
assert report.summary.change_percent is None
+
+
+# ---------------------------------------------------------------------------
+# Pure-function tests: _add_months
+# ---------------------------------------------------------------------------
+
+
+def test_add_months_simple():
+ assert _add_months(date(2025, 1, 15), 1) == date(2025, 2, 15)
+
+
+def test_add_months_year_rollover():
+ assert _add_months(date(2025, 11, 10), 3) == date(2026, 2, 10)
+
+
+def test_add_months_clamps_to_last_day():
+ # Jan 31 + 1 month → Feb 28 (or 29 in leap year)
+ assert _add_months(date(2025, 1, 31), 1) == date(2025, 2, 28)
+ assert _add_months(date(2024, 1, 31), 1) == date(2024, 2, 29)
+
+
+def test_add_months_zero_returns_same():
+ assert _add_months(date(2025, 6, 15), 0) == date(2025, 6, 15)
+
+
+def test_add_months_twelve_keeps_same_day():
+ assert _add_months(date(2025, 6, 15), 12) == date(2026, 6, 15)
+
+
+# ---------------------------------------------------------------------------
+# Cash flow report — service-level tests
+# ---------------------------------------------------------------------------
+
+
+async def _make_recurring(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ account_id: uuid.UUID,
+ amount: float,
+ txn_type: str,
+ frequency: str = "monthly",
+ *,
+ description: str | None = None,
+ day_of_month: int | None = None,
+ start_date: date | None = None,
+ end_date: date | None = None,
+ next_occurrence: date | None = None,
+ is_active: bool = True,
+ currency: str = "BRL",
+ category_id: uuid.UUID | None = None,
+) -> RecurringTransaction:
+ today = date.today()
+ start = start_date or today
+ nxt = next_occurrence or (today + timedelta(days=1))
+ rec = RecurringTransaction(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ account_id=account_id,
+ category_id=category_id,
+ description=description or f"Test {txn_type} {amount}",
+ amount=Decimal(str(amount)),
+ currency=currency,
+ type=txn_type,
+ frequency=frequency,
+ day_of_month=day_of_month,
+ start_date=start,
+ end_date=end_date,
+ is_active=is_active,
+ next_occurrence=nxt,
+ )
+ session.add(rec)
+ await session.commit()
+ await session.refresh(rec)
+ return rec
+
+
+async def test_cash_flow_report_structure(session: AsyncSession, test_user: User):
+ """Cash flow report returns a well-formed ReportResponse."""
+ account = await _make_manual_account(session, test_user.id, "CF Structure")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")
+
+ assert report.meta.type == "cash_flow"
+ assert report.meta.series_keys == ["balance"]
+ assert report.meta.currency == "BRL"
+ assert report.meta.interval == "daily"
+ assert len(report.trend) > 0
+ # Summary breakdowns are exactly the four cash-flow keys, in order.
+ keys = [b.key for b in report.summary.breakdowns]
+ assert keys == ["startingBalance", "projectedIncome", "projectedExpenses", "endingBalance"]
+
+
+async def test_cash_flow_starting_balance_matches_today(
+ session: AsyncSession, test_user: User
+):
+ """startingBalance breakdown == sum of account balances at today."""
+ account = await _make_manual_account(session, test_user.id, "CF Start")
+ await _add_txn(
+ session, test_user.id, account.id, 1234.56, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+ starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")
+ assert starting.value == 1234.56
+
+
+async def test_cash_flow_no_data_is_flat_at_zero(
+ session: AsyncSession, test_user: User
+):
+ """User with no accounts → flat line at 0."""
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+ assert report.summary.primary_value == 0.0
+ assert report.summary.change_amount == 0.0
+ assert report.summary.change_percent is None # zero starting → percent undefined
+ # Every trend point should be 0
+ assert all(p.value == 0.0 for p in report.trend)
+ assert report.composition == []
+
+
+async def test_cash_flow_no_data_with_balance_is_flat(
+ session: AsyncSession, test_user: User
+):
+ """Account with balance but no recurring → flat line at starting balance."""
+ account = await _make_manual_account(session, test_user.id, "CF Flat")
+ await _add_txn(
+ session, test_user.id, account.id, 2500, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+
+ assert report.summary.primary_value == 2500.0
+ assert report.summary.change_amount == 0.0
+ # All trend points equal to starting balance
+ assert all(p.value == 2500.0 for p in report.trend)
+
+
+async def test_cash_flow_recurring_credit_increases_balance(
+ session: AsyncSession, test_user: User
+):
+ """Monthly salary credit should drive ending balance above starting."""
+ account = await _make_manual_account(session, test_user.id, "CF Salary")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ salary_day = date(today.year + (today.month // 12), (today.month % 12) + 1, today.day)
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=3000, txn_type="credit", frequency="monthly",
+ day_of_month=today.day, next_occurrence=salary_day,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+
+ # 3 monthly occurrences over a 3-month window
+ assert proj_income.value >= 3000.0 # at least one occurrence
+ assert proj_exp.value == 0.0
+ assert ending.value > 1000.0
+ assert report.summary.change_amount > 0
+
+
+async def test_cash_flow_recurring_debit_decreases_balance(
+ session: AsyncSession, test_user: User
+):
+ """Monthly rent debit should drive ending balance below starting."""
+ account = await _make_manual_account(session, test_user.id, "CF Rent")
+ await _add_txn(
+ session, test_user.id, account.id, 10000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ nxt = today + timedelta(days=2)
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=1200, txn_type="debit", frequency="monthly",
+ day_of_month=nxt.day, next_occurrence=nxt,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+
+ assert proj_exp.value > 0
+ assert ending.value < 10000.0
+ assert report.summary.change_amount < 0
+
+
+async def test_cash_flow_inactive_recurring_excluded(
+ session: AsyncSession, test_user: User
+):
+ """is_active=False recurring should not contribute to projection."""
+ account = await _make_manual_account(session, test_user.id, "CF Inactive")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=999, txn_type="debit", frequency="monthly",
+ next_occurrence=today + timedelta(days=2), is_active=False,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ assert proj_exp.value == 0.0
+
+
+async def test_cash_flow_recurring_end_date_stops_contribution(
+ session: AsyncSession, test_user: User
+):
+ """Recurring with end_date in window should stop contributing past that date."""
+ account = await _make_manual_account(session, test_user.id, "CF EndDate")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ # Recurring monthly +500 USD, ends in ~45 days (only 1-2 occurrences in 6mo window)
+ end = today + timedelta(days=45)
+ nxt = today + timedelta(days=2)
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=500, txn_type="credit", frequency="monthly",
+ day_of_month=nxt.day, next_occurrence=nxt, end_date=end,
+ )
+
+ short_report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ long_report = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")
+
+ short_inc = next(b for b in short_report.summary.breakdowns if b.key == "projectedIncome")
+ long_inc = next(b for b in long_report.summary.breakdowns if b.key == "projectedIncome")
+ # Total projected income should not grow much when extending past end_date
+ assert long_inc.value == short_inc.value
+
+
+async def test_cash_flow_future_dated_booked_transaction_included(
+ session: AsyncSession, test_user: User
+):
+ """A Transaction with date > today is folded into the projection."""
+ account = await _make_manual_account(session, test_user.id, "CF Future Tx")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ # Post-dated bonus 10 days from now
+ await _add_txn(
+ session, test_user.id, account.id, 750, "credit",
+ date.today() + timedelta(days=10),
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+
+ assert proj_income.value >= 750.0
+ assert ending.value >= 1750.0
+
+
+async def test_cash_flow_opening_balance_excluded_from_inflow(
+ session: AsyncSession, test_user: User
+):
+ """opening_balance txns sit in starting balance and never count as inflow."""
+ account = await _make_manual_account(session, test_user.id, "CF OB")
+ # Future-dated opening-balance shouldn't show up as inflow
+ await _add_txn(
+ session, test_user.id, account.id, 9999, "credit",
+ date.today() + timedelta(days=5), source="opening_balance",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ assert proj_income.value == 0.0
+
+
+async def test_cash_flow_closed_account_excluded(
+ session: AsyncSession, test_user: User
+):
+ """Future-dated transactions on closed accounts are excluded."""
+ open_acct = await _make_manual_account(session, test_user.id, "CF Open")
+ await _add_txn(
+ session, test_user.id, open_acct.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ closed = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="CF Closed",
+ type="checking", balance=Decimal("0"), currency="BRL", is_closed=True,
+ )
+ session.add(closed)
+ await session.commit()
+
+ await _add_txn(
+ session, test_user.id, closed.id, 5000, "credit",
+ date.today() + timedelta(days=3),
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ assert proj_income.value == 0.0
+
+
+async def test_cash_flow_intervals(session: AsyncSession, test_user: User):
+ """All supported intervals produce valid trends."""
+ account = await _make_manual_account(session, test_user.id, "CF Intervals")
+ await _add_txn(
+ session, test_user.id, account.id, 2000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=300, txn_type="debit", frequency="weekly",
+ next_occurrence=today + timedelta(days=2),
+ )
+
+ intervals_seen = {}
+ for interval in ["daily", "weekly", "monthly"]:
+ rep = await get_cash_flow_report(session, test_user.id, months=2, interval=interval)
+ assert rep.meta.interval == interval
+ assert len(rep.trend) > 0
+ intervals_seen[interval] = rep.summary.breakdowns
+
+ # The total projected expenses should be ~equal across intervals
+ daily_exp = next(b.value for b in intervals_seen["daily"] if b.key == "projectedExpenses")
+ weekly_exp = next(b.value for b in intervals_seen["weekly"] if b.key == "projectedExpenses")
+ monthly_exp = next(b.value for b in intervals_seen["monthly"] if b.key == "projectedExpenses")
+ # Allow tiny rounding variance
+ assert abs(daily_exp - weekly_exp) < 1.0
+ assert abs(daily_exp - monthly_exp) < 1.0
+
+
+async def test_cash_flow_months_range(session: AsyncSession, test_user: User):
+ """Different `months` values produce trends ending at different dates."""
+ account = await _make_manual_account(session, test_user.id, "CF Months")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ rep_1 = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")
+ rep_6 = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")
+ rep_12 = await get_cash_flow_report(session, test_user.id, months=12, interval="daily")
+
+ # Daily intervals → 1mo ≈ 30 points, 6mo ≈ 184, 12mo ≈ 366
+ assert len(rep_1.trend) < len(rep_6.trend) < len(rep_12.trend)
+
+
+async def test_cash_flow_balance_is_running_cumulative(
+ session: AsyncSession, test_user: User
+):
+ """Each subsequent trend point's value reflects accumulated flows."""
+ account = await _make_manual_account(session, test_user.id, "CF Cumul")
+ await _add_txn(
+ session, test_user.id, account.id, 0, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ # +100 weekly so balance keeps rising
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=100, txn_type="credit", frequency="weekly",
+ next_occurrence=today + timedelta(days=2),
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ # The trend should be monotonically non-decreasing (no debits, only credits)
+ values = [p.value for p in report.trend]
+ for prev, curr in zip(values, values[1:]):
+ assert curr >= prev - 0.01 # tiny tolerance for floats
+
+
+async def test_cash_flow_composition_groups(session: AsyncSession, test_user: User):
+ """Composition splits recurring projections into income/expenses groups."""
+ account = await _make_manual_account(session, test_user.id, "CF Comp")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=500, txn_type="credit", frequency="monthly",
+ next_occurrence=today + timedelta(days=2),
+ description="Income recurring",
+ )
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=200, txn_type="debit", frequency="monthly",
+ next_occurrence=today + timedelta(days=3),
+ description="Expense recurring",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+
+ groups = {c.group for c in report.composition}
+ assert "income" in groups
+ assert "expenses" in groups
+ # Each group has positive values
+ for c in report.composition:
+ assert c.value > 0
+
+
+async def test_cash_flow_change_percent_zero_starting(
+ session: AsyncSession, test_user: User
+):
+ """When starting balance is 0, change_percent is None."""
+ account = await _make_manual_account(session, test_user.id, "CF Zero")
+ today = date.today()
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=100, txn_type="credit", frequency="monthly",
+ next_occurrence=today + timedelta(days=2),
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+ assert report.summary.change_percent is None
+
+
+async def test_cash_flow_weekly_recurring(session: AsyncSession, test_user: User):
+ """Weekly frequency expands into multiple occurrences in window."""
+ account = await _make_manual_account(session, test_user.id, "CF Weekly")
+ await _add_txn(
+ session, test_user.id, account.id, 0, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=80, txn_type="debit", frequency="weekly",
+ next_occurrence=today + timedelta(days=1),
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ # ~4-5 weekly occurrences in 1 month
+ assert 240.0 <= proj_exp.value <= 480.0
+
+
+async def test_cash_flow_only_recurrings_after_today(
+ session: AsyncSession, test_user: User
+):
+ """Recurring with next_occurrence == today is NOT counted (today is starting)."""
+ account = await _make_manual_account(session, test_user.id, "CF Today")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ # next_occurrence is today — same day as starting balance, should be excluded
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=999, txn_type="credit", frequency="monthly",
+ next_occurrence=today,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ # Over 2 months: 3 raw monthly occurrences (today, +1mo, +2mo) but the
+ # one ON today is excluded — so we expect exactly 2 × 999 = 1998.
+ assert proj_income.value == 1998.0
+
+
+# ---------------------------------------------------------------------------
+# Cash flow API-level tests
+# ---------------------------------------------------------------------------
+
+
+async def test_cash_flow_api_endpoint(client, auth_headers, test_transactions):
+ """GET /reports/cash-flow returns valid response."""
+ response = await client.get(
+ "/api/reports/cash-flow",
+ params={"months": 6, "interval": "daily"},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200, response.text
+ data = response.json()
+
+ assert data["meta"]["type"] == "cash_flow"
+ assert data["meta"]["series_keys"] == ["balance"]
+ assert "summary" in data
+ assert "trend" in data
+ breakdown_keys = [b["key"] for b in data["summary"]["breakdowns"]]
+ assert breakdown_keys == [
+ "startingBalance", "projectedIncome",
+ "projectedExpenses", "endingBalance",
+ ]
+
+
+async def test_cash_flow_api_validation(client, auth_headers):
+ """GET /reports/cash-flow rejects out-of-range params."""
+ # months > 12
+ resp = await client.get(
+ "/api/reports/cash-flow",
+ params={"months": 13},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+ # months < 1
+ resp = await client.get(
+ "/api/reports/cash-flow",
+ params={"months": 0},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+ # yearly is not a supported interval for cash flow
+ resp = await client.get(
+ "/api/reports/cash-flow",
+ params={"interval": "yearly"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+ # arbitrary string interval
+ resp = await client.get(
+ "/api/reports/cash-flow",
+ params={"interval": "garbage"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 422
+
+
+async def test_cash_flow_api_requires_auth(client):
+ """GET /reports/cash-flow requires authentication."""
+ resp = await client.get("/api/reports/cash-flow")
+ assert resp.status_code == 401
+
+
+async def test_cash_flow_api_default_params(client, auth_headers, test_transactions):
+ """GET /reports/cash-flow with no params uses defaults (months=6, interval=daily)."""
+ resp = await client.get("/api/reports/cash-flow", headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["meta"]["interval"] == "daily"
+ # 6 months * ~30 days = ~180 trend points
+ assert 150 <= len(data["trend"]) <= 200
+
+
+async def test_cash_flow_api_trend_point_shape(client, auth_headers, test_transactions):
+ """Every trend point exposes inflow/outflow breakdowns."""
+ resp = await client.get(
+ "/api/reports/cash-flow",
+ params={"months": 3, "interval": "daily"},
+ headers=auth_headers,
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ for p in data["trend"]:
+ assert "inflow" in p["breakdowns"]
+ assert "outflow" in p["breakdowns"]
+ assert "value" in p
+ assert "date" in p
+
+
+# ---------------------------------------------------------------------------
+# Cash flow — credit card accounting mode (cash vs accrual)
+# ---------------------------------------------------------------------------
+
+
+async def _make_cc_account(
+ session: AsyncSession, user_id: uuid.UUID, name: str, currency: str = "BRL",
+) -> Account:
+ acct = Account(
+ id=uuid.uuid4(), user_id=user_id, name=name,
+ type="credit_card", balance=Decimal("0"), currency=currency,
+ )
+ session.add(acct)
+ await session.commit()
+ await session.refresh(acct)
+ return acct
+
+
+async def _set_accounting_mode(session: AsyncSession, mode: str) -> None:
+ """Set the global credit_card_accounting_mode app setting."""
+ from app.models.app_settings import AppSetting
+ existing = await session.get(AppSetting, "credit_card_accounting_mode")
+ if existing:
+ existing.value = mode
+ else:
+ session.add(AppSetting(key="credit_card_accounting_mode", value=mode))
+ await session.commit()
+
+
+async def test_cash_flow_cash_mode_uses_transaction_date(
+ session: AsyncSession, test_user: User
+):
+ """In cash mode: a CC purchase made today (effective_date in future) is
+ already counted in starting balance via the CC liability — and is NOT
+ re-projected on its effective_date."""
+ await _set_accounting_mode(session, "cash")
+
+ bank = await _make_manual_account(session, test_user.id, "CF CashMode Bank")
+ cc = await _make_cc_account(session, test_user.id, "CF CashMode CC")
+ # $1000 in bank
+ await _add_txn(
+ session, test_user.id, bank.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ # CC purchase today, bill due in 20 days
+ today = date.today()
+ cc_purchase = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=cc.id,
+ description="CC Purchase", amount=Decimal("100"),
+ date=today, effective_date=today + timedelta(days=20),
+ type="debit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(cc_purchase)
+ await session.commit()
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+
+ starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+
+ # Cash mode: total balance = bank ($1000) - CC debt ($100) = $900
+ assert starting.value == 900.0
+ # No future flows queued — Transaction.date == today (not > today)
+ assert proj_exp.value == 0.0
+ assert ending.value == 900.0
+
+
+async def test_cash_flow_accrual_mode_projects_cc_on_effective_date(
+ session: AsyncSession, test_user: User
+):
+ """In accrual mode: a CC purchase with effective_date > today is added
+ back to starting balance (so it represents 'cash on hand right now') and
+ re-projected as an outflow on the bill due date."""
+ await _set_accounting_mode(session, "accrual")
+
+ bank = await _make_manual_account(session, test_user.id, "CF AccrualMode Bank")
+ cc = await _make_cc_account(session, test_user.id, "CF AccrualMode CC")
+ await _add_txn(
+ session, test_user.id, bank.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ cc_purchase = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=cc.id,
+ description="CC Purchase", amount=Decimal("100"),
+ date=today, effective_date=today + timedelta(days=20),
+ type="debit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(cc_purchase)
+ await session.commit()
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+
+ starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+
+ # Accrual: pending CC ($100 debt) is added back → $900 + $100 = $1000.
+ assert starting.value == 1000.0
+ # Future outflow on day +20: $100.
+ assert proj_exp.value == 100.0
+ # Ending: $1000 - $100 = $900 (same wealth as cash mode, just timed differently).
+ assert ending.value == 900.0
+
+ # The dip happens on the bill due date.
+ bill_label = (today + timedelta(days=20)).isoformat()
+ bill_point = next(p for p in report.trend if p.date == bill_label)
+ assert bill_point.breakdowns["outflow"] == 100.0
+ assert bill_point.value == 900.0
+ # The day before the bill, balance is still 1000.
+ pre_bill_label = (today + timedelta(days=19)).isoformat()
+ pre_bill_point = next(p for p in report.trend if p.date == pre_bill_label)
+ assert pre_bill_point.value == 1000.0
+
+
+async def test_cash_flow_accrual_mode_no_double_count(
+ session: AsyncSession, test_user: User
+):
+ """Accrual mode: the same CC purchase must not appear in both starting
+ balance AND future flows — sum of (starting + inflow - outflow) over the
+ window must equal final 'true' total balance (= what cash mode shows)."""
+ await _set_accounting_mode(session, "accrual")
+
+ bank = await _make_manual_account(session, test_user.id, "CF NoDouble Bank")
+ cc = await _make_cc_account(session, test_user.id, "CF NoDouble CC")
+ await _add_txn(
+ session, test_user.id, bank.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Two pending CC purchases with effective dates inside the window
+ for offset, amt in [(15, 80), (40, 120)]:
+ session.add(Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=cc.id,
+ description=f"Purchase {amt}", amount=Decimal(str(amt)),
+ date=today, effective_date=today + timedelta(days=offset),
+ type="debit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ ))
+ await session.commit()
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+
+ starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+
+ # starting = 5000 (bank) - 200 (CC debt) + 200 (added back pending) = 5000
+ assert starting.value == 5000.0
+ # both purchases project as outflows
+ assert proj_exp.value == 200.0
+ # ending matches cash mode's "what you'd have if you paid all CC bills"
+ assert ending.value == 4800.0
+
+
+async def test_cash_flow_accrual_mode_cc_purchase_outside_window_ignored(
+ session: AsyncSession, test_user: User
+):
+ """A CC purchase whose effective_date falls past the projection window is
+ not added back nor projected — its impact remains in starting balance."""
+ await _set_accounting_mode(session, "accrual")
+
+ bank = await _make_manual_account(session, test_user.id, "CF Outside Bank")
+ cc = await _make_cc_account(session, test_user.id, "CF Outside CC")
+ await _add_txn(
+ session, test_user.id, bank.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Bill due 6 months out; we project only 2 months
+ session.add(Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=cc.id,
+ description="CC Purchase Far", amount=Decimal("75"),
+ date=today, effective_date=today + timedelta(days=180),
+ type="debit", source="manual", currency="BRL",
+ created_at=datetime.now(timezone.utc),
+ ))
+ await session.commit()
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+
+ starting = next(b for b in report.summary.breakdowns if b.key == "startingBalance")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+
+ # CC debt is reflected in starting balance ($1000 - $75 = $925), no add-back
+ # because the bill is outside the projection window.
+ assert starting.value == 925.0
+ assert proj_exp.value == 0.0
+
+
+# ---------------------------------------------------------------------------
+# Cash flow — multi-currency
+# ---------------------------------------------------------------------------
+
+
+async def _seed_fx_rate(
+ session: AsyncSession, base: str, quote: str, rate: float, day: date | None = None,
+) -> None:
+ from app.models.fx_rate import FxRate
+ session.add(FxRate(
+ base_currency=base, quote_currency=quote,
+ rate=Decimal(str(rate)), date=day or date.today(),
+ source="test",
+ ))
+ await session.commit()
+
+
+def _next_first_of_month(d: date) -> date:
+ """Return the 1st day of the next month after `d` — useful to anchor
+ a monthly recurring at a predictable day_of_month=1 cadence."""
+ if d.month == 12:
+ return date(d.year + 1, 1, 1)
+ return date(d.year, d.month + 1, 1)
+
+
+async def test_cash_flow_recurring_in_foreign_currency(
+ session: AsyncSession, test_user: User
+):
+ """A recurring in USD with primary BRL is converted via the FX rate."""
+ # Primary currency for test_user is BRL. Seed USD->BRL = 5.0.
+ # rate(USD->BRL) via cross = usd_to_BRL / usd_to_USD = 5.0 / 1 = 5.0.
+ await _seed_fx_rate(session, "USD", "BRL", 5.0)
+
+ account = await _make_manual_account(session, test_user.id, "CF MultiCcy")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ nxt = _next_first_of_month(today)
+ # Recurring in USD: $200 on the 1st of each month → 1000 BRL @ rate 5.0
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=200, txn_type="credit", frequency="monthly",
+ day_of_month=1, next_occurrence=nxt, currency="USD",
+ )
+
+ # 3-month window from today. Window covers exactly 3 "1st of month" anchors.
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ # 3 occurrences × 200 USD × 5.0 = 3000 BRL
+ assert proj_income.value == 3000.0
+
+
+async def test_cash_flow_mixed_currencies(session: AsyncSession, test_user: User):
+ """Recurrings in multiple currencies converted correctly using cached rates."""
+ # Primary is BRL. Seed cross rates via USD anchor.
+ # USD->BRL = 5.0, USD->EUR = 0.5 ⇒ EUR->BRL = 5.0 / 0.5 = 10.0
+ await _seed_fx_rate(session, "USD", "BRL", 5.0)
+ await _seed_fx_rate(session, "USD", "EUR", 0.5)
+
+ account = await _make_manual_account(session, test_user.id, "CF Mixed")
+ await _add_txn(
+ session, test_user.id, account.id, 0, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ nxt = _next_first_of_month(today)
+ # 100 EUR on the 1st → 1000 BRL/month
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=100, txn_type="credit", frequency="monthly",
+ day_of_month=1, next_occurrence=nxt, currency="EUR",
+ description="EUR income",
+ )
+ # 100 BRL on the 1st (same anchor, no conversion)
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=100, txn_type="debit", frequency="monthly",
+ day_of_month=1, next_occurrence=nxt, currency="BRL",
+ description="BRL expense",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+
+ # Window covers exactly 2 "1st of month" anchors.
+ # 2 EUR occurrences × 100 × 10.0 = 2000 BRL
+ assert proj_income.value == 2000.0
+ # 2 BRL occurrences × 100 = 200 BRL (no conversion)
+ assert proj_exp.value == 200.0
+
+
+async def test_cash_flow_currency_conversion_uses_amount_primary_when_present(
+ session: AsyncSession, test_user: User
+):
+ """A future-dated transaction with amount_primary set uses that value,
+ skipping FX conversion."""
+ account = await _make_manual_account(session, test_user.id, "CF AmtPrimary")
+ await _add_txn(
+ session, test_user.id, account.id, 0, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Tx in USD with amount_primary already stamped at a frozen rate
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=account.id,
+ description="Frozen-rate tx",
+ amount=Decimal("100"), currency="USD",
+ amount_primary=Decimal("777.77"), # arbitrary stamped value
+ date=today + timedelta(days=5), effective_date=today + timedelta(days=5),
+ type="credit", source="manual",
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(txn)
+ await session.commit()
+
+ report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ assert proj_income.value == 777.77
+
+
+# ---------------------------------------------------------------------------
+# Cash flow — end_date stricter assertions
+# ---------------------------------------------------------------------------
+
+
+async def test_cash_flow_end_date_exact_occurrence_count(
+ session: AsyncSession, test_user: User
+):
+ """When end_date falls mid-window, exactly the expected number of
+ occurrences is projected — not more, not fewer."""
+ account = await _make_manual_account(session, test_user.id, "CF EndDateExact")
+ await _add_txn(
+ session, test_user.id, account.id, 0, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ # Recurring weekly +$50 starting in 1 day, ending 21 days from now (so
+ # exactly 3 occurrences fit: day+1, day+8, day+15; day+22 is past end).
+ nxt = today + timedelta(days=1)
+ end_d = today + timedelta(days=21)
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=50, txn_type="credit", frequency="weekly",
+ next_occurrence=nxt, end_date=end_d,
+ )
+
+ # Window of 6 months — well past end_date
+ report = await get_cash_flow_report(session, test_user.id, months=6, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ # Exactly 3 × 50 = 150
+ assert proj_income.value == 150.0
+
+
+async def test_cash_flow_end_date_balance_freezes_after(
+ session: AsyncSession, test_user: User
+):
+ """After the recurring's end_date, the running balance stops changing."""
+ account = await _make_manual_account(session, test_user.id, "CF EndDateFreeze")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ today = date.today()
+ nxt = today + timedelta(days=1)
+ end_d = today + timedelta(days=21)
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=50, txn_type="credit", frequency="weekly",
+ next_occurrence=nxt, end_date=end_d,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=4, interval="daily")
+
+ # Balance after end_date should match ending balance — it shouldn't keep
+ # growing once the recurring stops contributing.
+ after_end_label = (end_d + timedelta(days=10)).isoformat()
+ after_end_point = next(p for p in report.trend if p.date == after_end_label)
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+ assert after_end_point.value == ending.value
+ # And the value equals starting (1000) + 3 × 50 = 1150
+ assert ending.value == 1150.0
+
+
+async def test_cash_flow_end_date_at_exact_occurrence(
+ session: AsyncSession, test_user: User
+):
+ """end_date == an occurrence date — that occurrence should still count."""
+ account = await _make_manual_account(session, test_user.id, "CF EndDateExactDay")
+ await _add_txn(
+ session, test_user.id, account.id, 0, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Weekly: occurrences at day+7, day+14, day+21. end_date = day+14 includes 2.
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=10, txn_type="credit", frequency="weekly",
+ next_occurrence=today + timedelta(days=7),
+ end_date=today + timedelta(days=14),
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ # 2 occurrences × $10 = $20
+ assert proj_income.value == 20.0
+
+
+async def test_cash_flow_end_date_in_past_no_contribution(
+ session: AsyncSession, test_user: User
+):
+ """If end_date is in the past, no occurrences project."""
+ account = await _make_manual_account(session, test_user.id, "CF EndDatePast")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=999, txn_type="credit", frequency="monthly",
+ next_occurrence=today + timedelta(days=2),
+ end_date=today - timedelta(days=10),
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+ proj_income = next(b for b in report.summary.breakdowns if b.key == "projectedIncome")
+ assert proj_income.value == 0.0
+
+
+
+async def test_cash_flow_overdraft_crunch_point_goes_negative(
+ session: AsyncSession, test_user: User
+):
+ """Cash crunch / overdraft: when projected outflows exceed inflows + start,
+ the running balance must go negative (not be clamped at 0)."""
+ account = await _make_manual_account(session, test_user.id, "CF Crunch")
+ await _add_txn(
+ session, test_user.id, account.id, 100, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ nxt = _next_first_of_month(today)
+ # $200 monthly debit on the 1st — burns through the $100 starting balance
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=200, txn_type="debit", frequency="monthly",
+ day_of_month=1, next_occurrence=nxt,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=3, interval="daily")
+
+ negative_points = [p for p in report.trend if p.value < 0]
+ assert len(negative_points) > 0, "Trend never dips below zero — clamped?"
+ ending = next(b for b in report.summary.breakdowns if b.key == "endingBalance")
+ # 100 starting - 3*200 outflows = -500
+ assert ending.value == -500.0
+
+
+async def test_cash_flow_paycheck_timing_dip(
+ session: AsyncSession, test_user: User
+):
+ """Classic paycheck-timing dip: rent on day 5, salary on day 15. End of
+ month is positive, but mid-month should drop below the starting balance
+ (and possibly below 0). The trend must show that intra-month dip — not
+ just the net monthly figure."""
+ account = await _make_manual_account(session, test_user.id, "CF PayTiming")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+
+ # Anchor rent and salary in NEXT month so they fall in the projection
+ # window without ambiguity. day_of_month=5 for rent, =15 for salary.
+ next_month_first = _next_first_of_month(today)
+ rent_day = next_month_first.replace(day=5)
+ salary_day = next_month_first.replace(day=15)
+
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=1500, txn_type="debit", frequency="monthly",
+ day_of_month=5, next_occurrence=rent_day,
+ description="Rent",
+ )
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=3000, txn_type="credit", frequency="monthly",
+ day_of_month=15, next_occurrence=salary_day,
+ description="Salary",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+
+ # Fetch balance on rent day (after rent hit) and salary day (after salary hit)
+ rent_pt = next(p for p in report.trend if p.date == rent_day.isoformat())
+ salary_pt = next(p for p in report.trend if p.date == salary_day.isoformat())
+ end_pt = report.trend[-1]
+
+ # Day 5: 1000 - 1500 = -500 (overdraft mid-month!)
+ assert rent_pt.value == -500.0
+ # Day 15: -500 + 3000 = 2500
+ assert salary_pt.value == 2500.0
+ # End of window: net positive despite the mid-month dip
+ assert end_pt.value > 0
+
+
+async def test_cash_flow_large_one_off_purchase(
+ session: AsyncSession, test_user: User
+):
+ """User wants to plan a single large purchase (e.g., new laptop on day +20).
+ The chart must show a single dip on that exact day and recover for the
+ rest of the window (no recurring pattern)."""
+ account = await _make_manual_account(session, test_user.id, "CF Laptop")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ purchase_day = today + timedelta(days=20)
+ await _add_txn(
+ session, test_user.id, account.id, 1800, "debit", purchase_day,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+
+ # Day before purchase: full starting balance
+ pre_pt = next(p for p in report.trend if p.date == (purchase_day - timedelta(days=1)).isoformat())
+ purchase_pt = next(p for p in report.trend if p.date == purchase_day.isoformat())
+ end_pt = report.trend[-1]
+
+ assert pre_pt.value == 5000.0
+ assert purchase_pt.value == 3200.0
+ assert purchase_pt.breakdowns["outflow"] == 1800.0
+ # No recurrings → balance stays at 3200 for rest of window
+ assert end_pt.value == 3200.0
+
+
+async def test_cash_flow_multiple_recurrings_same_day(
+ session: AsyncSession, test_user: User
+):
+ """Multiple bills that hit the same day must be summed into one outflow
+ bucket on that day, not represented as separate days."""
+ account = await _make_manual_account(session, test_user.id, "CF SameDay")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ nxt = _next_first_of_month(today)
+
+ # Three different bills, all day 1
+ for amt, desc in [(800, "Rent"), (120, "Internet"), (60, "Streaming")]:
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=amt, txn_type="debit", frequency="monthly",
+ day_of_month=1, next_occurrence=nxt, description=desc,
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")
+ bill_day = next(p for p in report.trend if p.date == nxt.isoformat())
+
+ # All three bills stacked on the same day = 800 + 120 + 60 = 980
+ assert bill_day.breakdowns["outflow"] == 980.0
+ # No other day in the window has any outflow
+ other_outflow_days = [
+ p for p in report.trend
+ if p.date != nxt.isoformat() and p.breakdowns["outflow"] > 0
+ ]
+ assert other_outflow_days == []
+
+
+async def test_cash_flow_yearly_recurring(session: AsyncSession, test_user: User):
+ """Yearly recurring (e.g., annual car insurance): expansion in a 12-month
+ window should yield exactly one occurrence."""
+ account = await _make_manual_account(session, test_user.id, "CF Yearly")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Schedule it 30 days out so it falls inside both 1mo+ and 12mo windows
+ nxt = today + timedelta(days=30)
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=1200, txn_type="debit", frequency="yearly",
+ day_of_month=nxt.day, next_occurrence=nxt,
+ )
+
+ rep_12 = await get_cash_flow_report(session, test_user.id, months=12, interval="daily")
+ proj_exp_12 = next(b for b in rep_12.summary.breakdowns if b.key == "projectedExpenses")
+ assert proj_exp_12.value == 1200.0 # exactly one occurrence in 12 months
+
+ # In a 1-month window: also 1 (since nxt is +30 days)
+ rep_1 = await get_cash_flow_report(session, test_user.id, months=2, interval="daily")
+ proj_exp_1 = next(b for b in rep_1.summary.breakdowns if b.key == "projectedExpenses")
+ assert proj_exp_1.value == 1200.0
+
+
+async def test_cash_flow_recurring_starting_in_future(
+ session: AsyncSession, test_user: User
+):
+ """A recurring whose start_date is in the future (e.g., a new subscription
+ starting next month) must be projected from its start_date forward."""
+ account = await _make_manual_account(session, test_user.id, "CF FutureStart")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Subscription starts at the 1st of the month after next, $20/month
+ start = _next_first_of_month(_next_first_of_month(today))
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=20, txn_type="debit", frequency="monthly",
+ day_of_month=1, start_date=start, next_occurrence=start,
+ description="Future subscription",
+ )
+
+ report = await get_cash_flow_report(session, test_user.id, months=4, interval="daily")
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+
+ # The subscription starts 1-2 months out; at month=4 we expect ~2-3 hits.
+ # Loose check: at least 1 occurrence and the very first day shows no impact.
+ assert proj_exp.value >= 20.0
+ first_pt = report.trend[0]
+ assert first_pt.value == 1000.0 # starting balance untouched
+
+
+async def test_cash_flow_running_balance_arithmetic(
+ session: AsyncSession, test_user: User
+):
+ """Strict arithmetic: balance on day N == starting + sum(flows up to day N).
+ Anchors the math so refactors can't silently break the cumulative sum."""
+ account = await _make_manual_account(session, test_user.id, "CF Math")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+
+ # Place specific transactions on specific days
+ flows = [
+ (today + timedelta(days=3), 200, "credit"), # +200 on day 3
+ (today + timedelta(days=10), 50, "debit"), # -50 on day 10
+ (today + timedelta(days=15), 75, "debit"), # -75 on day 15
+ (today + timedelta(days=20), 500, "credit"), # +500 on day 20
+ ]
+ for d, amt, typ in flows:
+ await _add_txn(session, test_user.id, account.id, amt, typ, d)
+
+ report = await get_cash_flow_report(session, test_user.id, months=1, interval="daily")
+ by_date = {p.date: p for p in report.trend}
+
+ # Reconstruct expected running balance day by day.
+ expected = 1000.0
+ daily_signed = {d: (amt if typ == "credit" else -amt) for d, amt, typ in flows}
+ for offset in range(0, 25):
+ d = today + timedelta(days=offset)
+ if d in daily_signed:
+ expected += daily_signed[d]
+ pt = by_date.get(d.isoformat())
+ if pt is None:
+ continue # day past report window — not all 25 days fit
+ assert abs(pt.value - expected) < 0.01, (
+ f"Day {d}: got {pt.value}, expected {expected}"
+ )
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 01748489..a88f1373 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -642,6 +642,10 @@ export const reports = {
const { data } = await api.get('/reports/income-expenses', { params: { months, interval } })
return data
},
+ cashFlow: async (months = 6, interval = 'daily'): Promise<ReportResponse> => {
+ const { data } = await api.get('/reports/cash-flow', { params: { months, interval } })
+ return data
+ },
}
// Currencies
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 114ac386..2a6e6113 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -723,8 +723,10 @@
"trend": "Over Time",
"breakdown": "Breakdown",
"noData": "No data available for this period",
+ "range3m": "3M",
"range6m": "6M",
"range1y": "1Y",
+ "range12m": "12M",
"range2y": "2Y",
"intervalDaily": "D",
"intervalWeekly": "W",
@@ -734,6 +736,15 @@
"assets": "Assets",
"liabilities": "Liabilities",
"vsStart": "vs start of period",
+ "vsToday": "projected change",
+ "balance": "Balance",
+ "inflow": "Inflow",
+ "outflow": "Outflow",
+ "inflowOutflow": "Inflow vs Outflow",
+ "startingBalance": "Starting Balance",
+ "endingBalance": "Projected Balance",
+ "projectedIncome": "Projected Income",
+ "projectedExpenses": "Projected Expenses",
"incomeExpenses": "Income vs Expenses",
"cashFlow": "Cash Flow",
"comingSoon": "(coming soon)",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index e2c6512d..a3654316 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -723,8 +723,10 @@
"trend": "Ao Longo do Tempo",
"breakdown": "Composição",
"noData": "Nenhum dado disponível para este período",
+ "range3m": "3M",
"range6m": "6M",
"range1y": "1A",
+ "range12m": "12M",
"range2y": "2A",
"intervalDaily": "D",
"intervalWeekly": "S",
@@ -734,6 +736,15 @@
"assets": "Ativos",
"liabilities": "Passivos",
"vsStart": "vs início do período",
+ "vsToday": "variação projetada",
+ "balance": "Saldo",
+ "inflow": "Entrada",
+ "outflow": "Saída",
+ "inflowOutflow": "Entradas vs Saídas",
+ "startingBalance": "Saldo Atual",
+ "endingBalance": "Saldo Projetado",
+ "projectedIncome": "Receita Projetada",
+ "projectedExpenses": "Despesa Projetada",
"incomeExpenses": "Receitas vs Despesas",
"cashFlow": "Fluxo de Caixa",
"comingSoon": "(em breve)",
diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsx
index 0ac91ba6..846f5621 100644
--- a/frontend/src/pages/reports.tsx
+++ b/frontend/src/pages/reports.tsx
@@ -40,19 +40,33 @@ function formatCompact(value: number, currency = 'USD', locale = 'en-US') {
const COMPOSITION_TOP_N = 6
-const RANGE_OPTIONS = [
+type RangeOption = { key: string; months: number }
+
+const HISTORICAL_RANGE_OPTIONS: readonly RangeOption[] = [
{ key: '6m', months: 6 },
{ key: '1y', months: 12 },
{ key: '2y', months: 24 },
-] as const
+]
-const INTERVAL_OPTIONS = [
+const FORWARD_RANGE_OPTIONS: readonly RangeOption[] = [
+ { key: '3m', months: 3 },
+ { key: '6m', months: 6 },
+ { key: '12m', months: 12 },
+]
+
+const HISTORICAL_INTERVAL_OPTIONS = [
{ key: 'daily', value: 'daily' },
{ key: 'weekly', value: 'weekly' },
{ key: 'monthly', value: 'monthly' },
{ key: 'yearly', value: 'yearly' },
] as const
+const CASH_FLOW_INTERVAL_OPTIONS = [
+ { key: 'daily', value: 'daily' },
+ { key: 'weekly', value: 'weekly' },
+ { key: 'monthly', value: 'monthly' },
+] as const
+
const INTERVAL_LABELS: Record<string, string> = {
daily: 'intervalDaily',
weekly: 'intervalWeekly',
@@ -61,8 +75,10 @@ const INTERVAL_LABELS: Record<string, string> = {
}
const RANGE_LABELS: Record<string, string> = {
+ '3m': 'range3m',
'6m': 'range6m',
'1y': 'range1y',
+ '12m': 'range12m',
'2y': 'range2y',
}
@@ -76,7 +92,7 @@ interface ReportTab {
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 },
+ { key: 'cash_flow', labelKey: 'reports.cashFlow', fetch: (m, i) => reports.cashFlow(m, i), enabled: true },
]
export default function ReportsPage() {
@@ -95,6 +111,25 @@ export default function ReportsPage() {
const currentTab = REPORT_TABS.find((tab) => tab.key === activeTab) ?? REPORT_TABS[0]
+ const isCashFlow = activeTab === 'cash_flow'
+ const rangeOptions = isCashFlow ? FORWARD_RANGE_OPTIONS : HISTORICAL_RANGE_OPTIONS
+ const intervalOptions = isCashFlow ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONS
+
+ const handleSelectTab = (key: string) => {
+ setActiveTab(key)
+ setCompositionView('summary')
+ setSparklinePage(0)
+ // Clamp months/interval to options supported by the new tab
+ const nextRanges = key === 'cash_flow' ? FORWARD_RANGE_OPTIONS : HISTORICAL_RANGE_OPTIONS
+ if (!nextRanges.some((r) => r.months === months)) {
+ setMonths(key === 'cash_flow' ? 6 : 12)
+ }
+ const nextIntervals = key === 'cash_flow' ? CASH_FLOW_INTERVAL_OPTIONS : HISTORICAL_INTERVAL_OPTIONS
+ if (!nextIntervals.some((i) => i.value === interval)) {
+ setInterval(key === 'cash_flow' ? 'daily' : 'monthly')
+ }
+ }
+
const { data, isLoading } = useQuery<ReportResponse>({
queryKey: ['reports', activeTab, months, interval],
queryFn: () => currentTab.fetch(months, interval),
@@ -134,7 +169,7 @@ export default function ReportsPage() {
const tooltipItemStyle = { color: 'var(--foreground)' }
// Composition view options per report type
- const compositionOptions = meta?.type === 'income_expenses'
+ const compositionOptions = meta?.type === 'income_expenses' || meta?.type === 'cash_flow'
? ['summary', 'byIncome', 'byExpenses'] as const
: ['summary', 'detailed'] as const
@@ -143,8 +178,9 @@ export default function ReportsPage() {
const donutData = (() => {
if (compositionView === 'summary' || composition.length === 0) {
+ const excludedKeys = new Set(['netIncome', 'startingBalance', 'endingBalance'])
return breakdownData
- .filter((b) => b.value > 0 && b.key !== 'netIncome')
+ .filter((b) => b.value > 0 && !excludedKeys.has(b.key))
.map((b) => ({
name: t(`reports.${b.key}`, { defaultValue: b.label }),
value: b.value,
@@ -184,7 +220,7 @@ export default function ReportsPage() {
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) => (
+ {rangeOptions.map((opt) => (
<button
key={opt.key}
onClick={() => setMonths(opt.months)}
@@ -199,7 +235,7 @@ export default function ReportsPage() {
))}
</div>
<div className="flex items-center rounded-lg border border-border bg-card overflow-hidden">
- {INTERVAL_OPTIONS.map((opt) => (
+ {intervalOptions.map((opt) => (
<button
key={opt.key}
onClick={() => setInterval(opt.value)}
@@ -222,7 +258,7 @@ export default function ReportsPage() {
{REPORT_TABS.map((tab) => (
<button
key={tab.key}
- onClick={() => { if (tab.enabled) { setActiveTab(tab.key); setCompositionView('summary') } }}
+ onClick={() => { if (tab.enabled) handleSelectTab(tab.key) }}
disabled={!tab.enabled}
className={`relative px-4 py-2.5 text-sm font-medium transition-colors ${
activeTab === tab.key
@@ -275,7 +311,7 @@ export default function ReportsPage() {
</div>
<p className="text-xs text-muted-foreground mt-0.5">
{mask(`${changePrefix}${formatCurrency(summary?.change_amount ?? 0, userCurrency, locale)}`)}
- {' '}{t('reports.vsStart')}
+ {' '}{t(meta?.type === 'cash_flow' ? 'reports.vsToday' : 'reports.vsStart')}
</p>
</div>
<div className="flex flex-wrap gap-6">
@@ -337,7 +373,85 @@ export default function ReportsPage() {
<Skeleton className="h-full w-full" />
</div>
) : chartData.length > 0 ? (
- meta?.type === 'income_expenses' ? (
+ meta?.type === 'cash_flow' ? (() => {
+ const startingBalance = summary?.breakdowns.find((b) => b.key === 'startingBalance')?.value ?? 0
+ return (
+ <ResponsiveContainer width="100%" height="100%">
+ <AreaChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
+ <defs>
+ <linearGradient id="cashFlowGrad" 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
+ content={({ active, payload, label }) => {
+ if (!active || !payload || payload.length === 0) return null
+ const point = payload[0].payload as Record<string, number>
+ const balance = point.value ?? 0
+ const inflow = point.inflow ?? 0
+ const outflow = point.outflow ?? 0
+ return (
+ <div style={tooltipStyle} className="px-3 py-2">
+ <p className="text-xs font-medium mb-1">{label}</p>
+ <p className="text-xs" style={{ color: '#6366F1' }}>
+ {t('reports.balance', { defaultValue: 'Balance' })}:{' '}
+ {privacyMode ? MASK : formatCurrency(balance, userCurrency, locale)}
+ </p>
+ {inflow > 0 && (
+ <p className="text-xs" style={{ color: '#10B981' }}>
+ {t('reports.inflow')}:{' '}
+ {privacyMode ? MASK : `+${formatCurrency(inflow, userCurrency, locale)}`}
+ </p>
+ )}
+ {outflow > 0 && (
+ <p className="text-xs" style={{ color: '#F43F5E' }}>
+ {t('reports.outflow')}:{' '}
+ {privacyMode ? MASK : `-${formatCurrency(outflow, userCurrency, locale)}`}
+ </p>
+ )}
+ </div>
+ )
+ }}
+ />
+ <ReferenceLine
+ y={startingBalance}
+ stroke="var(--muted-foreground)"
+ strokeDasharray="4 4"
+ strokeOpacity={0.5}
+ />
+ <Area
+ type="monotone"
+ dataKey="value"
+ stroke="#6366F1"
+ strokeWidth={2.5}
+ fill="url(#cashFlowGrad)"
+ dot={false}
+ activeDot={{ r: 4, fill: '#6366F1' }}
+ />
+ </AreaChart>
+ </ResponsiveContainer>
+ )
+ })() : meta?.type === 'income_expenses' ? (
<ResponsiveContainer width="100%" height="100%">
<ComposedChart data={chartData} margin={{ top: 8, right: 16, left: 0, bottom: 0 }}>
<XAxis
@@ -477,12 +591,16 @@ export default function ReportsPage() {
? t('reports.expenses')
: meta?.type === 'income_expenses'
? t('reports.netIncome')
- : t(currentTab.labelKey)
+ : meta?.type === 'cash_flow'
+ ? t('reports.vsToday')
+ : t(currentTab.labelKey)
const centerValue = compositionView === 'byIncome'
- ? (summary?.breakdowns.find((b) => b.key === 'income')?.value ?? 0)
+ ? (summary?.breakdowns.find((b) => b.key === 'income' || b.key === 'projectedIncome')?.value ?? 0)
: compositionView === 'byExpenses'
- ? (summary?.breakdowns.find((b) => b.key === 'expenses')?.value ?? 0)
- : (summary?.primary_value ?? 0)
+ ? (summary?.breakdowns.find((b) => b.key === 'expenses' || b.key === 'projectedExpenses')?.value ?? 0)
+ : meta?.type === 'cash_flow'
+ ? (summary?.change_amount ?? 0)
+ : (summary?.primary_value ?? 0)
return (
<div className="flex flex-col items-center">
<div className="relative" style={{ width: 200, height: 200 }}>
@@ -552,7 +670,11 @@ export default function ReportsPage() {
<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')}
+ {meta?.type === 'income_expenses'
+ ? t('reports.categoryTrends')
+ : meta?.type === 'cash_flow'
+ ? t('reports.inflowOutflow')
+ : t('reports.evolution')}
</p>
{meta?.type === 'income_expenses' && (() => {
const groupKey = sparklineView === 'byIncome' ? 'income' : 'expenses'
@@ -746,18 +868,26 @@ export default function ReportsPage() {
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}
- />
- ))}
+ {(() => {
+ const barSeries = meta.type === 'cash_flow'
+ ? [
+ { key: 'inflow', color: '#10B981' },
+ { key: 'outflow', color: '#F43F5E' },
+ ]
+ : meta.series_keys.map((k) => ({ key: k, color: colorMap[k] || '#6366F1' }))
+ return barSeries
+ .filter(({ key }) => chartData.some((d) => (d[key] as number) > 0))
+ .map(({ key, color }, idx, arr) => (
+ <Bar
+ key={key}
+ dataKey={key}
+ stackId="stack"
+ fill={color}
+ radius={idx === arr.length - 1 ? [4, 4, 0, 0] : [0, 0, 0, 0]}
+ maxBarSize={32}
+ />
+ ))
+ })()}
</BarChart>
</ResponsiveContainer>
) : (