Open-source personal finance manager. Self-hosted, privacy-first.
feat: separate current balances from forecasts (#582)
Leonardo Zanivan5b8af5b278a7
diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.pyindex 09e0dbad..9f115d06 100644--- a/backend/app/api/accounts.py+++ b/backend/app/api/accounts.py@@ -65,11 +65,17 @@ async def get_account_summary(primary_currency = ctx.user.primary_currencyif account and account.currency != primary_currency:bal, _ = await convert(session, Decimal(str(summary["current_balance"])), account.currency, primary_currency)+ opening, _ = await convert(session, Decimal(str(summary["opening_balance"])), account.currency, primary_currency)inc, _ = await convert(session, Decimal(str(summary["monthly_income"])), account.currency, primary_currency)exp, _ = await convert(session, Decimal(str(summary["monthly_expenses"])), account.currency, primary_currency)+ projected_inc, _ = await convert(session, Decimal(str(summary["projected_income"])), account.currency, primary_currency)+ projected_exp, _ = await convert(session, Decimal(str(summary["projected_expenses"])), account.currency, primary_currency)summary["current_balance_primary"] = float(bal)+ summary["opening_balance_primary"] = float(opening)summary["monthly_income_primary"] = float(inc)summary["monthly_expenses_primary"] = float(exp)+ summary["projected_income_primary"] = float(projected_inc)+ summary["projected_expenses_primary"] = float(projected_exp)return summarydiff --git a/backend/app/api/dashboard.py b/backend/app/api/dashboard.pyindex f3540061..e19c22a7 100644--- a/backend/app/api/dashboard.py+++ b/backend/app/api/dashboard.py@@ -67,9 +67,22 @@ async def get_balance_history(@router.get("/projected-transactions", response_model=list[ProjectedTransaction])async def get_projected_transactions(month: Optional[date] = Query(None),+ account_id: Optional[uuid.UUID] = Query(None),+ from_date: Optional[date] = Query(None, alias="from"),+ to_date: Optional[date] = Query(None, alias="to"),ctx: WorkspaceContext = Depends(current_workspace),session: AsyncSession = Depends(get_async_session),):- return await dashboard_service.get_projected_transactions(- session, ctx.workspace.id, ctx.user_id, month- )+ try:+ return await dashboard_service.get_projected_transactions(+ session,+ ctx.workspace.id,+ ctx.user_id,+ month,+ account_id=account_id,+ from_date=from_date,+ to_date=to_date,+ )+ except ValueError as exc:+ from fastapi import HTTPException+ raise HTTPException(status_code=422, detail=str(exc)) from excdiff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex 798fa39e..ae582413 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -94,8 +94,14 @@ class CreditCardBillRead(BaseModel):class AccountSummary(BaseModel):account_id: uuid.UUIDcurrent_balance: float+ opening_balance: floatmonthly_income: floatmonthly_expenses: float+ projected_income: float = 0.0+ projected_expenses: float = 0.0current_balance_primary: Optional[float] = None+ opening_balance_primary: Optional[float] = Nonemonthly_income_primary: Optional[float] = Nonemonthly_expenses_primary: Optional[float] = None+ projected_income_primary: Optional[float] = None+ projected_expenses_primary: Optional[float] = Nonediff --git a/backend/app/schemas/budget.py b/backend/app/schemas/budget.pyindex bad187df..a3dfdc60 100644--- a/backend/app/schemas/budget.py+++ b/backend/app/schemas/budget.py@@ -38,6 +38,8 @@ class BudgetVsActual(BaseModel):group_name: Optional[str] = Nonebudget_amount: Optional[Decimal] = Noneactual_amount: Decimal+ projected_amount: Decimal = Decimal("0")prev_month_amount: Decimal = Decimal("0")+ projected_prev_month_amount: Decimal = Decimal("0")percentage_used: Optional[float] = Noneis_recurring: bool = Falsediff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.pyindex 3c83e910..5f6aa0ff 100644--- a/backend/app/schemas/dashboard.py+++ b/backend/app/schemas/dashboard.py@@ -1,20 +1,26 @@from typing import Optional-from pydantic import BaseModel+from pydantic import BaseModel, Fieldclass DashboardSummary(BaseModel):total_balance: dict[str, float] # currency -> amounttotal_balance_primary: float = 0.0 # consolidated in primary currency+ projected_balance: dict[str, float] = Field(default_factory=dict) # current balance plus forecast rows+ projected_balance_primary: float = 0.0 # consolidated projected balancebalance_date: str # ISO date string, e.g. "2026-03-02"monthly_income: floatmonthly_expenses: floatmonthly_income_primary: float = 0.0monthly_expenses_primary: float = 0.0+ projected_income: float = 0.0+ projected_expenses: float = 0.0+ projected_income_primary: float = 0.0+ projected_expenses_primary: float = 0.0accounts_count: intpending_categorization: intpending_categorization_amount: float- assets_value: dict[str, float] = {} # currency -> total asset value+ assets_value: dict[str, float] = Field(default_factory=dict) # currency -> total asset valueassets_value_primary: float = 0.0primary_currency: str = "USD"# Net pending balance from group splits (in primary currency).@@ -30,7 +36,10 @@ class SpendingByCategory(BaseModel):category_name: strcategory_icon: strcategory_color: str+ # Posted-only, so the breakdown sums to the expenses card.total: float+ # Actual plus forecast, mirroring the card's projected sub-line.+ projected_total: float = 0.0percentage: float@@ -52,6 +61,7 @@ class BalanceHistory(BaseModel):class ProjectedTransaction(BaseModel):recurring_id: str+ account_id: Optional[str] = Nonedescription: stramount: floatamount_primary: Optional[float] = Nonediff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.pyindex 38ce94a5..8ed6545d 100644--- a/backend/app/services/_query_filters.py+++ b/backend/app/services/_query_filters.py@@ -11,10 +11,64 @@ from typing import Optionalfrom sqlalchemy import and_, case, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.models.account import Accountfrom app.models.category import Categoryfrom app.models.transaction import Transaction+def is_confirmed():+ """SQL filter: the charge is settled rather than merely authorized.++ One of the two independent axes a transaction sits on. This one is about+ *confirmation*: a pending row is real money already committed, it just+ has not cleared yet. It says nothing about when the row is dated.+ """+ return Transaction.status == "posted"+++def is_not_future(as_of: date):+ """SQL filter: the transaction has already happened by ``as_of``.++ The other axis, and a pure date question. A future-dated row is forecast+ no matter how confirmed it is; a past-dated row has happened no matter+ whether the bank has cleared it.+ """+ return Transaction.date <= as_of+++def is_inside_provider_snapshot():+ """SQL filter: the provider's balance already accounts for this row.++ A connected account's current balance is the number the provider sends,+ not a sum of our rows, and providers net out the pending charges they+ report. A row typed by hand is ambiguous the same way, since the user is+ usually copying a charge the bank is already showing them.++ A recurring placeholder is the one case we can be sure about: we invented+ the row from a schedule, so no provider has ever seen it. Treating it as+ already counted makes it cancel itself out, leaving a charge that shows up+ in the forecast totals but moves no balance.+ """+ return Transaction.source != "recurring"+++def counts_in_current_balance(as_of: date):+ """SQL filter: the row belongs in the balance labelled "current".++ Composed from the two axes above so the definition lives in one place and+ moving the line later is a change here rather than at every query site.++ Today the line sits at "confirmed and not future", with one exception:+ a credit card's balance is the debt owed, and an authorized purchase is+ already owed, so pending card rows stay in. Without that carve-out the+ card's balance understates the debt while its own bill total includes it.+ """+ return and_(+ is_not_future(as_of),+ or_(is_confirmed(), Account.type == "credit_card"),+ )++def reporting_date_col(accounting_mode: str):"""The date column a transaction should be *bucketed by* in periodaggregations (dashboard, reports, budgets).@@ -157,6 +211,8 @@ async def owner_split_offset_pnl(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,+ date_col <= date.today(),+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(Transaction.currency)@@ -235,6 +291,8 @@ async def owner_split_offset_by_category(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,+ date_col <= date.today(),+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(Transaction.category_id, Transaction.currency)@@ -317,6 +375,8 @@ async def viewer_shared_pnl(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,+ date_col <= date.today(),+ Transaction.status == "posted",counts_as_pnl(),).group_by(Transaction.currency)@@ -394,6 +454,8 @@ async def viewer_shared_spending_by_category(Transaction.source != "opening_balance",date_col >= month_start,date_col < month_end,+ date_col <= date.today(),+ Transaction.status == "posted",counts_as_pnl(),).group_by(Transaction.category_id, Transaction.currency)diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex d60be6b7..959d8bc5 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -12,7 +12,13 @@ from app.models.bank_connection import BankConnectionfrom app.models.credit_card_bill import CreditCardBillfrom app.models.transaction import Transactionfrom app.schemas.account import AccountCreate, AccountUpdate-from app.services._query_filters import counts_as_pnl+from app.services._query_filters import (+ counts_as_pnl,+ counts_in_current_balance,+ is_confirmed,+ is_inside_provider_snapshot,+ is_not_future,+)from app.services.credit_card_service import apply_effective_date, compute_available_credit, get_cycle_datesfrom app.models.category import Category@@ -43,6 +49,7 @@ def _opening_balance_values(account_type: str, balance: Decimal) -> tuple[Decimaasync def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_closed: bool = False) -> list[dict]:+ today = _Date.today()# Subquery: compute current_balance per account from transactions in one pass# Use amount_primary only when tx currency differs from account currency# (converts foreign txs to account's reporting currency)@@ -63,6 +70,7 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c.join(Account, Transaction.account_id == Account.id).outerjoin(Category, Transaction.category_id == Category.id).where(+ counts_in_current_balance(today),Transaction.is_ignored == False,or_(Transaction.category_id.is_(None),@@ -74,7 +82,6 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c)# Subquery: compute previous_balance (balance at end of previous month)- today = _Date.today()first_of_month = today.replace(day=1)prev_month_end = first_of_month - timedelta(days=1)@@ -86,6 +93,7 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c.outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.date <= prev_month_end,+ Transaction.status == "posted",Transaction.is_ignored == False,or_(Transaction.category_id.is_(None),@@ -443,6 +451,12 @@ async def sync_opening_balance_for_connected_account(if account.connection_id is None:return+ # The provider balance is a snapshot for today. Future-dated transactions+ # are projections and must not change the synthetic opening transaction;+ # otherwise a later-dated row can shift the opening balance even though it+ # is not part of the provider's current balance yet.+ balance_cutoff = _Date.today()+# For connected CC accounts the stored balance is positive debt and the UI# displays it negated (account_service.serialize_account). The sum of signed# transaction amounts on a CC trends negative as debt accrues, so the target@@ -464,6 +478,14 @@ async def sync_opening_balance_for_connected_account(select(func.coalesce(func.sum(signed_amount), 0)).where(Transaction.account_id == account.id,Transaction.source != "opening_balance",+ Transaction.date <= balance_cutoff,+ Transaction.is_ignored == False,+ or_(+ Transaction.category_id.is_(None),+ Transaction.category_id.not_in(+ select(Category.id).where(Category.is_ignored == True)+ ),+ ),))tx_sum = Decimal(str(sum_result.scalar() or 0))@@ -488,6 +510,14 @@ async def sync_opening_balance_for_connected_account(select(func.min(Transaction.date)).where(Transaction.account_id == account.id,Transaction.source != "opening_balance",+ Transaction.date <= balance_cutoff,+ Transaction.is_ignored == False,+ or_(+ Transaction.category_id.is_(None),+ Transaction.category_id.not_in(+ select(Category.id).where(Category.is_ignored == True)+ ),+ ),))oldest_date = oldest_result.scalar()@@ -657,6 +687,11 @@ async def get_account_summary()).where(Transaction.account_id == account_id,+ is_not_future(today),+ # Same carve-out as the accounts list: a card's balance is the+ # debt owed and an authorized purchase is already owed. The+ # account is loaded here, so branch in Python rather than SQL.+ *([] if account.type == "credit_card" else [is_confirmed()]),Transaction.is_ignored == False,or_(Transaction.category_id.is_(None),@@ -749,6 +784,8 @@ async def get_account_summary(Transaction.account_id == account_id,Transaction.type == "credit",Transaction.source != "opening_balance",+ bucket_date <= today,+ Transaction.status == "posted",counts_as_pnl(),)))@@ -768,6 +805,8 @@ async def get_account_summary(_scope(select(func.coalesce(func.sum(signed_for_bill), 0)).where(Transaction.account_id == account_id,Transaction.source != "opening_balance",+ bucket_date <= today,+ Transaction.status == "posted",counts_as_pnl(),)))@@ -776,16 +815,145 @@ async def get_account_summary(_scope(select(func.coalesce(func.sum(func.abs(effective_amount)), 0)).where(Transaction.account_id == account_id,Transaction.type == "debit",+ bucket_date <= today,+ Transaction.status == "posted",counts_as_pnl(),)))monthly_expenses = float(expenses_result.scalar())+ # Forecast values use the same cycle/date scope as the actual totals, but+ # include every pending row and every row bucketed after today. The current+ # balance remains posted-only (or the provider number for connected+ # accounts); these fields are the payable/forecast view consumed by the+ # account-detail bill card.+ forecast_condition = or_(+ Transaction.status == "pending",+ bucket_date > today,+ )+ forecast_income_result = await session.execute(+ _scope(select(func.coalesce(func.sum(effective_amount), 0)).where(+ Transaction.account_id == account_id,+ Transaction.type == "credit",+ Transaction.source != "opening_balance",+ forecast_condition,+ counts_as_pnl(),+ ))+ )+ forecast_income = float(forecast_income_result.scalar() or 0)++ if account.type == "credit_card":+ forecast_expense_result = await session.execute(+ _scope(select(func.coalesce(func.sum(signed_for_bill), 0)).where(+ Transaction.account_id == account_id,+ Transaction.source != "opening_balance",+ forecast_condition,+ counts_as_pnl(),+ ))+ )+ else:+ forecast_expense_result = await session.execute(+ _scope(select(func.coalesce(func.sum(func.abs(effective_amount)), 0)).where(+ Transaction.account_id == account_id,+ Transaction.type == "debit",+ forecast_condition,+ counts_as_pnl(),+ ))+ )+ forecast_expenses = float(forecast_expense_result.scalar() or 0)++ # Opening balance: the projected balance at (date_from - 1 day). It seeds+ # the account-detail running-balance walk, so it includes pending rows and+ # future-dated rows that occur before the visible window. The opening row+ # itself is included when it falls inside the window and applied by the+ # same walk as every other transaction.+ if account.type != "credit_card" and date_from:+ ob_base_filters = [+ Transaction.account_id == account_id,+ Transaction.is_ignored == False,+ or_(+ Transaction.category_id.is_(None),+ Transaction.category_id.not_in(+ select(Category.id).where(Category.is_ignored == True)+ ),+ ),+ ]+ if account.connection_id:+ # Connected current balance is the provider snapshot. Reconstruct+ # the balance before the visible window from that snapshot and all+ # settled/pending rows in the visible historical portion. This+ # preserves the provider number even when it includes pending rows.+ # A recurring placeholder is left out of that unwinding: we+ # generated it ourselves so it was never in the snapshot, and+ # removing it here would cancel it out when the walk re-applies it.+ period_filters = [+ *ob_base_filters,+ Transaction.date >= date_from,+ Transaction.date <= today,+ ]+ posted_result = await session.execute(+ select(func.coalesce(func.sum(+ case(+ (Transaction.type == "credit", effective_amount),+ else_=-effective_amount,+ )+ ), 0)).where(*period_filters, Transaction.status == "posted")+ )+ pending_result = await session.execute(+ select(func.coalesce(func.sum(+ case(+ (Transaction.type == "credit", effective_amount),+ else_=-effective_amount,+ )+ ), 0)).where(+ *period_filters,+ Transaction.status == "pending",+ is_inside_provider_snapshot(),+ )+ )+ opening_balance = current_balance - float(posted_result.scalar() or 0)+ opening_balance -= float(pending_result.scalar() or 0)++ if date_from > today:+ before_window_result = await session.execute(+ select(func.coalesce(func.sum(+ case(+ (Transaction.type == "credit", effective_amount),+ else_=-effective_amount,+ )+ ), 0)).where(+ *ob_base_filters,+ Transaction.date > today,+ Transaction.date < date_from,+ Transaction.status.in_(("posted", "pending")),+ )+ )+ opening_balance += float(before_window_result.scalar() or 0)+ else:+ manual_result = await session.execute(+ select(func.coalesce(func.sum(+ case(+ (Transaction.type == "credit", effective_amount),+ else_=-effective_amount,+ )+ ), 0)).where(+ *ob_base_filters,+ Transaction.date < date_from,+ Transaction.status.in_(("posted", "pending")),+ )+ )+ opening_balance = float(manual_result.scalar() or 0)+ else:+ opening_balance = 0.0+return {"account_id": account_id,"current_balance": current_balance,+ "opening_balance": opening_balance,"monthly_income": monthly_income,"monthly_expenses": monthly_expenses,+ "projected_income": monthly_income + forecast_income,+ "projected_expenses": monthly_expenses + forecast_expenses,}@@ -813,7 +981,8 @@ async def _account_balance_at(.outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.account_id == account_id,- Transaction.date <= cutoff,+ Transaction.date <= min(cutoff, _Date.today()),+ Transaction.status == "posted",Transaction.is_ignored == False,or_(Transaction.category_id.is_(None),@@ -846,6 +1015,8 @@ async def _account_daily_balance_series(Transaction.account_id == account_id,Transaction.date >= date_from,Transaction.date <= date_to,+ Transaction.date <= _Date.today(),+ Transaction.status == "posted",Transaction.is_ignored == False,or_(Transaction.category_id.is_(None),diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.pyindex b4595849..ad556fad 100644--- a/backend/app/services/budget_service.py+++ b/backend/app/services/budget_service.py@@ -18,7 +18,11 @@ from app.services._query_filters import (reporting_date_col,)from app.services.admin_service import get_credit_card_accounting_mode-from app.services.dashboard_service import _get_recurring_projections+from app.services.dashboard_service import (+ _counts_as_user_pnl_row,+ _get_forecast_transactions,+ _get_recurring_projections,+)from app.services.fx_rate_service import convertfrom app.core.config import get_settings@@ -273,6 +277,8 @@ async def get_budget_vs_actual(report_date >= month_start,report_date < month_end,Transaction.category_id.isnot(None),+ report_date <= date.today(),+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(Transaction.category_id)@@ -314,6 +320,8 @@ async def get_budget_vs_actual(cat_id = str(cat_uuid)spending_map[cat_id] = spending_map.get(cat_id, Decimal("0")) + Decimal(str(total))+ projected_spending_map = dict(spending_map)+# Add projected recurring transactions for this month (converted to primary currency)projections = await _get_recurring_projections(session, workspace_id, month_start, month_end)for proj in projections:@@ -323,7 +331,24 @@ async def get_budget_vs_actual(converted, _ = await convert(session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,)- spending_map[cat_id] = spending_map.get(cat_id, Decimal("0")) + converted+ projected_spending_map[cat_id] = projected_spending_map.get(cat_id, Decimal("0")) + converted++ forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, month_start, month_end,+ range_date_col=report_date,+ )+ for tx in forecast_transactions:+ if tx.type != "debit" or not tx.category_id or not _counts_as_user_pnl_row(tx):+ continue+ cat_id = str(tx.category_id)+ amount = tx.amount_primary+ if amount is not None:+ converted = abs(Decimal(str(amount)))+ else:+ converted, _ = await convert(+ session, Decimal(str(abs(tx.amount))), tx.currency, primary_currency,+ )+ projected_spending_map[cat_id] = projected_spending_map.get(cat_id, Decimal("0")) + converted# Get previous month spending by category (exclude transfer pairs)# Use amount_primary for multi-currency support@@ -338,6 +363,8 @@ async def get_budget_vs_actual(report_date >= prev_month_start,report_date < prev_month_end,Transaction.category_id.isnot(None),+ report_date <= date.today(),+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(Transaction.category_id)@@ -374,6 +401,8 @@ async def get_budget_vs_actual(cat_id = str(cat_uuid)prev_spending_map[cat_id] = prev_spending_map.get(cat_id, Decimal("0")) + Decimal(str(total))+ projected_prev_spending_map = dict(prev_spending_map)+# Add projected recurring transactions for previous month (converted to primary currency)prev_projections = await _get_recurring_projections(session, workspace_id, prev_month_start, prev_month_end)for proj in prev_projections:@@ -383,24 +412,43 @@ async def get_budget_vs_actual(converted, _ = await convert(session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,)- prev_spending_map[cat_id] = prev_spending_map.get(cat_id, Decimal("0")) + converted+ projected_prev_spending_map[cat_id] = projected_prev_spending_map.get(cat_id, Decimal("0")) + converted++ prev_forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, prev_month_start, prev_month_end,+ range_date_col=report_date,+ )+ for tx in prev_forecast_transactions:+ if tx.type != "debit" or not tx.category_id or not _counts_as_user_pnl_row(tx):+ continue+ cat_id = str(tx.category_id)+ amount = tx.amount_primary+ if amount is not None:+ converted = abs(Decimal(str(amount)))+ else:+ converted, _ = await convert(+ session, Decimal(str(abs(tx.amount))), tx.currency, primary_currency,+ )+ projected_prev_spending_map[cat_id] = projected_prev_spending_map.get(cat_id, Decimal("0")) + convertedcomparisons = []for category, group in all_categories:cat_id = str(category.id)actual = spending_map.get(cat_id, Decimal("0"))+ projected = projected_spending_map.get(cat_id, Decimal("0"))prev_actual = prev_spending_map.get(cat_id, Decimal("0"))+ projected_prev = projected_prev_spending_map.get(cat_id, Decimal("0"))budget_entry = budget_map.get(cat_id)budget_amount = budget_entry[0] if budget_entry else Noneis_recurring = budget_entry[1] if budget_entry else False# Skip categories with no spending in either month and no budget- if actual == 0 and prev_actual == 0 and budget_amount is None:+ if actual == 0 and projected == 0 and prev_actual == 0 and projected_prev == 0 and budget_amount is None:continuepercentage = Noneif budget_amount and budget_amount > 0:- percentage = round(float(actual / budget_amount * 100), 1)+ percentage = round(float(projected / budget_amount * 100), 1)comparisons.append(BudgetVsActual(category_id=category.id,@@ -411,7 +459,9 @@ async def get_budget_vs_actual(group_name=group.name if group else None,budget_amount=budget_amount,actual_amount=actual,+ projected_amount=projected,prev_month_amount=prev_actual,+ projected_prev_month_amount=projected_prev,percentage_used=percentage,is_recurring=is_recurring,))diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex a90b2821..fa5fe07d 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -5,6 +5,7 @@ from typing import Optionalfrom sqlalchemy import select, func, case, or_from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import selectinloadfrom app.core.config import get_settingsfrom app.models.account import Account@@ -24,7 +25,7 @@ from app.services._query_filters import (from app.services.admin_service import get_credit_card_accounting_modefrom app.services.recurring_transaction_service import get_occurrences_in_rangefrom app.services.asset_service import get_asset_values_at-from app.services.fx_rate_service import convert+from app.services.fx_rate_service import _resolve_rate, convertfrom app.models.user import User@@ -38,45 +39,93 @@ def _month_range(month: date) -> tuple[date, date]:return month_start, month_end+async def _materialized_recurring_occurrences(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ recurring_ids: set[uuid.UUID],+ range_start: date,+ range_end: date,+) -> set[tuple[uuid.UUID, date]]:+ """Return linked recurring occurrences already represented by real rows."""+ if not recurring_ids:+ return set()++ result = await session.execute(+ select(Transaction.recurring_transaction_id, Transaction.date).where(+ Transaction.workspace_id == workspace_id,+ Transaction.recurring_transaction_id.in_(recurring_ids),+ Transaction.date >= range_start,+ Transaction.date < range_end,+ )+ )+ return {+ (recurring_id, transaction_date)+ for recurring_id, transaction_date in result.all()+ if recurring_id is not None+ }++async def _get_recurring_projections(session: AsyncSession,workspace_id: uuid.UUID,month_start: date,month_end: date,account_ids: Optional[list[uuid.UUID]] = None,+ *,+ include_transfer_like: bool = False,) -> list[dict]:"""Compute virtual recurring transaction projections for a month.Pure read — no DB writes. Returns list of dicts with category_id, amount, type, currency.When ``account_ids`` is given (Collection filter), only recurring rules on- those accounts are projected. Empty list → no projections."""+ those accounts are projected. Empty list → no projections.++ Transfer-like categories are excluded by default because most callers use+ these rows for P&L, budgets, reports, or spending. Balance projections can+ opt in because transfers and investment applications still move cash in+ the affected account. Ignored categories never participate."""if account_ids is not None and len(account_ids) == 0:return []+ filters = [+ RecurringTransaction.workspace_id == workspace_id,+ RecurringTransaction.is_active == True,+ RecurringTransaction.start_date < month_end + timedelta(days=2),+ or_(+ RecurringTransaction.category_id.is_(None),+ Category.is_ignored.is_not(True),+ ),+ ]+ if not include_transfer_like:+ filters.append(or_(+ RecurringTransaction.category_id.is_(None),+ Category.treat_as_transfer.is_not(True),+ ))stmt = (select(RecurringTransaction).outerjoin(Category, RecurringTransaction.category_id == Category.id)- .where(- RecurringTransaction.workspace_id == workspace_id,- RecurringTransaction.is_active == True,- RecurringTransaction.start_date < month_end + timedelta(days=2),- or_(- RecurringTransaction.category_id.is_(None),- Category.treat_as_transfer.is_not(True),- ),- or_(- RecurringTransaction.category_id.is_(None),- Category.is_ignored.is_not(True),- ),- )+ .where(*filters))if account_ids:stmt = stmt.where(RecurringTransaction.account_id.in_(account_ids))result = await session.execute(stmt)recurring_list = list(result.scalars().all())+ # A recurrence may already have been materialized without its nominal+ # pointer being advanced yet (for example by generate-ahead workflows).+ # Suppress the matching virtual row so clients never render or total the+ # same occurrence twice.+ materialized_occurrences = await _materialized_recurring_occurrences(+ session,+ workspace_id,+ {rec.id for rec in recurring_list},+ month_start,+ month_end,+ )+projections = []for rec in recurring_list:- # Compute occurrences starting from next_occurrence (skips already-created transactions)+ # Compute occurrences from the nominal pointer; linked rows are+ # filtered explicitly below because the pointer can lag materialization.occurrences = get_occurrences_in_range(start=rec.next_occurrence,frequency=rec.frequency,@@ -87,6 +136,8 @@ async def _get_recurring_projections(weekend_adjustment=rec.weekend_adjustment,)for occ_date in occurrences:+ if (rec.id, occ_date) in materialized_occurrences:+ continueprojections.append({"category_id": rec.category_id,"amount": float(rec.amount),@@ -97,6 +148,64 @@ async def _get_recurring_projections(return projections+async def _get_forecast_transactions(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ range_start: date,+ range_end: date,+ account_ids: Optional[list[uuid.UUID]] = None,+ range_date_col=None,+) -> list[Transaction]:+ """Return real rows that belong to the forecast, not the current balance.++ A pending row is forecast regardless of its date. A posted row dated after+ today is also forecast: this is how future installments and generate-ahead+ recurring rows follow the same rule as bank pending rows without needing a+ source-specific branch at every consumer.+ """+ if account_ids is not None and len(account_ids) == 0:+ return []++ today = date.today()+ bucket_date = range_date_col if range_date_col is not None else Transaction.date+ stmt = (+ select(Transaction)+ .join(Account, Transaction.account_id == Account.id)+ .outerjoin(Category, Transaction.category_id == Category.id)+ .where(+ Transaction.workspace_id == workspace_id,+ Account.is_closed == False,+ bucket_date >= range_start,+ bucket_date < range_end,+ Transaction.source != "opening_balance",+ or_(+ Transaction.status == "pending",+ bucket_date > today,+ ),+ )+ .options(+ selectinload(Transaction.account),+ selectinload(Transaction.category),+ )+ .order_by(Transaction.date.asc(), Transaction.created_at.asc())+ )+ if account_ids:+ stmt = stmt.where(Transaction.account_id.in_(account_ids))+ result = await session.execute(stmt)+ return list(result.scalars().all())+++def _counts_as_user_pnl_row(tx: Transaction) -> bool:+ """Python equivalent of ``counts_as_user_pnl`` for loaded forecast rows."""+ category = tx.category+ return not (+ tx.transfer_pair_id+ or tx.is_ignored+ or tx.source == "settlement"+ or (category and (category.treat_as_transfer or category.is_ignored))+ )++async def get_summary(session: AsyncSession,workspace_id: uuid.UUID,@@ -140,25 +249,72 @@ async def get_summary(# Current or future month: todaycutoff = today+ # ``total_balance`` is deliberately current/posted-only. Forecast rows are+ # accumulated separately so a future installment or pending bank row never+ # silently changes the number labelled as the current balance.total_balance = await _total_balance_by_currency(session, workspace_id, cutoff, account_ids)-- # For current/future months, project the total balance by adding recurring- # projections from cutoff+1 through month_end.- if month_end > cutoff:+ projected_balance = dict(total_balance)++ # For current/future months, project the balance by adding recurring+ # projections and real forecast rows from cutoff+1 through month_end.+ # A month that has already elapsed has no forecast: `cutoff` is its own+ # last day there, so `month_end > cutoff` alone would still let the whole+ # pending backlog land on a month that is already history.+ if month_end > cutoff and month_end > today:projection_start = cutoff + timedelta(days=1)balance_projections = await _get_recurring_projections(- session, workspace_id, projection_start, month_end, account_ids+ session,+ workspace_id,+ projection_start,+ month_end,+ account_ids,+ include_transfer_like=True,)for proj in balance_projections:signed = proj["amount"] if proj["type"] == "credit" else -proj["amount"]- total_balance[proj["currency"]] = total_balance.get(proj["currency"], 0.0) + signed+ projected_balance[proj["currency"]] = projected_balance.get(proj["currency"], 0.0) + signed++ # Pending rows are forecast regardless of their transaction date. A+ # future-month dashboard still needs to carry an old/stale pending row+ # into the projected balance, so do not narrow this query to the+ # selected month's start.+ balance_forecast_start = date.min+ balance_forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, balance_forecast_start, month_end, account_ids+ )+ for tx in balance_forecast_transactions:+ if tx.is_ignored or (tx.category and tx.category.is_ignored):+ continue+ # A connected provider is authoritative for today's current+ # number. If it exposes a pending row dated today or earlier, do+ # not add that same row again to the projected walk. A recurring+ # placeholder is the exception: we generated it from a schedule, so+ # it is missing from that number and still has to be applied.+ if (+ tx.account+ and tx.account.connection_id+ and tx.status == "pending"+ and tx.date <= today+ and tx.source != "recurring"+ ):+ continue+ account_currency = tx.account.currency if tx.account else tx.currency+ amount = (+ tx.amount+ if tx.currency == account_currency+ else (tx.amount_primary or tx.amount)+ )+ signed = amount if tx.type == "credit" else -amount+ projected_balance[account_currency] = (+ projected_balance.get(account_currency, 0.0) + float(signed)+ )# Monthly income and expenses — exclude opening_balance so initial deposits# don't inflate the month's income figure. counts_as_user_pnl() skips# paired transfers, transfer-like categories AND settlement movements# (whose offset is already in the owner's share, see share-only model).- # Only posted (settled) transactions count; pending entries stay out of- # the period totals until they post.+ # Only posted (settled) transactions count in the actual period totals;+ # pending and future rows are layered into the forecast fields below.monthly_result = await session.execute(select(func.sum(case((Transaction.type == "credit", Transaction.amount), else_=0)),@@ -170,6 +326,7 @@ async def get_summary(Account.is_closed == False,report_date >= month_start,report_date < month_end,+ report_date <= today,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -203,19 +360,33 @@ async def get_summary(monthly_income += shared_incomemonthly_expenses += shared_expenses- # Save real-only totals before adding projections (used for primary init)+ # Keep actual and forecast totals separate. Pending rows, future-dated+ # installments and generate-ahead rows belong only to the projected view.real_monthly_income = monthly_incomereal_monthly_expenses = monthly_expenses+ projected_monthly_income = real_monthly_income+ projected_monthly_expenses = real_monthly_expenses# Add virtual recurring projectionsprojections = await _get_recurring_projections(session, workspace_id, month_start, month_end, account_ids)+ forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, month_start, month_end, account_ids,+ range_date_col=report_date,+ )for proj in projections:if proj["type"] == "credit":- monthly_income += proj["amount"]+ projected_monthly_income += proj["amount"]+ else:+ projected_monthly_expenses += proj["amount"]+ for tx in forecast_transactions:+ if not _counts_as_user_pnl_row(tx):+ continue+ if tx.type == "credit":+ projected_monthly_income += float(tx.amount)else:- monthly_expenses += proj["amount"]+ projected_monthly_expenses += float(tx.amount)# Account count — the active collection's accounts when filtered, else all# accounts in this workspace (manual + bank-connected).@@ -267,6 +438,7 @@ async def get_summary(# Add asset values to total balancefor currency, amount in assets_value.items():total_balance[currency] = total_balance.get(currency, 0.0) + amount+ projected_balance[currency] = projected_balance.get(currency, 0.0) + amount# Convert totals to primary currencytotal_balance_primary = 0.0@@ -274,6 +446,11 @@ async def get_summary(converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency, cutoff)total_balance_primary += float(converted)+ projected_balance_primary = 0.0+ for currency, amount in projected_balance.items():+ converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency, cutoff)+ projected_balance_primary += float(converted)+# Convert income/expenses to primary currency using amount_primary when available# Use real-only totals (without projections) to avoid double-counting;# projections are added separately below via convert().@@ -293,6 +470,7 @@ async def get_summary(Account.is_closed == False,report_date >= month_start,report_date < month_end,+ report_date <= today,Transaction.source != "opening_balance",Transaction.status == "posted",counts_as_user_pnl(),@@ -357,6 +535,8 @@ async def get_summary(Transaction.source != "opening_balance",report_date >= month_start,report_date < month_end,+ report_date <= today,+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(Transaction.currency)@@ -376,16 +556,32 @@ async def get_summary()monthly_expenses_primary += abs(float(debit_pri))- # Add recurring projections to primary totals (convert each)+ projected_income_primary = monthly_income_primary+ projected_expenses_primary = monthly_expenses_primary++ # Add recurring projections to primary forecast totals (convert each)for proj in projections:proj_converted, _ = await convert(session, Decimal(str(proj["amount"])),proj["currency"], primary_currency,)if proj["type"] == "credit":- monthly_income_primary += float(proj_converted)+ projected_income_primary += float(proj_converted)else:- monthly_expenses_primary += float(proj_converted)+ projected_expenses_primary += float(proj_converted)+ for tx in forecast_transactions:+ if not _counts_as_user_pnl_row(tx):+ continue+ if tx.amount_primary is not None:+ forecast_converted = Decimal(str(tx.amount_primary))+ else:+ forecast_converted, _ = await convert(+ session, Decimal(str(tx.amount)), tx.currency, primary_currency,+ )+ if tx.type == "credit":+ projected_income_primary += abs(float(forecast_converted))+ else:+ projected_expenses_primary += abs(float(forecast_converted))# Aggregate the user's net pending balance across all groups they# participate in. We reuse the group balance computation so partial@@ -401,11 +597,17 @@ async def get_summary(return DashboardSummary(total_balance=total_balance,total_balance_primary=round(total_balance_primary, 2),+ projected_balance=projected_balance,+ projected_balance_primary=round(projected_balance_primary, 2),balance_date=cutoff.isoformat(),- monthly_income=monthly_income,- monthly_expenses=abs(monthly_expenses),+ monthly_income=real_monthly_income,+ monthly_expenses=abs(real_monthly_expenses),monthly_income_primary=round(monthly_income_primary, 2),monthly_expenses_primary=round(monthly_expenses_primary, 2),+ projected_income=projected_monthly_income,+ projected_expenses=abs(projected_monthly_expenses),+ projected_income_primary=round(projected_income_primary, 2),+ projected_expenses_primary=round(projected_expenses_primary, 2),accounts_count=accounts_count,pending_categorization=pending_categorization,pending_categorization_amount=pending_categorization_amount,@@ -494,6 +696,7 @@ async def get_spending_by_category(month = date.today().replace(day=1)month_start, month_end = _month_range(month)+ today = date.today()filtered = account_ids is not Noneacct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []@@ -521,6 +724,8 @@ async def get_spending_by_category(Transaction.type == "debit",report_date >= month_start,report_date < month_end,+ report_date <= today,+ Transaction.status == "posted",counts_as_user_pnl(),*acct_filter,)@@ -537,6 +742,7 @@ async def get_spending_by_category("icon": row[2] or "circle-help","color": row[3] or "#6B7280","total": abs(float(row[4] or 0)),+ "projected": 0.0,}# Subtract non-owner shares per category — owner-side splits should@@ -595,6 +801,7 @@ async def get_spending_by_category("icon": meta["icon"],"color": meta["color"],"total": share_total,+ "projected": 0.0,}# Add virtual recurring projections (debit only), converted to primary currency@@ -626,17 +833,58 @@ async def get_spending_by_category(proj_amount_float = float(proj_amount)if cat_id in spending_map:- spending_map[cat_id]["total"] += proj_amount_float+ spending_map[cat_id]["projected"] += proj_amount_floatelse:info = cat_cache.get(cat_id, {"name": "Sem categoria", "icon": "circle-help", "color": "#6B7280"})spending_map[cat_id] = {"name": info["name"],"icon": info["icon"],"color": info["color"],- "total": proj_amount_float,+ "total": 0.0,+ "projected": proj_amount_float,}- # Convert to list and compute percentages+ # Pending and future-dated real transactions are forecast rows. They are+ # deliberately layered after posted actuals, alongside recurring rules.+ forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, month_start, month_end, account_ids,+ range_date_col=report_date,+ )+ for tx in forecast_transactions:+ if tx.type != "debit" or tx.is_ignored:+ continue+ category = tx.category+ if not _counts_as_user_pnl_row(tx):+ continue+ cat_id = str(tx.category_id) if tx.category_id else None+ if cat_id and cat_id not in cat_cache:+ cat_cache[cat_id] = {+ "name": category.name if category else "Sem categoria",+ "icon": category.icon if category else "circle-help",+ "color": category.color if category else "#6B7280",+ }+ if tx.amount_primary is not None:+ projected_amount = float(abs(tx.amount_primary))+ else:+ amount, _ = await convert(+ session,+ Decimal(str(abs(tx.amount))),+ tx.currency,+ primary_currency,+ )+ projected_amount = float(amount)+ if cat_id in spending_map:+ spending_map[cat_id]["projected"] += projected_amount+ else:+ info = cat_cache.get(+ cat_id,+ {"name": "Sem categoria", "icon": "circle-help", "color": "#6B7280"},+ )+ spending_map[cat_id] = {**info, "total": 0.0, "projected": projected_amount}++ # `total` stays posted-only so the breakdown adds up to the expenses card,+ # which is also posted-only. The forecast rides along in `projected_total`+ # (actual + forecast) for callers that want the same split the card shows.grand_total = sum(entry["total"] for entry in spending_map.values())spending = []for cat_id, entry in sorted(spending_map.items(), key=lambda x: x[1]["total"], reverse=True):@@ -646,6 +894,7 @@ async def get_spending_by_category(category_icon=entry["icon"],category_color=entry["color"],total=entry["total"],+ projected_total=entry["total"] + entry.get("projected", 0.0),percentage=(entry["total"] / grand_total * 100) if grand_total else 0,))@@ -661,6 +910,7 @@ async def get_monthly_trend() -> list[MonthlyTrend]:filtered = account_ids is not Noneacct_filter = [Transaction.account_id.in_(account_ids)] if filtered else []+ today = date.today()accounting_mode = await get_credit_card_accounting_mode(session)report_date = reporting_date_col(accounting_mode)month_label = func.to_char(report_date, 'YYYY-MM').label('month')@@ -676,6 +926,8 @@ async def get_monthly_trend(Transaction.workspace_id == workspace_id,Account.is_closed == False,Transaction.source != "opening_balance",+ report_date <= today,+ Transaction.status == "posted",counts_as_user_pnl(),*acct_filter,)@@ -687,9 +939,51 @@ async def get_monthly_trend(user = await session.get(User, user_id)primary_currency = user.primary_currency if user else get_settings().default_currency- trends_raw: list[tuple[str, float, float]] = []+ trend_map: dict[str, list[float]] = {}for row in result.all():- trends_raw.append((row[0], float(row[1] or 0), abs(float(row[2] or 0))))+ trend_map[row[0]] = [float(row[1] or 0), abs(float(row[2] or 0))]++ # Keep the dashboard trend's current month useful even when its only+ # activity is still pending or future-dated. Those rows are forecast data,+ # not actuals, but this endpoint has no separate actual/projected series.+ forecast_start = today.replace(day=1)+ for _ in range(max(months - 1, 0)):+ forecast_start = (+ forecast_start.replace(year=forecast_start.year - 1, month=12)+ if forecast_start.month == 1+ else forecast_start.replace(month=forecast_start.month - 1)+ )+ forecast_end = _month_range(today.replace(day=1))[1]+ forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, forecast_start, forecast_end, account_ids,+ range_date_col=report_date,+ )+ for tx in forecast_transactions:+ if not _counts_as_user_pnl_row(tx):+ continue+ tx_report_date = (+ tx.effective_bill_date+ or (tx.effective_date if accounting_mode == "accrual" else tx.date)+ )+ month_key = f"{tx_report_date.year:04d}-{tx_report_date.month:02d}"+ bucket = trend_map.setdefault(month_key, [0.0, 0.0])+ if tx.amount_primary is not None:+ amount = abs(float(tx.amount_primary))+ else:+ converted, _ = await convert(+ session, Decimal(str(abs(tx.amount))), tx.currency, primary_currency,+ )+ amount = abs(float(converted))+ if tx.type == "credit":+ bucket[0] += amount+ else:+ bucket[1] += amount++ trends_raw = sorted(+ ((month, values[0], values[1]) for month, values in trend_map.items()),+ key=lambda row: row[0],+ reverse=True,+ )[:months]# Subtract owner non-owner-share offsets per month, and add the# viewer's shares of others' splits.@@ -732,37 +1026,63 @@ async def get_projected_transactions(workspace_id: uuid.UUID,user_id: uuid.UUID,month: Optional[date] = None,+ *,+ account_id: Optional[uuid.UUID] = None,+ from_date: Optional[date] = None,+ to_date: Optional[date] = None,) -> list[ProjectedTransaction]:"""Return virtual recurring transaction projections for a month,- enriched with description and category info for display."""- if not month:- month = date.today().replace(day=1)+ enriched with description and category info for display.- month_start, month_end = _month_range(month)+ A date range is inclusive at the API boundary. It is useful for Account+ Detail, while the month argument remains the compact dashboard contract.++ Transfer-like rules stay in: this lists upcoming movements rather than+ P&L, and an investment contribution is money that will leave the account.+ The P&L-shaped callers exclude them on their own side, through+ ``_get_recurring_projections(include_transfer_like=False)``.+ """+ if (from_date is None) != (to_date is None):+ raise ValueError("from_date and to_date must be provided together")+ if from_date and to_date:+ if from_date > to_date:+ raise ValueError("from_date must be before or equal to to_date")+ range_start, range_end = from_date, to_date + timedelta(days=1)+ else:+ if not month:+ month = date.today().replace(day=1)+ range_start, range_end = _month_range(month)# Get user's primary currency for live conversionuser = await session.get(User, user_id)primary_currency = user.primary_currency if user else get_settings().default_currency- result = await session.execute(+ stmt = (select(RecurringTransaction).outerjoin(Category, RecurringTransaction.category_id == Category.id).where(RecurringTransaction.workspace_id == workspace_id,RecurringTransaction.is_active == True,- RecurringTransaction.start_date < month_end + timedelta(days=2),- or_(- RecurringTransaction.category_id.is_(None),- Category.treat_as_transfer.is_not(True),- ),+ RecurringTransaction.start_date < range_end + timedelta(days=2),or_(RecurringTransaction.category_id.is_(None),Category.is_ignored.is_not(True),),))+ if account_id is not None:+ stmt = stmt.where(RecurringTransaction.account_id == account_id)+ result = await session.execute(stmt)recurring_list = list(result.scalars().all())+ materialized_occurrences = await _materialized_recurring_occurrences(+ session,+ workspace_id,+ {rec.id for rec in recurring_list},+ range_start,+ range_end,+ )+# Pre-fetch categories for all recurring templates that have onecat_ids = {r.category_id for r in recurring_list if r.category_id}cat_map: dict[uuid.UUID, tuple[str, str, str]] = {}@@ -780,24 +1100,32 @@ async def get_projected_transactions(start=rec.next_occurrence,frequency=rec.frequency,end_date=rec.end_date,- range_start=month_start,- range_end=month_end,+ range_start=range_start,+ range_end=range_end,intended_day=rec.day_of_month or rec.start_date.day,weekend_adjustment=rec.weekend_adjustment,)cat_name, cat_icon, cat_color = cat_map.get(rec.category_id, (None, None, None)) if rec.category_id else (None, None, None)- # Convert to primary currency at current rate (consistent with summary)+ # Convert to primary currency at the latest real rate. A missing rate+ # stays unknown; virtual projections must never manufacture a 1:1+ # conversion just to render a number.amt_primary = Noneif rec.currency != primary_currency:- converted, _ = await convert(- session, Decimal(str(rec.amount)), rec.currency, primary_currency,+ rate = await _resolve_rate(+ session, rec.currency, primary_currency,)- amt_primary = float(converted)+ if rate is not None:+ amt_primary = float(+ (Decimal(str(rec.amount)) * rate).quantize(Decimal("0.01"))+ )for occ_date in occurrences:+ if (rec.id, occ_date) in materialized_occurrences:+ continueprojections.append(ProjectedTransaction(recurring_id=str(rec.id),+ account_id=str(rec.account_id) if rec.account_id else None,description=rec.description,amount=float(rec.amount),amount_primary=amt_primary,@@ -829,6 +1157,32 @@ def _signed_balance_expr(account_currency: str = ""):)+def _signed_transaction_amount(tx: Transaction) -> float:+ """Return a loaded transaction's signed amount in its account currency."""+ account_currency = tx.account.currency if tx.account else tx.currency+ amount = (+ tx.amount+ if tx.currency == account_currency+ else (tx.amount_primary or tx.amount)+ )+ signed = amount if tx.type == "credit" else -amount+ return float(signed)+++async def _signed_forecast_amount_primary(+ session: AsyncSession, tx: Transaction, primary_currency: str+) -> float:+ """Convert a loaded forecast row's signed account amount to primary."""+ account_currency = tx.account.currency if tx.account else tx.currency+ converted, _ = await convert(+ session,+ Decimal(str(_signed_transaction_amount(tx))),+ account_currency,+ primary_currency,+ )+ return float(converted)++def _primary_amount_expr():"""Amount in primary currency: uses amount_primary when available, falls back to amount."""return func.coalesce(Transaction.amount_primary, Transaction.amount)@@ -874,19 +1228,33 @@ async def _get_open_accounts(async def _account_balance_at(- session: AsyncSession, account: Account, cutoff: date+ session: AsyncSession,+ account: Account,+ cutoff: date,+ *,+ include_pending: bool = False,) -> float:"""Get balance for a single account at a specific date.- For bank-connected accounts, backtrack from the provider's current balance- by subtracting transaction deltas that occurred after the cutoff.- For manual accounts, sum transactions up to the cutoff date.+ The default is the current/posted view: pending rows and future-dated rows+ do not affect it. Connected accounts are the one explicit exception at the+ current cutoff: their provider balance is returned verbatim so it keeps+ matching the bank app. Forecast callers add pending/future rows separately."""+ today = date.today()+ balance_cutoff = min(cutoff, today)if account.connection_id:# Start from the provider's authoritative current balancecurrent_bal = float(account.balance)if account.type == "credit_card":current_bal = -current_bal++ # The provider number is the source of truth for the current balance,+ # including whatever pending entries the provider happens to include.+ if cutoff >= today:+ return current_bal++ status_filter = [] if include_pending else [Transaction.status == "posted"]# Subtract activity after cutoff to get the balance AT cutoff# Exclude ignored transactions from balance calculationdelta_after = await session.scalar(@@ -895,24 +1263,48 @@ async def _account_balance_at(.where(Transaction.account_id == account.id,Transaction.date > cutoff,+ Transaction.date <= today,Transaction.is_ignored == False,+ *status_filter,or_(Transaction.category_id.is_(None),Category.is_ignored == False,),))- return current_bal - float(delta_after or 0)+ historical = current_bal - float(delta_after or 0)+ if not include_pending:+ # Provider snapshots can include pending rows. Remove those from+ # historical posted-only snapshots; the current snapshot above is+ # intentionally left untouched to preserve provider parity.+ pending_delta = await session.scalar(+ select(func.coalesce(func.sum(_signed_balance_expr(account.currency)), 0))+ .outerjoin(Category, Transaction.category_id == Category.id)+ .where(+ Transaction.account_id == account.id,+ Transaction.date <= today,+ Transaction.status == "pending",+ Transaction.is_ignored == False,+ or_(+ Transaction.category_id.is_(None),+ Category.is_ignored == False,+ ),+ )+ )+ historical -= float(pending_delta or 0)+ return historicalelse:# Manual: sum signed transactions up to cutoff# Exclude ignored transactions from balance calculation+ status_filter = [] if include_pending else [Transaction.status == "posted"]result = await session.scalar(select(func.coalesce(func.sum(_signed_balance_expr(account.currency)), 0)).outerjoin(Category, Transaction.category_id == Category.id).where(Transaction.account_id == account.id,- Transaction.date <= cutoff,+ Transaction.date <= balance_cutoff,Transaction.is_ignored == False,+ *status_filter,or_(Transaction.category_id.is_(None),Category.is_ignored == False,@@ -925,12 +1317,16 @@ async def _account_balance_at(async def _total_balance_by_currency(session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,account_ids: Optional[list[uuid.UUID]] = None,+ *,+ include_pending: bool = False,) -> dict[str, float]:"""Get total balance across all open accounts at a date, grouped by currency."""accounts = await _get_open_accounts(session, workspace_id, account_ids)totals: dict[str, float] = {}for account in accounts:- bal = await _account_balance_at(session, account, cutoff)+ bal = await _account_balance_at(+ session, account, cutoff, include_pending=include_pending+ )totals[account.currency] = totals.get(account.currency, 0) + balreturn totals@@ -939,13 +1335,16 @@ async def _balance_at(session: AsyncSession, workspace_id: uuid.UUID, cutoff: date,*, primary_currency_hint: Optional[str] = None,account_ids: Optional[list[uuid.UUID]] = None,+ include_pending: bool = False,) -> float:"""Get total balance across all open accounts at a specific date, converted to primary currency.`primary_currency_hint` lets callers avoid an extra User lookup when theyalready know the workspace's primary currency."""- totals = await _total_balance_by_currency(session, workspace_id, cutoff, account_ids)+ totals = await _total_balance_by_currency(+ session, workspace_id, cutoff, account_ids, include_pending=include_pending+ )if not totals:return 0.0@@ -969,6 +1368,7 @@ async def _daily_balance_deltas_by_date(*,primary_currency_hint: Optional[str] = None,account_ids: Optional[list[uuid.UUID]] = None,+ include_pending: bool = False,) -> dict[date, float]:"""Get daily balance deltas for a date range [start, end), keyed by date.@@ -985,6 +1385,7 @@ async def _daily_balance_deltas_by_date((Transaction.type == "credit", effective),else_=-effective,)+ status_filter = [] if include_pending else [Transaction.status == "posted"]result = await session.execute(select(Transaction.date,@@ -998,7 +1399,9 @@ async def _daily_balance_deltas_by_date(Account.is_closed == False,Transaction.date >= start,Transaction.date < end,+ Transaction.date <= date.today(),Transaction.is_ignored == False,+ *status_filter,or_(Transaction.category_id.is_(None),Category.is_ignored == False,@@ -1027,6 +1430,7 @@ async def _daily_deltas(*,primary_currency_hint: Optional[str] = None,account_ids: Optional[list[uuid.UUID]] = None,+ include_pending: bool = False,) -> dict[int, float]:"""Get daily balance deltas for a date range [start, end), keyed by day-of-month."""by_date = await _daily_balance_deltas_by_date(@@ -1036,6 +1440,7 @@ async def _daily_deltas(end,primary_currency_hint=primary_currency_hint,account_ids=account_ids,+ include_pending=include_pending,)return {tx_date.day: amount for tx_date, amount in by_date.items()}@@ -1089,7 +1494,46 @@ async def get_balance_history(# Recurring projections for future days of current month (converted to primary currency)proj_deltas: dict[int, float] = {}if month_end > today:+ # A future month's chart starts from the posted-only current balance.+ # Carry forecast rows dated before that month into its projected+ # opening position. Connected accounts are the one exception: their+ # provider snapshot is authoritative and may already include pending+ # rows dated today or earlier.+ if month_start > today:+ carried_forecasts = await _get_forecast_transactions(+ session, workspace_id, date.min, month_start, account_ids+ )+ for tx in carried_forecasts:+ if tx.is_ignored or (tx.category and tx.category.is_ignored):+ continue+ if tx.account and tx.account.connection_id and tx.status == "pending" and tx.date <= today:+ continue+ current_start += await _signed_forecast_amount_primary(+ session, tx, primary_currency+ )+proj_start = max(month_start, today + timedelta(days=1))+ forecast_transactions = await _get_forecast_transactions(+ session,+ workspace_id,+ proj_start,+ month_end,+ account_ids,+ )+ for tx in forecast_transactions:+ if tx.is_ignored or (tx.category and tx.category.is_ignored):+ continue+ amount = _signed_transaction_amount(tx)+ if tx.account and tx.account.connection_id and tx.date <= today:+ continue+ converted, _ = await convert(+ session,+ Decimal(str(amount)),+ tx.account.currency if tx.account else tx.currency,+ primary_currency,+ )+ proj_deltas[tx.date.day] = proj_deltas.get(tx.date.day, 0) + float(converted)+projections = await _get_recurring_projections(session, workspace_id, proj_start, month_end, account_ids)diff --git a/backend/app/services/fx_rate_service.py b/backend/app/services/fx_rate_service.pyindex 5b22bd34..758b59fb 100644--- a/backend/app/services/fx_rate_service.py+++ b/backend/app/services/fx_rate_service.py@@ -27,7 +27,11 @@ async def sync_rates(Idempotent — existing rates for the same date are updated.Returns the number of rates synced."""- target = target_date or date.today()+ requested_target = target_date or date.today()+ # Providers cannot return a historical rate for a date that has not+ # happened yet. Treat a future request as a request for today's latest+ # published rate and store it under today's date.+ target = min(requested_target, date.today())supported = set(get_settings().supported_currencies.split(","))if target == date.today():@@ -78,7 +82,11 @@ async def _resolve_rate(if from_currency == to_currency:return Decimal("1")- target = target_date or date.today()+ requested_target = target_date or date.today()+ # A future transaction must use the latest real rate, never query a+ # not-yet-existing historical snapshot. Looking up against today also+ # lets the closest-rate fallback select the last cached business day.+ target = min(requested_target, date.today())# Step 1: Try exact dateusd_to_source = await _get_exact_date_rate(session, from_currency, target)diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.pyindex 896e6bf4..2a509dc2 100644--- a/backend/app/services/recurring_transaction_service.py+++ b/backend/app/services/recurring_transaction_service.py@@ -285,6 +285,25 @@ async def generate_pending(if existing_real is not None:existing_real.recurring_transaction_id = recurring.idelse:+ account = await session.get(Account, recurring.account_id)+ # Only occurrences that already came due reach this point, so+ # the row is a charge that happened rather than a forecast.+ # Whether to trust that depends on who else writes to the+ # account:+ #+ # Bank-synced: the incoming charge often fails to match this+ # placeholder, and two posted rows for one charge inflate the+ # balance silently. Holding the placeholder as pending keeps+ # it out of the actuals until something confirms it, so a+ # missed match costs a visible stale row instead of a wrong+ # number. Improving the match itself is the real fix (#588);+ # this is the guard until then.+ #+ # Manual: nothing else ever writes to the account, so there is+ # no charge to duplicate against and nothing that would ever+ # post the row. Pending there buys no safety and stops the+ # balance from moving.+ is_synced_account = account is not None and account.connection_id is not Nonetransaction = Transaction(user_id=user_id,account_id=recurring.account_id,@@ -295,9 +314,9 @@ async def generate_pending(date=effective_occurrence,type=recurring.type,source="recurring",+ status="pending" if is_synced_account else "posted",recurring_transaction_id=recurring.id,)- account = await session.get(Account, recurring.account_id)apply_effective_date(transaction, account)session.add(transaction)await session.flush()diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 6d932002..9d2e958b 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -32,7 +32,12 @@ from app.schemas.report import (ReportResponse,ReportSummary,)-from app.services.dashboard_service import _get_open_accounts, _account_balance_at+from app.services.dashboard_service import (+ _account_balance_at,+ _counts_as_user_pnl_row,+ _get_forecast_transactions,+ _get_open_accounts,+)CATEGORY_TREND_TOP_N = 11@@ -411,6 +416,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_user_pnl(),*acct_filter,)@@ -418,7 +424,9 @@ async def get_income_expenses_report(.order_by(label_expr))- # Build data map from query results+ # Build the actual (posted-only) data map. Forecast rows are kept in a+ # separate map below so the report can expose the same distinction as+ # balances: actual income/expenses never silently absorb pending entries.data_map: dict[str, tuple[float, float]] = {}for row in result.all():income = float(row[1] or 0)@@ -468,6 +476,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(label_expr, Transaction.currency)@@ -531,6 +540,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(label_expr, Transaction.currency)@@ -556,6 +566,8 @@ async def get_income_expenses_report(existing_expenses + share_expenses_pri,)+ forecast_map: dict[str, tuple[float, float]] = {}+# Add recurring projections for each month in the range (consistent with dashboard)from app.services.dashboard_service import _month_range, _get_recurring_projections@@ -574,11 +586,35 @@ async def get_income_expenses_report()proj_amount = float(converted)label = _format_date_label(cursor, interval)- existing_income, existing_expenses = data_map.get(label, (0.0, 0.0))+ existing_income, existing_expenses = forecast_map.get(label, (0.0, 0.0))if proj["type"] == "credit":- data_map[label] = (existing_income + proj_amount, existing_expenses)+ forecast_map[label] = (existing_income + proj_amount, existing_expenses)+ else:+ forecast_map[label] = (existing_income, existing_expenses + proj_amount)+ forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, max(m_start, start), m_end, account_ids,+ range_date_col=report_date,+ )+ for tx in forecast_transactions:+ if not _counts_as_user_pnl_row(tx):+ continue+ if tx.amount_primary is not None:+ amount = abs(float(tx.amount_primary))+ else:+ converted, _ = await fx_convert(+ session, Decimal(str(abs(tx.amount))), tx.currency, primary_currency,+ )+ amount = abs(float(converted))+ tx_report_date = (+ tx.effective_bill_date+ or (tx.effective_date if accounting_mode == "accrual" else tx.date)+ )+ label = _format_date_label(tx_report_date, interval)+ existing_income, existing_expenses = forecast_map.get(label, (0.0, 0.0))+ if tx.type == "credit":+ forecast_map[label] = (existing_income + amount, existing_expenses)else:- data_map[label] = (existing_income, existing_expenses + proj_amount)+ forecast_map[label] = (existing_income, existing_expenses + amount)# Advance to next monthif cursor.month == 12:cursor = date(cursor.year + 1, 1, 1)@@ -590,10 +626,10 @@ async def get_income_expenses_report(trend: list[ReportDataPoint] = []total_income = 0.0total_expenses = 0.0-for point in points:label = _format_date_label(point, interval)income, expenses = data_map.get(label, (0.0, 0.0))+ forecast_income, forecast_expenses = forecast_map.get(label, (0.0, 0.0))net = round(income - expenses, 2)total_income += incometotal_expenses += expenses@@ -603,9 +639,18 @@ async def get_income_expenses_report(breakdowns={"income": round(income, 2),"expenses": round(expenses, 2),+ "projectedIncome": round(forecast_income, 2),+ "projectedExpenses": round(forecast_expenses, 2),},))+ # A daily report's visible axis ends today, but the monthly forecast query+ # can still contain future installments/generate-ahead rows in the current+ # month. Keep those rows in the projected summary even when they have no+ # historical point to render yet.+ projected_income = sum(income for income, _ in forecast_map.values())+ projected_expenses = sum(expenses for _, expenses in forecast_map.values())+total_net = round(total_income - total_expenses, 2)# Compare last point vs first point net income@@ -635,6 +680,18 @@ async def get_income_expenses_report(value=round(total_expenses, 2),color="#F43F5E",),+ ReportBreakdown(+ key="projectedIncome",+ label="Projected Income",+ value=round(projected_income, 2),+ color="#34D399",+ ),+ ReportBreakdown(+ key="projectedExpenses",+ label="Projected Expenses",+ value=round(projected_expenses, 2),+ color="#FB7185",+ ),ReportBreakdown(key="netIncome",label="Net Income",@@ -646,7 +703,7 @@ async def get_income_expenses_report(meta = ReportMeta(type="income_expenses",- series_keys=["income", "expenses"],+ series_keys=["income", "expenses", "projectedIncome", "projectedExpenses"],currency=primary_currency,interval=interval,)@@ -669,6 +726,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_user_pnl(),*acct_filter,)@@ -732,6 +790,7 @@ async def get_income_expenses_report(report_date <= today,Transaction.source != "opening_balance",Transaction.type == "debit",+ Transaction.status == "posted",Transaction.transfer_pair_id.is_(None),Transaction.is_ignored.is_(False),Category.treat_as_transfer.is_(True),@@ -769,6 +828,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_user_pnl(),*acct_filter,)@@ -816,6 +876,7 @@ async def get_income_expenses_report(report_date >= start,report_date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_user_pnl(),).group_by(label_expr, Transaction.category_id, Transaction.currency)@@ -896,6 +957,61 @@ async def get_income_expenses_report(cat_trend_map[comp_key]["periods"].get(period_label, 0.0) + proj_amount)+ forecast_transactions = await _get_forecast_transactions(+ session, workspace_id, m_start, m_end, account_ids,+ range_date_col=report_date,+ )+ for tx in forecast_transactions:+ if not _counts_as_user_pnl_row(tx):+ continue+ cat_id_str = str(tx.category_id) if tx.category_id else "uncategorized"+ group = "income" if tx.type == "credit" else "expenses"+ tx_report_date = (+ tx.effective_bill_date+ or (tx.effective_date if accounting_mode == "accrual" else tx.date)+ )+ forecast_period_label = _format_date_label(tx_report_date, interval)+ if cat_id_str != "uncategorized" and cat_id_str not in cat_cache:+ cat_row = await session.execute(+ select(Category.name, Category.color).where(Category.id == tx.category_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"}+ )+ if tx.amount_primary is not None:+ forecast_amount = abs(float(tx.amount_primary))+ else:+ converted, _ = await fx_convert(+ session, Decimal(str(abs(tx.amount))), tx.currency, primary_currency,+ )+ forecast_amount = abs(float(converted))+ comp_key = (cat_id_str, group)+ if comp_key in comp_map:+ comp_map[comp_key]["value"] += forecast_amount+ else:+ comp_map[comp_key] = {+ "label": info["label"],+ "color": info["color"],+ "value": forecast_amount,+ }+ if comp_key not in cat_trend_map:+ cat_trend_map[comp_key] = {+ "label": info["label"],+ "color": info["color"],+ "total": 0.0,+ "periods": {},+ }+ cat_trend_map[comp_key]["total"] += forecast_amount+ cat_trend_map[comp_key]["periods"][forecast_period_label] = (+ cat_trend_map[comp_key]["periods"].get(forecast_period_label, 0.0)+ + forecast_amount+ )+if cursor2.month == 12:cursor2 = date(cursor2.year + 1, 1, 1)else:@@ -1042,6 +1158,7 @@ async def _get_baseline_projection(Account.is_closed == False,Transaction.date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_pnl(),*acct_filter,)@@ -1065,6 +1182,7 @@ async def _get_baseline_projection(Transaction.date >= window_start,Transaction.date <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_pnl(),*acct_filter,)@@ -1201,6 +1319,7 @@ async def get_cash_flow_report(flow_date_col > chart_start,flow_date_col <= today,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_pnl(),*acct_filter,)@@ -1230,6 +1349,7 @@ async def get_cash_flow_report(flow_date_col > today,flow_date_col <= end,Transaction.source != "opening_balance",+ Transaction.status == "posted",counts_as_pnl(),*acct_filter,)@@ -1244,42 +1364,60 @@ async def get_cash_flow_report(continue_add_flow(flow_date, abs(amount_primary), tx_type == "credit")- # 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(- Transaction.type,- Transaction.amount,- Transaction.amount_primary,- Transaction.currency,- )- .join(Account, Transaction.account_id == Account.id)- .where(- Transaction.workspace_id == workspace_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(),- *acct_filter,- )- )- for tx_type, amt, amt_primary, ccy in pending_cc.all():- if amt_primary is not None:- amount_primary = float(amt_primary)+ # 2. Pending rows are forecast rows. They never enter the past/actual+ # section, including pending credit-card purchases in accrual mode.+ # Use the effective bill date when cash leaves on the card's due date.+ # Pending rows whose forecast date is already past still belong to the+ # payable position today, so carry them into the forward projected walk+ # instead of silently dropping them.+ pending_current_delta = 0.0+ pending_forecast = await _get_forecast_transactions(+ session, workspace_id, date.min, end + timedelta(days=1), account_ids,+ range_date_col=flow_date_col,+ )+ for tx in pending_forecast:+ if tx.status != "pending" or not _counts_as_user_pnl_row(tx):+ continue+ flow_date = tx.effective_bill_date or (tx.effective_date if accrual else tx.date)+ if flow_date > end:+ continue+ if tx.amount_primary is not None:+ amount_primary = abs(float(tx.amount_primary))+ else:+ amount_primary = await _to_primary(Decimal(str(abs(tx.amount))), tx.currency)+ if amount_primary:+ if flow_date <= today:+ # A connected account's provider number is authoritative and+ # may already include this pending row. Keep provider parity+ # rather than guessing whether it was included.+ if not (tx.account and tx.account.connection_id):+ pending_current_delta += amount_primary if tx.type == "credit" else -amount_primaryelse:- amount_primary = await _to_primary(Decimal(str(amt or 0)), ccy)- if amount_primary == 0:+ _add_flow(flow_date, amount_primary, tx.type == "credit")++ # In accrual mode, a posted card purchase made today is already part of a+ # manual card's liability, while its cash impact belongs on the future bill+ # date. Move that posted amount back into the projected starting position+ # before the booked future flow is applied. Pending rows intentionally do+ # not use this adjustment: their posted-only current balance has excluded+ # them and the generic pending handling above is sufficient.+ if accrual:+ for tx in pending_forecast:+ if tx.status != "posted" or not _counts_as_user_pnl_row(tx):+ continue+ if not tx.account or tx.account.type != "credit_card" or tx.date > today:continue- if tx_type == "debit":- current_balance += abs(amount_primary)+ flow_date = tx.effective_bill_date or tx.effective_date+ if flow_date <= today or flow_date > end:+ continue+ if tx.amount_primary is not None:+ amount_primary = abs(float(tx.amount_primary))+ else:+ amount_primary = await _to_primary(Decimal(str(abs(tx.amount))), tx.currency)+ if tx.type == "debit":+ current_balance += amount_primaryelse:- current_balance -= abs(amount_primary)+ current_balance -= amount_primary# 3. Forward projection. Default: deterministic recurring rules.# Baseline mode: replace them with a historical-mean estimate so the@@ -1334,7 +1472,9 @@ async def get_cash_flow_report(cat_totals[key] = {"label": info["label"], "color": info["color"], "value": 0.0}cat_totals[key]["value"] += amount_primary- # 4. Walk day-by-day. The walk is anchored at today's authoritative+ # 4. Walk day-by-day. The actual section is anchored at today's+ # authoritative balance. The forward projected section starts from that+ # balance plus pending payables already dated today or earlier.# 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@@ -1364,8 +1504,10 @@ async def get_cash_flow_report(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+ # Forward walk: balance(d+1) = balance(d) + net_flow(d+1). Pending rows+ # already due are part of the projected starting position, not a second+ # dated flow in the future.+ running = current_balance + pending_current_deltacursor_d = todaywhile cursor_d < end:cursor_d = cursor_d + timedelta(days=1)diff --git a/backend/app/services/transaction_calendar_service.py b/backend/app/services/transaction_calendar_service.pyindex 55113cfd..6bf0f346 100644--- a/backend/app/services/transaction_calendar_service.py+++ b/backend/app/services/transaction_calendar_service.py@@ -18,7 +18,11 @@ from app.schemas.transaction_calendar import (TransactionCalendarItem,TransactionCalendarResponse,)-from app.services.dashboard_service import _balance_at, _daily_balance_deltas_by_date+from app.services.dashboard_service import (+ _balance_at,+ _daily_balance_deltas_by_date,+ _get_forecast_transactions,+)from app.services.fx_rate_service import convert as fx_convertfrom app.services.recurring_transaction_service import (adjust_weekend_date,@@ -78,8 +82,24 @@ async def get_transaction_calendar(grid_start - timedelta(days=1),primary_currency_hint=primary_currency,account_ids=requested_account_ids,+ include_pending=True,)+ # A future calendar month starts after today's current balance. Carry real+ # forecast rows that fall in the gap into the projected seed, just like+ # virtual recurring occurrences are carried below.+ if grid_start > date.today():+ before_grid_rows = await _get_forecast_transactions(+ session, workspace_id, date.today() + timedelta(days=1), grid_start,+ requested_account_ids,+ )+ for tx in before_grid_rows:+ if tx.is_ignored or (tx.category and tx.category.is_ignored):+ continue+ start_balance += await _signed_balance_delta_primary(+ session, tx, primary_currency+ )+actual_rows = await _load_actual_transactions(session, workspace_id, grid_start, grid_end, requested_account_ids)@@ -122,6 +142,46 @@ async def get_transaction_calendar(day.actual_count += 1day.items.append(_actual_item(tx, amount_primary, is_transfer, ignored))+ forecast_rows = await _get_forecast_transactions(+ session, workspace_id, grid_start, grid_end, requested_account_ids+ )+ forecast_deltas: dict[date, float] = {}+ for tx in forecast_rows:+ if tx.date not in days:+ continue+ day = days[tx.date]+ amount_primary = await _positive_primary_amount(+ session, tx.amount, tx.currency, primary_currency, tx.amount_primary+ )+ is_transfer = bool(tx.transfer_pair_id) or bool(+ tx.category and tx.category.treat_as_transfer+ )+ ignored = bool(tx.is_ignored or (tx.category and tx.category.is_ignored))+ if not ignored:+ if is_transfer or tx.source == "transfer":+ delta = await _signed_balance_delta_primary(session, tx, primary_currency)+ day.transfer_net += delta+ day.projected_transfer_net += delta+ day.has_transfer = True+ elif tx.type == "credit":+ day.income += amount_primary+ day.projected_income += amount_primary+ day.has_income = True+ else:+ day.expense += amount_primary+ day.projected_expense += amount_primary+ day.has_expense = True+ day.projected_count += 1+ day.items.append(_forecast_item(tx, amount_primary, is_transfer, ignored))++ # Forecast rows are excluded from actual deltas but included in the+ # projected walk. The seed already contains forecast rows before the+ # grid; rows inside the grid are applied here.+ if not ignored:+ forecast_deltas[tx.date] = forecast_deltas.get(tx.date, 0.0) + await _signed_balance_delta_primary(+ session, tx, primary_currency+ )+projected_items, projected_deltas, carried_projected_delta = await _project_recurring_items(session,workspace_id,@@ -156,6 +216,8 @@ async def get_transaction_calendar(for delta_date, delta in projected_deltas.items():balance_deltas[delta_date] = balance_deltas.get(delta_date, 0.0) + delta+ for delta_date, delta in forecast_deltas.items():+ balance_deltas[delta_date] = balance_deltas.get(delta_date, 0.0) + deltarunning = start_balanceresponse_days: list[TransactionCalendarDay] = []@@ -234,6 +296,8 @@ async def _load_actual_transactions(Account.is_closed == False,Transaction.date >= start,Transaction.date < end,+ Transaction.date <= date.today(),+ Transaction.status == "posted",).options(selectinload(Transaction.account),@@ -309,6 +373,34 @@ def _actual_item()+def _forecast_item(+ tx: Transaction, amount_primary: float, is_transfer: bool, ignored: bool+) -> TransactionCalendarItem:+ category = tx.category+ account = tx.account+ return TransactionCalendarItem(+ kind="projected",+ id=tx.id,+ date=tx.date,+ description=tx.description,+ amount=float(tx.amount),+ amount_primary=amount_primary,+ currency=tx.currency,+ type=cast(Literal["debit", "credit"], tx.type),+ account_id=tx.account_id,+ account_name=account.display_name or account.name if account else None,+ category_id=tx.category_id,+ category_name=category.name if category else None,+ category_icon=category.icon if category else None,+ category_color=category.color if category else None,+ status=tx.status,+ source=tx.source,+ transfer_pair_id=tx.transfer_pair_id,+ is_transfer=is_transfer,+ is_ignored=ignored,+ )++def _count_occurrences_before(recurring: RecurringTransaction, end: date) -> int:"""Count still-virtual effective occurrences before ``end`` without truncating."""nominal_start = recurring.next_occurrencediff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 261294ad..d4de6248 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -1370,6 +1370,15 @@ async def _apply_update_to_row(has_fx_override = "amount_primary" in update_data or "fx_rate_used" in update_dataoverride_amount_primary = update_data.get("amount_primary")override_fx_rate = update_data.get("fx_rate_used")+ heals_fx_on_post = (+ tx.status == "pending"+ and update_data.get("status") == "posted"+ and (+ tx.amount_primary is None+ or tx.fx_rate_used is None+ or tx.fx_rate_used == 1+ )+ )fx_keys = {"amount_primary", "fx_rate_used"}for key, value in update_data.items():@@ -1392,7 +1401,7 @@ async def _apply_update_to_row(override_amount_primary,override_fx_rate,)- elif needs_restamp:+ elif needs_restamp or heals_fx_on_post:await stamp_primary_amount(session, user_id, tx)# Refresh effective_date when the purchase date, account, or the manualdiff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.pyindex 3d1fcbc6..c6e9115d 100644--- a/backend/tests/test_account_service.py+++ b/backend/tests/test_account_service.py@@ -33,6 +33,7 @@ from app.services.account_service import (get_accounts,reopen_account,serialize_account,+ sync_opening_balance_for_connected_account,update_account,)@@ -68,6 +69,7 @@ async def _add_txn(session: AsyncSession, user_id: uuid.UUID, account_id: uuid.UUID,amount: float, txn_type: str, txn_date: date,source: str = "manual", transfer_pair_id: uuid.UUID | None = None,+ status: str = "posted",) -> Transaction:from datetime import datetime, timezonetxn = Transaction(@@ -79,6 +81,7 @@ async def _add_txn(date=txn_date,type=txn_type,source=source,+ status=status,currency="BRL",transfer_pair_id=transfer_pair_id,created_at=datetime.now(timezone.utc),@@ -771,6 +774,182 @@ async def test_get_account_summary_not_found(session: AsyncSession, test_user, tassert result is None+async def test_get_account_summary_excludes_pending_non_cc(session: AsyncSession, test_user, test_workspace):+ """Non-CC manual accounts exclude pending from current_balance.++ Mirrors the get_accounts behavior: credit 100 posted + debit 20 pending →+ displayed balance is 100 (pending debit dropped), not 80.+ """+ account = await _make_account(session, test_user.id, "Summary Pending")+ today = date.today()+ await _add_txn(session, test_user.id, account.id, 100, "credit", today)+ await _add_txn(session, test_user.id, account.id, 20, "debit", today, status="pending")++ summary = await get_account_summary(session, account.id, test_workspace.id)+ assert summary is not None+ assert summary["current_balance"] == pytest.approx(100.0)+ assert summary["monthly_expenses"] == pytest.approx(0.0)+ assert summary["projected_expenses"] == pytest.approx(20.0)+++async def test_get_account_summary_keeps_pending_for_credit_card(session: AsyncSession, test_user, test_workspace):+ """A card's balance is the debt owed, and an authorized purchase is+ already owed. Keeping pending out would make the balance disagree with+ the card's own bill total, which includes it."""+ account = await _make_account(session, test_user.id, "Summary CC", acc_type="credit_card")+ today = date.today()+ await _add_txn(+ session, test_user.id, account.id, 100, "credit", today,+ source="opening_balance",+ )+ await _add_txn(session, test_user.id, account.id, 20, "debit", today, status="pending")++ summary = await get_account_summary(session, account.id, test_workspace.id)+ assert summary is not None+ # 100 opening minus the 20 authorized purchase.+ assert summary["current_balance"] == pytest.approx(80.0)+ # P&L still waits for the charge to settle.+ assert summary["monthly_expenses"] == pytest.approx(0.0)+ assert summary["projected_expenses"] == pytest.approx(20.0)+++async def test_get_account_summary_opening_balance_connected_excludes_period_pending(+ session, test_user, test_workspace, test_connection+):+ """Connected non-CC opening balance backs out period pending so the+ frontend walk (opening + displayed period rows) does not double count them.++ Provider balance 780 = posted 500 (last month) + posted 300 + pending −20+ (this month). opening_balance must be 500 (= posted before period), not+ 480 (= 780 − posted-in-period, which would leave pending counted twice).+ """+ account = await _make_account(+ session, test_user.id, "Conn Opening", balance="780.00",+ connection_id=test_connection.id,+ )+ today = date.today()+ month_start = today.replace(day=1)+ prev_month = (month_start - timedelta(days=1)).replace(day=1)+ await _add_txn(session, test_user.id, account.id, 500, "credit", prev_month + timedelta(days=5))+ await _add_txn(session, test_user.id, account.id, 300, "credit", month_start + timedelta(days=2))+ pending_day = min(month_start + timedelta(days=4), today)+ await _add_txn(session, test_user.id, account.id, 20, "debit", pending_day, status="pending")++ summary = await get_account_summary(+ session, account.id, test_workspace.id,+ date_from=month_start, date_to=today,+ )+ assert summary is not None+ assert summary["current_balance"] == pytest.approx(780.0)+ assert summary["opening_balance"] == pytest.approx(500.0)+++async def test_get_account_summary_connected_keeps_recurring_pending_in_the_walk(+ session, test_user, test_workspace, test_connection+):+ """A recurring placeholder still moves the projected balance on a+ connected account.++ The provider's 780 covers only what it reported, so backing the+ placeholder out of the opening balance would cancel it against the walk+ that re-applies it: the charge would sit in the forecast totals while the+ projected balance ignored it.+ """+ account = await _make_account(+ session, test_user.id, "Conn Recurring", balance="780.00",+ connection_id=test_connection.id,+ )+ today = date.today()+ month_start = today.replace(day=1)+ prev_month = (month_start - timedelta(days=1)).replace(day=1)+ await _add_txn(session, test_user.id, account.id, 500, "credit", prev_month + timedelta(days=5))+ await _add_txn(session, test_user.id, account.id, 300, "credit", month_start + timedelta(days=2))+ await _add_txn(+ session, test_user.id, account.id, 20, "debit",+ min(month_start + timedelta(days=4), today),+ source="recurring", status="pending",+ )++ summary = await get_account_summary(+ session, account.id, test_workspace.id,+ date_from=month_start, date_to=today,+ )+ assert summary is not None+ # The provider snapshot is untouched.+ assert summary["current_balance"] == pytest.approx(780.0)+ # 780 − 300 posted in period, with the placeholder left in so the frontend+ # walk lands on 760 rather than back on 780.+ assert summary["opening_balance"] == pytest.approx(480.0)+ assert summary["monthly_expenses"] == pytest.approx(0.0)+ assert summary["projected_expenses"] == pytest.approx(20.0)+++async def test_get_account_summary_connected_excludes_future_rows_from_opening_balance(+ session, test_user, test_workspace, test_connection+):+ """Future-dated rows remain projections and do not shift today's opening."""+ account = await _make_account(+ session, test_user.id, "Conn Future Rows", balance="780.00",+ connection_id=test_connection.id,+ )+ today = date.today()+ month_start = today.replace(day=1)+ prev_month = (month_start - timedelta(days=1)).replace(day=1)+ await _add_txn(session, test_user.id, account.id, 500, "credit", prev_month + timedelta(days=5))+ await _add_txn(session, test_user.id, account.id, 300, "credit", month_start + timedelta(days=2))+ await _add_txn(+ session, test_user.id, account.id, 20, "debit",+ min(month_start + timedelta(days=4), today), status="pending",+ )+ await _add_txn(+ session, test_user.id, account.id, 1000, "credit",+ today + timedelta(days=10),+ )++ summary = await get_account_summary(+ session, account.id, test_workspace.id,+ date_from=month_start, date_to=today,+ )++ assert summary is not None+ assert summary["opening_balance"] == pytest.approx(500.0)+++async def test_sync_opening_balance_ignores_future_and_ignored_rows(+ session, test_user, test_workspace, test_connection+):+ """Provider reconciliation uses only active rows dated through today."""+ account = await _make_account(+ session, test_user.id, "Sync Future Rows", balance="600.00",+ connection_id=test_connection.id,+ )+ today = date.today()+ await _add_txn(session, test_user.id, account.id, 500, "credit", today - timedelta(days=5))+ await _add_txn(session, test_user.id, account.id, 1000, "credit", today + timedelta(days=10))+ ignored = await _add_txn(session, test_user.id, account.id, 75, "debit", today - timedelta(days=2))+ ignored.is_ignored = True+ await session.commit()++ await sync_opening_balance_for_connected_account(session, account)+ from sqlalchemy import select+ result = await session.execute(+ select(Transaction).where(+ Transaction.account_id == account.id,+ Transaction.source == "opening_balance",+ )+ )+ opening = result.scalar_one()++ assert opening.type == "credit"+ assert opening.amount == Decimal("100.00")++# ---------------------------------------------------------------------------# get_account_balance_history# ---------------------------------------------------------------------------diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.pyindex c283954d..04f76ff7 100644--- a/backend/tests/test_credit_card_accounting_mode.py+++ b/backend/tests/test_credit_card_accounting_mode.py@@ -1686,14 +1686,15 @@ class TestEffectiveBillDateFiltersList:)@pytest.mark.asyncio- async def test_summary_includes_pending_sync_with_override(+ async def test_summary_forecast_includes_pending_sync_with_override(self, session, test_user, test_workspace, cc_account):"""get_account_summary mirrors get_transactions: a pending sync txwith `effective_bill_date` in the cycle window must contribute to- the totals card and bar chart even when the override doesn't snap- to a bill's due_date (so bill_id stays null). Without this the- strip pill totals diverge from the tx list (issue #162)."""+ the projected totals even when the override doesn't snap to a bill's+ due_date (so bill_id stays null). Actual totals remain posted-only.+ Without this the projected bill total diverges from the tx list+ (issue #162)."""from app.services.account_service import get_account_summaryfrom app.models.credit_card_bill import CreditCardBillfrom datetime import datetime, timezone@@ -1725,7 +1726,8 @@ class TestEffectiveBillDateFiltersList:)assert summary is not None- assert summary["monthly_expenses"] == 105.0+ assert summary["monthly_expenses"] == 0.0+ assert summary["projected_expenses"] == 105.0@pytest.mark.asyncioasync def test_override_past_in_progress_window_lands_in_in_progress(diff --git a/backend/tests/test_dashboard_api.py b/backend/tests/test_dashboard_api.pyindex 23ba3cb7..68017dc2 100644--- a/backend/tests/test_dashboard_api.py+++ b/backend/tests/test_dashboard_api.py@@ -1,9 +1,13 @@"""Tests for dashboard API endpoints."""import calendar+import uuidfrom datetime import date, timedelta+from decimal import Decimalimport pytest+from app.models.transaction import Transaction+def _current_month_str() -> str:"""Return the 1st of the current month as 'YYYY-MM-DD'."""@@ -136,7 +140,8 @@ async def test_dashboard_virtual_recurring_projection()assert cat_spending is not None# At least 4 weekly occurrences in a month = at least 200- assert cat_spending["total"] >= 200.0+ assert cat_spending["total"] == 0.0+ assert cat_spending["projected_total"] >= 200.0# CRITICAL: No transactions should have been created in the DB (virtual projection)# Compute the last day of next month for the query range@@ -160,7 +165,9 @@ async def test_dashboard_virtual_recurring_projection(headers=auth_headers,)assert summary_resp.status_code == 200- assert summary_resp.json()["monthly_expenses"] >= 200.0+ summary = summary_resp.json()+ assert summary["monthly_expenses"] == 0.0+ assert summary["projected_expenses"] >= 200.0@pytest.mark.asyncio@@ -259,7 +266,8 @@ async def test_recurring_projection_respects_end_date((s for s in spending_resp.json() if s["category_id"] == str(test_categories[0].id)), None)assert cat_spending is not None- assert cat_spending["total"] == 60.0+ assert cat_spending["total"] == 0.0+ assert cat_spending["projected_total"] == 60.0@pytest.mark.asyncio@@ -353,10 +361,57 @@ async def test_total_balance_computed_from_transactions(client, auth_headers):@pytest.mark.asyncio-async def test_future_month_balance_includes_recurring_projections(+async def test_pending_and_future_rows_are_current_vs_projected(+ client, auth_headers+):+ """Pending and future rows affect the forecast, never a manual current balance."""+ today = date.today()+ acc_resp = await client.post(+ "/api/accounts",+ json={"name": "Forecast split", "type": "checking", "balance": 1000.00, "currency": "BRL"},+ headers=auth_headers,+ )+ assert acc_resp.status_code == 201+ acc_id = acc_resp.json()["id"]++ for payload in (+ {+ "description": "Pending bank debit",+ "amount": 100.00,+ "currency": "BRL",+ "type": "debit",+ "date": today.isoformat(),+ "status": "pending",+ },+ {+ "description": "Future installment",+ "amount": 200.00,+ "currency": "BRL",+ "type": "debit",+ "date": (today + timedelta(days=3)).isoformat(),+ "status": "posted",+ },+ ):+ payload["account_id"] = acc_id+ tx_resp = await client.post("/api/transactions", json=payload, headers=auth_headers)+ assert tx_resp.status_code == 201++ resp = await client.get(+ "/api/dashboard/summary",+ params={"month": _current_month_str()},+ headers=auth_headers,+ )+ assert resp.status_code == 200+ data = resp.json()+ assert sum(float(v) for v in data["total_balance"].values()) == pytest.approx(1000.0)+ assert sum(float(v) for v in data["projected_balance"].values()) == pytest.approx(700.0)+++async def test_future_month_balance_exposes_recurring_projection_separately(client, auth_headers, test_categories):- """When viewing a future month, total_balance must reflect projected recurring cash flows."""+ """Current balance stays stable while the selected future month is projected."""next_month = _next_month_str()month_after = _future_month_str(2)@@ -394,14 +449,19 @@ async def test_future_month_balance_includes_recurring_projections(assert current_resp.status_code == 200base_total = sum(float(v) for v in current_resp.json()["total_balance"].values())- # Next month: 2000 - 500 (projected rent) = 1500+ # Next month: current remains 2000; the projected month-end value is 1500.next_resp = await client.get("/api/dashboard/summary", params={"month": next_month}, headers=auth_headers)assert next_resp.status_code == 200- next_total = sum(float(v) for v in next_resp.json()["total_balance"].values())- assert next_total == base_total - 500.0, (- f"Next month balance should be 500 less; got {next_total} vs {base_total}"+ next_data = next_resp.json()+ next_total = sum(float(v) for v in next_data["total_balance"].values())+ next_projected = sum(float(v) for v in next_data["projected_balance"].values())+ assert next_total == base_total, (+ f"Future-month current balance should remain unchanged; got {next_total} vs {base_total}"+ )+ assert next_projected == base_total - 500.0, (+ f"Next month projected balance should be 500 less; got {next_projected} vs {base_total}")# Month after: 2000 - 500 - 500 = 1000@@ -409,9 +469,12 @@ async def test_future_month_balance_includes_recurring_projections("/api/dashboard/summary", params={"month": month_after}, headers=auth_headers)assert after_resp.status_code == 200- after_total = sum(float(v) for v in after_resp.json()["total_balance"].values())- assert after_total == base_total - 1000.0, (- f"Month+2 balance should be 1000 less; got {after_total} vs {base_total}"+ after_data = after_resp.json()+ after_total = sum(float(v) for v in after_data["total_balance"].values())+ after_projected = sum(float(v) for v in after_data["projected_balance"].values())+ assert after_total == base_total+ assert after_projected == base_total - 1000.0, (+ f"Month+2 projected balance should be 1000 less; got {after_projected} vs {base_total}")@@ -554,3 +617,187 @@ async def test_balance_date_parameter_overrides_default_cutoff(client, auth_head)total2 = sum(float(v) for v in resp2.json()["total_balance"].values())assert total2 == 700.0, f"Expected 700.0 with default cutoff, got {total2}"+++async def test_projected_transactions_account_id_and_range(client, auth_headers, test_account, test_categories):+ """projected-transactions filters by account_id and an inclusive from/to range."""+ next_month = _next_month_str()++ # Second account via API so we can prove the account_id filter.+ resp = await client.post(+ "/api/accounts",+ headers=auth_headers,+ json={"name": "Conta Investimentos", "type": "wallet", "balance": "0.00", "currency": "BRL"},+ )+ assert resp.status_code == 201+ second_account_id = resp.json()["id"]++ # Recurring on each account, both starting the 1st of next month.+ for account_id, desc in ((str(test_account.id), "Assinatura A"), (second_account_id, "Assinatura B")):+ rec_resp = await client.post(+ "/api/recurring-transactions",+ json={+ "description": desc,+ "amount": 30.00,+ "currency": "BRL",+ "type": "debit",+ "frequency": "monthly",+ "start_date": next_month,+ "category_id": str(test_categories[0].id),+ "account_id": account_id,+ },+ headers=auth_headers,+ )+ assert rec_resp.status_code == 201++ # account_id + inclusive one-day range [1st, 1st] → exactly the 1st occurrence of A.+ filtered = await client.get(+ "/api/dashboard/projected-transactions",+ params={"account_id": str(test_account.id), "from": next_month, "to": next_month},+ headers=auth_headers,+ )+ assert filtered.status_code == 200+ items = filtered.json()+ assert len(items) == 1+ assert items[0]["description"] == "Assinatura A"+ assert items[0]["date"] == next_month++ # Same range without account_id → both accounts project.+ both = await client.get(+ "/api/dashboard/projected-transactions",+ params={"from": next_month, "to": next_month},+ headers=auth_headers,+ )+ assert both.status_code == 200+ assert {p["description"] for p in both.json()} == {"Assinatura A", "Assinatura B"}++ # No params → defaults to the current month, where nothing is projected.+ defaults = await client.get("/api/dashboard/projected-transactions", headers=auth_headers)+ assert defaults.status_code == 200+ assert defaults.json() == []+++async def test_projected_transactions_range_excludes_outside_dates(+ client, auth_headers, test_account, test_categories+):+ """The from/to range is inclusive: dates outside it are not projected."""+ next_month = _next_month_str()+ next_month_date = date.fromisoformat(next_month)+ day_after = (next_month_date + timedelta(days=1)).isoformat()++ rec_resp = await client.post(+ "/api/recurring-transactions",+ json={+ "description": "Aluguel",+ "amount": 900.00,+ "currency": "BRL",+ "type": "debit",+ "frequency": "monthly",+ "start_date": next_month,+ "category_id": str(test_categories[0].id),+ "account_id": str(test_account.id),+ },+ headers=auth_headers,+ )+ assert rec_resp.status_code == 201++ # Range entirely before the occurrence → nothing returned.+ prev_month = _prev_month_str()+ empty = await client.get(+ "/api/dashboard/projected-transactions",+ params={"from": prev_month, "to": prev_month},+ headers=auth_headers,+ )+ assert empty.status_code == 200+ assert empty.json() == []++ # Range covering the 1st and the day after → only the 1st occurrence.+ covering = await client.get(+ "/api/dashboard/projected-transactions",+ params={"from": next_month, "to": day_after},+ headers=auth_headers,+ )+ assert covering.status_code == 200+ assert len(covering.json()) == 1+ assert covering.json()[0]["date"] == next_month+++async def test_projected_transactions_excludes_materialized_occurrence(+ client, auth_headers, session, test_user, test_workspace, test_account,+ test_categories,+):+ """A linked real row replaces, rather than duplicates, its projection."""+ occurrence = _next_month_str()+ rec_resp = await client.post(+ "/api/recurring-transactions",+ json={+ "description": "CXC - Auth0",+ "amount": 13037.13,+ "currency": "BRL",+ "type": "credit",+ "frequency": "monthly",+ "start_date": occurrence,+ "category_id": str(test_categories[0].id),+ "account_id": str(test_account.id),+ },+ headers=auth_headers,+ )+ assert rec_resp.status_code == 201+ recurring_id = uuid.UUID(rec_resp.json()["id"])+ occurrence_date = date.fromisoformat(occurrence)++ session.add(Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=test_account.id,+ category_id=test_categories[0].id,+ description="CXC - Auth0",+ amount=Decimal("13037.13"),+ currency="BRL",+ date=occurrence_date,+ effective_date=occurrence_date,+ type="credit",+ source="recurring",+ status="pending",+ recurring_transaction_id=recurring_id,+ ))+ await session.commit()++ response = await client.get(+ "/api/dashboard/projected-transactions",+ params={"account_id": str(test_account.id), "from": occurrence, "to": occurrence},+ headers=auth_headers,+ )++ assert response.status_code == 200+ assert response.json() == []+++async def test_projected_transactions_from_to_must_be_pair(client, auth_headers, test_account, test_categories):+ """Lone or inverted from/to bounds are rejected with 422."""+ next_month = _next_month_str()++ lone_from = await client.get(+ "/api/dashboard/projected-transactions",+ params={"from": next_month},+ headers=auth_headers,+ )+ assert lone_from.status_code == 422++ lone_to = await client.get(+ "/api/dashboard/projected-transactions",+ params={"to": next_month},+ headers=auth_headers,+ )+ assert lone_to.status_code == 422++ prev_month = _prev_month_str()+ inverted = await client.get(+ "/api/dashboard/projected-transactions",+ params={"from": next_month, "to": prev_month},+ headers=auth_headers,+ )+ assert inverted.status_code == 422diff --git a/backend/tests/test_dashboard_service.py b/backend/tests/test_dashboard_service.pyindex 9e52c7b5..af738fc5 100644--- a/backend/tests/test_dashboard_service.py+++ b/backend/tests/test_dashboard_service.py@@ -600,6 +600,58 @@ async def test_get_projected_transactions_no_category(session: AsyncSession, tesassert proj.category_id is None+async def test_get_projected_transactions_shows_transfer_like_but_not_ignored_categories(+ session: AsyncSession, test_user, test_workspace+):+ """Transfer/investment rows are visible projections without becoming P&L."""+ month_start = date.today().replace(day=1)+ transfer_like = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Investments",+ icon="trending-up",+ color="#0EA5E9",+ treat_as_transfer=True,+ )+ ignored = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Ignored",+ is_ignored=True,+ )+ session.add_all([transfer_like, ignored])+ for description, category_id in (+ ("Monthly investment", transfer_like.id),+ ("Hidden recurring", ignored.id),+ ):+ session.add(RecurringTransaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ description=description,+ amount=Decimal("100"),+ currency="BRL",+ type="debit",+ frequency="monthly",+ start_date=month_start,+ next_occurrence=month_start,+ is_active=True,+ category_id=category_id,+ ))+ await session.commit()++ projections = await get_projected_transactions(+ session, test_workspace.id, test_user.id, month=month_start+ )++ by_description = {p.description: p for p in projections}+ assert by_description["Monthly investment"].category_name == "Investments"+ assert "Hidden recurring" not in by_description++@pytest.mark.asyncioasync def test_account_balance_manual_future_date(session, test_user):acct = Account(@@ -740,7 +792,7 @@ async def test_get_recurring_projections(session, test_user, test_workspace):@pytest.mark.asyncio-async def test_get_recurring_projections_excludes_ignored_categories(+async def test_get_recurring_projections_filters_non_pnl_categories_by_default(session, test_user, test_workspace):month_start = date.today().replace(day=1)@@ -789,8 +841,16 @@ async def test_get_recurring_projections_excludes_ignored_categories(projections = await _get_recurring_projections(session, test_workspace.id, month_start, month_end)+ balance_projections = await _get_recurring_projections(+ session,+ test_workspace.id,+ month_start,+ month_end,+ include_transfer_like=True,+ )assert [p["amount"] for p in projections] == [100.0]+ assert {p["amount"] for p in balance_projections} == {100.0, 300.0}@pytest.mark.asyncio@@ -816,6 +876,38 @@ async def test_balance_history_basic(session, test_user, test_workspace):assert len(history.previous) > 0+async def test_future_balance_history_carries_pending_into_projected_opening(+ session: AsyncSession, test_user, test_workspace+):+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Future balance", type="checking", balance=Decimal("0"), currency="BRL",+ )+ opening = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Opening", amount=Decimal("1000"),+ currency="BRL", date=date.today(), type="credit", source="opening_balance",+ status="posted",+ )+ pending = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Pending bill", amount=Decimal("100"),+ currency="BRL", date=date.today(), type="debit", source="sync",+ status="pending",+ )+ session.add_all([account, opening, pending])+ await session.commit()++ next_month = (date.today().replace(day=1) + timedelta(days=32)).replace(day=1)+ history = await get_balance_history(+ session, test_workspace.id, test_user.id,+ month=next_month, account_ids=[account.id],+ )++ assert history.current[0].balance == 900.0++@pytest.mark.asyncioasync def test_balance_history_ignored_category_is_consistent_across_months(session: AsyncSession, test_user, test_workspace@@ -993,7 +1085,8 @@ async def test_get_summary_includes_recurring_projections(session, test_user, teawait session.commit()summary = await get_summary(session, test_workspace.id, test_user.id, month=month_start)- assert summary.monthly_income >= 10000.0+ assert summary.monthly_income == pytest.approx(0.0)+ assert summary.projected_income >= 10000.0# ---------------------------------------------------------------------------@@ -1032,7 +1125,10 @@ async def test_spending_by_category_includes_recurring(session, test_user, test_assert len(spending) >= 1transport = next((s for s in spending if s.category_name == "Transport"), None)assert transport is not None- assert transport.total >= 200.0+ # Recurring projections are forecast: they live in projected_total so the+ # posted-only `total` keeps matching the expenses card.+ assert transport.total == 0.0+ assert transport.projected_total >= 200.0# ---------------------------------------------------------------------------diff --git a/backend/tests/test_dashboard_service_coverage.py b/backend/tests/test_dashboard_service_coverage.pyindex cc9ea99e..e1f2efee 100644--- a/backend/tests/test_dashboard_service_coverage.py+++ b/backend/tests/test_dashboard_service_coverage.py@@ -10,6 +10,7 @@ from datetime import date, datetime, timedelta, timezonefrom decimal import Decimalimport pytest+from unittest.mock import AsyncMock, patchfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Account@@ -61,11 +62,12 @@ async def _make_account(session, user_id, workspace_id, *, currency="BRL",async def _add_txn(session, user_id, account_id, workspace_id, amount, typ, dt,*, currency="BRL", source="manual", category_id=None,- amount_primary=None, transfer_pair_id=None):+ amount_primary=None, transfer_pair_id=None, status="posted"):txn = Transaction(id=uuid.uuid4(), user_id=user_id, account_id=account_id,workspace_id=workspace_id, description="t", amount=Decimal(str(amount)),date=dt, type=typ, source=source, currency=currency,+ status=status,category_id=category_id,amount_primary=Decimal(str(amount_primary)) if amount_primary is not None else None,transfer_pair_id=transfer_pair_id,@@ -330,6 +332,31 @@ async def test_projected_transactions_currency_conversion(session, test_user, teassert projections[0].amount_primary == pytest.approx(50.0, abs=1.0)+async def test_projected_transactions_do_not_expose_fake_one_to_one(+ session, test_user, test_workspace+):+ today = date.today()+ month_start = today.replace(day=1)+ session.add(RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ description="USD without rate", amount=Decimal("10"), type="debit",+ frequency="monthly", currency="USD",+ start_date=month_start, next_occurrence=month_start,+ ))+ await session.commit()++ with patch(+ "app.services.dashboard_service._resolve_rate",+ new=AsyncMock(return_value=None),+ ):+ projections = await get_projected_transactions(+ session, test_workspace.id, test_user.id, month=month_start+ )++ assert projections[0].amount_primary is None++# ---------------------------------------------------------------------------# _daily_deltas multi-currency (914-925) + balance_history projection (979-985)# ---------------------------------------------------------------------------@@ -442,9 +469,10 @@ async def test_monthly_trend(session, test_user, test_workspace):@pytest.mark.asyncio-async def test_summary_current_month_projection_adjusts_balance(session, test_user, test_workspace):- """When viewing the current month with no balance_date, month_end > today- so recurring projections from today+1..month_end adjust total_balance."""+async def test_summary_current_month_projection_only_adjusts_projected_balance(+ session, test_user, test_workspace+):+ """Future recurring rows affect projected, never current, balance."""today = date.today()month_start = today.replace(day=1)# Only run when there's at least one future day in the month.@@ -463,8 +491,100 @@ async def test_summary_current_month_projection_adjusts_balance(session, test_usawait session.commit()summary = await get_summary(session, test_workspace.id, test_user.id, month=month_start)- # Projected credits should push the BRL balance above the 1000 opening balance- assert summary.total_balance.get("BRL", 0) > 1000.0+ assert summary.total_balance.get("BRL", 0) == 1000.0+ assert summary.projected_balance.get("BRL", 0) > 1000.0+++async def test_transfer_like_recurring_adjusts_balance_without_becoming_expense(+ session, test_user, test_workspace+):+ """An investment projection moves cash but remains outside P&L totals."""+ today = date.today()+ next_month = (+ date(today.year + 1, 1, 1)+ if today.month == 12+ else date(today.year, today.month + 1, 1)+ )+ account = await _make_account(+ session, test_user.id, test_workspace.id, currency="BRL"+ )+ await _add_txn(+ session,+ test_user.id,+ account.id,+ test_workspace.id,+ 1000,+ "credit",+ today,+ source="opening_balance",+ )+ investments = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Investments",+ treat_as_transfer=True,+ )+ session.add(investments)+ session.add(RecurringTransaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ description="Monthly investment",+ amount=Decimal("100"),+ type="debit",+ frequency="monthly",+ currency="BRL",+ start_date=next_month,+ next_occurrence=next_month,+ category_id=investments.id,+ ))+ await session.commit()++ summary = await get_summary(+ session, test_workspace.id, test_user.id, month=next_month+ )++ assert summary.total_balance.get("BRL", 0) == pytest.approx(1000.0)+ assert summary.projected_balance.get("BRL", 0) == pytest.approx(900.0)+ assert summary.projected_expenses == pytest.approx(0.0)+++async def test_summary_connected_pending_split_by_who_reported_it(+ session, test_user, test_workspace, test_connection+):+ """On a connected account, only a provider-reported pending row is treated+ as already inside the provider's balance.++ Both rows sit in the forecast, but the synced one is assumed to be netted+ out of the 1000 the provider sent, while the recurring placeholder still+ has to come off the projected balance.+ """+ today = date.today()+ account = await _make_account(+ session, test_user.id, test_workspace.id, balance="1000.00",+ connection_id=test_connection.id,+ )+ await _add_txn(+ session, test_user.id, account.id, test_workspace.id, 40, "debit",+ today, source="sync", status="pending",+ )+ await _add_txn(+ session, test_user.id, account.id, test_workspace.id, 25, "debit",+ today, source="recurring", status="pending",+ )++ summary = await get_summary(session, test_workspace.id, test_user.id, month=today)++ assert summary.total_balance.get("BRL", 0) == pytest.approx(1000.0)+ # Only the placeholder moves the projection; the synced row is already in.+ assert summary.projected_balance.get("BRL", 0) == pytest.approx(975.0)+ # Neither has settled, so both stay out of the actual expenses.+ assert summary.monthly_expenses == pytest.approx(0.0)+ assert summary.projected_expenses == pytest.approx(65.0)@pytest.mark.asynciodiff --git a/backend/tests/test_fx_rates.py b/backend/tests/test_fx_rates.pyindex f729aa26..ca3e7e31 100644--- a/backend/tests/test_fx_rates.py+++ b/backend/tests/test_fx_rates.py@@ -203,6 +203,23 @@ class TestResolveRate:rate = await _resolve_rate(session, "USD", "BRL", allow_fetch=False)assert rate == Decimal("5.0000000000")+ @pytest.mark.asyncio+ async def test_future_date_fetches_latest_rate_instead_of_future_history(+ self, session: AsyncSession, clean_db+ ):+ from app.services.fx_rate_service import _resolve_rate++ async def sync_latest(db: AsyncSession, target: date) -> int:+ assert target == date.today()+ await _insert_rate(db, "BRL", Decimal("5.2500000000"), target)+ return 1++ future_date = date.today() + timedelta(days=10)+ with patch("app.services.fx_rate_service.sync_rates", side_effect=sync_latest):+ rate = await _resolve_rate(session, "USD", "BRL", future_date)++ assert rate == Decimal("5.2500000000")+@pytest.mark.asyncioasync def test_get_rate_still_falls_back_to_one_for_live_reads(self, session: AsyncSession@@ -727,6 +744,25 @@ class TestSyncRates:# Should call fetch_latest (not fetch_historical) when no date givenmock_provider.fetch_latest.assert_awaited_once()+ @pytest.mark.asyncio+ async def test_sync_rates_future_date_calls_provider_latest(self):+ from app.services.fx_rate_service import sync_rates++ mock_provider = MagicMock()+ mock_provider.name = "test_provider"+ mock_provider.fetch_latest = AsyncMock(return_value={+ "BRL": Decimal("5.25"),+ })+ mock_session = AsyncMock()+ mock_session.execute = AsyncMock()+ mock_session.commit = AsyncMock()++ with patch("app.services.fx_rate_service._provider", mock_provider):+ await sync_rates(mock_session, date.today() + timedelta(days=10))++ mock_provider.fetch_latest.assert_awaited_once()+ mock_provider.fetch_historical.assert_not_called()+# ═══════════════════════════════════════════════════════════════════════════# 7. STAMP_PRIMARY_AMOUNT EDGE CASESdiff --git a/backend/tests/test_goal_service_coverage.py b/backend/tests/test_goal_service_coverage.pyindex 06cec7dc..bcccf767 100644--- a/backend/tests/test_goal_service_coverage.py+++ b/backend/tests/test_goal_service_coverage.py@@ -54,11 +54,15 @@ async def _make_account(return acc-async def _add_txn(session, user_id, account_id, workspace_id, amount, typ, dt, currency="BRL"):+async def _add_txn(+ session, user_id, account_id, workspace_id, amount, typ, dt,+ currency="BRL", status="posted",+):txn = Transaction(id=uuid.uuid4(), user_id=user_id, account_id=account_id,workspace_id=workspace_id, description="t", amount=Decimal(str(amount)),date=dt, type=typ, source="manual", currency=currency,+ status=status,created_at=datetime.now(timezone.utc),)session.add(txn)@@ -275,6 +279,30 @@ async def test_resolve_account_same_currency(session, test_user, test_workspace)assert val == pytest.approx(Decimal("1500"))+async def test_resolve_account_excludes_pending_and_future_rows(+ session, test_user, test_workspace+):+ """Goal current amount follows posted balance, including for forecast rows."""+ today = date.today()+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 1500, "credit", today)+ await _add_txn(+ session, test_user.id, acc.id, test_workspace.id, 200, "debit", today,+ status="pending",+ )+ await _add_txn(+ session, test_user.id, acc.id, test_workspace.id, 300, "debit",+ today + timedelta(days=3),+ )+ goal = await _make_goal(+ session, test_user.id, test_workspace.id,+ tracking_type="account", account_id=acc.id, currency="BRL",+ )+ val = await _resolve_current_amount(session, goal, test_user.id)+ assert val == pytest.approx(Decimal("1500"))++@pytest.mark.asyncioasync def test_resolve_account_cross_currency(session, test_user, test_workspace):today = date.today()diff --git a/backend/tests/test_recurring_match.py b/backend/tests/test_recurring_match.pyindex fb625459..74fdcaef 100644--- a/backend/tests/test_recurring_match.py+++ b/backend/tests/test_recurring_match.py@@ -337,6 +337,8 @@ async def test_generate_pending_stamps_placeholder_link(session, test_user, test)tx = result.scalar_one()assert tx.recurring_transaction_id == bill.id+ # Due occurrences are actuals; forecast lives in the projection layer.+ assert tx.status == "posted"@pytest.mark.asynciodiff --git a/backend/tests/test_recurring_match_sync.py b/backend/tests/test_recurring_match_sync.pyindex 5b93698f..81120e05 100644--- a/backend/tests/test_recurring_match_sync.py+++ b/backend/tests/test_recurring_match_sync.py@@ -27,7 +27,10 @@ from app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction import Transactionfrom app.schemas.recurring_transaction import RecurringTransactionCreatefrom app.services.connection_service import sync_connection-from app.services.recurring_transaction_service import create_recurring_transaction+from app.services.recurring_transaction_service import (+ create_recurring_transaction,+ generate_pending,+)@pytest_asyncio.fixture@@ -136,25 +139,22 @@ async def test_sync_links_and_advances_bill(session, test_user, test_workspace,@pytest.mark.asyncio-async def test_sync_merges_into_placeholder(session, test_user, test_workspace, conn_account):+async def test_sync_promotes_pending_placeholder_to_posted(+ session, test_user, test_workspace, conn_account+):conn, account = conn_accountconn_id, account_id = conn.id, account.idbill = await _make_bill(session, test_workspace, test_user, account,start_date=date(2025, 1, 10))bill_id = bill.id- # Placeholder as generate_pending would have written it (occurrence already- # advanced next_occurrence to Feb).- bill.next_occurrence = date(2025, 2, 10)- placeholder = Transaction(- id=uuid.uuid4(), user_id=test_user.id, account_id=account_id,- workspace_id=test_workspace.id, description="Netflix Subscription",- amount=Decimal("39.90"), currency="BRL", date=date(2025, 1, 10),- type="debit", source="recurring", status="posted",- recurring_transaction_id=bill_id, created_at=datetime.now(timezone.utc),- )- session.add(placeholder)- await session.commit()+ assert await generate_pending(session, test_user.id, up_to=date(2025, 1, 10)) == 1+ placeholder = (await session.execute(+ select(Transaction).where(Transaction.source == "recurring")+ )).scalar_one()placeholder_id = placeholder.id+ # Synced account: the placeholder is held pending until a real+ # charge confirms it, so a missed match never inflates the balance.+ assert placeholder.status == "pending"provider = _provider([_tx(external_id="s1", description="NETFLIX SUBSCRIPTION",amount=Decimal("39.90"), date=date(2025, 1, 11))])@@ -166,6 +166,7 @@ async def test_sync_merges_into_placeholder(session, test_user, test_workspace,assert merged.id == placeholder_idassert merged.external_id == "s1"assert merged.source == "sync"+ assert merged.status == "posted"assert merged.recurring_transaction_id == bill_idrefreshed = await session.get(RecurringTransaction, bill_id)assert refreshed.next_occurrence == date(2025, 2, 10) # NOT advanced againdiff --git a/backend/tests/test_recurring_transaction_service.py b/backend/tests/test_recurring_transaction_service.pyindex 7b30a35f..ba4c223b 100644--- a/backend/tests/test_recurring_transaction_service.py+++ b/backend/tests/test_recurring_transaction_service.py@@ -571,12 +571,60 @@ async def test_generate_pending(session: AsyncSession, test_user, test_workspace)txns = result.scalars().all()assert len(txns) == 3+ # Only occurrences that already came due are materialized, so they are+ # actuals. Marking them pending would keep them out of every current+ # figure with no way back on an account that never syncs.+ assert {tx.status for tx in txns} == {"posted"}# next_occurrence should be advanced past cutoffawait session.refresh(rec)assert rec.next_occurrence == date(2025, 4, 1)+async def test_generate_pending_holds_synced_account_rows_pending(+ session: AsyncSession, test_user, test_workspace, test_connection+):+ """On a synced account the placeholder waits for the real charge.++ The incoming charge often fails to match, and two posted rows for one+ charge inflate the balance silently. Holding it pending makes a missed+ match cost a visible stale row instead of a wrong number.+ """+ synced = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Synced",+ type="checking",+ balance=Decimal("0"),+ currency="BRL",+ connection_id=test_connection.id,+ )+ session.add(synced)+ await session.commit()++ await create_recurring_transaction(+ session,+ test_workspace.id, test_user.id,+ RecurringTransactionCreate(+ description="Synced Sub",+ amount=Decimal("10"),+ type="debit",+ frequency="monthly",+ start_date=date(2025, 1, 1),+ account_id=synced.id,+ ),+ )+ assert await generate_pending(session, test_user.id, up_to=date(2025, 1, 1)) == 1++ result = await session.execute(+ select(Transaction).where(Transaction.account_id == synced.id)+ )+ [txn] = result.scalars().all()+ assert txn.status == "pending"++@pytest.mark.asyncioasync def test_generate_pending_quarterly_respects_end_date(session: AsyncSession, test_user, test_workspace, test_account_for_recurringdiff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.pyindex 2a57648c..bc23e2b9 100644--- a/backend/tests/test_report_service.py+++ b/backend/tests/test_report_service.py@@ -454,7 +454,9 @@ async def test_income_expenses_api_endpoint(client, auth_headers, test_transactidata = response.json()assert data["meta"]["type"] == "income_expenses"- assert data["meta"]["series_keys"] == ["income", "expenses"]+ assert data["meta"]["series_keys"] == [+ "income", "expenses", "projectedIncome", "projectedExpenses"+ ]assert "summary" in dataassert "trend" in data@@ -559,7 +561,7 @@ async def test_income_expenses_api_accepts_ytd_period(client, auth_headers, monktrend=[],meta=ReportMeta(type="income_expenses",- series_keys=["income", "expenses"],+ series_keys=["income", "expenses", "projectedIncome", "projectedExpenses"],currency=currency,interval=interval,),@@ -594,7 +596,7 @@ async def test_income_expenses_api_forwards_days_window(client, auth_headers, motrend=[],meta=ReportMeta(type="income_expenses",- series_keys=["income", "expenses"],+ series_keys=["income", "expenses", "projectedIncome", "projectedExpenses"],currency=currency,interval=interval,),diff --git a/backend/tests/test_report_service_coverage.py b/backend/tests/test_report_service_coverage.pyindex a49b0a8a..85798e44 100644--- a/backend/tests/test_report_service_coverage.py+++ b/backend/tests/test_report_service_coverage.py@@ -107,13 +107,13 @@ async def _add_txn(amount: float, txn_type: str, txn_date: date, *,source: str = "manual", category_id: uuid.UUID | None = None,currency: str = "BRL", effective_date: date | None = None,- workspace_id: uuid.UUID | None = None,+ workspace_id: uuid.UUID | None = None, status: str = "posted",) -> Transaction:txn = Transaction(id=uuid.uuid4(), user_id=user_id, account_id=account_id,category_id=category_id, description=f"Test {txn_type} {amount}",amount=Decimal(str(amount)), date=txn_date, type=txn_type,- source=source, currency=currency,+ source=source, status=status, currency=currency,effective_date=effective_date or txn_date,created_at=datetime.now(timezone.utc),)@@ -195,13 +195,17 @@ async def test_income_expenses_basic_structure(session, test_user, test_workspac)assert report.meta.type == "income_expenses"- assert report.meta.series_keys == ["income", "expenses"]+ assert report.meta.series_keys == [+ "income", "expenses", "projectedIncome", "projectedExpenses"+ ]assert report.meta.currency == "BRL"assert report.meta.interval == "monthly"bd = {b.key: b.value for b in report.summary.breakdowns}assert bd["income"] == pytest.approx(5000.0)assert bd["expenses"] == pytest.approx(1500.0)+ assert bd["projectedIncome"] == pytest.approx(0.0)+ assert bd["projectedExpenses"] == pytest.approx(0.0)assert bd["netIncome"] == pytest.approx(3500.0)# Composition contains the two named categories + uncategorized@@ -214,6 +218,8 @@ async def test_income_expenses_basic_structure(session, test_user, test_workspacfor dp in report.trend:assert "income" in dp.breakdownsassert "expenses" in dp.breakdowns+ assert "projectedIncome" in dp.breakdowns+ assert "projectedExpenses" in dp.breakdowns# Category trend present with proper groupinggroups = {ct.group for ct in report.category_trend}@@ -306,13 +312,34 @@ async def test_income_expenses_with_recurring_projection(session, test_user, tessession, test_workspace.id, test_user.id, months=2, interval="monthly")bd = {b.key: b.value for b in report.summary.breakdowns}- assert bd["expenses"] >= 800.0- assert bd["income"] >= 1500.0+ assert bd["expenses"] == pytest.approx(0.0)+ assert bd["income"] == pytest.approx(0.0)+ assert bd["projectedExpenses"] >= 800.0+ assert bd["projectedIncome"] >= 1500.0labels = {c.label for c in report.composition}assert "Rent" in labels+async def test_income_expenses_pending_is_projected_not_actual(+ session, test_user, test_workspace+):+ """Pending rows belong to the payable forecast, never actual P&L."""+ acct = await _make_account(session, test_user.id, "IE Pending")+ today = date.today()+ await _add_txn(session, test_user.id, acct.id, 100, "debit", today)+ await _add_txn(+ session, test_user.id, acct.id, 50, "debit", today, status="pending"+ )++ report = await get_income_expenses_report(+ session, test_workspace.id, test_user.id, months=1, interval="monthly"+ )+ bd = {b.key: b.value for b in report.summary.breakdowns}+ assert bd["expenses"] == pytest.approx(100.0)+ assert bd["projectedExpenses"] == pytest.approx(50.0)++async def test_income_expenses_many_categories_triggers_other_bucket(session, test_user, test_workspace):"""More than CATEGORY_TREND_TOP_N expense categories → an 'Other' bucket."""acct = await _make_account(session, test_user.id, "IE Many")diff --git a/backend/tests/test_transaction_calendar_service.py b/backend/tests/test_transaction_calendar_service.pyindex 1f408de3..14d3caf1 100644--- a/backend/tests/test_transaction_calendar_service.py+++ b/backend/tests/test_transaction_calendar_service.py@@ -156,6 +156,37 @@ async def test_transaction_calendar_respects_account_filter(assert [item.description for item in july_3.items] == ["Kept income"]+async def test_transaction_calendar_keeps_pending_in_projected_activity(+ session: AsyncSession, test_user, test_workspace+):+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ name="Pending calendar", type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add(account)+ await session.flush()+ pending = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,+ account_id=account.id, description="Pending bill", amount=Decimal("80"),+ currency="BRL", date=date(2026, 7, 8), type="debit", source="sync",+ status="pending",+ )+ session.add(pending)+ await session.commit()++ calendar = await get_transaction_calendar(+ session, test_workspace.id, test_user.id, month=date(2026, 7, 1)+ )+ july_8 = next(day for day in calendar.days if day.date == date(2026, 7, 8))+ assert july_8.actual_count == 0+ assert july_8.projected_count == 1+ assert july_8.actual_expense == 0.0+ assert july_8.projected_expense == 80.0+ assert july_8.ending_balance == -80.0+ assert july_8.items[0].kind == "projected"++@pytest.mark.asyncioasync def test_transaction_calendar_single_foreign_account_uses_primary_currency_balance(session: AsyncSession, test_user, test_workspacediff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.pyindex 5ffc0473..75b8bf5e 100644--- a/backend/tests/test_transaction_service.py+++ b/backend/tests/test_transaction_service.py@@ -2,6 +2,7 @@ import uuidfrom datetime import date, datetime, timezonefrom decimal import Decimalfrom typing import TypedDict+from unittest.mock import AsyncMock, patchimport pytestimport pytest_asyncio@@ -1212,6 +1213,78 @@ async def test_update_transaction_restamp_on_amount_change(assert updated.amount == Decimal("200")+async def test_pending_to_posted_restamps_only_when_fx_is_missing(+ session: AsyncSession, test_user, test_workspace, txn_account+):+ txn = Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=txn_account.id,+ description="Pending USD",+ amount=Decimal("10"),+ currency="USD",+ date=date.today(),+ type="credit",+ source="manual",+ status="pending",+ amount_primary=None,+ fx_rate_used=None,+ )+ session.add(txn)+ await session.commit()++ with patch(+ "app.services.transaction_service.stamp_primary_amount",+ new=AsyncMock(),+ ) as restamp:+ await update_transaction(+ session,+ txn.id,+ test_workspace.id,+ test_user.id,+ TransactionUpdate(status="posted"),+ )++ restamp.assert_awaited_once()+++async def test_pending_to_posted_preserves_valid_fx_stamp(+ session: AsyncSession, test_user, test_workspace, txn_account+):+ txn = Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=txn_account.id,+ description="Pending USD stamped",+ amount=Decimal("10"),+ currency="USD",+ date=date.today(),+ type="credit",+ source="manual",+ status="pending",+ amount_primary=Decimal("51.75"),+ fx_rate_used=Decimal("5.175"),+ )+ session.add(txn)+ await session.commit()++ with patch(+ "app.services.transaction_service.stamp_primary_amount",+ new=AsyncMock(),+ ) as restamp:+ await update_transaction(+ session,+ txn.id,+ test_workspace.id,+ test_user.id,+ TransactionUpdate(status="posted"),+ )++ restamp.assert_not_awaited()++@pytest.mark.asyncioasync def test_update_transfer_cascades(session: AsyncSession, test_user, test_workspace, txn_accountdiff --git a/frontend/src/components/mobile-transaction-row.tsx b/frontend/src/components/mobile-transaction-row.tsxindex 46fdd886..1deb6045 100644--- a/frontend/src/components/mobile-transaction-row.tsx+++ b/frontend/src/components/mobile-transaction-row.tsx@@ -2,7 +2,7 @@ import { getAccountName } from '@/lib/account-utils'import { AccountIcon } from '@/components/account-icon'import { CategoryIcon } from '@/components/category-icon'import type { Transaction, Account } from '@/types'-import { AlertTriangle, ArrowLeftRight, Clock, EyeClosed, Paperclip } from 'lucide-react'+import { AlertTriangle, ArrowLeftRight, CalendarClock, Clock, EyeClosed, Paperclip } from 'lucide-react'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useTranslation } from 'react-i18next'import { formatCurrency } from '@/lib/format'@@ -58,15 +58,20 @@ export function MobileTransactionRow({? 'text-emerald-600': 'text-rose-500'+ const virtual = tx.virtual === true+return (<divref={highlighted ? highlightedRowRef : undefined}className={`flex items-center gap-3 pl-3 pr-3 py-3 border-b border-border last:border-0 transition-colors ${selected ? 'bg-primary/5' : 'bg-card'} ${highlighted ? 'securo-highlight-flash' : ''} ${- tx.is_shared || !canWrite ? 'cursor-default' : 'cursor-pointer active:bg-muted/60'+ virtual ? 'opacity-80' : ''+ } ${+ virtual || tx.is_shared || !canWrite ? 'cursor-default' : 'cursor-pointer active:bg-muted/60'}`}onClick={() => {+ if (virtual) returnif (tx.is_shared) returnif (!canWrite) returnonClick(tx)@@ -108,10 +113,13 @@ export function MobileTransactionRow({{!!tx.transfer_pair_id && (<ArrowLeftRight className="h-3 w-3 text-blue-600 shrink-0" />)}+ {virtual && (+ <CalendarClock className="h-3 w-3 text-primary shrink-0" />+ )}{tx.is_ignored && (<EyeClosed className="h-3 w-3 text-gray-500 shrink-0" />)}- {tx.recurring_transaction_id != null && (+ {tx.recurring_transaction_id != null && !virtual && (<span className="text-[9px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1 py-0.5 rounded-full shrink-0">R</span>diff --git a/frontend/src/components/projected-transaction-badge.tsx b/frontend/src/components/projected-transaction-badge.tsxnew file mode 100644index 00000000..82f26a6f--- /dev/null+++ b/frontend/src/components/projected-transaction-badge.tsx@@ -0,0 +1,12 @@+import { useTranslation } from 'react-i18next'++/** Canonical badge for a virtual transaction projection. */+export function ProjectedTransactionBadge() {+ const { t } = useTranslation()++ return (+ <span className="inline-flex items-center rounded-full border border-violet-200 bg-violet-50 px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-violet-700 shrink-0 dark:border-violet-900 dark:bg-violet-950/40 dark:text-violet-300">+ {t('transactions.projected')}+ </span>+ )+}diff --git a/frontend/src/components/transaction-calendar-view.tsx b/frontend/src/components/transaction-calendar-view.tsxindex f592b2db..46c1215c 100644--- a/frontend/src/components/transaction-calendar-view.tsx+++ b/frontend/src/components/transaction-calendar-view.tsx@@ -6,8 +6,9 @@ import type { Account, TransactionCalendarDay, TransactionCalendarItem, Transactimport { Skeleton } from '@/components/ui/skeleton'import { AccountIcon } from '@/components/account-icon'import { CategoryIcon } from '@/components/category-icon'+import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'import { getAccountName } from '@/lib/account-utils'-import { activityChartData, dayActivity } from '@/lib/calendar-activity'+import { activityChartData, dayActivity, isCalendarItemInteractive } from '@/lib/calendar-activity'import { weekdayShortLabels } from '@/lib/date-utils'import { cn } from '@/lib/utils'import { formatCurrency } from '@/lib/format'@@ -1212,7 +1213,7 @@ function CalendarItemRow({onOpenTransaction: (id: string) => void}) {const { t } = useTranslation()- const interactive = item.kind === 'actual' && !!item.id+ const interactive = isCalendarItemInteractive(item)const amountColor = item.is_ignored? 'text-gray-500': item.type === 'credit'@@ -1225,7 +1226,9 @@ function CalendarItemRow({onClick={() => { if (item.id) onOpenTransaction(item.id) }}className={cn('w-full flex items-center gap-3 pl-3 pr-3 py-3 text-left',- interactive ? 'hover:bg-muted/50 active:bg-muted/60 transition-colors' : 'cursor-default',+ interactive+ ? 'hover:bg-muted/50 active:bg-muted/60 transition-colors'+ : 'cursor-default opacity-80',)}><div className="shrink-0">@@ -1235,9 +1238,7 @@ function CalendarItemRow({<div className="flex items-center gap-1.5"><p className="text-sm font-semibold text-foreground truncate leading-tight">{item.description}</p>{item.kind === 'projected' && item.source === 'recurring' && item.status !== 'pending' && (- <span className="inline-flex items-center text-[9px] font-semibold uppercase tracking-wide text-violet-700 bg-violet-50 border border-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:border-violet-900 px-1 py-0.5 rounded-full shrink-0">- {t('transactions.calendarProjected')}- </span>+ <ProjectedTransactionBadge />)}{item.is_transfer && (<ArrowLeftRight className="h-3 w-3 text-blue-600 shrink-0" />diff --git a/frontend/src/components/transaction-drill-down.tsx b/frontend/src/components/transaction-drill-down.tsxindex b5ea03a6..227934b9 100644--- a/frontend/src/components/transaction-drill-down.tsx+++ b/frontend/src/components/transaction-drill-down.tsx@@ -5,6 +5,7 @@ import { useQuery } from '@tanstack/react-query'import { transactions as transactionsApi, dashboard, admin } from '@/lib/api'import { AlertTriangle, Info, Paperclip, X } from 'lucide-react'import { CategoryIcon } from '@/components/category-icon'+import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'import { useAuth } from '@/contexts/auth-context'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import type { Transaction } from '@/types'@@ -77,7 +78,7 @@ export function TransactionDrillDown({const { data: projectedTxs } = useQuery({queryKey: ['dashboard', 'projected-transactions', monthParam],- queryFn: () => dashboard.projectedTransactions(monthParam),+ queryFn: () => dashboard.projectedTransactions({ month: monthParam }),enabled: !!filter && !!monthParam,})@@ -251,9 +252,7 @@ export function TransactionDrillDown({<div className="flex items-center gap-2"><p className="text-sm font-medium text-foreground truncate">{item.description}</p>{item.isProjected && (- <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold bg-violet-100 text-violet-600 shrink-0">- {t('transactions.recurringBadge')}- </span>+ <ProjectedTransactionBadge />)}{item.attachmentCount > 0 && (<Paperclip size={12} className="text-muted-foreground shrink-0" />diff --git a/frontend/src/lib/account-detail-utils.test.ts b/frontend/src/lib/account-detail-utils.test.tsnew file mode 100644index 00000000..e9ea2aff--- /dev/null+++ b/frontend/src/lib/account-detail-utils.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from 'vitest'++import {+ applyTransactionToBalance,+ excludeMaterializedProjections,+} from './account-detail-utils'++describe('applyTransactionToBalance', () => {+ it('does not change the balance for ignored transactions', () => {+ expect(applyTransactionToBalance(100, {+ amount: 30,+ amount_primary: null,+ currency: 'BRL',+ is_ignored: true,+ source: 'manual',+ type: 'debit',+ }, false, 'BRL')).toBe(100)+ })++ it('uses the selected currency amount for active transactions', () => {+ const transaction = {+ amount: 10,+ amount_primary: 50,+ currency: 'USD',+ is_ignored: false,+ source: 'manual',+ type: 'credit' as const,+ }++ expect(applyTransactionToBalance(100, transaction, false, 'USD')).toBe(110)+ expect(applyTransactionToBalance(100, transaction, true, 'BRL')).toBe(150)+ })++ it('does not treat a missing cross-currency conversion as 1:1', () => {+ const transaction = {+ amount: 13037.13,+ amount_primary: null,+ currency: 'USD',+ is_ignored: false,+ source: 'manual',+ type: 'credit' as const,+ }++ expect(applyTransactionToBalance(8925.76, transaction, true, 'BRL')).toBe(8925.76)+ })++ it('applies an opening balance row when it is inside the visible period', () => {+ expect(applyTransactionToBalance(100, {+ amount: 500,+ amount_primary: null,+ currency: 'BRL',+ is_ignored: false,+ source: 'opening_balance',+ type: 'credit',+ }, false, 'BRL')).toBe(600)+ })+})++describe('excludeMaterializedProjections', () => {+ it('removes only the occurrence already linked and materialized on that date', () => {+ const projections = [+ { recurring_id: 'rec-1', date: '2026-08-25' },+ { recurring_id: 'rec-1', date: '2026-09-25' },+ { recurring_id: 'rec-2', date: '2026-08-25' },+ ]++ const result = excludeMaterializedProjections(projections, [+ { recurring_transaction_id: 'rec-1', date: '2026-08-25' },+ { recurring_transaction_id: null, date: '2026-09-25' },+ ])++ expect(result).toEqual([projections[1], projections[2]])+ })+})diff --git a/frontend/src/lib/account-detail-utils.ts b/frontend/src/lib/account-detail-utils.tsnew file mode 100644index 00000000..70069a3c--- /dev/null+++ b/frontend/src/lib/account-detail-utils.ts@@ -0,0 +1,63 @@+import type { ProjectedTransaction, Transaction } from '../types'++type BalanceTransaction = Pick<+ Transaction,+ 'amount' | 'amount_primary' | 'currency' | 'is_ignored' | 'source' | 'type'+>++type MaterializedTransaction = Pick<Transaction, 'date' | 'recurring_transaction_id'>++/** Return the usable amount in the selected currency, or null if FX is unknown. */+export function transactionAmountForBalance(+ transaction: BalanceTransaction,+ usePrimary: boolean,+ displayCurrency: string,+): number | null {+ if (+ usePrimary+ && transaction.amount_primary == null+ && transaction.currency !== displayCurrency+ ) return null++ return usePrimary && transaction.amount_primary != null+ ? Number(transaction.amount_primary)+ : Number(transaction.amount)+}++/** Apply one transaction to a running balance using Account Detail semantics. */+export function applyTransactionToBalance(+ balance: number,+ transaction: BalanceTransaction,+ usePrimary: boolean,+ displayCurrency: string,+): number {+ if (transaction.is_ignored) return balance++ // A missing cross-currency conversion is unknown, not a 1:1 rate. Keep the+ // running balance unchanged until the transaction has a real FX stamp.+ const amount = transactionAmountForBalance(transaction, usePrimary, displayCurrency)+ if (amount == null) return balance+ return balance + (transaction.type === 'credit' ? amount : -amount)+}++/**+ * Hide virtual occurrences that already have a materialized transaction.+ * The recurring link plus the effective occurrence date is authoritative;+ * description and amount can legitimately change after materialization.+ */+export function excludeMaterializedProjections<+ T extends Pick<ProjectedTransaction, 'date' | 'recurring_id'>,+>(+ projections: T[],+ transactions: MaterializedTransaction[],+): T[] {+ const materialized = new Set(+ transactions+ .filter((transaction) => transaction.recurring_transaction_id != null)+ .map((transaction) => `${transaction.recurring_transaction_id}:${transaction.date}`),+ )++ return projections.filter(+ (projection) => !materialized.has(`${projection.recurring_id}:${projection.date}`),+ )+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex e6f22360..0d3cec82 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1000,8 +1000,8 @@ export const dashboard = {const { data } = await api.get('/dashboard/monthly-trend', { params: { months, ...(extra.params ?? {}) }, ...(extra.paramsSerializer ? { paramsSerializer: extra.paramsSerializer } : {}) })return data},- projectedTransactions: async (month?: string): Promise<ProjectedTransaction[]> => {- const { data } = await api.get('/dashboard/projected-transactions', { params: { month } })+ projectedTransactions: async (params?: { month?: string; account_id?: string; from?: string; to?: string }): Promise<ProjectedTransaction[]> => {+ const { data } = await api.get('/dashboard/projected-transactions', { params })return data},balanceHistory: async (month?: string, accountIds?: string[]): Promise<BalanceHistory> => {diff --git a/frontend/src/lib/calendar-activity.test.ts b/frontend/src/lib/calendar-activity.test.tsindex f195af12..5cf03d9b 100644--- a/frontend/src/lib/calendar-activity.test.ts+++ b/frontend/src/lib/calendar-activity.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest'-import type { TransactionCalendarDay } from '../types'-import { activityChartData, dayActivity } from './calendar-activity'+import type { TransactionCalendarDay, TransactionCalendarItem } from '../types'+import { activityChartData, dayActivity, isCalendarItemInteractive } from './calendar-activity'function day(overrides: Partial<TransactionCalendarDay>): TransactionCalendarDay {return {@@ -112,3 +112,24 @@ describe('activityChartData', () => {expect(data.hasActivity).toBe(false)})})++describe('isCalendarItemInteractive', () => {+ it('allows persisted pending and future forecast rows to open', () => {+ const item = {+ kind: 'projected',+ id: 'transaction-id',+ } as TransactionCalendarItem++ expect(isCalendarItemInteractive(item)).toBe(true)+ })++ it('keeps virtual recurring projections read-only', () => {+ const item = {+ kind: 'projected',+ id: null,+ recurring_id: 'recurring-id',+ } as TransactionCalendarItem++ expect(isCalendarItemInteractive(item)).toBe(false)+ })+})diff --git a/frontend/src/lib/calendar-activity.ts b/frontend/src/lib/calendar-activity.tsindex beb8e07c..a163decc 100644--- a/frontend/src/lib/calendar-activity.ts+++ b/frontend/src/lib/calendar-activity.ts@@ -1,4 +1,9 @@-import type { TransactionCalendarDay } from '../types'+import type { TransactionCalendarDay, TransactionCalendarItem } from '../types'++/** Persisted forecast rows remain editable; only virtual occurrences lack an id. */+export function isCalendarItemInteractive(item: TransactionCalendarItem): boolean {+ return item.id != null+}export interface CalendarDayActivity {date: stringdiff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 6bd83d12..62dee31f 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Spiegelt wider, was du in deinen Gruppen schuldest / dir geschuldet wird, vor einer Abrechnung.","monthlyIncome": "Monatliche Einnahmen","monthlyExpenses": "Monatliche Ausgaben",+ "projectedBalance": "Prognostizierter Saldo",+ "projectedIncome": "Prognostizierte Einnahmen",+ "projectedExpenses": "Prognostizierte Ausgaben","pendingCategorization": "Nicht kategorisiert","recentTransactions": "Letzte Transaktionen","periodTransactions": "Zeitraum-Transaktionen",@@ -519,6 +522,7 @@"calendarItemCount_plural": "{{count}} Einträge","calendarProjectedCount": "{{count}} geplant","calendarProjected": "Geplant",+ "projected": "Prognostiziert","calendarBalanceTrend": "Saldoverlauf","calendarLegend": "Legende","calendarDensity": "Ansicht",@@ -607,6 +611,10 @@"currentBalance": "Aktueller Saldo","income": "Einnahmen","expenses": "Ausgaben",+ "projectedBalance": "Prognostizierter Saldo",+ "notSettled": "Nicht abgerechnet",+ "projectedIncome": "Prognostizierte Einnahmen",+ "projectedExpenses": "Prognostizierte Ausgaben","thisMonth": "Diesen Monat","backToAccounts": "Zurück zu den Konten","runningBalance": "Saldo",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex a7a67fc0..d241b8e4 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Reflects what you owe / are owed across your groups, before any settlement.","monthlyIncome": "Monthly Income","monthlyExpenses": "Monthly Expenses",+ "projectedBalance": "Projected Balance",+ "projectedIncome": "Projected Income",+ "projectedExpenses": "Projected Expenses","pendingCategorization": "Uncategorized","recentTransactions": "Recent Transactions","periodTransactions": "Period Transactions",@@ -519,6 +522,7 @@"calendarItemCount_plural": "{{count}} items","calendarProjectedCount": "{{count}} projected","calendarProjected": "Projected",+ "projected": "Projected","calendarBalanceTrend": "Balance trend","calendarLegend": "Legend","calendarDensity": "View",@@ -607,6 +611,10 @@"currentBalance": "Current balance","income": "Income","expenses": "Expenses",+ "projectedBalance": "Projected Balance",+ "notSettled": "Not settled",+ "projectedIncome": "Projected Income",+ "projectedExpenses": "Projected Expenses","thisMonth": "This month","backToAccounts": "Back to accounts","runningBalance": "Balance",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex c8ce594a..f44adea5 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Refleja lo que debes / te deben en tus grupos, antes de cualquier liquidación.","monthlyIncome": "Ingresos mensuales","monthlyExpenses": "Gastos mensuales",+ "projectedBalance": "Saldo proyectado",+ "projectedIncome": "Ingresos proyectados",+ "projectedExpenses": "Gastos proyectados","pendingCategorization": "Sin categorizar","recentTransactions": "Transacciones recientes","periodTransactions": "Transacciones del periodo",@@ -519,6 +522,7 @@"calendarItemCount_plural": "{{count}} elementos","calendarProjectedCount": "{{count}} previsto","calendarProjected": "Previsto",+ "projected": "Prevista","calendarBalanceTrend": "Tendencia del saldo","calendarLegend": "Leyenda","calendarDensity": "Vista",@@ -607,6 +611,10 @@"currentBalance": "Saldo actual","income": "Ingresos","expenses": "Gastos",+ "projectedBalance": "Saldo proyectado",+ "notSettled": "Sin liquidar",+ "projectedIncome": "Ingresos proyectados",+ "projectedExpenses": "Gastos proyectados","thisMonth": "Este mes","backToAccounts": "Volver a cuentas","runningBalance": "Saldo",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 14bf2482..45e41cf9 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Reflète ce que vous devez / ce qu'on vous doit dans vos groupes, avant tout règlement.","monthlyIncome": "Revenus mensuels","monthlyExpenses": "Dépenses mensuelles",+ "projectedBalance": "Solde projeté",+ "projectedIncome": "Revenus projetés",+ "projectedExpenses": "Dépenses projetées","pendingCategorization": "Non catégorisé","recentTransactions": "Transactions récentes","periodTransactions": "Transactions de la période",@@ -519,6 +522,7 @@"calendarItemCount_plural": "{{count}} éléments","calendarProjectedCount": "{{count}} prévu(s)","calendarProjected": "Prévu",+ "projected": "Prévue","calendarBalanceTrend": "Évolution du solde","calendarLegend": "Légende","calendarDensity": "Affichage",@@ -607,6 +611,10 @@"currentBalance": "Solde actuel","income": "Revenus","expenses": "Dépenses",+ "projectedBalance": "Solde projeté",+ "notSettled": "Non réglé",+ "projectedIncome": "Revenus projetés",+ "projectedExpenses": "Dépenses projetées","thisMonth": "Ce mois-ci","backToAccounts": "Retour aux comptes","runningBalance": "Solde",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 146bf7e7..455a270c 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Riflette ciò che devi / ti è dovuto nei tuoi gruppi, prima di qualsiasi saldo.","monthlyIncome": "Entrate mensili","monthlyExpenses": "Spese mensili",+ "projectedBalance": "Saldo previsto",+ "projectedIncome": "Entrate previste",+ "projectedExpenses": "Spese previste","pendingCategorization": "Senza categoria","recentTransactions": "Transazioni recenti","periodTransactions": "Transazioni del periodo",@@ -519,6 +522,7 @@"calendarItemCount_plural": "{{count}} elementi","calendarProjectedCount": "{{count}} previsto","calendarProjected": "Previsto",+ "projected": "Prevista","calendarBalanceTrend": "Andamento del saldo","calendarLegend": "Legenda","calendarDensity": "Vista",@@ -607,6 +611,10 @@"currentBalance": "Saldo attuale","income": "Entrate","expenses": "Spese",+ "projectedBalance": "Saldo previsto",+ "notSettled": "Non liquidato",+ "projectedIncome": "Entrate previste",+ "projectedExpenses": "Spese previste","thisMonth": "Questo mese","backToAccounts": "Torna ai conti","runningBalance": "Saldo",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 053eb272..33b6e2f7 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Odzwierciedla to, co jesteś winien / co jest Ci winne w grupach, przed rozliczeniem.","monthlyIncome": "Przychody miesięczne","monthlyExpenses": "Wydatki miesięczne",+ "projectedBalance": "Saldo prognozowane",+ "projectedIncome": "Prognozowane przychody",+ "projectedExpenses": "Prognozowane wydatki","pendingCategorization": "Nieskategoryzowane","recentTransactions": "Ostatnie transakcje","periodTransactions": "Transakcje z okresu",@@ -552,6 +555,7 @@"calendarItemCount_plural": "{{count}} pozycje","calendarProjectedCount": "{{count}} planowane","calendarProjected": "Planowane",+ "projected": "Prognozowana","calendarBalanceTrend": "Trend salda","calendarLegend": "Legenda","calendarDensity": "Widok",@@ -646,6 +650,10 @@"currentBalance": "Bieżące saldo","income": "Przychody","expenses": "Wydatki",+ "projectedBalance": "Saldo prognozowane",+ "notSettled": "Nierozliczone",+ "projectedIncome": "Prognozowane przychody",+ "projectedExpenses": "Prognozowane wydatki","thisMonth": "Bieżący miesiąc","backToAccounts": "Powrót do kont","runningBalance": "Saldo",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 4552b6ec..075b43ec 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Reflete o que você deve ou vai receber em grupos, antes de qualquer acerto.","monthlyIncome": "Entradas do Mês","monthlyExpenses": "Saídas do Mês",+ "projectedBalance": "Saldo projetado",+ "projectedIncome": "Entradas previstas",+ "projectedExpenses": "Saídas previstas","pendingCategorization": "Sem Categoria","recentTransactions": "Transações Recentes","periodTransactions": "Transações do Período",@@ -519,6 +522,7 @@"calendarItemCount_plural": "{{count}} itens","calendarProjectedCount": "{{count}} previsto(s)","calendarProjected": "Previsto",+ "projected": "Prevista","calendarBalanceTrend": "Tendência do saldo","calendarLegend": "Legenda","calendarDensity": "Visualização",@@ -607,6 +611,10 @@"currentBalance": "Saldo atual","income": "Entradas","expenses": "Saídas",+ "projectedBalance": "Saldo projetado",+ "notSettled": "Não liquidado",+ "projectedIncome": "Entradas previstas",+ "projectedExpenses": "Saídas previstas","thisMonth": "Este mês","backToAccounts": "Voltar para contas","runningBalance": "Saldo",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 8505414c..99927761 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Reflete o que deves ou vais receber em grupos, antes de qualquer acerto.","monthlyIncome": "Entradas do Mês","monthlyExpenses": "Saídas do Mês",+ "projectedBalance": "Saldo projetado",+ "projectedIncome": "Entradas previstas",+ "projectedExpenses": "Saídas previstas","pendingCategorization": "Sem Categoria","recentTransactions": "Transações Recentes","periodTransactions": "Transações do Período",@@ -515,6 +518,7 @@"calendarItemCount_plural": "{{count}} itens","calendarProjectedCount": "{{count}} previsto(s)","calendarProjected": "Previsto",+ "projected": "Prevista","calendarBalanceTrend": "Tendência do saldo","calendarLegend": "Legenda","calendarDensity": "Visualização",@@ -607,6 +611,10 @@"currentBalance": "Saldo atual","income": "Entradas","expenses": "Saídas",+ "projectedBalance": "Saldo projetado",+ "notSettled": "Não liquidado",+ "projectedIncome": "Entradas previstas",+ "projectedExpenses": "Saídas previstas","thisMonth": "Este mês","backToAccounts": "Voltar para contas","runningBalance": "Saldo",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex b1edd323..44595e26 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Отражает, что вы должны / вам должны по вашим группам, до урегулирования.","monthlyIncome": "Ежемесячный доход","monthlyExpenses": "Ежемесячные расходы",+ "projectedBalance": "Прогнозируемый баланс",+ "projectedIncome": "Прогнозируемый доход",+ "projectedExpenses": "Прогнозируемые расходы","pendingCategorization": "Без категории","recentTransactions": "Последние транзакции","periodTransactions": "Транзакции за период",@@ -525,6 +528,7 @@"calendarItemCount_plural": "{{count}} записей","calendarProjectedCount": "{{count}} запланировано","calendarProjected": "Запланировано",+ "projected": "Прогнозируемая","calendarBalanceTrend": "Динамика баланса","calendarLegend": "Легенда","calendarDensity": "Вид",@@ -613,6 +617,10 @@"currentBalance": "Текущий баланс","income": "Доход","expenses": "Расходы",+ "projectedBalance": "Прогнозируемый баланс",+ "notSettled": "Не проведено",+ "projectedIncome": "Прогнозируемый доход",+ "projectedExpenses": "Прогнозируемые расходы","thisMonth": "Этот месяц","backToAccounts": "Назад к счетам","runningBalance": "Баланс",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex a05f05ad..7941faee 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -242,6 +242,9 @@"pendingSharesTooltip": "Відображає, що ви винні / вам винні за вашими групами, до врегулювання.","monthlyIncome": "Щомісячний дохід","monthlyExpenses": "Щомісячні витрати",+ "projectedBalance": "Прогнозований баланс",+ "projectedIncome": "Прогнозований дохід",+ "projectedExpenses": "Прогнозовані витрати","pendingCategorization": "Без категорії","recentTransactions": "Останні транзакції","periodTransactions": "Транзакції за період",@@ -525,6 +528,7 @@"calendarItemCount_plural": "{{count}} записи","calendarProjectedCount": "{{count}} заплановано","calendarProjected": "Заплановано",+ "projected": "Прогнозована","calendarBalanceTrend": "Динаміка балансу","calendarLegend": "Легенда","calendarDensity": "Вигляд",@@ -613,6 +617,10 @@"currentBalance": "Поточний баланс","income": "Дохід","expenses": "Витрати",+ "projectedBalance": "Прогнозований баланс",+ "notSettled": "Не проведено",+ "projectedIncome": "Прогнозований дохід",+ "projectedExpenses": "Прогнозовані витрати","thisMonth": "Цей місяць","backToAccounts": "Назад до рахунків","runningBalance": "Баланс",diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex 8fe222ce..e22e582c 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -5,17 +5,19 @@ import { useTranslation } from 'react-i18next'import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query'import { format, addDays, addMonths, parseISO } from 'date-fns'-import { accounts, transactions, categories as categoriesApi, categoryGroups as categoryGroupsApi } from '@/lib/api'+import { accounts, dashboard, transactions, categories as categoriesApi, categoryGroups as categoryGroupsApi } from '@/lib/api'import { localDateString } from '@/lib/date-utils'+import { applyTransactionToBalance, excludeMaterializedProjections, transactionAmountForBalance } from '@/lib/account-detail-utils'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { shouldShowPendingBadge } from '@/lib/transaction-status'import { toast } from 'sonner'-import type { CreditCardBill, Transaction } from '@/types'+import type { CreditCardBill, ProjectedTransaction, Transaction } from '@/types'import { Skeleton } from '@/components/ui/skeleton'import { Button } from '@/components/ui/button'import { ArrowLeft, ArrowLeftRight, CalendarClock, ChevronLeft, ChevronRight, Clock, EyeClosed, HelpCircle, Paperclip, Pencil, X } from 'lucide-react'import { MobileTransactionRow } from '@/components/mobile-transaction-row'import { CategoryIcon } from '@/components/category-icon'+import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'import { TransactionDialog, extractApiError, type TransactionSavePayload } from '@/components/transaction-dialog'import { TransferDialog } from '@/components/transfer-dialog'import { DatePickerInput } from '@/components/ui/date-picker-input'@@ -45,7 +47,8 @@ function defaultFrom() {}function defaultTo() {- return localDateString()+ const now = new Date()+ return localDateString(new Date(now.getFullYear(), now.getMonth() + 1, 0))}function daysInMonth(year: number, month: number): number {@@ -499,12 +502,6 @@ export default function AccountDetailPage() {})),})- const { data: balanceHistory, isLoading: balanceHistoryLoading } = useQuery({- queryKey: ['accounts', id, 'balance-history', filterFrom, filterTo],- queryFn: () => accounts.balanceHistory(id!, filterFrom || undefined, filterTo || undefined),- enabled: !!id,- })-const { data: txData, isLoading: txLoading } = useQuery({queryKey: ['transactions', { account_id: id, bill_id: activeBill?.id, from: filterFrom, to: filterTo, limit: 500, include_opening_balance: true, unbilled_only: isInProgressCycle }],queryFn: () => transactions.list({@@ -526,6 +523,15 @@ export default function AccountDetailPage() {enabled: !!id,})+ // Non-materialized recurring projections are forecast rows. They are kept+ // separate from real transactions so pending and future commitments never+ // alter the current balance.+ const { data: projectedTxData } = useQuery({+ queryKey: ['dashboard', 'projected-transactions', { account_id: id, from: filterFrom, to: filterTo }],+ queryFn: () => dashboard.projectedTransactions({ account_id: id!, from: filterFrom, to: filterTo }),+ enabled: !!id && account?.type !== 'credit_card',+ })+const { data: categoriesList } = useQuery({queryKey: ['categories'],queryFn: categoriesApi.list,@@ -623,8 +629,74 @@ export default function AccountDetailPage() {const usePrimary = !isForeignCurrency || showPrimaryconst displayCurrency = (isForeignCurrency && !showPrimary) ? (account?.currency || userCurrency) : userCurrency+ // Pseudo-transaction rows for non-materialized recurring projections.+ // Virtual: rendered with a "Previsão" badge, non-clickable, and merged+ // into displayRows where running balances are computed for them.+ const projectedRows = useMemo((): TxWithBalance[] => {+ if (!projectedTxData) return []+ const unmaterialized = excludeMaterializedProjections(+ projectedTxData,+ txData?.items ?? [],+ )+ return unmaterialized.map((p: ProjectedTransaction): TxWithBalance => ({+ id: `projected-${p.recurring_id}-${p.date}`,+ user_id: '',+ account_id: id ?? null,+ category_id: p.category_id,+ category: p.category_name || p.category_icon || p.category_color+ ? {+ id: p.category_id ?? '',+ user_id: '',+ group_id: null,+ name: p.category_name ?? '',+ icon: p.category_icon ?? '',+ color: p.category_color ?? '',+ is_system: false,+ treat_as_transfer: false,+ is_ignored: false,+ }+ : null,+ external_id: null,+ description: p.description,+ amount: p.amount,+ currency: p.currency,+ date: p.date,+ type: p.type,+ source: 'projected',+ status: 'posted',+ payee: null,+ payee_id: null,+ payee_name: null,+ notes: null,+ transfer_pair_id: null,+ amount_primary: p.amount_primary,+ fx_rate_used: null,+ fx_fallback: false,+ installment_series_id: null,+ installment_number: null,+ total_installments: null,+ installment_total_amount: null,+ installment_purchase_date: null,+ bill_id: null,+ effective_bill_date: null,+ recurring_transaction_id: p.recurring_id,+ splits: [],+ is_ignored: false,+ virtual: true,+ runningBalance: 0,+ }))+ }, [projectedTxData, txData?.items, id])++ // Balance at the start of the period, used to seed the running-balance+ // walk so that the last row's balance matches the projected balance at+ // date_to. For CC accounts this is not used (cycle total starts from 0).+ const openingBalance = usePrimary+ ? (summary?.opening_balance_primary ?? summary?.opening_balance ?? 0)+ : (summary?.opening_balance ?? 0)+// Chart data:- // - Non-CC: daily running balance from /balance-history+ // - Non-CC: daily running balance seeded from the current posted balance.+ // Pending and recurring rows are added only to this forecast walk.// - CC: cumulative charges within the current cycle, starting at 0// (answers "how much have I spent this cycle", ignores bill payments/transfers)const chartData = useMemo(() => {@@ -635,7 +707,8 @@ export default function AccountDetailPage() {if (tx.type !== 'debit') continueif (tx.source === 'opening_balance') continueif (tx.transfer_pair_id) continue- const amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)+ const amt = transactionAmountForBalance(tx, usePrimary, displayCurrency)+ if (amt == null) continuebyDay.set(tx.date, (byDay.get(tx.date) ?? 0) + amt)}// Chart span: when a real bill is active, derive the range from the@@ -672,58 +745,75 @@ export default function AccountDetailPage() {}return series}- if (!balanceHistory) return []- return balanceHistory.map(p => ({- label: formatDateStr(p.date, dateLocale),- date: p.date,- balance: usePrimary ? (p.balance_primary ?? p.balance) : p.balance,- }))- }, [isCreditCard, txData, filterFrom, filterTo, balanceHistory, locale, dateLocale, usePrimary, activeBill])-- // Running balance computation for transaction table- const txWithRunningBalance = useMemo((): TxWithBalance[] => {- if (!txData?.items) return []-- if (isCreditCard) {- // Cycle running total: debits add, refund credits subtract (net- // matches the bank's bill total). Excludes opening_balance and any- // transfer-paired tx (bill payments — those zero out separately).- // Computed oldest → newest, then reversed (not re-sorted) so- // same-day rows read monotonically top-down.- const ascending = [...txData.items].sort(- (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),- )- let running = 0- const withBalance = ascending.map((tx) => {- if (tx.source !== 'opening_balance' && !tx.transfer_pair_id) {- const amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)- if (tx.type === 'debit') running += amt- else if (tx.type === 'credit') running -= amt- }- return { ...tx, runningBalance: running }- })- return withBalance.reverse()+ if (!txData?.items || !summary || !filterFrom || !filterTo) return []+ const allTx = [...txData.items, ...projectedRows]+ const txByDay = new Map<string, number>()+ for (const tx of allTx) {+ const previous = txByDay.get(tx.date) ?? 0+ txByDay.set(tx.date, applyTransactionToBalance(previous, tx, usePrimary, displayCurrency))+ }+ const series: { label: string; date: string; balance: number }[] = []+ let balance = openingBalance+ const cur = new Date(filterFrom + 'T00:00:00')+ const end = new Date(filterTo + 'T00:00:00')+ while (cur <= end) {+ const key = cur.toLocaleDateString('sv-SE')+ balance += txByDay.get(key) ?? 0+ series.push({ label: formatDateStr(key, dateLocale), date: key, balance })+ cur.setDate(cur.getDate() + 1)}+ return series+ }, [isCreditCard, txData, projectedRows, filterFrom, filterTo, dateLocale, usePrimary, displayCurrency, summary, openingBalance, activeBill])- if (summary === undefined) return []- const endBalance = usePrimary- ? (balanceHistory?.length- ? (balanceHistory[balanceHistory.length - 1].balance_primary ?? balanceHistory[balanceHistory.length - 1].balance)- : (summary.current_balance_primary ?? summary.current_balance))- : (balanceHistory?.length- ? balanceHistory[balanceHistory.length - 1].balance- : summary.current_balance)- const sorted = [...txData.items].sort(- (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()+ const ccRunningTotal = useMemo((): TxWithBalance[] => {+ if (!isCreditCard || !txData?.items) return []+ const ascending = [...txData.items].sort(+ (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),)- let running = endBalance- return sorted.map((tx) => {- const balanceAtPoint = running- const amt = usePrimary && tx.amount_primary != null ? Number(tx.amount_primary) : Number(tx.amount)- running -= tx.type === 'credit' ? amt : -amt- return { ...tx, runningBalance: balanceAtPoint }+ let running = 0+ const withBalance = ascending.map((tx) => {+ if (!tx.is_ignored && tx.source !== 'opening_balance' && !tx.transfer_pair_id) {+ const amt = transactionAmountForBalance(tx, usePrimary, displayCurrency)+ if (amt == null) return { ...tx, runningBalance: running }+ if (tx.type === 'debit') running += amt+ else if (tx.type === 'credit') running -= amt+ }+ return { ...tx, runningBalance: running }})- }, [txData, summary, isCreditCard, balanceHistory, usePrimary])+ return withBalance.reverse()+ }, [txData, isCreditCard, usePrimary, displayCurrency])++ // Merged list: real transactions, pending rows, and virtual recurring+ // projections. The newest row is the forecast at the end of the range.+ const displayRows = useMemo((): TxWithBalance[] => {+ if (isCreditCard) return ccRunningTotal+ if (!txData?.items || summary === undefined) return []++ // Secondary sort by the original index in txData.items preserves the+ // API's insertion order for same-day transactions (creation sequence).+ const txIndex = new Map(txData.items.map((t, i) => [t.id, i]))+ const merged = [...txData.items, ...projectedRows].sort(+ (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()+ || (txIndex.get(a.id) ?? Infinity) - (txIndex.get(b.id) ?? Infinity),+ )++ let balance = openingBalance+ const withBalance = merged.map((tx) => ({+ ...tx,+ runningBalance: balance = applyTransactionToBalance(balance, tx, usePrimary, displayCurrency),+ }))+ return withBalance.reverse()+ }, [txData, projectedRows, isCreditCard, summary, usePrimary, displayCurrency, openingBalance, ccRunningTotal])++ const totalBalance = (usePrimary ? summary?.current_balance_primary : undefined) ?? summary?.current_balance ?? 0+ const projectedBalance = displayRows.length > 0 ? displayRows[0].runningBalance : openingBalance++ const actualIncome = (usePrimary ? summary?.monthly_income_primary : undefined) ?? summary?.monthly_income ?? 0+ const actualExpenses = (usePrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0+ const projectedIncome = (usePrimary ? summary?.projected_income_primary : undefined) ?? summary?.projected_income ?? actualIncome+ const projectedExpenses = (usePrimary ? summary?.projected_expenses_primary : undefined) ?? summary?.projected_expenses ?? actualExpenses+ const hasProjectedIncome = Math.abs(projectedIncome - actualIncome) > 0.005+ const hasProjectedExpenses = Math.abs(projectedExpenses - actualExpenses) > 0.005const resolvedDefaultRange = account?.type === 'credit_card'? defaultCycleForCreditCard(account.statement_close_day, account.payment_due_day, new Date())@@ -735,7 +825,7 @@ export default function AccountDetailPage() {const groupedByDate = useMemo(() => {const groups: { date: string; label: string; items: TxWithBalance[] }[] = []let current: { date: string; label: string; items: TxWithBalance[] } | null = null- for (const tx of txWithRunningBalance) {+ for (const tx of displayRows) {if (!current || current.date !== tx.date) {current = {date: tx.date,@@ -752,7 +842,7 @@ export default function AccountDetailPage() {current.items.push(tx)}return groups- }, [txWithRunningBalance, dateLocale])+ }, [displayRows, dateLocale])const isLoading = accountLoading || summaryLoading@@ -981,7 +1071,7 @@ export default function AccountDetailPage() {// filtered by bill_id when the cycle has a bill (handles dynamic// close days) or by [start, end] otherwise. Same number whether// the bar is active or not — clicking doesn't shift the value.- const total = Number(q.data?.monthly_expenses ?? 0)+ const total = Number(q.data?.projected_expenses ?? q.data?.monthly_expenses ?? 0)return {...c,total,@@ -1043,7 +1133,7 @@ export default function AccountDetailPage() {// can lag any charges added since the last sync). Otherwise use the// summary endpoint's monthly_expenses now nets refund credits against// debits for CC accounts (matches the bank's bill total).- const billTotal = (showPrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0+ const billTotal = (showPrimary ? summary?.projected_expenses_primary : undefined) ?? summary?.projected_expenses ?? summary?.monthly_expenses ?? 0// "Default cycle" = the bill the user is here to pay (next due). The// AGORA tag on Limite disponível only shows when viewing a different cycle.const isDefaultCycle =@@ -1149,33 +1239,51 @@ export default function AccountDetailPage() {{t('accounts.currentBalance')}</p><p className={`text-[length:clamp(0.7rem,3.5vw,1.25rem)] sm:text-2xl font-bold tabular-nums ${(summary?.current_balance ?? 0) < 0 ? 'text-rose-500' : 'text-emerald-600'}`}>- {mask(formatCurrency(- (showPrimary ? summary?.current_balance_primary : undefined) ?? summary?.current_balance ?? 0,- displayCurrency, locale- ))}+ {mask(formatCurrency(totalBalance, displayCurrency, locale))}+ </p>+ </div>+ <div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4 overflow-hidden">+ <p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1 truncate">+ {t('accounts.projectedBalance', 'Projected balance')}</p>+ <p className={`text-[length:clamp(0.7rem,3.5vw,1.25rem)] sm:text-2xl font-bold tabular-nums ${projectedBalance < 0 ? 'text-rose-500' : 'text-emerald-600'}`}>+ {mask(formatCurrency(projectedBalance, displayCurrency, locale))}+ </p>+ {/* Naming the gap keeps the two cards from reading as a+ contradiction: the forecast is the current balance plus the+ money that has not settled yet. Same "label: value" shape as+ the projected income/expense sub-lines beside it. */}+ {Math.abs(projectedBalance - totalBalance) > 0.005 && (+ <p className="text-[10px] sm:text-xs text-muted-foreground truncate">+ {t('accounts.notSettled')}: {mask(formatCurrency(Math.abs(projectedBalance - totalBalance), displayCurrency, locale))}+ </p>+ )}</div><div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4 overflow-hidden"><p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1 truncate">{t('accounts.income')}</p><p className="text-[length:clamp(0.7rem,3.5vw,1.25rem)] sm:text-2xl font-bold tabular-nums text-emerald-600">- {mask(formatCurrency(- (showPrimary ? summary?.monthly_income_primary : undefined) ?? summary?.monthly_income ?? 0,- displayCurrency, locale- ))}+ {mask(formatCurrency(actualIncome, displayCurrency, locale))}</p>+ {hasProjectedIncome && (+ <p className="text-[10px] sm:text-xs text-muted-foreground truncate">+ {t('accounts.projectedIncome')}: {mask(formatCurrency(projectedIncome, displayCurrency, locale))}+ </p>+ )}</div><div className="bg-card rounded-xl border border-border shadow-sm p-3 sm:p-4 overflow-hidden"><p className="text-[10px] sm:text-xs font-medium text-muted-foreground mb-1 truncate">{t('accounts.expenses')}</p><p className="text-[length:clamp(0.7rem,3.5vw,1.25rem)] sm:text-2xl font-bold tabular-nums text-rose-500">- {mask(formatCurrency(- (showPrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0,- displayCurrency, locale- ))}+ {mask(formatCurrency(actualExpenses, displayCurrency, locale))}</p>+ {hasProjectedExpenses && (+ <p className="text-[10px] sm:text-xs text-muted-foreground truncate">+ {t('accounts.projectedExpenses')}: {mask(formatCurrency(projectedExpenses, displayCurrency, locale))}+ </p>+ )}</div></div>)}@@ -1186,7 +1294,7 @@ export default function AccountDetailPage() {// currently being viewed. For the current cycle this matches the "current// open balance" since nothing has been paid yet; for past cycles it shows// that month's burn rate against the (current) limit.- const cycleBillTotal = (showPrimary ? summary?.monthly_expenses_primary : undefined) ?? summary?.monthly_expenses ?? 0+ const cycleBillTotal = (showPrimary ? summary?.projected_expenses_primary : undefined) ?? summary?.projected_expenses ?? summary?.monthly_expenses ?? 0const utilized = limit != null ? cycleBillTotal : nullconst rawPct = limit != null && limit > 0 && utilized != null ? (utilized / limit) * 100 : nullconst pct = rawPct != null ? Math.min(100, rawPct) : null@@ -1276,15 +1384,23 @@ export default function AccountDetailPage() {{(() => {const cycleEmpty = isCreditCard && chartData.length > 0 && chartData[chartData.length - 1].balance === 0const balances = chartData.map(d => d.balance)- const chartMin = Math.min(0, ...balances)- const chartMax = Math.max(0, ...balances)const dataMin = balances.length > 0 ? Math.min(...balances) : 0const dataMax = balances.length > 0 ? Math.max(...balances) : 0- const flat = chartMin === chartMax- const zeroFrac = flat+ const flat = dataMin === 0 && dataMax === 0+ // The Y axis rounds its bounds outward to hundreds and the area path+ // is drawn down to that rounded floor, so the fill's gradient box+ // spans the axis domain, not the data. Deriving the zero split from+ // the data would put the colour flip at the wrong height: for a+ // series of [-680, 105] the real zero sits at 22% of the domain while+ // the data ratio says 13%. Keep both in step with the axis below.+ const domainMin = dataMin < 0 ? Math.floor(dataMin / 100) * 100 : 0+ const domainMax = dataMax === 0 ? 100 : Math.ceil(dataMax / 100) * 100+ const zeroFrac = domainMax === domainMin? 1- : Math.min(1, Math.max(0, chartMax / (chartMax - chartMin)))+ : Math.min(1, Math.max(0, domainMax / (domainMax - domainMin)))const crossesZero = dataMin < 0 && dataMax > 0+ // The line path never touches the baseline, so its gradient box is+ // the data extent rather than the domain.const strokeSplit = crossesZero? Math.min(1, Math.max(0, dataMax / (dataMax - dataMin))): 1@@ -1299,7 +1415,7 @@ export default function AccountDetailPage() {</p></div><div className="px-1 pb-4 h-[280px]">- {(isCreditCard ? txLoading : balanceHistoryLoading) ? (+ {txLoading ? (<Skeleton className="h-full w-full" />) : cycleEmpty ? (<div className="h-full w-full flex flex-col items-center justify-center gap-2 text-muted-foreground">@@ -1417,7 +1533,7 @@ export default function AccountDetailPage() {<div className="p-6 space-y-3">{Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-10" />)}</div>- ) : txWithRunningBalance.length === 0 ? (+ ) : displayRows.length === 0 ? (<p className="p-6 text-center text-muted-foreground">{t('accounts.noTransactions')}</p>) : isMobile ? (<div>@@ -1469,17 +1585,17 @@ export default function AccountDetailPage() {</tr></thead><tbody>- {txWithRunningBalance.map((tx) => {+ {displayRows.map((tx) => {const isOpening = tx.source === 'opening_balance'const isTransfer = !!tx.transfer_pair_id- const isPending = tx.status === 'pending'const isIgnored = tx.is_ignored+ const isVirtual = tx.virtual === truereturn (<trkey={tx.id}- className={`border-b last:border-0 transition-colors ${isOpening ? 'bg-muted/60' : isPending ? 'opacity-60' : canWrite ? 'hover:bg-muted cursor-pointer' : ''}`}+ className={`border-b last:border-0 transition-colors ${isOpening ? 'bg-muted/60' : (canWrite && !isVirtual) ? 'hover:bg-muted cursor-pointer' : ''} ${isVirtual ? 'opacity-80' : ''}`}onClick={() => {- if (!isOpening && canWrite) {+ if (!isOpening && !isVirtual && canWrite) {setEditingTx(tx)setDialogOpen(true)}@@ -1511,7 +1627,10 @@ export default function AccountDetailPage() {<span title={t('transactions.ignoreTransferHint')}><HelpCircle className="h-3 w-3 text-blue-400" /></span></span>)}- {tx.recurring_transaction_id != null && (+ {isVirtual && (+ <ProjectedTransactionBadge />+ )}+ {tx.recurring_transaction_id != null && !isVirtual && (<spanclassName="text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1.5 py-0.5 rounded-full shrink-0"title={t('transactions.recurringLinkedTooltip')}diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex c7c624a6..9ff19bb1 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -10,6 +10,7 @@ import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { toast } from 'sonner'import { Skeleton } from '@/components/ui/skeleton'import { Button } from '@/components/ui/button'+import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'import {Select,SelectContent,@@ -210,7 +211,7 @@ export default function DashboardPage() {const { data: projectedTxs, isLoading: projectedTxLoading } = useQuery({queryKey: ['dashboard', 'projected-transactions', selectedMonth],- queryFn: () => dashboard.projectedTransactions(monthParam),+ queryFn: () => dashboard.projectedTransactions({ month: monthParam }),})const { data: budgetComparison } = useQuery({@@ -343,11 +344,15 @@ export default function DashboardPage() {const primaryCurrency = summary?.primary_currency ?? userCurrencyconst totalBalance = summary?.total_balance_primary ?? Object.values(summary?.total_balance ?? {}).reduce((a, b) => a + Number(b), 0)+ const projectedBalance = summary?.projected_balance_primary ?? Object.values(summary?.projected_balance ?? {}).reduce((a, b) => a + Number(b), 0)+ const hasProjectedBalance = Math.abs(projectedBalance - totalBalance) >= 0.01// Savings rate & projectionconst income = Number(summary?.monthly_income_primary ?? summary?.monthly_income ?? 0)const expenses = Number(summary?.monthly_expenses_primary ?? summary?.monthly_expenses ?? 0)+ const projectedIncome = Number(summary?.projected_income_primary ?? summary?.projected_income ?? income)+ const projectedExpenses = Number(summary?.projected_expenses_primary ?? summary?.projected_expenses ?? expenses)const savingsRate = income > 0 ? ((income - expenses) / income) * 100 : 0const isCurrentMonth = selectedMonth === currentMonth()const daysElapsed = isCurrentMonth ? new Date().getDate() : monthLastDay(selectedMonth)@@ -492,7 +497,7 @@ export default function DashboardPage() {categoryIcon: pt.category_icon,categoryName: pt.category_name,categoryColor: pt.category_color ?? null,- accountId: null,+ accountId: pt.account_id,isProjected: true,attachmentCount: 0,isShared: false,@@ -616,6 +621,11 @@ export default function DashboardPage() {))}</div>)}+ {hasProjectedBalance && (+ <p className="text-[10px] text-muted-foreground tabular-nums mt-0.5">+ {t('dashboard.projectedBalance')} {mask(formatCurrency(projectedBalance, primaryCurrency, locale))}+ </p>+ )}{/* Net of pending group shares — show only whenmeaningfully nonzero so users without groupssee the same UI as before. */}@@ -655,9 +665,16 @@ export default function DashboardPage() {{summaryLoading ? (<Skeleton className="h-7 w-24" />) : (- <p className="text-lg font-bold tabular-nums text-emerald-600">- +{mask(formatCurrency(income, primaryCurrency, locale))}- </p>+ <>+ <p className="text-lg font-bold tabular-nums text-emerald-600">+ +{mask(formatCurrency(income, primaryCurrency, locale))}+ </p>+ {Math.abs(projectedIncome - income) >= 0.01 && (+ <p className="text-[10px] text-muted-foreground tabular-nums mt-0.5">+ {t('dashboard.projectedIncome')} {mask(formatCurrency(projectedIncome, primaryCurrency, locale))}+ </p>+ )}+ </>)}</div>@@ -675,9 +692,16 @@ export default function DashboardPage() {{summaryLoading ? (<Skeleton className="h-7 w-24" />) : (- <p className="text-lg font-bold tabular-nums text-rose-500">- -{mask(formatCurrency(expenses, primaryCurrency, locale))}- </p>+ <>+ <p className="text-lg font-bold tabular-nums text-rose-500">+ -{mask(formatCurrency(expenses, primaryCurrency, locale))}+ </p>+ {Math.abs(projectedExpenses - expenses) >= 0.01 && (+ <p className="text-[10px] text-muted-foreground tabular-nums mt-0.5">+ {t('dashboard.projectedExpenses')} {mask(formatCurrency(projectedExpenses, primaryCurrency, locale))}+ </p>+ )}+ </>)}</div>@@ -1096,9 +1120,7 @@ export default function DashboardPage() {</span>)}{row.isProjected && (- <span className="inline-flex items-center text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1.5 py-0.5 rounded-full shrink-0">- {t('transactions.recurringBadge')}- </span>+ <ProjectedTransactionBadge />)}{row.installmentNumber != null && row.totalInstallments != null && (<span className="inline-flex items-center text-[9px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1 py-0.5 rounded-full shrink-0">@@ -1213,9 +1235,7 @@ export default function DashboardPage() {</span>)}{row.isProjected && (- <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold bg-violet-100 text-violet-600 shrink-0">- {t('transactions.recurringBadge')}- </span>+ <ProjectedTransactionBadge />)}{row.installmentNumber != null && row.totalInstallments != null && (<span className="inline-flex items-center text-[10px] font-bold tabular-nums text-amber-700 dark:text-amber-400 bg-amber-100 dark:bg-amber-500/20 border border-amber-200 dark:border-amber-500/30 px-1.5 py-0.5 rounded-full shrink-0">diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex 4909cd96..9b713df5 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -843,8 +843,10 @@ export default function ReportsPage() {contentStyle={tooltipStyle}/><ReferenceLine y={0} stroke="var(--border)" strokeDasharray="3 3" />- <Bar dataKey="income" fill="#10B981" radius={[4, 4, 0, 0]} maxBarSize={24} />- <Bar dataKey="expenses" fill="#F43F5E" radius={[4, 4, 0, 0]} maxBarSize={24} />+ <Bar dataKey="income" fill="#10B981" radius={[4, 4, 0, 0]} maxBarSize={20} />+ <Bar dataKey="expenses" fill="#F43F5E" radius={[4, 4, 0, 0]} maxBarSize={20} />+ <Bar dataKey="projectedIncome" fill="#34D399" radius={[4, 4, 0, 0]} maxBarSize={20} fillOpacity={0.65} />+ <Bar dataKey="projectedExpenses" fill="#FB7185" radius={[4, 4, 0, 0]} maxBarSize={20} fillOpacity={0.65} /><Linetype="monotone"dataKey="value"diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex d0af75e7..ab3968ff 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -186,11 +186,17 @@ export interface Collection {export interface AccountSummary {account_id: stringcurrent_balance: number+ opening_balance: numbermonthly_income: numbermonthly_expenses: numbercurrent_balance_primary: number | null+ opening_balance_primary: number | nullmonthly_income_primary: number | nullmonthly_expenses_primary: number | null+ projected_income?: number+ projected_expenses?: number+ projected_income_primary?: number | null+ projected_expenses_primary?: number | null}export interface Transaction {@@ -242,6 +248,7 @@ export interface Transaction {parent_owner_name?: string | null// Flag to exclude this transaction from reports and dashboard aggregationsis_ignored: boolean+ virtual?: boolean}// Scope for installment-series edits/deletes: "this" (default) only touches@@ -491,6 +498,7 @@ export interface RecurringTransaction {export interface ProjectedTransaction {recurring_id: string+ account_id: string | nulldescription: stringamount: numberamount_primary: number | null@@ -558,11 +566,17 @@ export interface TransactionCalendarResponse {export interface DashboardSummary {total_balance: Record<string, number>total_balance_primary: number+ projected_balance: Record<string, number>+ projected_balance_primary: numberbalance_date: stringmonthly_income: numbermonthly_expenses: numbermonthly_income_primary: numbermonthly_expenses_primary: number+ projected_income?: number+ projected_expenses?: number+ projected_income_primary?: number+ projected_expenses_primary?: numberaccounts_count: numberpending_categorization: numberpending_categorization_amount: number@@ -618,7 +632,9 @@ export interface BudgetVsActual {group_name: string | nullbudget_amount: number | nullactual_amount: number+ projected_amount: numberprev_month_amount: number+ projected_prev_month_amount: numberpercentage_used: number | nullis_recurring: boolean}