Skip to content

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

feat: cash flow baseline forecast (closes #179) (#225)

Tássio Noronha5432343ed250
diff --git a/backend/app/api/reports.py b/backend/app/api/reports.py
index e860fd08..32e99dde 100644
--- a/backend/app/api/reports.py
+++ b/backend/app/api/reports.py
@@ -38,9 +38,10 @@ async def get_income_expenses(
async def get_cash_flow(
months: int = Query(6, ge=1, le=12),
interval: str = Query("daily", pattern="^(daily|weekly|monthly)$"),
+ baseline: bool = Query(False),
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
+ session, user.id, months, interval, user.primary_currency, baseline=baseline,
)
diff --git a/backend/app/schemas/report.py b/backend/app/schemas/report.py
index 2626e540..8fc51459 100644
--- a/backend/app/schemas/report.py
+++ b/backend/app/schemas/report.py
@@ -26,6 +26,9 @@ class ReportMeta(BaseModel):
series_keys: list[str]
currency: str
interval: str
+ forecast_start_date: str | None = None
+ baseline_active: bool = False
+ baseline_lookback_days: int | None = None
class ReportCompositionItem(BaseModel):
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.py
index 9e08e8cb..8b52287d 100644
--- a/backend/app/services/report_service.py
+++ b/backend/app/services/report_service.py
@@ -869,38 +869,148 @@ def _add_months(d: date, months: int) -> date:
return date(new_year, new_month, new_day)
+_BASELINE_MAX_LOOKBACK_MONTHS = 12
+_PAST_HISTORY_MONTHS = 1
+
+
+async def _get_baseline_projection(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ today: date,
+ end: date,
+ primary_currency: str,
+ to_primary,
+) -> tuple[list[dict], int]:
+ """Estimate future flows by averaging the user's recent transaction history.
+
+ Replaces deterministic recurring projections when baseline mode is on:
+ sums all non-ignored, P&L-counting transactions inside the look-back
+ window, splits into mean daily inflow and outflow, then emits one
+ synthetic flow per day from today+1 to end.
+
+ The look-back window is **adaptive**: capped at
+ ``_BASELINE_MAX_LOOKBACK_MONTHS`` (12) but shrunk to the user's earliest
+ qualifying transaction date when they have less history. This means a
+ user with 4 months of activity gets a 4-month average; a user with
+ 3 years gets a 12-month average. More history → more stable estimate;
+ less history → still works, just noisier.
+
+ Symmetric for income and expense — fixes the "no recurring salary set
+ up, chart looks catastrophic" case as well as the "no recurring expenses
+ set up, chart looks rosy" case.
+
+ Returns ``(projections, lookback_days)`` so the caller can surface the
+ actual window used in the response (zero when there's no history).
+ """
+ cap_start = _add_months(today, -_BASELINE_MAX_LOOKBACK_MONTHS)
+ earliest_result = await session.execute(
+ select(func.min(Transaction.date))
+ .join(Account, Transaction.account_id == Account.id)
+ .where(
+ Transaction.user_id == user_id,
+ Account.is_closed == False,
+ Transaction.date <= today,
+ Transaction.source != "opening_balance",
+ counts_as_pnl(),
+ )
+ )
+ earliest_date = earliest_result.scalar_one_or_none()
+ if earliest_date is None:
+ return [], 0
+ window_start = max(earliest_date, cap_start)
+
+ rows = 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,
+ Transaction.date >= window_start,
+ Transaction.date <= today,
+ Transaction.source != "opening_balance",
+ counts_as_pnl(),
+ )
+ )
+ total_inflow_primary = 0.0
+ total_outflow_primary = 0.0
+ for tx_type, amt, amt_primary, ccy in rows.all():
+ if amt_primary is not None:
+ amount = float(amt_primary)
+ else:
+ amount = await to_primary(Decimal(str(amt or 0)), ccy)
+ if amount == 0:
+ continue
+ if tx_type == "credit":
+ total_inflow_primary += abs(amount)
+ else:
+ total_outflow_primary += abs(amount)
+
+ lookback_days = max((today - window_start).days, 1)
+ daily_inflow = total_inflow_primary / lookback_days
+ daily_outflow = total_outflow_primary / lookback_days
+
+ projections: list[dict] = []
+ if daily_inflow == 0 and daily_outflow == 0:
+ return projections, lookback_days
+
+ cursor = today + timedelta(days=1)
+ while cursor <= end:
+ if daily_inflow > 0:
+ projections.append({
+ "date": cursor,
+ "amount": daily_inflow,
+ "currency": primary_currency,
+ "type": "credit",
+ "category_id": None,
+ })
+ if daily_outflow > 0:
+ projections.append({
+ "date": cursor,
+ "amount": daily_outflow,
+ "currency": primary_currency,
+ "type": "debit",
+ "category_id": None,
+ })
+ cursor = cursor + timedelta(days=1)
+ return projections, lookback_days
+
+
async def get_cash_flow_report(
session: AsyncSession,
user_id: uuid.UUID,
months: int = 6,
interval: str = "daily",
currency: str = "USD",
+ baseline: bool = False,
) -> ReportResponse:
- """Forward-looking cash flow projection.
+ """Cash flow chart with a short past window plus a forward 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).
+ Past window (``_PAST_HISTORY_MONTHS`` months back to today) shows actual
+ booked transactions so the user has a visible "this is real" anchor next
+ to the forecast. Forward window walks from today to ``today + months``
+ applying either deterministic recurring projections (default) or a
+ historical-mean baseline (when ``baseline=True``) — see
+ ``_get_baseline_projection`` for the latter.
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.
+ - **cash**: flows queried by ``Transaction.date``.
+ - **accrual**: flows queried by ``Transaction.effective_date`` so CC
+ purchases show up as cash leaving on their bill due date. The
+ balance at past-history start is also adjusted to add back any
+ pending CC purchases whose effective_date is in the future window,
+ avoiding double-counting against ``_balance_at``.
"""
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)
+ chart_start = _add_months(today, -_PAST_HISTORY_MONTHS)
user = await session.get(User, user_id)
primary_currency = user.primary_currency if user else get_settings().default_currency
@@ -908,10 +1018,11 @@ async def get_cash_flow_report(
accounting_mode = await get_credit_card_accounting_mode(session)
accrual = accounting_mode == "accrual"
- starting_balance = await _balance_at(session, user_id, today)
+ # "Saldo Atual" shown in the hero card. The walk is anchored at this
+ # value (not at balance-at-chart_start) so opening-balance transactions
+ # inside the past-history window can't introduce drift.
+ current_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:
@@ -923,7 +1034,6 @@ async def get_cash_flow_report(
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:
@@ -933,11 +1043,38 @@ async def get_cash_flow_report(
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
+
+ # 1a. Past actual transactions (chart_start, today]. Gives the chart a
+ # "real" section before the forecast so the today-marker has meaning.
+ past_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 > chart_start,
+ flow_date_col <= today,
+ Transaction.source != "opening_balance",
+ counts_as_pnl(),
+ )
+ )
+ for flow_date, tx_type, amt, amt_primary, ccy in past_result.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
+ _add_flow(flow_date, abs(amount_primary), tx_type == "credit")
+
+ # 1b. Future booked transactions whose cash impact is past today.
booked_result = await session.execute(
select(
flow_date_col,
@@ -966,11 +1103,10 @@ async def get_cash_flow_report(
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.
+ # 2. Accrual mode: pending CC purchases (purchase date <= today, due
+ # date in the forward window) already reduced today's balance via the
+ # CC liability. We re-project them as outflows on their effective_date,
+ # so add them back to both balance snapshots to avoid double-counting.
if accrual:
pending_cc = await session.execute(
select(
@@ -998,22 +1134,28 @@ async def get_cash_flow_report(
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)
+ current_balance += abs(amount_primary)
else:
- starting_balance -= abs(amount_primary)
+ current_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).
+ # 3. Forward projection. Default: deterministic recurring rules.
+ # Baseline mode: replace them with a historical-mean estimate so the
+ # chart reflects the user's actual recent lifestyle, not just what
+ # they've explicitly marked as recurring.
cat_totals: dict[tuple[str, str], dict] = {}
cat_cache: dict[str, dict] = {}
+ baseline_lookback_days = 0
+
+ if baseline:
+ projections, baseline_lookback_days = await _get_baseline_projection(
+ session, user_id, today, end, primary_currency, _to_primary,
+ )
+ else:
+ projections = await _get_recurring_projections(
+ session, user_id, today + timedelta(days=1), end + timedelta(days=1),
+ )
- 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:
@@ -1025,9 +1167,11 @@ async def get_cash_flow_report(
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"
+ if cat_id:
+ cat_id_str = str(cat_id)
+ else:
+ cat_id_str = "baseline" if baseline 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(
@@ -1038,17 +1182,47 @@ async def get_cash_flow_report(
"label": row[0] if row else "Uncategorized",
"color": row[1] if row else "#6B7280",
}
+ elif cat_id_str == "baseline" and cat_id_str not in cat_cache:
+ # Frontend translates via reports.baseline; label is the fallback.
+ cat_cache[cat_id_str] = {"label": "Baseline", "color": "#94A3B8"}
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
+ # 4. Walk day-by-day. The walk is anchored at today's authoritative
+ # balance (``current_balance`` from ``_balance_at``) rather than at
+ # ``chart_starting_balance``: opening-balance transactions are excluded
+ # from the past-actuals query, so a forward walk seeded from
+ # ``chart_starting_balance`` would drift if any opening balance falls
+ # inside the past-history window. Anchoring at today eliminates that
+ # class of bug and keeps the past trend visually correct.
+ daily_balance: dict[date, float] = {today: current_balance}
+ daily_inflow: dict[date, float] = {}
+ daily_outflow: dict[date, float] = {}
+
+ # Today's own inflow/outflow bucket (for tooltip), but the balance at
+ # end-of-today is already current_balance regardless of today's flows
+ # (they're folded into the authoritative number from _balance_at).
+ today_bucket = flows.get(today, {"inflow": 0.0, "outflow": 0.0})
+ daily_inflow[today] = today_bucket["inflow"]
+ daily_outflow[today] = today_bucket["outflow"]
+
+ # Backward walk: balance(d-1) = balance(d) - net_flow(d).
+ running = current_balance
+ cursor_d = today
+ while cursor_d > chart_start:
+ bucket = flows.get(cursor_d, {"inflow": 0.0, "outflow": 0.0})
+ running -= bucket["inflow"] - bucket["outflow"]
+ cursor_d = cursor_d - timedelta(days=1)
+ daily_balance[cursor_d] = running
+ prev_bucket = flows.get(cursor_d, {"inflow": 0.0, "outflow": 0.0})
+ daily_inflow[cursor_d] = prev_bucket["inflow"]
+ daily_outflow[cursor_d] = prev_bucket["outflow"]
+
+ # Forward walk: balance(d+1) = balance(d) + net_flow(d+1).
+ running = current_balance
cursor_d = today
while cursor_d < end:
cursor_d = cursor_d + timedelta(days=1)
@@ -1058,9 +1232,8 @@ async def get_cash_flow_report(
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)
+ # 5. Aggregate to interval.
+ points = _date_points(chart_start, end, interval)
trend: list[ReportDataPoint] = []
if interval == "daily":
@@ -1074,22 +1247,22 @@ async def get_cash_flow_report(
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
+ cur = chart_start
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}
+ label,
+ {"balance": daily_balance.get(cur, running), "last_d": cur,
+ "inflow": 0.0, "outflow": 0.0},
)
if cur >= g["last_d"]:
- g["balance"] = daily_balance[cur]
+ g["balance"] = daily_balance.get(cur, running)
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)
@@ -1108,13 +1281,20 @@ async def get_cash_flow_report(
},
))
- # 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)
+ # 6. Summary. "Projected income/expenses" sums only the forward portion,
+ # not the past actuals that the chart now also includes.
+ ending_balance = trend[-1].value if trend else round(current_balance, 2)
+ forward_inflow = 0.0
+ forward_outflow = 0.0
+ for d, bucket in flows.items():
+ if today < d <= end:
+ forward_inflow += bucket["inflow"]
+ forward_outflow += bucket["outflow"]
+ total_inflow = round(forward_inflow, 2)
+ total_outflow = round(forward_outflow, 2)
+ change_amount = round(ending_balance - current_balance, 2)
change_percent = (
- (change_amount / abs(starting_balance) * 100) if starting_balance != 0 else None
+ (change_amount / abs(current_balance) * 100) if current_balance != 0 else None
)
summary = ReportSummary(
@@ -1124,7 +1304,7 @@ async def get_cash_flow_report(
breakdowns=[
ReportBreakdown(
key="startingBalance", label="Starting Balance",
- value=round(starting_balance, 2), color="#6366F1",
+ value=round(current_balance, 2), color="#6366F1",
),
ReportBreakdown(
key="projectedIncome", label="Projected Income",
@@ -1146,6 +1326,9 @@ async def get_cash_flow_report(
series_keys=["balance"],
currency=primary_currency,
interval=interval,
+ forecast_start_date=_format_date_label(today, interval),
+ baseline_active=baseline,
+ baseline_lookback_days=baseline_lookback_days if baseline else None,
)
composition: list[ReportCompositionItem] = []
diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.py
index 0779a188..d8290950 100644
--- a/backend/tests/test_report_service.py
+++ b/backend/tests/test_report_service.py
@@ -1401,8 +1401,8 @@ async def test_cash_flow_api_default_params(client, auth_headers, test_transacti
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
+ # 1 month past + 6 months forward * ~30 days = ~210 trend points
+ assert 180 <= len(data["trend"]) <= 230
@pytest.mark.asyncio
@@ -2104,3 +2104,220 @@ async def test_cash_flow_running_balance_arithmetic(
assert abs(pt.value - expected) < 0.01, (
f"Day {d}: got {pt.value}, expected {expected}"
)
+
+
+# ---------------------------------------------------------------------------
+# Baseline mode (historical-mean forecast) — issue #179
+# ---------------------------------------------------------------------------
+
+
+async def test_cash_flow_baseline_off_uses_recurring(
+ session: AsyncSession, test_user: User
+):
+ """baseline=False is the legacy behavior: only recurring rules project."""
+ account = await _make_manual_account(session, test_user.id, "CF Baseline Off")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # 30 days of past actuals that baseline mode would otherwise pick up.
+ for offset in range(1, 31):
+ await _add_txn(
+ session, test_user.id, account.id, 100, "debit",
+ today - timedelta(days=offset),
+ )
+ # One recurring rule.
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=1500, 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", baseline=False,
+ )
+
+ assert report.meta.baseline_active is False
+ assert report.meta.baseline_lookback_days is None
+ 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")
+ # Recurring credit fires; past debits do NOT project forward.
+ assert proj_income.value >= 1500.0
+ assert proj_exp.value == 0.0
+
+
+async def test_cash_flow_baseline_on_replaces_recurring_with_mean(
+ session: AsyncSession, test_user: User
+):
+ """baseline=True ignores recurring rules and projects from historical mean.
+
+ Setup: 30 days × R$100 debits in the past (no income, no recurring
+ debits set up). Baseline should pick those up and project them forward.
+ """
+ account = await _make_manual_account(session, test_user.id, "CF Baseline On")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Past actuals: 30 daily R$100 debits → total R$3000 over the lookback.
+ for offset in range(1, 31):
+ await _add_txn(
+ session, test_user.id, account.id, 100, "debit",
+ today - timedelta(days=offset),
+ )
+ # A recurring credit rule that baseline mode should IGNORE.
+ await _make_recurring(
+ session, test_user.id, account.id,
+ amount=9999, 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", baseline=True,
+ )
+
+ assert report.meta.baseline_active is True
+ # Lookback window = 30 days of past data (capped by earliest tx, not by
+ # the 12-month maximum).
+ assert report.meta.baseline_lookback_days == 30
+ 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")
+ # Recurring R$9999 credit should NOT appear (baseline replaces recurring).
+ assert proj_income.value < 100.0
+ # Outflow should reflect ~R$100/day × 3 months ≈ R$9000.
+ assert proj_exp.value > 8000.0
+ assert proj_exp.value < 10000.0
+
+
+async def test_cash_flow_baseline_lookback_caps_at_twelve_months(
+ session: AsyncSession, test_user: User
+):
+ """User with >12 months of history sees lookback capped at 365 days."""
+ account = await _make_manual_account(session, test_user.id, "CF Baseline Cap")
+ await _add_txn(
+ session, test_user.id, account.id, 5000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Single very old transaction (18 months ago) plus one recent one.
+ await _add_txn(
+ session, test_user.id, account.id, 50, "debit",
+ today - timedelta(days=540),
+ )
+ await _add_txn(
+ session, test_user.id, account.id, 50, "debit",
+ today - timedelta(days=10),
+ )
+
+ report = await get_cash_flow_report(
+ session, test_user.id, months=3, interval="daily", baseline=True,
+ )
+
+ # Window is bounded by `today - 365 days`, not by the 540-days-ago tx.
+ # Allow ±2-day tolerance for month-arithmetic edge cases.
+ assert report.meta.baseline_lookback_days is not None
+ assert 363 <= report.meta.baseline_lookback_days <= 367
+
+
+async def test_cash_flow_baseline_lookback_adapts_to_short_history(
+ session: AsyncSession, test_user: User
+):
+ """User with only N days of history sees lookback shrink to N."""
+ account = await _make_manual_account(session, test_user.id, "CF Baseline Short")
+ await _add_txn(
+ session, test_user.id, account.id, 1000, "credit",
+ date.today(), source="opening_balance",
+ )
+ today = date.today()
+ # Just 7 days of activity.
+ for offset in range(1, 8):
+ await _add_txn(
+ session, test_user.id, account.id, 20, "debit",
+ today - timedelta(days=offset),
+ )
+
+ report = await get_cash_flow_report(
+ session, test_user.id, months=3, interval="daily", baseline=True,
+ )
+
+ # Earliest tx is 7 days ago, so lookback is 7 days.
+ assert report.meta.baseline_lookback_days == 7
+ proj_exp = next(b for b in report.summary.breakdowns if b.key == "projectedExpenses")
+ # 7 days × R$20 = R$140 over 7 days → R$20/day → ~R$1820 over ~91 days.
+ assert proj_exp.value > 1500.0
+ assert proj_exp.value < 2200.0
+
+
+async def test_cash_flow_baseline_no_history_returns_empty_projection(
+ session: AsyncSession, test_user: User
+):
+ """User with no qualifying transactions → baseline contributes zero.
+
+ Chart should still show starting balance flat across the forecast.
+ """
+ account = await _make_manual_account(session, test_user.id, "CF Baseline Empty")
+ await _add_txn(
+ session, test_user.id, account.id, 2000, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ report = await get_cash_flow_report(
+ session, test_user.id, months=3, interval="daily", baseline=True,
+ )
+
+ assert report.meta.baseline_active is True
+ assert report.meta.baseline_lookback_days == 0
+ 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")
+ assert proj_income.value == 0.0
+ assert proj_exp.value == 0.0
+ # Ending balance equals starting (flat line).
+ assert report.summary.change_amount == 0.0
+
+
+async def test_cash_flow_meta_carries_forecast_start_date(
+ session: AsyncSession, test_user: User
+):
+ """forecast_start_date in meta lets the UI split solid vs dashed at today."""
+ account = await _make_manual_account(session, test_user.id, "CF Forecast Start")
+ await _add_txn(
+ session, test_user.id, account.id, 100, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ report = await get_cash_flow_report(
+ session, test_user.id, months=3, interval="daily",
+ )
+
+ assert report.meta.forecast_start_date == date.today().isoformat()
+
+
+async def test_cash_flow_chart_includes_past_history(
+ session: AsyncSession, test_user: User
+):
+ """Trend starts ~1 month before today so the today-marker has context."""
+ account = await _make_manual_account(session, test_user.id, "CF Past")
+ await _add_txn(
+ session, test_user.id, account.id, 500, "credit",
+ date.today(), source="opening_balance",
+ )
+
+ report = await get_cash_flow_report(
+ session, test_user.id, months=3, interval="daily",
+ )
+
+ # First trend point should be ~30 days before today.
+ first_date = date.fromisoformat(report.trend[0].date)
+ today = date.today()
+ delta_days = (today - first_date).days
+ # _PAST_HISTORY_MONTHS = 1 (28–31 days depending on month).
+ assert 27 <= delta_days <= 32
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 9efdf59d..eca150e2 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -850,8 +850,8 @@ 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 } })
+ cashFlow: async (months = 6, interval = 'daily', baseline = false): Promise<ReportResponse> => {
+ const { data } = await api.get('/reports/cash-flow', { params: { months, interval, baseline } })
return data
},
}
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 7cf4b5cd..f97c66be 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -866,7 +866,13 @@
"byExpenses": "By Expenses",
"other": "Other",
"uncategorized": "Uncategorized",
- "categoryTrends": "Category Trends"
+ "categoryTrends": "Category Trends",
+ "today": "Today",
+ "forecast": "Forecast",
+ "forecastBaseline": "Forecast with estimate",
+ "includeEstimate": "Include estimate",
+ "includeEstimateHelp": "Estimates future inflows and outflows from your history average (up to 12 months, or all available data), instead of using your recurring rules",
+ "baseline": "Estimate"
},
"payees": {
"title": "Payees",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index f921d56f..47b76215 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -866,7 +866,13 @@
"byExpenses": "Por Despesa",
"other": "Outros",
"uncategorized": "Sem categoria",
- "categoryTrends": "Tendência por Categoria"
+ "categoryTrends": "Tendência por Categoria",
+ "today": "Hoje",
+ "forecast": "Projeção",
+ "forecastBaseline": "Projeção com estimativa",
+ "includeEstimate": "Incluir estimativa",
+ "includeEstimateHelp": "Estima entradas e saídas futuras pela média do seu histórico (até 12 meses, ou todo o histórico disponível), em vez das transações recorrentes cadastradas",
+ "baseline": "Estimativa"
},
"payees": {
"title": "Beneficiários",
diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsx
index 846f5621..e1a91efc 100644
--- a/frontend/src/pages/reports.tsx
+++ b/frontend/src/pages/reports.tsx
@@ -18,6 +18,7 @@ import {
ReferenceLine,
ResponsiveContainer,
} from 'recharts'
+import { HelpCircle } from 'lucide-react'
import { reports } from '@/lib/api'
import { Skeleton } from '@/components/ui/skeleton'
import { PageHeader } from '@/components/page-header'
@@ -108,6 +109,7 @@ export default function ReportsPage() {
const [compositionView, setCompositionView] = useState<string>('summary')
const [sparklineView, setSparklineView] = useState<'byExpenses' | 'byIncome'>('byExpenses')
const [sparklinePage, setSparklinePage] = useState(0)
+ const [cashFlowBaseline, setCashFlowBaseline] = useState(false)
const currentTab = REPORT_TABS.find((tab) => tab.key === activeTab) ?? REPORT_TABS[0]
@@ -131,8 +133,11 @@ export default function ReportsPage() {
}
const { data, isLoading } = useQuery<ReportResponse>({
- queryKey: ['reports', activeTab, months, interval],
- queryFn: () => currentTab.fetch(months, interval),
+ queryKey: ['reports', activeTab, months, interval, isCashFlow ? cashFlowBaseline : false],
+ queryFn: () =>
+ isCashFlow
+ ? reports.cashFlow(months, interval, cashFlowBaseline)
+ : currentTab.fetch(months, interval),
enabled: currentTab.enabled,
})
@@ -140,11 +145,22 @@ export default function ReportsPage() {
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>))
+ // For cash flow we split the line at `forecast_start_date` so the past
+ // section renders solid and the forward projection renders dashed.
+ // The boundary point is duplicated in both series so the line visually
+ // connects without a gap.
+ const forecastStart = meta?.forecast_start_date ?? null
+ const chartData = trend.map((dp) => {
+ const isPast = forecastStart ? dp.date < forecastStart : false
+ const isBoundary = forecastStart ? dp.date === forecastStart : false
+ return {
+ date: dp.date,
+ value: dp.value,
+ valuePast: isPast || isBoundary ? dp.value : null,
+ valueForecast: !isPast ? dp.value : null,
+ ...dp.breakdowns,
+ } as Record<string, string | number | null>
+ })
const allBreakdowns = summary?.breakdowns ?? []
const breakdownData = allBreakdowns.filter((b) => b.value > 0)
@@ -201,11 +217,12 @@ export default function ReportsPage() {
const rest = sorted.slice(COMPOSITION_TOP_N)
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,
- }))
+ const result = top.map((c) => {
+ let name = c.label
+ if (c.key === 'uncategorized') name = t('reports.uncategorized')
+ else if (c.key === 'baseline') name = t('reports.baseline')
+ return { name, value: c.value, color: c.color }
+ })
if (otherValue > 0) {
result.push({ name: t('reports.other'), value: Math.round(otherValue * 100) / 100, color: '#6B7280' })
}
@@ -219,6 +236,42 @@ export default function ReportsPage() {
title={t(currentTab.labelKey)}
action={
<div className="flex items-center gap-2">
+ {isCashFlow && (
+ <div
+ className={`flex items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-semibold transition-colors ${
+ cashFlowBaseline
+ ? 'border-primary/40 bg-primary/10 text-primary'
+ : 'border-border bg-card text-muted-foreground'
+ }`}
+ >
+ <button
+ type="button"
+ onClick={() => setCashFlowBaseline((v) => !v)}
+ className="flex items-center gap-2 hover:text-foreground transition-colors"
+ aria-pressed={cashFlowBaseline}
+ >
+ <span
+ className={`relative inline-flex h-3.5 w-6 shrink-0 items-center rounded-full transition-colors ${
+ cashFlowBaseline ? 'bg-primary' : 'bg-muted'
+ }`}
+ >
+ <span
+ className={`inline-block h-2.5 w-2.5 transform rounded-full bg-white transition-transform ${
+ cashFlowBaseline ? 'translate-x-3' : 'translate-x-0.5'
+ }`}
+ />
+ </span>
+ {t('reports.includeEstimate')}
+ </button>
+ <span
+ title={t('reports.includeEstimateHelp')}
+ aria-label={t('reports.includeEstimateHelp')}
+ className="inline-flex cursor-help"
+ >
+ <HelpCircle className="h-3.5 w-3.5 opacity-60" />
+ </span>
+ </div>
+ )}
<div className="flex items-center rounded-lg border border-border bg-card overflow-hidden">
{rangeOptions.map((opt) => (
<button
@@ -364,6 +417,14 @@ export default function ReportsPage() {
</span>
</div>
)}
+ {meta.type === 'cash_flow' && (
+ <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">
+ {meta.baseline_active ? t('reports.forecastBaseline') : t('reports.forecast')}
+ </span>
+ </div>
+ )}
</div>
)}
</div>
@@ -439,12 +500,39 @@ export default function ReportsPage() {
strokeDasharray="4 4"
strokeOpacity={0.5}
/>
+ {forecastStart && (
+ <ReferenceLine
+ x={forecastStart}
+ stroke="var(--muted-foreground)"
+ strokeDasharray="3 3"
+ strokeOpacity={0.6}
+ label={{
+ value: t('reports.today'),
+ position: 'insideTopRight',
+ fill: 'var(--muted-foreground)',
+ fontSize: 10,
+ }}
+ />
+ )}
+ <Area
+ type="monotone"
+ dataKey="valuePast"
+ stroke="#6366F1"
+ strokeWidth={2.5}
+ fill="url(#cashFlowGrad)"
+ dot={false}
+ activeDot={{ r: 4, fill: '#6366F1' }}
+ isAnimationActive={false}
+ connectNulls={false}
+ />
<Area
type="monotone"
- dataKey="value"
+ dataKey="valueForecast"
stroke="#6366F1"
strokeWidth={2.5}
+ strokeDasharray="6 3"
fill="url(#cashFlowGrad)"
+ fillOpacity={0.4}
dot={false}
activeDot={{ r: 4, fill: '#6366F1' }}
/>
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 9e40bc2d..99f08a82 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -596,6 +596,9 @@ export interface ReportMeta {
series_keys: string[]
currency: string
interval: string
+ forecast_start_date?: string | null
+ baseline_active?: boolean
+ baseline_lookback_days?: number | null
}
export interface ReportCompositionItem {