Open-source personal finance manager. Self-hosted, privacy-first.
fix(accounts): compute account page balances on the server (#1212)
APenalbaf57d777d7ae0
diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.pyindex ab0f8302..e5981d6a 100644--- a/backend/app/api/accounts.py+++ b/backend/app/api/accounts.py@@ -6,6 +6,8 @@ from typing import Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSession+from app.api.reports import _add_years+from app.core.app_clock import app_todayfrom app.core.database import get_async_sessionfrom app.core.workspace_context import (WorkspaceContext,@@ -15,15 +17,22 @@ from app.core.workspace_context import (from app.schemas.account import (AccountCreate,AccountRead,+ AccountRunningBalancePoint,AccountSummary,AccountUpdate,CreditCardBillRead,)from app.services import account_service+from app.services.admin_service import get_credit_card_accounting_modefrom app.services.fx_rate_service import _resolve_raterouter = APIRouter(prefix="/api/accounts", tags=["accounts"])+# Same cap as the reports' custom range (`_MAX_CUSTOM_RANGE_YEARS`), counted+# the same way: the series has one point per day. The account page charts the+# latest part of a longer range (#1202).+_MAX_RUNNING_BALANCE_YEARS = 10+@router.get("", response_model=list[AccountRead])async def list_accounts(@@ -116,6 +125,42 @@ async def get_account_balance_history(return history[email protected]("/{account_id}/running-balance", response_model=list[AccountRunningBalancePoint])+async def get_account_running_balance(+ account_id: uuid.UUID,+ date_from: Optional[date] = Query(None, alias="from"),+ date_to: Optional[date] = Query(None, alias="to"),+ ctx: WorkspaceContext = Depends(current_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ """Daily balance matching the transaction list's `running_balance` (#1202).++ Missing bounds default like the summary's: month start to today.+ """+ today = app_today()+ date_from = date_from or today.replace(day=1)+ date_to = date_to or today+ if date_to < date_from:+ raise HTTPException(status_code=422, detail="to must be on or after from")+ if date_to > _add_years(date_from, _MAX_RUNNING_BALANCE_YEARS):+ raise HTTPException(+ status_code=422,+ detail=f"Range is too wide (max {_MAX_RUNNING_BALANCE_YEARS} years)",+ )++ accounting_mode = await get_credit_card_accounting_mode(session)+ try:+ series = await account_service.get_account_running_balance(+ session, account_id, ctx.workspace.id, ctx.user.primary_currency,+ date_from, date_to, accounting_mode=accounting_mode,+ )+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))+ if series is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")+ return series++@router.get("/{account_id}/bills", response_model=list[CreditCardBillRead])async def get_account_bills(account_id: uuid.UUID,diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex ee296cc6..0fe9492c 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -126,6 +126,7 @@ async def list_transactions(page: int = Query(1, ge=1),limit: int = Query(50, ge=1, le=500),include_opening_balance: bool = Query(False),+ include_running_balance: bool = Query(False, description="Fill running_balance per row (issue #1202): one non-credit-card account, `from` set, include_opening_balance, no other filter, default order; null otherwise"),exclude_transfers: bool = Query(False),user_pnl_only: bool = Query(False, description="Return only rows that count toward dashboard/user income/expense totals"),exclude_ignored: bool = Query(False, description="Drop rows the user marked ignored, or whose category is ignored"),@@ -158,6 +159,8 @@ async def list_transactions(min_amount=min_amount,max_amount=max_amount,include_summary=True,+ include_running_balance=include_running_balance,+ primary_currency=ctx.user.primary_currency,)primary_currency = ctx.user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.pyindex 2b4c6a25..301df526 100644--- a/backend/app/models/transaction.py+++ b/backend/app/models/transaction.py@@ -139,6 +139,8 @@ class Transaction(Base):parent_owner_name = cast(Optional[str], None)attachment_count: int = 0payee_name = cast(Optional[str], None)+ running_balance = cast(Optional[float], None)+ running_balance_primary = cast(Optional[float], None)# Safety net: `effective_date` is NOT NULL. For non-CC transactions it alwaysdiff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex 2224822c..05f74268 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -112,3 +112,11 @@ class AccountSummary(BaseModel):# True when no real FX rate is available, so the *_primary fields are# left unset rather than a 1:1 guess.fx_fallback: bool = False+++class AccountRunningBalancePoint(BaseModel):+ """End-of-day balance on the account page's walk (#1202)."""++ date: date+ balance: float+ balance_primary: Optional[float] = Nonediff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex bc67c02c..aae2e8ea 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -201,6 +201,12 @@ class TransactionRead(TransactionBase):parent_owner_name: Optional[str] = Noneis_ignored: bool = Falseexclude_from_pnl: bool = False+ # Account balance right after this row, set only when the list asked for+ # it on one non-credit-card account's unfiltered ledger (#1202). The+ # primary-currency value is null when the account is already in it, or+ # when no real rate is available (#1165).+ running_balance: Optional[float] = None+ running_balance_primary: Optional[float] = None@model_validator(mode="after")def reflect_ignored_category(self):diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex 5cd29e51..7f768483 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -3,7 +3,7 @@ from datetime import date as _Date, datetime, timedelta, timezonefrom decimal import Decimalfrom typing import Optional-from sqlalchemy import case, delete, func, select, or_, update+from sqlalchemy import ColumnElement, Select, case, delete, func, select, or_, updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import contains_eager@@ -20,8 +20,11 @@ from app.services._query_filters import (is_confirmed,is_inside_provider_snapshot,is_not_future,+ is_not_ignored,+ reporting_date_col,)from app.services.credit_card_service import apply_effective_date, compute_available_credit, get_cycle_dates+from app.services.fx_rate_service import _resolve_ratefrom app.models.category import Category@@ -961,75 +964,89 @@ async def get_account_summary()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)- ),+ opening_balance = (+ await get_period_opening_balance(session, account, date_from)+ if account.type != "credit_card"+ else 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,+ }+++async def get_period_opening_balance(+ session: AsyncSession, account: Account, date_from: _Date,+) -> float:+ """Projected balance of a non-credit-card account 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. Shared by the summary, the+ list's `running_balance` and the running-balance series so all three start+ from the same number (#1202).+ """+ today = app_today()+ # Use amount_primary only when tx currency differs from account currency+ effective_amount = case(+ (Transaction.currency == account.currency, Transaction.amount),+ else_=func.coalesce(Transaction.amount_primary, Transaction.amount),+ )+ 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,]- 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(),+ 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)+ )+ opening_balance = float(account.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(+ if date_from > today:+ before_window_result = await session.execute(select(func.coalesce(func.sum(case((Transaction.type == "credit", effective_amount),@@ -1037,23 +1054,27 @@ async def get_account_summary()), 0)).where(*ob_base_filters,+ Transaction.date > today,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,- }+ opening_balance += float(before_window_result.scalar() or 0)+ return opening_balance++ 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")),+ )+ )+ return float(manual_result.scalar() or 0)def _signed_amount_expr(account_currency: str):@@ -1161,3 +1182,147 @@ async def get_account_balance_history(point["balance"] = round(point["balance"] * sign, 2)return series+++def _running_balance_delta(account_currency: str):+ """A row's effect on the account-detail running balance (#1202).++ Shared by the transaction list and the daily series so a row moves both by+ the same amount. Ignored rows, by flag or by category, stay listed but move+ nothing, as in `get_period_opening_balance`. Status and date are not+ looked at: the walk is a projection, so pending and future-dated rows count.+ """+ return case((is_not_ignored(), _signed_amount_expr(account_currency)), else_=0)+++def _running_balance_delta_primary(primary_currency: str):+ """`_running_balance_delta` in the user's primary currency.++ A foreign row with no FX stamp moves nothing rather than being counted+ 1:1, the same call the account page made when it walked the rows itself.+ """+ amount = case(+ (Transaction.amount_primary.is_not(None), Transaction.amount_primary),+ (Transaction.currency == primary_currency, Transaction.amount),+ else_=0,+ )+ signed = case((Transaction.type == "credit", amount), else_=-amount)+ return case((is_not_ignored(), signed), else_=0)+++async def _running_balance_seed(+ session: AsyncSession, account: Account, date_from: _Date, primary_currency: str,+) -> tuple[Decimal, Optional[Decimal]]:+ """Opening balance, and its primary-currency value when the account is in+ another currency, converted like the summary's `opening_balance_primary`:+ with a real rate only, and left unset without one (#1165)."""+ opening = Decimal(str(await get_period_opening_balance(session, account, date_from)))+ if account.currency == primary_currency:+ return opening, None+ rate = await _resolve_rate(session, account.currency, primary_currency)+ if rate is None:+ return opening, None+ return opening, (opening * rate).quantize(Decimal("0.01"))+++async def get_running_balances(+ session: AsyncSession, account: Account, filtered_ids: Select, order_col: ColumnElement,+ date_from: _Date, row_ids: list[uuid.UUID], primary_currency: str,+) -> dict[uuid.UUID, tuple[float, Optional[float]]]:+ """Balance right after each of `row_ids`, walking the whole filtered list.++ `filtered_ids` selects the ids of every row the list matched, not just the+ page, so a row's value does not depend on which page it was loaded on+ (#1202). The window orders by the exact reverse of the list's default+ order, so the newest row carries the balance at the end of the range.+ """+ opening, opening_primary = await _running_balance_seed(+ session, account, date_from, primary_currency,+ )+ order_by = (order_col.asc(), Transaction.created_at.asc(), Transaction.id.asc())+ columns = [+ Transaction.id,+ func.sum(_running_balance_delta(account.currency))+ .over(order_by=order_by, rows=(None, 0))+ .label("walk"),+ ]+ if opening_primary is not None:+ columns.append(+ func.sum(_running_balance_delta_primary(primary_currency))+ .over(order_by=order_by, rows=(None, 0))+ .label("walk_primary")+ )+ walk = select(*columns).where(Transaction.id.in_(filtered_ids)).subquery()+ result = await session.execute(select(walk).where(walk.c.id.in_(row_ids)))++ balances: dict[uuid.UUID, tuple[float, Optional[float]]] = {}+ for row in result.mappings():+ balance = float(opening + Decimal(str(row["walk"] or 0)))+ balance_primary = (+ float(opening_primary + Decimal(str(row["walk_primary"] or 0)))+ if opening_primary is not None+ else None+ )+ balances[row["id"]] = (balance, balance_primary)+ return balances+++async def get_account_running_balance(+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID,+ primary_currency: str, date_from: _Date, date_to: _Date,+ accounting_mode: Optional[str] = None,+) -> Optional[list[dict]]:+ """End-of-day balance for every day in [date_from, date_to] (#1202).++ The same walk as the list's `running_balance` over the unfiltered account+ list for that range, opening row included, so the last point equals the+ newest row's value. Unlike `get_account_balance_history`, pending and+ future-dated rows count: this is the account page's projected balance.+ """+ account = await get_account(session, account_id, workspace_id)+ if not account:+ return None+ # A card's page walks its bill cycle client-side; its balance is the debt.+ if account.type == "credit_card":+ raise ValueError("Running balance is not available for credit card accounts")++ opening, opening_primary = await _running_balance_seed(+ session, account, date_from, primary_currency,+ )+ # Bucket by the list's date column so each row lands on the day it is+ # listed under.+ date_col = reporting_date_col(accounting_mode or "cash")+ result = await session.execute(+ select(+ date_col,+ func.sum(_running_balance_delta(account.currency)),+ func.sum(_running_balance_delta_primary(primary_currency)),+ )+ .where(+ Transaction.account_id == account.id,+ Transaction.workspace_id == workspace_id,+ date_col >= date_from,+ date_col <= date_to,+ )+ .group_by(date_col)+ )+ deltas = {+ day: (Decimal(str(delta or 0)), Decimal(str(delta_primary or 0)))+ for day, delta, delta_primary in result.all()+ }++ series = []+ balance, balance_primary = opening, opening_primary+ current = date_from+ while current <= date_to:+ delta, delta_primary = deltas.get(current, (Decimal(0), Decimal(0)))+ balance += delta+ if balance_primary is not None:+ balance_primary += delta_primary+ series.append({+ "date": current,+ "balance": float(balance),+ "balance_primary": float(balance_primary) if balance_primary is not None else None,+ })+ current += timedelta(days=1)+ return seriesdiff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 8de7a072..7245c0e3 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -24,6 +24,7 @@ from app.schemas.transaction import ()from app.schemas.transaction_split import TransactionSplitInput, TransactionSplitsInputfrom app.services import reconciliation_service, split_service+from app.services.account_service import get_account, get_running_balancesfrom app.services.credit_card_service import apply_effective_datefrom app.services.rule_service import apply_rules_to_transactionfrom app.services.fx_rate_service import stamp_primary_amount, convert as fx_convert@@ -132,12 +133,19 @@ async def get_transactions(include_summary: bool = False,user_pnl_only: bool = False,exclude_ignored: bool = False,+ include_running_balance: bool = False,+ primary_currency: Optional[str] = None,) -> tuple[list[Transaction], int, Optional[dict]]:"""List transactions for a workspace.`workspace_id` scopes the tenant (which transactions are visible). `user_id`is the *viewer* — used for Splitwise projection (linked-member visibility,is-shared tagging) which is identity-based, not tenancy-based.++ `include_running_balance` fills `running_balance` (and, for an account in a+ currency other than `primary_currency`, `running_balance_primary`) when the+ list is one non-credit-card account's ledger from `from_date` in the default+ order; see `_running_balance_account`."""# In "accrual" mode, bucket/order by effective_date so list filters# line up with the cash-flow view used by the dashboard and reports.@@ -539,9 +547,61 @@ async def get_transactions(# and the frontend needs `is_shared` to lock them from edits.await _tag_shared_view(session, transactions, user_id)+ if include_running_balance and from_date and primary_currency:+ running_account = await _running_balance_account(+ session, workspace_id,+ account_ids=account_ids or ([account_id] if account_id else []),+ narrowed=any((+ category_id, category_ids, payee_id, search, uncategorized,+ txn_type, tags, status, currency, account_types, transaction_ids,+ min_amount is not None, max_amount is not None,+ exclude_transfers, user_pnl_only, exclude_ignored,+ group_id, bill_id, unbilled_only,+ # Without the opening row the walk misses its amount+ # whenever it falls inside the range.+ not include_opening_balance,+ )),+ default_order=not sort_by or (sort_by == "date" and sort_dir == "desc"),+ )+ if running_account is not None:+ balances = await get_running_balances(+ session, running_account,+ filtered_ids=select(base_query.subquery().c.id),+ order_col=default_order_col,+ date_from=from_date,+ row_ids=[tx.id for tx in transactions],+ primary_currency=primary_currency,+ )+ for tx in transactions:+ # A row deleted between the page query and the window+ # query has no balance; leave it null rather than fail.+ tx.running_balance, tx.running_balance_primary = balances.get(tx.id, (None, None))+return transactions, total or 0, summary+async def _running_balance_account(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ account_ids: list[uuid.UUID],+ narrowed: bool,+ default_order: bool,+) -> Optional[Account]:+ """The account whose running balance the list can carry, if any (#1202).++ A running balance only means something on one account's full ledger read+ newest first: a filter would skip rows the balance moved by, another order+ would show values out of sequence. A card's balance is the bill cycle, which+ the account page walks itself. Anything else gets no value, not an error.+ """+ if narrowed or not default_order or len(set(account_ids)) != 1:+ return None+ account = await get_account(session, account_ids[0], workspace_id)+ if account is None or account.type == "credit_card":+ return None+ return account++async def _tag_shared_view(session: AsyncSession,transactions: list[Transaction],diff --git a/backend/tests/api_contract/baseline.json b/backend/tests/api_contract/baseline.jsonindex 640ae0c1..3abbb522 100644--- a/backend/tests/api_contract/baseline.json+++ b/backend/tests/api_contract/baseline.json@@ -46,6 +46,7 @@"GET /api/accounts/{account_id}": 401,"GET /api/accounts/{account_id}/balance-history": 401,"GET /api/accounts/{account_id}/bills": 401,+ "GET /api/accounts/{account_id}/running-balance": 401,"GET /api/accounts/{account_id}/summary": 401,"GET /api/admin/accounting-mode": 401,"GET /api/admin/date-format": 401,@@ -432,6 +433,7 @@"GET /api/accounts/{account_id}": 200,"GET /api/accounts/{account_id}/balance-history": 200,"GET /api/accounts/{account_id}/bills": 200,+ "GET /api/accounts/{account_id}/running-balance": 200,"GET /api/accounts/{account_id}/summary": 200,"GET /api/admin/accounting-mode": 200,"GET /api/admin/date-format": 200,@@ -745,6 +747,7 @@"GET /api/accounts/{account_id}": 404,"GET /api/accounts/{account_id}/balance-history": 404,"GET /api/accounts/{account_id}/bills": 404,+ "GET /api/accounts/{account_id}/running-balance": 404,"GET /api/accounts/{account_id}/summary": 404,"GET /api/admin/users/{user_id}": 404,"GET /api/agents/connections/{conn_id}": 404,diff --git a/backend/tests/test_account_running_balance.py b/backend/tests/test_account_running_balance.pynew file mode 100644index 00000000..86bcbe22--- /dev/null+++ b/backend/tests/test_account_running_balance.py@@ -0,0 +1,426 @@+"""Server-side running balance for the account page (#1202).++The account page used to walk its balance column, chart and projected balance+from `summary.opening_balance` over the rows it had loaded, capped at 500, so+anything past that cap never moved the balance. These cover the two places the+server now does that walk:++- `running_balance` / `running_balance_primary` on GET /api/transactions+- GET /api/accounts/{id}/running-balance, the daily series behind the chart+"""+import uuid+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal++import pytest+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.category import Category+from app.models.fx_rate import FxRate+from app.models.transaction import Transaction+from app.models.user import User+from app.services.workspace_service import create_personal_workspace_for_user+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++_CREATED = datetime(2026, 1, 1, tzinfo=timezone.utc)+++async def _make_account(+ session: AsyncSession, user_id: uuid.UUID,+ acc_type: str = "checking", currency: str = "BRL",+) -> Account:+ account = Account(+ id=uuid.uuid4(), user_id=user_id, name=f"Running {acc_type}",+ type=acc_type, balance=Decimal("0"), currency=currency,+ )+ session.add(account)+ await session.commit()+ await session.refresh(account)+ return account+++async def _add_txn(+ session: AsyncSession, user_id: uuid.UUID, account: Account,+ amount: str, txn_type: str, txn_date: date,+ created_at: datetime | None = None, **extra,+) -> Transaction:+ txn = Transaction(+ id=uuid.uuid4(), user_id=user_id, account_id=account.id,+ description=f"{txn_type} {amount}", amount=Decimal(amount),+ currency=extra.pop("currency", account.currency), type=txn_type,+ date=txn_date, source=extra.pop("source", "manual"),+ # Distinct by default so rows sharing a date keep a known order.+ created_at=created_at or datetime.now(timezone.utc),+ **extra,+ )+ session.add(txn)+ await session.commit()+ await session.refresh(txn)+ return txn+++async def _list(client: AsyncClient, headers: dict, **params) -> list[dict]:+ response = await client.get(+ "/api/transactions",+ params={"include_running_balance": "true", "include_opening_balance": "true", **params},+ headers=headers,+ )+ assert response.status_code == 200, response.text+ return response.json()["items"]+++async def _series(client: AsyncClient, headers: dict, account_id, **params):+ return await client.get(+ f"/api/accounts/{account_id}/running-balance", params=params, headers=headers,+ )+++# ---------------------------------------------------------------------------+# GET /api/transactions?include_running_balance=true+# ---------------------------------------------------------------------------+++async def test_running_balance_is_continuous_across_pages(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ """Each row carries opening + every older row in the range, whichever page+ it is on, and the newest row lands on the series' last point."""+ account = await _make_account(session, test_user.id)+ # Before the range: only reaches the walk through the opening balance.+ await _add_txn(+ session, test_user.id, account, "1000", "credit", date(2026, 1, 15),+ source="opening_balance",+ )+ for amount, txn_type, day in [+ ("200", "credit", 2), ("50", "debit", 5), ("30", "debit", 5),+ ("100", "credit", 10), ("400", "debit", 20),+ ]:+ await _add_txn(session, test_user.id, account, amount, txn_type, date(2026, 2, day))++ params = {"account_id": str(account.id), "from": "2026-02-01", "to": "2026-02-28", "limit": 3}+ items = (+ await _list(client, auth_headers, **params, page=1)+ + await _list(client, auth_headers, **params, page=2)+ )++ assert [tx["running_balance"] for tx in items] == [820, 1220, 1120, 1150, 1200]+ assert all(tx["running_balance_primary"] is None for tx in items)++ summary = await client.get(+ f"/api/accounts/{account.id}/summary",+ params={"from": "2026-02-01", "to": "2026-02-28"}, headers=auth_headers,+ )+ assert summary.json()["opening_balance"] == 1000++ series = await _series(client, auth_headers, account.id, **{"from": "2026-02-01", "to": "2026-02-28"})+ assert series.status_code == 200+ assert series.json()[-1]["balance"] == items[0]["running_balance"]+++async def test_running_balance_breaks_same_date_ties_like_the_list(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ """Rows on one date walk in the reverse of the list order (created_at,+ then id), so the balances read top to bottom without jumps."""+ account = await _make_account(session, test_user.id)+ day = date(2026, 3, 3)+ # Three rows share created_at, as a bank sync batch does; powers of two+ # make every ordering produce a different set of balances.+ for amount in ("1", "2", "4"):+ await _add_txn(session, test_user.id, account, amount, "credit", day, created_at=_CREATED)+ await _add_txn(+ session, test_user.id, account, "8", "credit", day,+ created_at=_CREATED + timedelta(seconds=1),+ )++ items = await _list(+ client, auth_headers, account_ids=[str(account.id)], **{"from": "2026-03-01", "to": "2026-03-31"},+ )++ expected, balance = [], Decimal(0)+ for tx in reversed(items):+ balance += Decimal(tx["amount"])+ expected.append(float(balance))+ assert [tx["running_balance"] for tx in reversed(items)] == expected+ assert items[0]["description"] == "credit 8"+++async def test_running_balance_counts_rows_like_the_account_page(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ """Ignored rows stay listed but move nothing; pending, future-dated and+ the opening row inside the range all move the balance."""+ account = await _make_account(session, test_user.id)+ ignored_category = Category(+ id=uuid.uuid4(), user_id=test_user.id, name="Ignored", is_ignored=True,+ )+ session.add(ignored_category)+ await session.commit()+ today = date.today()+ await _add_txn(+ session, test_user.id, account, "1000", "credit", today - timedelta(days=5),+ source="opening_balance",+ )+ await _add_txn(+ session, test_user.id, account, "100", "debit", today - timedelta(days=4), is_ignored=True,+ )+ await _add_txn(+ session, test_user.id, account, "200", "debit", today - timedelta(days=3),+ category_id=ignored_category.id,+ )+ await _add_txn(+ session, test_user.id, account, "50", "debit", today - timedelta(days=2), status="pending",+ )+ await _add_txn(session, test_user.id, account, "300", "credit", today + timedelta(days=5))++ range_params = {+ "from": (today - timedelta(days=5)).isoformat(),+ "to": (today + timedelta(days=10)).isoformat(),+ }+ items = await _list(client, auth_headers, account_id=str(account.id), **range_params)++ assert [tx["running_balance"] for tx in items] == [1250, 950, 1000, 1000, 1000]+ series = await _series(client, auth_headers, account.id, **range_params)+ assert series.json()[-1]["balance"] == 1250+++async def test_running_balance_on_connected_account_starts_from_summary_opening(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_account,+):+ """A connected account seeds the walk from the provider snapshot exactly+ as the summary does, so the walk ends on the provider's balance."""+ today = date.today()+ await _add_txn(session, test_user.id, test_account, "500", "credit", today - timedelta(days=30))+ await _add_txn(session, test_user.id, test_account, "300", "credit", today - timedelta(days=10))+ await _add_txn(+ session, test_user.id, test_account, "20", "debit", today - timedelta(days=5), status="pending",+ )+ range_params = {"from": (today - timedelta(days=20)).isoformat(), "to": today.isoformat()}++ summary = (await client.get(+ f"/api/accounts/{test_account.id}/summary", params=range_params, headers=auth_headers,+ )).json()+ items = await _list(client, auth_headers, account_id=str(test_account.id), **range_params)++ # Provider 1500, less the 300 posted and the −20 pending inside the range.+ assert summary["opening_balance"] == 1220+ assert [tx["running_balance"] for tx in items] == [1500, 1520]+ assert items[0]["running_balance"] == summary["current_balance"]+ series = await _series(client, auth_headers, test_account.id, **range_params)+ assert series.json()[0]["balance"] == summary["opening_balance"]+ assert series.json()[-1]["balance"] == 1500+++async def test_running_balance_primary_for_foreign_currency_account(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ """A USD account for a BRL user also walks in BRL: the opening converted+ like the summary's, then each row's stamped amount_primary. A row with no+ stamp moves only the native balance."""+ session.add(FxRate(+ base_currency="USD", quote_currency="BRL", date=date.today(),+ rate=Decimal("5"), source="test",+ ))+ await session.commit()+ account = await _make_account(session, test_user.id, currency="USD")+ await _add_txn(+ session, test_user.id, account, "100", "credit", date(2026, 1, 10),+ source="opening_balance", amount_primary=Decimal("480"),+ )+ await _add_txn(+ session, test_user.id, account, "10", "debit", date(2026, 2, 3),+ amount_primary=Decimal("52"),+ )+ await _add_txn(session, test_user.id, account, "5", "debit", date(2026, 2, 4))+ range_params = {"from": "2026-02-01", "to": "2026-02-28"}++ items = await _list(client, auth_headers, account_id=str(account.id), **range_params)+ summary = (await client.get(+ f"/api/accounts/{account.id}/summary", params=range_params, headers=auth_headers,+ )).json()++ assert summary["opening_balance_primary"] == 500+ assert [tx["running_balance"] for tx in items] == [85, 90]+ assert [tx["running_balance_primary"] for tx in items] == [448, 448]+ series = (await _series(client, auth_headers, account.id, **range_params)).json()+ assert series[-1]["balance"] == 85+ assert series[-1]["balance_primary"] == 448++[email protected]("case", [+ "flag_off", "no_from", "search", "category", "sort_amount", "sort_date_asc",+ "two_accounts", "credit_card", "no_opening_row",+])+async def test_running_balance_is_null_when_the_list_is_not_one_ledger(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, case,+):+ """Filtered, reordered or multi-account lists would show balances out of+ sequence, so they get null rather than a wrong number. No error either."""+ account = await _make_account(session, test_user.id)+ other = await _make_account(session, test_user.id)+ card = await _make_account(session, test_user.id, acc_type="credit_card")+ category = Category(id=uuid.uuid4(), user_id=test_user.id, name="Food")+ session.add(category)+ await session.commit()+ for target in (account, other, card):+ await _add_txn(+ session, test_user.id, target, "10", "debit", date(2026, 2, 3), category_id=category.id,+ )++ params = {"account_id": str(account.id), "from": "2026-02-01", "to": "2026-02-28"}+ if case == "flag_off":+ params["include_running_balance"] = "false"+ elif case == "no_from":+ del params["from"]+ elif case == "search":+ params["q"] = "debit"+ elif case == "category":+ params["category_id"] = str(category.id)+ elif case == "sort_amount":+ params["sort_by"] = "amount"+ elif case == "sort_date_asc":+ params.update(sort_by="date", sort_dir="asc")+ elif case == "two_accounts":+ del params["account_id"]+ params["account_ids"] = [str(account.id), str(other.id)]+ elif case == "credit_card":+ params["account_id"] = str(card.id)+ elif case == "no_opening_row":+ params["include_opening_balance"] = "false"++ items = await _list(client, auth_headers, **params)++ assert items+ assert all(tx["running_balance"] is None for tx in items)+ assert all(tx["running_balance_primary"] is None for tx in items)+++# ---------------------------------------------------------------------------+# GET /api/accounts/{id}/running-balance+# ---------------------------------------------------------------------------+++async def test_running_balance_series_has_one_end_of_day_point_per_day(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ account = await _make_account(session, test_user.id)+ await _add_txn(session, test_user.id, account, "100", "credit", date(2026, 4, 30))+ await _add_txn(session, test_user.id, account, "40", "debit", date(2026, 5, 2))+ await _add_txn(session, test_user.id, account, "10", "debit", date(2026, 5, 2))+ await _add_txn(session, test_user.id, account, "25", "credit", date(2026, 5, 4))++ response = await _series(client, auth_headers, account.id, **{"from": "2026-05-01", "to": "2026-05-05"})++ assert response.status_code == 200+ assert response.json() == [+ {"date": "2026-05-01", "balance": 100, "balance_primary": None},+ {"date": "2026-05-02", "balance": 50, "balance_primary": None},+ {"date": "2026-05-03", "balance": 50, "balance_primary": None},+ {"date": "2026-05-04", "balance": 75, "balance_primary": None},+ {"date": "2026-05-05", "balance": 75, "balance_primary": None},+ ]+++async def test_running_balance_series_defaults_to_the_current_month(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ """Missing bounds default like the summary's: month start to today."""+ account = await _make_account(session, test_user.id)++ response = await _series(client, auth_headers, account.id)++ today = date.today()+ assert response.status_code == 200+ points = response.json()+ assert points[0]["date"] == today.replace(day=1).isoformat()+ assert points[-1]["date"] == today.isoformat()+++async def test_running_balance_series_hides_other_workspaces_accounts(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ other_user = User(+ id=uuid.uuid4(), email="[email protected]",+ hashed_password="synthetic-unused", is_active=True, is_verified=True,+ )+ session.add(other_user)+ await session.flush()+ workspace = await create_personal_workspace_for_user(session, other_user)+ foreign = Account(+ id=uuid.uuid4(), user_id=other_user.id, workspace_id=workspace.id,+ name="Private", type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add(foreign)+ await session.commit()++ assert (await _series(client, auth_headers, foreign.id)).status_code == 404+ assert (await _series(client, auth_headers, uuid.uuid4())).status_code == 404+++async def test_running_balance_series_rejects_credit_cards(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ card = await _make_account(session, test_user.id, acc_type="credit_card")++ response = await _series(client, auth_headers, card.id)++ assert response.status_code == 400++[email protected]("date_from, date_to", [+ ("2026-05-02", "2026-05-01"),+ # One day past ten calendar years, the reports' custom-range cap.+ ("2016-01-01", "2026-01-02"),+])+async def test_running_balance_series_rejects_bad_ranges(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, date_from, date_to,+):+ account = await _make_account(session, test_user.id)++ response = await _series(client, auth_headers, account.id, **{"from": date_from, "to": date_to})++ assert response.status_code == 422+++async def test_running_balance_series_accepts_the_longest_range(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+):+ account = await _make_account(session, test_user.id)+ date_from = date(2016, 1, 1)+ date_to = date(2026, 1, 1)++ response = await _series(+ client, auth_headers, account.id, **{"from": date_from.isoformat(), "to": date_to.isoformat()},+ )++ assert response.status_code == 200+ assert len(response.json()) == (date_to - date_from).days + 1+++async def test_running_balance_series_is_readable_by_viewer(+ client: AsyncClient, viewer_auth_headers, session: AsyncSession, test_user,+):+ account = await _make_account(session, test_user.id)++ response = await _series(client, viewer_auth_headers, account.id)++ assert response.status_code == 200diff --git a/backend/tests/test_account_running_balance_postgres.py b/backend/tests/test_account_running_balance_postgres.pynew file mode 100644index 00000000..45b7a957--- /dev/null+++ b/backend/tests/test_account_running_balance_postgres.py@@ -0,0 +1,85 @@+"""Running balance (#1202) on real PostgreSQL: the window and the daily series."""+import uuid+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal++import pytest+import pytest_asyncio+from httpx import ASGITransport, AsyncClient++from app.core.database import get_async_session+from app.main import app+from app.models.account import Account+from app.models.category import Category+from app.models.transaction import Transaction++pytestmark = pytest.mark.asyncio+++@pytest_asyncio.fixture+async def session(postgres_sessions):+ async with postgres_sessions() as session:+ yield session+ await session.rollback()+++def clean_db(postgres_sessions):+ """The reused user/data fixtures start in a fresh per-test PostgreSQL schema."""+++@pytest_asyncio.fixture+async def client(postgres_sessions, monkeypatch):+ async def pg_session():+ async with postgres_sessions() as session:+ yield session++ monkeypatch.setitem(app.dependency_overrides, get_async_session, pg_session)+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ yield client+++async def test_running_balance_list_and_series_agree(client, auth_headers, session, test_user):+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, name="Running PG", type="checking",+ balance=Decimal("0"), currency="BRL",+ )+ ignored = Category(id=uuid.uuid4(), user_id=test_user.id, name="Ignored", is_ignored=True)+ session.add_all([account, ignored])+ await session.commit()+ created = datetime(2026, 1, 1, tzinfo=timezone.utc)+ for offset, (amount, txn_type, day, extra) in enumerate([+ ("1000", "credit", date(2026, 1, 20), {"source": "opening_balance"}),+ ("200", "credit", date(2026, 2, 2), {}),+ ("50", "debit", date(2026, 2, 5), {"status": "pending"}),+ ("30", "debit", date(2026, 2, 5), {"category_id": ignored.id}),+ ("400", "debit", date(2026, 2, 20), {}),+ ]):+ session.add(Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=account.id,+ description=f"{txn_type} {amount}", amount=Decimal(amount), currency="BRL",+ type=txn_type, date=day, source=extra.pop("source", "manual"),+ created_at=created + timedelta(seconds=offset), **extra,+ ))+ await session.commit()+ range_params = {"from": "2026-02-01", "to": "2026-02-28"}++ pages = []+ for page in (1, 2):+ response = await client.get("/api/transactions", params={+ "account_id": str(account.id), "include_running_balance": "true",+ "include_opening_balance": "true", "limit": 2, "page": page, **range_params,+ }, headers=auth_headers)+ assert response.status_code == 200, response.text+ pages += response.json()["items"]+ series = await client.get(+ f"/api/accounts/{account.id}/running-balance", params=range_params, headers=auth_headers,+ )++ assert [tx["running_balance"] for tx in pages] == [750, 1150, 1150, 1200]+ assert series.status_code == 200, series.text+ points = series.json()+ assert len(points) == 28+ assert points[0]["balance"] == 1000+ assert points[4]["balance"] == 1150+ assert points[-1]["balance"] == pages[0]["running_balance"]diff --git a/frontend/src/lib/account-detail-utils.test.ts b/frontend/src/lib/account-detail-utils.test.tsindex e9ea2aff..92cbc88a 100644--- a/frontend/src/lib/account-detail-utils.test.ts+++ b/frontend/src/lib/account-detail-utils.test.ts@@ -3,6 +3,8 @@ import { describe, expect, it } from 'vitest'import {applyTransactionToBalance,excludeMaterializedProjections,+ mergeRunningBalances,+ runningBalanceChartFrom,} from './account-detail-utils'describe('applyTransactionToBalance', () => {@@ -72,3 +74,108 @@ describe('excludeMaterializedProjections', () => {expect(result).toEqual([projections[1], projections[2]])})})++describe('mergeRunningBalances', () => {+ // Real rows as the API sends them: newest first, each with the balance+ // right after it.+ const row = (id: string, date: string, balance: number, balancePrimary: number | null = null) => ({+ id, date, running_balance: balance, running_balance_primary: balancePrimary,+ })+ const projection = (id: string, date: string, amount: number, type: 'debit' | 'credit' = 'debit') => ({+ id, date, amount, amount_primary: null, currency: 'BRL', is_ignored: false, source: 'projected', type,+ })+ const options = { openingBalance: 1000, hasMore: false, usePrimary: false, displayCurrency: 'BRL' }+ const balances = (merged: { id: string; runningBalance: number }[]) =>+ merged.map(({ id, runningBalance }) => [id, runningBalance])++ it('places a projection after the real rows of its date and adds it to later rows', () => {+ const rows = [row('c', '2026-09-20', 700), row('b', '2026-09-10', 900), row('a', '2026-09-10', 950)]++ const merged = mergeRunningBalances(rows, [projection('p', '2026-09-10', 100)], options)++ expect(balances(merged)).toEqual([+ ['c', 600],+ ['p', 800],+ ['b', 900],+ ['a', 950],+ ])+ })++ it('stacks projections dated after the newest row on top of it', () => {+ const rows = [row('a', '2026-09-05', 500)]++ const merged = mergeRunningBalances(rows, [+ projection('p2', '2026-09-28', 50),+ projection('p1', '2026-09-15', 200, 'credit'),+ ], options)++ expect(balances(merged)).toEqual([+ ['p2', 650],+ ['p1', 700],+ ['a', 500],+ ])+ })++ it('starts a projection dated before every row from the opening balance', () => {+ const rows = [row('a', '2026-09-10', 1200)]++ const merged = mergeRunningBalances(rows, [projection('p', '2026-09-02', 100)], options)++ expect(balances(merged)).toEqual([+ ['a', 1100],+ ['p', 900],+ ])+ })++ it('leaves out a projection whose starting row is on a page not loaded yet', () => {+ const rows = [row('b', '2026-09-20', 700), row('a', '2026-09-15', 800)]+ const projections = [projection('p', '2026-09-05', 100)]++ const merged = mergeRunningBalances(rows, projections, { ...options, hasMore: true })++ // The newer rows still count it: it sorts before them either way.+ expect(balances(merged)).toEqual([+ ['b', 600],+ ['a', 700],+ ])++ const older = [...rows, row('z', '2026-09-01', 950)]+ expect(balances(mergeRunningBalances(older, projections, { ...options, hasMore: true }))).toEqual([+ ['b', 600],+ ['a', 700],+ ['p', 850],+ ['z', 950],+ ])+ })++ it('shows projections from the opening balance when the range has no rows', () => {+ const merged = mergeRunningBalances([], [projection('p', '2026-09-10', 100)], options)++ expect(balances(merged)).toEqual([['p', 900]])+ expect(mergeRunningBalances([], [], options)).toEqual([])+ })++ it('reads the primary-currency balance only when the primary currency is shown', () => {+ const rows = [row('a', '2026-09-10', 100, 520)]++ expect(balances(mergeRunningBalances(rows, [], options))).toEqual([['a', 100]])+ expect(balances(mergeRunningBalances(rows, [], { ...options, usePrimary: true }))).toEqual([['a', 520]])+ // An account in the primary currency has no separate primary balance.+ const domestic = [row('a', '2026-09-10', 100)]+ expect(balances(mergeRunningBalances(domestic, [], { ...options, usePrimary: true }))).toEqual([['a', 100]])+ })+})++describe('runningBalanceChartFrom', () => {+ it('keeps a range the endpoint accepts', () => {+ expect(runningBalanceChartFrom('2025-08-01', '2026-10-31')).toBe('2025-08-01')+ })++ it('charts the latest ten years of a longer range', () => {+ expect(runningBalanceChartFrom('2000-01-01', '2026-10-31')).toBe('2016-10-31')+ })++ it('stays inside the cap when the range ends on Feb 29', () => {+ expect(runningBalanceChartFrom('2000-01-01', '2024-02-29')).toBe('2014-03-01')+ })+})diff --git a/frontend/src/lib/account-detail-utils.ts b/frontend/src/lib/account-detail-utils.tsindex 70069a3c..ff1bb06f 100644--- a/frontend/src/lib/account-detail-utils.ts+++ b/frontend/src/lib/account-detail-utils.ts@@ -1,3 +1,5 @@+import { addDays, addYears, format, parseISO, subYears } from 'date-fns'+import type { ProjectedTransaction, Transaction } from '../types'type BalanceTransaction = Pick<@@ -61,3 +63,84 @@ export function excludeMaterializedProjections<(projection) => !materialized.has(`${projection.recurring_id}:${projection.date}`),)}++type ServerBalanceRow = Pick<Transaction, 'date' | 'running_balance' | 'running_balance_primary'>++type ProjectionRow = BalanceTransaction & Pick<Transaction, 'date'>++/**+ * Give every loaded row and recurring projection its running balance, newest+ * first (#1202).+ *+ * `rows` are real transactions in API order (newest first, possibly only the+ * first pages) carrying the server's balance right after each of them. The+ * server walks the whole range, so a row's balance never depends on which+ * pages are loaded; projections are the only thing added on top.+ *+ * Projections keep the placement the walk always gave them: by date, after+ * the real rows of the same date. So a real row adds every projection dated+ * before it, and a projection starts from the newest real row dated on or+ * before it (or `openingBalance` when the range has none) and adds every+ * projection up to and including itself. While older pages remain, a+ * projection with no loaded row on or before its date is left out: its+ * starting point is on a page not fetched yet.+ */+export function mergeRunningBalances<R extends ServerBalanceRow, P extends ProjectionRow>(+ rows: R[],+ projections: P[],+ options: {+ openingBalance: number+ hasMore: boolean+ usePrimary: boolean+ displayCurrency: string+ },+): Array<(R | P) & { runningBalance: number }> {+ const { openingBalance, hasMore, usePrimary, displayCurrency } = options+ // The page only lists rows the server walked, so a null here is not expected.+ const serverBalance = (row: R) => (+ usePrimary ? row.running_balance_primary ?? row.running_balance : row.running_balance+ ) ?? 0++ // Stable, so same-day projections keep the order they came in.+ const ascending = [...projections].sort((a, b) => a.date.localeCompare(b.date))+ let total = 0+ const projectedUpTo = ascending.map((projection) => (+ total = applyTransactionToBalance(total, projection, usePrimary, displayCurrency)+ ))++ const merged: Array<(R | P) & { runningBalance: number }> = []+ let next = ascending.length - 1+ for (let i = 0; i <= rows.length; i++) {+ const row = rows[i] as R | undefined+ // Projections on or after this row's date sit above it, and this row is+ // the newest real row on or before each of them.+ for (; next >= 0 && (!row || ascending[next].date >= row.date); next--) {+ if (!row && hasMore) continue+ const start = row ? serverBalance(row) : openingBalance+ merged.push({ ...ascending[next], runningBalance: start + projectedUpTo[next] })+ }+ if (row) {+ merged.push({ ...row, runningBalance: serverBalance(row) + (next >= 0 ? projectedUpTo[next] : 0) })+ }+ }+ return merged+}++// Mirrors the backend's `_MAX_RUNNING_BALANCE_YEARS` (backend/app/api/accounts.py),+// in calendar years like the reports' custom range.+const RUNNING_BALANCE_MAX_YEARS = 10++/**+ * First day the chart asks the running-balance series for. A range longer than+ * the endpoint allows charts its latest part; the list still covers it all.+ */+export function runningBalanceChartFrom(from: string, to: string): string {+ if (!from || !to) return from+ const end = parseISO(to)+ let earliest = subYears(end, RUNNING_BALANCE_MAX_YEARS)+ // Ten years back from a Feb 29 lands on Feb 28, and the backend's year step+ // from there stops a day short of `to`.+ if (addYears(earliest, RUNNING_BALANCE_MAX_YEARS) < end) earliest = addDays(earliest, 1)+ const earliestDay = format(earliest, 'yyyy-MM-dd')+ return from < earliestDay ? earliestDay : from+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 6be66d2a..71d78bac 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -15,6 +15,7 @@ import type {ConnectionSettings,Account,AccountSummary,+ AccountRunningBalancePoint,Collection,CreditCardBill,DescriptionSuggestion,@@ -487,6 +488,10 @@ export const accounts = {const { data } = await api.get(`/accounts/${id}/balance-history`, { params: { from, to } })return data},+ runningBalance: async (id: string, from?: string, to?: string): Promise<AccountRunningBalancePoint[]> => {+ const { data } = await api.get(`/accounts/${id}/running-balance`, { params: { from, to } })+ return data+ },bills: async (id: string, limit = 24): Promise<CreditCardBill[]> => {const { data } = await api.get(`/accounts/${id}/bills`, { params: { limit } })return data@@ -521,6 +526,7 @@ export const transactions = {page?: numberlimit?: numberinclude_opening_balance?: boolean+ include_running_balance?: booleanexclude_transfers?: booleanuser_pnl_only?: booleanexclude_ignored?: booleandiff --git a/frontend/src/pages/account-detail-opening-balance.test.tsx b/frontend/src/pages/account-detail-opening-balance.test.tsxindex 08a01e14..54f61765 100644--- a/frontend/src/pages/account-detail-opening-balance.test.tsx+++ b/frontend/src/pages/account-detail-opening-balance.test.tsx@@ -19,7 +19,7 @@ const asgiFixture = asgiFixturePath: nullconst api = vi.hoisted(() => ({- accounts: { get: vi.fn(), bills: vi.fn(), summary: vi.fn(), list: vi.fn(), update: vi.fn() },+ accounts: { get: vi.fn(), bills: vi.fn(), summary: vi.fn(), list: vi.fn(), update: vi.fn(), runningBalance: vi.fn() },transactions: { list: vi.fn(), update: vi.fn(), delete: vi.fn(), create: vi.fn() },dashboard: { projectedTransactions: vi.fn() },categories: { list: vi.fn() },@@ -94,6 +94,7 @@ beforeEach(async () => {api.transactions.list.mockResolvedValue(asgiFixture?.responses.en ?? { items, total: items.length },)+ api.accounts.runningBalance.mockResolvedValue([])api.dashboard.projectedTransactions.mockResolvedValue([])api.categories.list.mockResolvedValue([])api.categoryGroups.list.mockResolvedValue([])diff --git a/frontend/src/pages/account-detail-running-balance.test.tsx b/frontend/src/pages/account-detail-running-balance.test.tsxnew file mode 100644index 00000000..7683f0b2--- /dev/null+++ b/frontend/src/pages/account-detail-running-balance.test.tsx@@ -0,0 +1,206 @@+/**+ * Account balances past the first page of transactions (#1202).+ *+ * The page used to fetch one page of 500 rows and walk them from the opening+ * balance, so every row past the 500th was never applied: the Balance column,+ * the chart and the Projected Balance card all stopped short of the truth.+ * A non-credit-card account now pages through the list and takes each row's+ * balance, and the chart's series, from the server. A credit card keeps its+ * cycle math, over every page of the cycle.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, waitFor, within } from '@testing-library/react'++import AccountDetailPage from '@/pages/account-detail'+import { renderWithProviders } from '@/test/utils'+import type { Transaction } from '@/types'++const api = vi.hoisted(() => ({+ accounts: {+ get: vi.fn(),+ bills: vi.fn(),+ summary: vi.fn(),+ list: vi.fn(),+ update: vi.fn(),+ runningBalance: vi.fn(),+ },+ transactions: { list: vi.fn(), update: vi.fn(), delete: vi.fn(), create: vi.fn() },+ dashboard: { projectedTransactions: vi.fn() },+ categories: { list: vi.fn() },+ categoryGroups: { list: vi.fn() },+}))++vi.mock('@/lib/api', () => ({+ accounts: api.accounts,+ transactions: api.transactions,+ dashboard: api.dashboard,+ categories: api.categories,+ categoryGroups: api.categoryGroups,+}))+vi.mock('@/hooks/use-mobile', () => ({ useIsMobile: () => false }))+vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))+vi.mock('@/hooks/use-privacy-mode', () => ({+ usePrivacyMode: () => ({ mask: (value: string) => value, privacyMode: false, MASK: '***' }),+}))+vi.mock('@/contexts/auth-context', () => ({+ useAuth: () => ({ user: { preferences: { currency_display: 'BRL' } } }),+}))+vi.mock('@/contexts/workspace-context', () => ({+ useWorkspace: () => ({ canWrite: true }),+}))++const checking = {+ id: 'acc-1', name: 'Checking', type: 'checking', currency: 'BRL',+ balance: 9000, current_balance: 9000, is_active: true,+}++const card = {+ id: 'acc-1', name: 'Card', type: 'credit_card', currency: 'BRL',+ balance: -501, is_active: true, credit_limit: 5000,+ statement_close_day: 30, payment_due_day: 10,+}++/** A R$1 debit. Its amount alone can never add up to the balances below,+ * so any balance on screen that matches them came from the server. */+function tx(index: number, date: string, runningBalance: number | null): Transaction {+ return {+ id: `tx-${index}`, user_id: 'user-1', account_id: 'acc-1', category_id: null,+ category: null, external_id: null, description: `Payment ${index}`,+ original_description: null, amount: 1, currency: 'BRL', date, type: 'debit',+ source: 'manual', status: 'posted', payee: null, payee_id: null,+ payee_name: null, notes: null, transfer_pair_id: null, amount_primary: null,+ fx_rate_used: null, fx_fallback: false, installment_number: null,+ total_installments: null, installment_total_amount: null,+ installment_purchase_date: null, installment_series_id: null, bill_id: null,+ effective_bill_date: null, splits: [], is_ignored: false,+ running_balance: runningBalance, running_balance_primary: null,+ }+}++// 150 rows newest first, six a day from 2026-09-27 down; the server's+// balance after row i is 9000 - 10i.+const ledger = Array.from({ length: 150 }, (_, i) =>+ tx(i, `2026-09-${String(27 - Math.floor(i / 6)).padStart(2, '0')}`, 9000 - 10 * i),+)++function listPage(rows: Transaction[], args: { page?: number; limit?: number }) {+ const limit = args.limit ?? 50+ const page = args.page ?? 1+ return { items: rows.slice((page - 1) * limit, page * limit), total: rows.length, page, limit }+}++function balanceCell(description: string) {+ const row = screen.getByText(description).closest('tr')!+ return row.querySelectorAll('td')[4]+}++async function renderPage() {+ return renderWithProviders(<AccountDetailPage />, {+ route: '/accounts/acc-1',+ path: '/accounts/:id',+ })+}++beforeEach(() => {+ vi.clearAllMocks()+ vi.setSystemTime(new Date('2026-09-15T12:00:00'))+ api.accounts.list.mockResolvedValue([])+ api.accounts.bills.mockResolvedValue([])+ api.accounts.summary.mockResolvedValue({+ opening_balance: 0, current_balance: 9000, monthly_income: 0, monthly_expenses: 0,+ projected_income: 0, projected_expenses: 0,+ })+ api.categories.list.mockResolvedValue([])+ api.categoryGroups.list.mockResolvedValue([])+ api.dashboard.projectedTransactions.mockResolvedValue([])+ api.accounts.runningBalance.mockResolvedValue([])+})++describe('a non-credit-card account with more rows than one page', () => {+ beforeEach(() => {+ api.accounts.get.mockResolvedValue(checking)+ api.transactions.list.mockImplementation(async (args) => listPage(ledger, args))+ api.dashboard.projectedTransactions.mockResolvedValue([{+ recurring_id: 'rec-1', account_id: 'acc-1', description: 'Rent', amount: 500,+ amount_primary: null, currency: 'BRL', type: 'debit', date: '2026-09-28',+ category_id: null, category_name: null, category_icon: null, category_color: null,+ }])+ })++ it('shows the balance the server computed over the whole period', async () => {+ await renderPage()++ expect(await screen.findByText('Payment 0')).toBeVisible()+ expect(balanceCell('Payment 0')).toHaveTextContent('R$9,000.00')+ expect(balanceCell('Payment 99')).toHaveTextContent('R$8,010.00')+ // The projection sits on top of the newest row it follows.+ expect(balanceCell('Rent')).toHaveTextContent('R$8,500.00')+ expect(screen.queryByText('Payment 100')).not.toBeInTheDocument()+ expect(api.transactions.list).toHaveBeenCalledWith(expect.objectContaining({+ page: 1, limit: 100, include_running_balance: true, include_opening_balance: true,+ }))+ })++ it('takes the Projected Balance card from the newest row', async () => {+ await renderPage()++ const card = (await screen.findByText('Projected Balance')).parentElement!+ await waitFor(() => expect(within(card).getByText('R$8,500.00')).toBeVisible())+ expect(within(card).getByText('Not settled: R$500.00')).toBeVisible()+ })++ it('appends the next page when asked to show more', async () => {+ const { user } = await renderPage()++ await user.click(await screen.findByRole('button', { name: '+50 more' }))++ expect(await screen.findByText('Payment 149')).toBeVisible()+ expect(balanceCell('Payment 149')).toHaveTextContent('R$7,510.00')+ expect(balanceCell('Payment 0')).toHaveTextContent('R$9,000.00')+ expect(api.transactions.list).toHaveBeenLastCalledWith(expect.objectContaining({ page: 2, limit: 100 }))+ expect(screen.queryByRole('button', { name: /more$/ })).not.toBeInTheDocument()+ })++ it('draws the chart from the running-balance series', async () => {+ // One point a day; nothing in the loaded rows comes close to 20,000.+ api.accounts.runningBalance.mockResolvedValue(+ Array.from({ length: 30 }, (_, i) => ({+ date: `2026-09-${String(i + 1).padStart(2, '0')}`,+ balance: 20000,+ balance_primary: null,+ })),+ )++ await renderPage()++ expect(await screen.findByText('R$20,000')).toBeInTheDocument()+ expect(api.accounts.runningBalance).toHaveBeenCalledWith('acc-1', '2026-09-01', '2026-09-30')+ })+})++describe('a credit-card cycle with more rows than one page', () => {+ it('loads every page of the cycle', async () => {+ api.accounts.get.mockResolvedValue(card)+ // One charge past a full page, newest first, 25 a day from 2026-09-21.+ const cycle = Array.from({ length: 501 }, (_, i) =>+ tx(i, `2026-09-${String(21 - Math.floor(i / 25)).padStart(2, '0')}`, null),+ )+ api.transactions.list.mockImplementation(async (args) => listPage(cycle, args))++ await renderPage()++ expect(await screen.findByText('Payment 500')).toBeInTheDocument()+ // The top row carries the cumulative cycle spend: all 501 charges, not+ // the first 500.+ const topRow = screen.getAllByRole('row')[1]+ expect(topRow.querySelectorAll('td')[4]).toHaveTextContent('R$501.00')+ expect(api.transactions.list).toHaveBeenCalledWith(expect.objectContaining({ page: 2, limit: 500 }))+ expect(api.accounts.runningBalance).not.toHaveBeenCalled()+ expect(screen.queryByRole('button', { name: /more$/ })).not.toBeInTheDocument()+ // Over 500 table rows is the point of the test, and rendering them under+ // a fully parallel run takes longer than the default 5s.+ }, 20_000)+})diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex 1dc2fbfa..28dbc6fe 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -3,11 +3,11 @@ import { getAccountName } from '@/lib/account-utils'import { useParams, Link } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'-import { useQuery, useQueries, useMutation, useQueryClient } from '@tanstack/react-query'+import { useQuery, useQueries, useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { format, addDays, addMonths, parseISO } from 'date-fns'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 { applyTransactionToBalance, excludeMaterializedProjections, mergeRunningBalances, runningBalanceChartFrom, transactionAmountForBalance } from '@/lib/account-detail-utils'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { shouldShowPendingBadge } from '@/lib/transaction-status'import { closeDateForBill, isOpenCycleWindow } from '@/lib/credit-card-cycle'@@ -45,6 +45,12 @@ import {ResponsiveContainer,} from 'recharts'+// Rows per "Show more" on a non-credit-card account. Balances come from the+// server, so they hold whatever has been loaded (#1202).+const TRANSACTIONS_PAGE_SIZE = 100+// The API's cap on one page; a credit-card cycle is fetched in full.+const CYCLE_PAGE_SIZE = 500+function defaultFrom() {const now = new Date()return localDateString(new Date(now.getFullYear(), now.getMonth(), 1))@@ -510,25 +516,77 @@ export default function AccountDetailPage() {})),})- 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({+ // A credit-card cycle is bounded by its bill, so the card keeps the+ // client-side cycle math below, which needs every row of the cycle rather+ // than the first page (#1202).+ const { data: cycleTxData, isLoading: cycleTxLoading } = useQuery({+ queryKey: ['transactions', { account_id: id, bill_id: activeBill?.id, from: filterFrom, to: filterTo, include_opening_balance: true, unbilled_only: isInProgressCycle }],+ queryFn: async () => {+ const params = {+ account_id: id,+ // When the active cycle is a real bill, prefer bill_id (Pluggy's+ // truth — picks up charges the bank rolled outside the nominal date+ // range) AND keep from/to so manual / non-bill-linked txs (recurring+ // fills, CSV imports) bucketed into this cycle still show up.+ bill_id: activeBill?.id,+ // For the in-progress cycle (CC has bills, but no bill matches the+ // current view), exclude already-billed txs so the bar/list only+ // shows what's accumulating toward the next bill.+ unbilled_only: isInProgressCycle || undefined,+ from: filterFrom || undefined,+ to: filterTo || undefined,+ limit: CYCLE_PAGE_SIZE,+ include_opening_balance: true,+ }+ const first = await transactions.list({ ...params, page: 1 })+ const items = [...first.items]+ // An empty page ends the loop even if `total` moved under us.+ for (let page = 2; items.length < first.total; page++) {+ const next = await transactions.list({ ...params, page })+ if (next.items.length === 0) break+ items.push(...next.items)+ }+ return { ...first, items }+ },+ enabled: !!id && account?.type === 'credit_card',+ })++ // Any other account pages through the period newest first. Each row+ // carries the balance right after it, which the server walks over the+ // whole range, so a page's balances don't depend on the pages before or+ // after it being loaded (#1202).+ const ledger = useInfiniteQuery({+ queryKey: ['transactions', { account_id: id, from: filterFrom, to: filterTo, limit: TRANSACTIONS_PAGE_SIZE, include_opening_balance: true, include_running_balance: true }],+ queryFn: ({ pageParam }) => transactions.list({account_id: id,- // When the active cycle is a real bill, prefer bill_id (Pluggy's- // truth — picks up charges the bank rolled outside the nominal date- // range) AND keep from/to so manual / non-bill-linked txs (recurring- // fills, CSV imports) bucketed into this cycle still show up.- bill_id: activeBill?.id,- // For the in-progress cycle (CC has bills, but no bill matches the- // current view), exclude already-billed txs so the bar/list only- // shows what's accumulating toward the next bill.- unbilled_only: isInProgressCycle || undefined,from: filterFrom || undefined,to: filterTo || undefined,- limit: 500,+ page: pageParam,+ limit: TRANSACTIONS_PAGE_SIZE,include_opening_balance: true,+ include_running_balance: true,}),- enabled: !!id,+ initialPageParam: 1,+ getNextPageParam: (lastPage, pages) => {+ const loaded = pages.reduce((count, page) => count + page.items.length, 0)+ return loaded < lastPage.total && lastPage.items.length > 0 ? pages.length + 1 : undefined+ },+ enabled: !!id && !!account && account.type !== 'credit_card',+ })+ const ledgerItems = useMemo(+ () => ledger.data?.pages.flatMap((page) => page.items),+ [ledger.data],+ )+ const ledgerTotal = ledger.data?.pages.at(-1)?.total ?? 0++ // The chart spans the whole period whichever pages the list has loaded,+ // so its balances come from the server as well (#1202). A range longer than+ // the endpoint allows charts its latest part; the list still covers it all.+ const chartFrom = runningBalanceChartFrom(filterFrom, filterTo)+ const { data: runningBalanceSeries, isLoading: runningBalanceLoading } = useQuery({+ queryKey: ['accounts', id, 'running-balance', chartFrom, filterTo],+ queryFn: () => accounts.runningBalance(id!, chartFrom || undefined, filterTo || undefined),+ enabled: !!id && !!account && account.type !== 'credit_card',})// Non-materialized recurring projections are forecast rows. They are kept@@ -640,17 +698,21 @@ export default function AccountDetailPage() {const primaryShown = showPrimary && !fxFallbackconst usePrimary = !isForeignCurrency || primaryShownconst displayCurrency = (isForeignCurrency && !primaryShown) ? (account?.currency || userCurrency) : userCurrency+ const txLoading = isCreditCard ? cycleTxLoading : ledger.isLoading+ const chartLoading = isCreditCard ? cycleTxLoading : runningBalanceLoading// 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[] => {+ // into displayRows where running balances are computed for them. The+ // projections endpoint already drops materialized occurrences; checking+ // the loaded rows as well covers a list fresher than the projections.+ const projectedRows = useMemo((): Transaction[] => {if (!projectedTxData) return []const unmaterialized = excludeMaterializedProjections(projectedTxData,- txData?.items ?? [],+ ledgerItems ?? [],)- return unmaterialized.map((p: ProjectedTransaction): TxWithBalance => ({+ return unmaterialized.map((p: ProjectedTransaction): Transaction => ({id: `projected-${p.recurring_id}-${p.date}`,user_id: '',account_id: id ?? null,@@ -697,27 +759,26 @@ export default function AccountDetailPage() {splits: [],is_ignored: false,virtual: true,- runningBalance: 0,}))- }, [projectedTxData, txData?.items, id])+ }, [projectedTxData, ledgerItems, 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).+ // Balance at the start of the period, which projections dated before the+ // first real row of the range start from. 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 seeded from the current posted balance.- // Pending and recurring rows are added only to this forecast walk.+ // - Non-CC: the server's end-of-day balance (pending rows included), with+ // recurring projections added on top as a running forecast.// - 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(() => {if (isCreditCard) {- if (!txData?.items) return []+ if (!cycleTxData?.items) return []const byDay = new Map<string, number>()- for (const tx of txData.items) {+ for (const tx of cycleTxData.items) {if (tx.type !== 'debit') continueif (tx.source === 'opening_balance') continueif (tx.transfer_pair_id) continue@@ -759,29 +820,23 @@ export default function AccountDetailPage() {}return series}- 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))+ if (!runningBalanceSeries) return []+ const projectedByDay = new Map<string, number>()+ for (const tx of projectedRows) {+ const previous = projectedByDay.get(tx.date) ?? 0+ projectedByDay.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])+ let projected = 0+ return runningBalanceSeries.map((point) => {+ projected += projectedByDay.get(point.date) ?? 0+ const balance = usePrimary ? (point.balance_primary ?? point.balance) : point.balance+ return { label: formatDateStr(point.date, dateLocale), date: point.date, balance: balance + projected }+ })+ }, [isCreditCard, cycleTxData, runningBalanceSeries, projectedRows, filterFrom, filterTo, dateLocale, usePrimary, displayCurrency, activeBill])const ccRunningTotal = useMemo((): TxWithBalance[] => {- if (!isCreditCard || !txData?.items) return []- const ascending = [...txData.items].sort(+ if (!isCreditCard || !cycleTxData?.items) return []+ const ascending = [...cycleTxData.items].sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),)let running = 0@@ -795,29 +850,21 @@ export default function AccountDetailPage() {return { ...tx, runningBalance: running }})return withBalance.reverse()- }, [txData, isCreditCard, usePrimary, displayCurrency])+ }, [cycleTxData, 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.+ // projections. The newest row is the forecast at the end of the range,+ // even before the older pages are loaded (#1202).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])+ if (!ledgerItems || summary === undefined) return []+ return mergeRunningBalances(ledgerItems, projectedRows, {+ openingBalance,+ hasMore: ledger.hasNextPage,+ usePrimary,+ displayCurrency,+ })+ }, [ledgerItems, ledger.hasNextPage, projectedRows, isCreditCard, summary, usePrimary, displayCurrency, openingBalance, ccRunningTotal])const totalBalance = (usePrimary ? summary?.current_balance_primary : undefined) ?? summary?.current_balance ?? 0const projectedBalance = displayRows.length > 0 ? displayRows[0].runningBalance : openingBalance@@ -1439,7 +1486,7 @@ export default function AccountDetailPage() {</p></div><div className="px-1 pb-4 h-[280px]">- {txLoading ? (+ {chartLoading ? (<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">@@ -1722,6 +1769,20 @@ export default function AccountDetailPage() {</table></div>)}+ {!isCreditCard && ledger.hasNextPage && (+ <button+ type="button"+ className="w-full px-4 py-2.5 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors border-t border-border disabled:cursor-not-allowed disabled:opacity-50"+ disabled={ledger.isFetchingNextPage}+ onClick={() => ledger.fetchNextPage()}+ >+ {ledger.isFetchingNextPage+ ? t('common.loading')+ : t('common.showMore', {+ count: Math.min(TRANSACTIONS_PAGE_SIZE, ledgerTotal - (ledgerItems?.length ?? 0)),+ })}+ </button>+ )}</div></div>diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex c81786f8..f4db89ee 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -305,6 +305,12 @@ export interface Transaction {is_ignored: boolean// Keeps the transaction in the ledger/balance while excluding it from P&L.exclude_from_pnl?: boolean+ // Balance right after this row, filled by the server only when the list+ // was asked for it on a single non-credit-card account (#1202).+ // `running_balance_primary` is null when the account is in the primary+ // currency.+ running_balance?: number | null+ running_balance_primary?: number | nullvirtual?: boolean}@@ -747,6 +753,13 @@ export interface DailyBalance {balance: number | null}+/** End-of-day balance of one account, one point per day (#1202). */+export interface AccountRunningBalancePoint {+ date: string+ balance: number+ balance_primary: number | null+}+export interface BalanceHistory {current: DailyBalance[]previous: DailyBalance[]