Open-source personal finance manager. Self-hosted, privacy-first.
fix(accounts): hold a card's limit for future-dated charges (#1197)
Shayn Hornik76d28b13b13f
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex 425a7432..5cd29e51 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -112,20 +112,48 @@ def _balance_subqueries(today: _Date):.subquery())- return balance_sq, prev_balance_sq+ # Subquery: charges dated after today (future installments, scheduled+ # purchases). They are not owed yet, so the balance leaves them out, but a+ # card's limit is already held for them (issue #1185).+ future_charges_sq = (+ select(+ Transaction.account_id,+ func.coalesce(func.sum(effective_amount), 0).label("future_charges"),+ )+ .join(Account, Transaction.account_id == Account.id)+ .outerjoin(Category, Transaction.category_id == Category.id)+ .where(+ Account.type == "credit_card",+ Transaction.type == "debit",+ Transaction.date > today,+ Transaction.is_ignored == False,+ or_(+ Transaction.category_id.is_(None),+ Category.is_ignored == False,+ ),+ )+ .group_by(Transaction.account_id)+ .subquery()+ )++ return balance_sq, prev_balance_sq, future_charges_sq-def _accounts_with_balances_query(workspace_id: uuid.UUID, balance_sq, prev_balance_sq):+def _accounts_with_balances_query(+ workspace_id: uuid.UUID, balance_sq, prev_balance_sq, future_charges_sq+):return (select(Account,BankConnection,func.coalesce(balance_sq.c.current_balance, 0).label("current_balance"),func.coalesce(prev_balance_sq.c.previous_balance, 0).label("previous_balance"),+ func.coalesce(future_charges_sq.c.future_charges, 0).label("future_charges"),).outerjoin(BankConnection).outerjoin(balance_sq, Account.id == balance_sq.c.account_id).outerjoin(prev_balance_sq, Account.id == prev_balance_sq.c.account_id)+ .outerjoin(future_charges_sq, Account.id == future_charges_sq.c.account_id).where(or_(Account.workspace_id == workspace_id,@@ -136,15 +164,16 @@ def _accounts_with_balances_query(workspace_id: uuid.UUID, balance_sq, prev_balaasync 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)+ query = _accounts_with_balances_query(workspace_id, *_balance_subqueries(app_today()))if not include_closed:query = query.where(Account.is_closed == False)query = query.order_by(Account.name)result = await session.execute(query)return [- serialize_account(acc, current_balance, previous_balance, connection)- for acc, connection, current_balance, previous_balance in result.all()+ serialize_account(+ acc, current_balance, previous_balance, connection, future_charges=future_charges+ )+ for acc, connection, current_balance, previous_balance, future_charges in result.all()]@@ -152,15 +181,16 @@ 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- )+ query = _accounts_with_balances_query(+ workspace_id, *_balance_subqueries(app_today())+ ).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)+ acc, connection, current_balance, previous_balance, future_charges = row+ return serialize_account(+ acc, current_balance, previous_balance, connection, future_charges=future_charges+ )def _institution(@@ -190,6 +220,8 @@ def serialize_account(current_balance: Optional[Decimal],previous_balance: Optional[Decimal],connection: Optional[BankConnection] = None,+ *,+ future_charges: Optional[Decimal] = None,) -> dict:# Connected CC: provider stores positive for debt → negate.# Manual accounts: transaction math already gives correct sign.@@ -229,7 +261,13 @@ def serialize_account(}if acc.type == "credit_card":- available = compute_available_credit(acc.credit_limit, Decimal(str(resolved_balance)))+ # A manual card's limit also covers charges dated after today, such as+ # the remaining installments of a purchase. A connected card's+ # provider balance is used as-is.+ held = Decimal("0") if acc.connection_id else Decimal(str(future_charges or 0))+ available = compute_available_credit(+ acc.credit_limit, Decimal(str(resolved_balance)) - held+ )payload["available_credit"] = float(available) if available is not None else Nonecycle = get_cycle_dates(acc.statement_close_day, acc.payment_due_day)payload["next_close_date"] = cycle["next_close_date"]diff --git a/backend/tests/test_accounts_api.py b/backend/tests/test_accounts_api.pyindex e40a2e59..baeb631d 100644--- a/backend/tests/test_accounts_api.py+++ b/backend/tests/test_accounts_api.py@@ -804,3 +804,113 @@ async def test_get_account_reports_same_balance_as_list(assert detail["current_balance"] == listed["current_balance"] == -400.0assert detail["available_credit"] == listed["available_credit"] == 600.0+++async def test_available_credit_holds_future_dated_charges(+ client: AsyncClient, auth_headers, session, test_user, test_workspace+):+ """Future installments are not owed yet, but the card's limit is already+ held for them, so available credit subtracts them (issue #1185)."""+ import uuid as _uuid+ from datetime import date, timedelta+ 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="Installments Card",+ type="credit_card",+ balance=Decimal("0.00"),+ credit_limit=Decimal("11001.00"),+ currency="BRL",+ )+ session.add(card)+ await session.commit()++ today = date.today()+ for description, amount, txn_type, when in [+ ("Apple iCloud", "19.90", "debit", today),+ ("MOBILLS 2/12", "19.90", "debit", today + timedelta(days=20)),+ ("Mercado Livre 3/10", "479.45", "debit", today + timedelta(days=23)),+ # A future-dated refund does not free the limit before it happens.+ ("Refund", "50.00", "credit", today + timedelta(days=5)),+ ]:+ session.add(+ Transaction(+ id=_uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=card.id,+ description=description,+ amount=Decimal(amount),+ type=txn_type,+ date=when,+ 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()++ # Owed today is unchanged; the limit is held for the two future installments.+ assert detail["current_balance"] == listed["current_balance"] == pytest.approx(-19.90)+ assert detail["available_credit"] == listed["available_credit"] == pytest.approx(10481.75)+++async def test_available_credit_of_connected_card_ignores_future_rows(+ client: AsyncClient, auth_headers, session, test_user, test_workspace, test_connection+):+ """A connected card's provider balance is the truth; future-dated rows+ synced onto it don't change its available credit."""+ import uuid as _uuid+ from datetime import date, timedelta+ 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,+ connection_id=test_connection.id,+ name="Connected Card",+ type="credit_card",+ balance=Decimal("300.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="Future installment",+ amount=Decimal("100.00"),+ type="debit",+ date=date.today() + timedelta(days=10),+ status="posted",+ source="sync",+ currency="BRL",+ )+ )+ await session.commit()++ detail = (await client.get(f"/api/accounts/{card.id}", headers=auth_headers)).json()++ assert detail["available_credit"] == pytest.approx(700.0)