Skip to content

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

feat(accounts): show each card's open bill on shared credit lines in the sidebar (#1256)

Tássio Noronhab02463ad3861
diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.py
index d82c1e2b..51c18b55 100644
--- a/backend/app/api/accounts.py
+++ b/backend/app/api/accounts.py
@@ -41,21 +41,29 @@ async def list_accounts(
session: AsyncSession = Depends(get_async_session),
):
accounts = await account_service.get_accounts(session, ctx.workspace.id, include_closed=include_closed)
- primary_currency = ctx.user.primary_currency
for acc in accounts:
- if acc["currency"] != primary_currency:
- # Use the real rate only: the 1:1 fallback would present a foreign
- # balance as already converted (issue #1165). Leaving it unset makes
- # the UI show the native currency and flag the missing rate.
- rate = await _resolve_rate(session, acc["currency"], primary_currency)
- if rate is None:
- acc["fx_fallback"] = True
- else:
- converted = Decimal(str(acc["current_balance"])) * rate
- acc["balance_primary"] = float(converted.quantize(Decimal("0.01")))
+ await _convert_to_primary(session, acc, ctx.user.primary_currency)
return accounts
+async def _convert_to_primary(session: AsyncSession, acc: dict, primary_currency: str) -> None:
+ """Fill the primary-currency balance and open bill of a serialized account."""
+ if acc["currency"] == primary_currency:
+ return
+ # Use the real rate only: the 1:1 fallback would present a foreign
+ # balance as already converted (issue #1165). Leaving it unset makes
+ # the UI show the native currency and flag the missing rate.
+ rate = await _resolve_rate(session, acc["currency"], primary_currency)
+ if rate is None:
+ acc["fx_fallback"] = True
+ return
+ converted = Decimal(str(acc["current_balance"])) * rate
+ acc["balance_primary"] = float(converted.quantize(Decimal("0.01")))
+ if acc["open_bill_total"] is not None:
+ bill = Decimal(str(acc["open_bill_total"])) * rate
+ acc["open_bill_total_primary"] = float(bill.quantize(Decimal("0.01")))
+
+
@router.get("/{account_id}/summary", response_model=AccountSummary)
async def get_account_summary(
account_id: uuid.UUID,
@@ -191,6 +199,7 @@ async def get_account(
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")
+ await _convert_to_primary(session, account, ctx.user.primary_currency)
return account
diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.py
index d46e949a..445dafa6 100644
--- a/backend/app/schemas/account.py
+++ b/backend/app/schemas/account.py
@@ -77,6 +77,14 @@ class AccountRead(AccountBase):
card_brand: Optional[str] = None
card_level: Optional[str] = None
shared_balance_group: Optional[str] = None
+ # Open bill of a card on a shared credit line (earliest due_date on or
+ # after today), in the account's currency. The sidebar leads with it so
+ # every card stops repeating the contract-wide balance. Null when the
+ # card has no such bill, and for all accounts outside a shared line.
+ open_bill_total: Optional[float] = None
+ # Same bill converted to the user's primary currency. None when the
+ # account is already in it or no real FX rate is available.
+ open_bill_total_primary: Optional[float] = None
is_closed: bool = False
closed_at: Optional[datetime] = None
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index 2bc474a2..59737902 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -3,7 +3,17 @@ from datetime import date as _Date, datetime, timedelta, timezone
from decimal import Decimal
from typing import Optional
-from sqlalchemy import ColumnElement, Select, case, delete, func, select, or_, update
+from sqlalchemy import (
+ ColumnElement,
+ Select,
+ and_,
+ case,
+ delete,
+ func,
+ or_,
+ select,
+ update,
+)
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import contains_eager
@@ -141,11 +151,35 @@ def _balance_subqueries(today: _Date):
.subquery()
)
- return balance_sq, prev_balance_sq, future_charges_sq
+ # Subquery: the open bill of each card on a shared credit line (earliest
+ # due_date on or after today; one row per account via rn = 1). Every card
+ # on one consolidated line repeats the contract-wide balance, so the
+ # sidebar shows the card's own bill instead (issue #684).
+ open_bill_sq = (
+ select(
+ CreditCardBill.account_id,
+ CreditCardBill.total_amount,
+ func.row_number()
+ .over(
+ partition_by=CreditCardBill.account_id,
+ order_by=CreditCardBill.due_date,
+ )
+ .label("rn"),
+ )
+ .join(Account, CreditCardBill.account_id == Account.id)
+ .where(
+ Account.type == "credit_card",
+ Account.shared_balance_group.isnot(None),
+ CreditCardBill.due_date >= today,
+ )
+ .subquery()
+ )
+
+ return balance_sq, prev_balance_sq, future_charges_sq, open_bill_sq
def _accounts_with_balances_query(
- workspace_id: uuid.UUID, balance_sq, prev_balance_sq, future_charges_sq
+ workspace_id: uuid.UUID, balance_sq, prev_balance_sq, future_charges_sq, open_bill_sq
):
return (
select(
@@ -154,6 +188,7 @@ def _accounts_with_balances_query(
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"),
+ open_bill_sq.c.total_amount.label("open_bill_total"),
# The opening balance's date, so the edit form can show it and
# leave it alone (issue #1204).
select(func.min(Transaction.date))
@@ -169,6 +204,10 @@ def _accounts_with_balances_query(
.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)
+ .outerjoin(
+ open_bill_sq,
+ and_(Account.id == open_bill_sq.c.account_id, open_bill_sq.c.rn == 1),
+ )
.where(
or_(
Account.workspace_id == workspace_id,
@@ -191,6 +230,7 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c
previous_balance,
connection,
future_charges=future_charges,
+ open_bill_total=open_bill_total,
balance_date=balance_date,
)
for (
@@ -199,6 +239,7 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c
current_balance,
previous_balance,
future_charges,
+ open_bill_total,
balance_date,
) in result.all()
]
@@ -214,13 +255,14 @@ async def get_account_with_balances(
row = (await session.execute(query)).first()
if row is None:
return None
- acc, connection, current_balance, previous_balance, future_charges, balance_date = row
+ acc, connection, current_balance, previous_balance, future_charges, open_bill_total, balance_date = row
return serialize_account(
acc,
current_balance,
previous_balance,
connection,
future_charges=future_charges,
+ open_bill_total=open_bill_total,
balance_date=balance_date,
)
@@ -254,6 +296,7 @@ def serialize_account(
connection: Optional[BankConnection] = None,
*,
future_charges: Optional[Decimal] = None,
+ open_bill_total: Optional[Decimal] = None,
balance_date: Optional[_Date] = None,
) -> dict:
# Connected CC: provider stores positive for debt → negate.
@@ -287,6 +330,10 @@ def serialize_account(
"card_brand": acc.card_brand,
"card_level": acc.card_level,
"shared_balance_group": acc.shared_balance_group,
+ # The card's own open bill, when it sits on a shared credit line.
+ # Null for every other account and for shared cards without one.
+ "open_bill_total": float(open_bill_total) if open_bill_total is not None else None,
+ "open_bill_total_primary": None,
"institution_name": institution_name,
"institution_logo_url": institution_logo_url,
"balance_date": balance_date,
diff --git a/backend/tests/test_accounts_shared_line_bills.py b/backend/tests/test_accounts_shared_line_bills.py
new file mode 100644
index 00000000..237388bd
--- /dev/null
+++ b/backend/tests/test_accounts_shared_line_bills.py
@@ -0,0 +1,191 @@
+"""Issue #684: per-card open bill on shared credit lines in the account list.
+
+Every card on one consolidated line repeats the contract-wide balance, so the
+list also reports the card's own open bill (earliest due_date on or after
+today). Non-shared cards and shared cards without an open bill get null.
+"""
+
+import uuid
+from datetime import timedelta
+from decimal import Decimal
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.app_clock import app_today
+from app.models.account import Account
+from app.models.credit_card_bill import CreditCardBill
+from app.models.fx_rate import FxRate
+from app.models.transaction import Transaction
+
+SHARED_LINE = "test-provider:line-684"
+
+
+async def _make_card(
+ session: AsyncSession,
+ user_id,
+ workspace_id,
+ name: str,
+ external_id: str,
+ *,
+ shared: bool = True,
+ currency: str = "BRL",
+ opening: Decimal = Decimal("1500.00"),
+) -> Account:
+ """A manual credit card with an opening balance transaction."""
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ name=name,
+ type="credit_card",
+ shared_balance_group=SHARED_LINE if shared else None,
+ currency=currency,
+ external_id=external_id,
+ )
+ session.add(account)
+ await session.flush()
+ session.add(
+ Transaction(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ account_id=account.id,
+ description="OPENING BALANCE",
+ amount=opening,
+ date=app_today().replace(day=1),
+ type="debit",
+ source="opening_balance",
+ )
+ )
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+async def _add_bill(
+ session: AsyncSession,
+ user_id,
+ workspace_id,
+ account_id,
+ external_id: str,
+ due_in_days: int,
+ total,
+ currency: str = "BRL",
+):
+ bill = CreditCardBill(
+ id=uuid.uuid4(),
+ user_id=user_id,
+ workspace_id=workspace_id,
+ account_id=account_id,
+ external_id=external_id,
+ due_date=app_today() + timedelta(days=due_in_days),
+ total_amount=Decimal(str(total)),
+ currency=currency,
+ )
+ session.add(bill)
+ await session.commit()
+
+
+async def test_list_accounts_shared_line_per_card_open_bill(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_workspace
+):
+ """Each card of a shared line reports its own open bill, not the line's balance."""
+ one = await _make_card(session, test_user.id, test_workspace.id, "R684 Card One", "acc-684-1")
+ two = await _make_card(session, test_user.id, test_workspace.id, "R684 Card Two", "acc-684-2")
+ await _add_bill(session, test_user.id, test_workspace.id, one.id, "bill-1", 5, "820.50")
+ await _add_bill(session, test_user.id, test_workspace.id, two.id, "bill-2", 12, "2140.00")
+
+ resp = await client.get("/api/accounts", headers=auth_headers)
+ assert resp.status_code == 200
+ by_name = {a["name"]: a for a in resp.json()}
+ card_one, card_two = by_name["R684 Card One"], by_name["R684 Card Two"]
+
+ # The line's balance is still reported on both cards: that duplication is
+ # what the sidebar hides now, not something the API stops sending.
+ assert card_one["current_balance"] == pytest.approx(-1500.0)
+ assert card_two["current_balance"] == pytest.approx(-1500.0)
+
+ # Each card's row carries its own open bill.
+ assert card_one["open_bill_total"] == pytest.approx(820.50)
+ assert card_two["open_bill_total"] == pytest.approx(2140.00)
+ # BRL is this user's primary currency: no separate primary field.
+ assert card_one["open_bill_total_primary"] is None
+
+
+async def test_list_accounts_shared_line_earliest_open_bill_wins(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_workspace
+):
+ """With several open bills, the earliest due one is the card's open bill."""
+ card = await _make_card(session, test_user.id, test_workspace.id, "R684 Card", "acc-684-3")
+ await _add_bill(session, test_user.id, test_workspace.id, card.id, "bill-early", 3, "100.00")
+ await _add_bill(session, test_user.id, test_workspace.id, card.id, "bill-late", 10, "900.00")
+
+ resp = await client.get("/api/accounts", headers=auth_headers)
+ card_row = next(a for a in resp.json() if a["name"] == "R684 Card")
+ assert card_row["open_bill_total"] == pytest.approx(100.00)
+
+
+async def test_list_accounts_shared_line_no_open_bill_is_null(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_workspace
+):
+ """Only past-due bills, or no bills at all: the row falls back to the balance."""
+ past = await _make_card(session, test_user.id, test_workspace.id, "R684 Card Past", "acc-684-4")
+ await _make_card(session, test_user.id, test_workspace.id, "R684 Card Bare", "acc-684-5")
+ await _add_bill(session, test_user.id, test_workspace.id, past.id, "bill-past", -2, "300.00")
+
+ resp = await client.get("/api/accounts", headers=auth_headers)
+ by_name = {a["name"]: a for a in resp.json()}
+ assert by_name["R684 Card Past"]["open_bill_total"] is None
+ assert by_name["R684 Card Bare"]["open_bill_total"] is None
+ # ...and the balance still shows as before.
+ assert by_name["R684 Card Past"]["current_balance"] == pytest.approx(-1500.0)
+
+
+async def test_list_accounts_non_shared_card_has_no_open_bill(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_workspace
+):
+ """The field is restricted to shared lines: a solo card reports null."""
+ card = await _make_card(
+ session, test_user.id, test_workspace.id, "R684 Solo Card", "acc-684-6", shared=False
+ )
+ await _add_bill(session, test_user.id, test_workspace.id, card.id, "bill-solo", 5, "700.00")
+
+ resp = await client.get("/api/accounts", headers=auth_headers)
+ card_row = next(a for a in resp.json() if a["name"] == "R684 Solo Card")
+ assert card_row["open_bill_total"] is None
+ assert card_row["open_bill_total_primary"] is None
+
+
+async def test_list_accounts_shared_line_open_bill_foreign_currency(
+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_workspace
+):
+ """A foreign-currency card's bill converts with the same rate as its balance."""
+ session.add(FxRate(
+ base_currency="USD", quote_currency="BRL", date=app_today(),
+ rate=Decimal("5.0"), source="test",
+ ))
+ await session.commit()
+ card = await _make_card(
+ session, test_user.id, test_workspace.id, "R684 USD Card", "acc-684-7",
+ currency="USD", opening=Decimal("100.00"),
+ )
+ await _add_bill(
+ session, test_user.id, test_workspace.id, card.id, "bill-usd", 5, "200.00", currency="USD"
+ )
+
+ resp = await client.get("/api/accounts", headers=auth_headers)
+ card_row = next(a for a in resp.json() if a["name"] == "R684 USD Card")
+ assert card_row["open_bill_total"] == pytest.approx(200.0)
+ assert card_row["open_bill_total_primary"] == pytest.approx(1000.0)
+ assert card_row["balance_primary"] == pytest.approx(-500.0)
+ assert card_row["fx_fallback"] is False
+
+ # The single-account route converts the same way as the list.
+ single = (await client.get(f"/api/accounts/{card.id}", headers=auth_headers)).json()
+ assert single["open_bill_total_primary"] == pytest.approx(1000.0)
+ assert single["balance_primary"] == pytest.approx(-500.0)
diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsx
index 0e157293..fdc5a025 100644
--- a/frontend/src/components/app-layout.tsx
+++ b/frontend/src/components/app-layout.tsx
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect, useMemo, lazy, Suspense } from 'react'
-import { getAccountName, sortAccountsByAbsoluteBalance, sumAccountsTotal } from '@/lib/account-utils'
+import { getAccountName, sidebarAccountBalance, sortAccountsByAbsoluteBalance, sumAccountsTotal } from '@/lib/account-utils'
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useDisplayLocale } from '@/hooks/use-display-locale'
@@ -508,9 +508,9 @@ export function AppLayout() {
</button>
{accountsExpanded && (
<div className="mt-1 space-y-0.5">
- {sortAccountsByAbsoluteBalance(visibleAccounts, (a) => a.balance_primary ?? a.current_balance).slice(0, accountsShowAll ? visibleAccounts.length : 3).map((acc) => {
- const balance = Number(acc.balance_primary ?? acc.current_balance) || 0
- const balanceCurrency = acc.balance_primary != null ? userCurrency : acc.currency
+ {sortAccountsByAbsoluteBalance(visibleAccounts, (a) => sidebarAccountBalance(a).amount).slice(0, accountsShowAll ? visibleAccounts.length : 3).map((acc) => {
+ const { amount: balance, isPrimary: balanceIsPrimary } = sidebarAccountBalance(acc)
+ const balanceCurrency = balanceIsPrimary ? userCurrency : acc.currency
const typeKey = acc.type.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase()).replace(/^./, c => c.toUpperCase())
return (
diff --git a/frontend/src/lib/account-utils.test.ts b/frontend/src/lib/account-utils.test.ts
index 5f829e1b..660ede73 100644
--- a/frontend/src/lib/account-utils.test.ts
+++ b/frontend/src/lib/account-utils.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { sortAccountsByAbsoluteBalance, sortAccountsByDisplayName, sumAccountsTotal } from './account-utils'
+import { sidebarAccountBalance, sortAccountsByAbsoluteBalance, sortAccountsByDisplayName, sumAccountsTotal } from './account-utils'
describe('sortAccountsByDisplayName', () => {
it('orders accounts by display name when present and falls back to name', () => {
@@ -90,3 +90,58 @@ describe('sumAccountsTotal', () => {
expect(sumAccountsTotal(accounts)).toBe(3500)
})
})
+
+describe('sidebarAccountBalance', () => {
+ const sharedCard = (extra: Record<string, unknown> = {}) => ({
+ type: 'credit_card',
+ shared_balance_group: 'provider:line-1',
+ balance_primary: null,
+ current_balance: -1500,
+ open_bill_total: null,
+ open_bill_total_primary: null,
+ ...extra,
+ })
+
+ it('shows a shared card own open bill instead of the line balance', () => {
+ const { amount, isPrimary } = sidebarAccountBalance(
+ sharedCard({ open_bill_total: 820.5 }),
+ )
+
+ expect(amount).toBe(-820.5)
+ expect(isPrimary).toBe(false)
+ })
+
+ it('prefers the converted bill when the account is in a foreign currency', () => {
+ const { amount, isPrimary } = sidebarAccountBalance(
+ sharedCard({ open_bill_total: 200, open_bill_total_primary: 1000 }),
+ )
+
+ expect(amount).toBe(-1000)
+ expect(isPrimary).toBe(true)
+ })
+
+ it('keeps the balance when a shared card has no open bill', () => {
+ const { amount, isPrimary } = sidebarAccountBalance(sharedCard())
+
+ expect(amount).toBe(-1500)
+ expect(isPrimary).toBe(false)
+ })
+
+ it('keeps the balance for a non-shared card even if a bill value is present', () => {
+ const { amount, isPrimary } = sidebarAccountBalance(
+ sharedCard({ shared_balance_group: null, open_bill_total: 700 }),
+ )
+
+ expect(amount).toBe(-1500)
+ expect(isPrimary).toBe(false)
+ })
+
+ it('keeps the converted balance for a non-credit-card account', () => {
+ const { amount, isPrimary } = sidebarAccountBalance(
+ sharedCard({ type: 'checking', balance_primary: 90, open_bill_total: null }),
+ )
+
+ expect(amount).toBe(90)
+ expect(isPrimary).toBe(true)
+ })
+})
diff --git a/frontend/src/lib/account-utils.ts b/frontend/src/lib/account-utils.ts
index 560d935b..00ecf532 100644
--- a/frontend/src/lib/account-utils.ts
+++ b/frontend/src/lib/account-utils.ts
@@ -22,6 +22,42 @@ export function sumAccountBalances(
}, 0)
}
+/**
+ * The number a sidebar account row shows.
+ *
+ * Every card on one shared credit line repeats the contract-wide balance, so
+ * the row for such a card leads with its own open bill (the one due today or
+ * later) instead; the "shared" label next to the name still identifies the
+ * line. Without an open bill, and for every other account, the balance stands.
+ * The returned amount is signed like a balance: money owed is negative.
+ */
+export function sidebarAccountBalance(
+ account: Pick<
+ Account,
+ | 'type'
+ | 'shared_balance_group'
+ | 'balance_primary'
+ | 'current_balance'
+ | 'open_bill_total'
+ | 'open_bill_total_primary'
+ >,
+): { amount: number; isPrimary: boolean } {
+ const sharedCard =
+ account.type === 'credit_card' && account.shared_balance_group != null
+ if (sharedCard && account.open_bill_total != null) {
+ const raw = account.open_bill_total_primary ?? account.open_bill_total
+ // A bill is an amount to pay, so the row shows it as debt.
+ return {
+ amount: -Number(raw) || 0,
+ isPrimary: account.open_bill_total_primary != null,
+ }
+ }
+ return {
+ amount: Number(account.balance_primary ?? account.current_balance) || 0,
+ isPrimary: account.balance_primary != null,
+ }
+}
+
/**
* The accounts total the sidebar shows. Loans are long-term debt that the
* net worth already counts, so they stay out of this money-on-hand total.
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index bbc6db21..93e9aee7 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -198,6 +198,12 @@ export interface Account {
card_brand: string | null
card_level: string | null
shared_balance_group: string | null
+ // Open bill (due today or later) of a card on a shared credit line, in the
+ // account's currency. Null when the card has no such bill; the row then
+ // keeps showing the balance.
+ open_bill_total?: number | null
+ // Same bill in the user's primary currency; null when not converted.
+ open_bill_total_primary?: number | null
is_closed: boolean
closed_at: string | null
}