Skip to content

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

fix(accounts): report real balances from the single-account endpoints (#1064)

Paul Spallini34834cb78ba8
diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.py
index a308ceee..a4268f1d 100644
--- a/backend/app/api/accounts.py
+++ b/backend/app/api/accounts.py
@@ -136,10 +136,10 @@ async def get_account(
ctx: WorkspaceContext = Depends(current_workspace),
session: AsyncSession = Depends(get_async_session),
):
- account = await account_service.get_account(session, account_id, ctx.workspace.id)
+ account = await account_service.get_account_with_balances(session, account_id, ctx.workspace.id)
if not account:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")
- return account_service.serialize_account(account, None, None, account.connection)
+ return account
@router.post("", response_model=AccountRead, status_code=status.HTTP_201_CREATED)
@@ -167,10 +167,10 @@ async def update_account(
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")
# Re-read post-commit so the response resolves the institution/display
# name pair exactly like GET (update_account leaves the row expired).
- account = await account_service.get_account(session, account_id, ctx.workspace.id)
+ account = await account_service.get_account_with_balances(session, account_id, ctx.workspace.id)
if not account:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Account not found")
- return account_service.serialize_account(account, None, None, account.connection)
+ return account
@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index ffad2149..425a7432 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -50,8 +50,13 @@ def _opening_balance_values(account_type: str, balance: Decimal) -> tuple[Decima
return amount, "credit" if is_credit else "debit"
-async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_closed: bool = False) -> list[dict]:
- today = app_today()
+def _balance_subqueries(today: _Date):
+ """Per-account current and previous balances, as two subqueries.
+
+ Shared by the list and the single-account read so both report the same
+ number for the same account: the detail endpoint used to serialize with no
+ balance at all, which made available_credit fall back to the full limit.
+ """
# 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)
@@ -107,8 +112,11 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c
.subquery()
)
- # Build the query
- query = (
+ return balance_sq, prev_balance_sq
+
+
+def _accounts_with_balances_query(workspace_id: uuid.UUID, balance_sq, prev_balance_sq):
+ return (
select(
Account,
BankConnection,
@@ -125,6 +133,11 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c
)
)
)
+
+
+async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_closed: bool = False) -> list[dict]:
+ balance_sq, prev_balance_sq = _balance_subqueries(app_today())
+ query = _accounts_with_balances_query(workspace_id, balance_sq, prev_balance_sq)
if not include_closed:
query = query.where(Account.is_closed == False)
query = query.order_by(Account.name)
@@ -135,6 +148,21 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c
]
+async def get_account_with_balances(
+ session: AsyncSession, account_id: uuid.UUID, workspace_id: uuid.UUID
+) -> Optional[dict]:
+ """One account, serialized with the same balances the list reports."""
+ balance_sq, prev_balance_sq = _balance_subqueries(app_today())
+ query = _accounts_with_balances_query(workspace_id, balance_sq, prev_balance_sq).where(
+ Account.id == account_id
+ )
+ row = (await session.execute(query)).first()
+ if row is None:
+ return None
+ acc, connection, current_balance, previous_balance = row
+ return serialize_account(acc, current_balance, previous_balance, connection)
+
+
def _institution(
acc: Account, connection: Optional[BankConnection]
) -> tuple[Optional[str], Optional[str]]:
diff --git a/backend/tests/test_accounts_api.py b/backend/tests/test_accounts_api.py
index beb7d702..e40a2e59 100644
--- a/backend/tests/test_accounts_api.py
+++ b/backend/tests/test_accounts_api.py
@@ -747,3 +747,60 @@ async def test_get_account_bills_rejects_invalid_limit(
f"/api/accounts/{cc.id}/bills", headers=auth_headers, params={"limit": 0},
)
assert resp.status_code == 422 # Query(ge=1) bound
+
+
+async def test_get_account_reports_same_balance_as_list(
+ client: AsyncClient, auth_headers, session, test_user, test_workspace
+):
+ """A manual credit card's detail read must agree with the list (issue #535).
+
+ The detail endpoint used to serialize with no balance, so available_credit
+ fell back to the full limit while the list showed the real figure for the
+ same card at the same moment.
+ """
+ import uuid as _uuid
+ from datetime import date
+ from decimal import Decimal
+
+ from app.models.account import Account
+ from app.models.transaction import Transaction
+
+ card = Account(
+ id=_uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Card",
+ type="credit_card",
+ balance=Decimal("0.00"),
+ credit_limit=Decimal("1000.00"),
+ currency="BRL",
+ )
+ session.add(card)
+ await session.commit()
+
+ session.add(
+ Transaction(
+ id=_uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=card.id,
+ description="Spend",
+ amount=Decimal("400.00"),
+ type="debit",
+ date=date.today(),
+ status="posted",
+ source="manual",
+ currency="BRL",
+ )
+ )
+ await session.commit()
+
+ listed = next(
+ a for a in (await client.get("/api/accounts", headers=auth_headers)).json()
+ if a["id"] == str(card.id)
+ )
+ detail = (await client.get(f"/api/accounts/{card.id}", headers=auth_headers)).json()
+
+ assert detail["current_balance"] == listed["current_balance"] == -400.0
+ assert detail["available_credit"] == listed["available_credit"] == 600.0