Skip to content

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

fix(reports): count a shared credit line once in net worth (#1192)

Shayn Hornik7aaa59616c8a
diff --git a/backend/app/services/goal_service.py b/backend/app/services/goal_service.py
index e1c7eb03..8f905fbe 100644
--- a/backend/app/services/goal_service.py
+++ b/backend/app/services/goal_service.py
@@ -97,7 +97,14 @@ async def _resolve_current_amount(
accounts = await _get_open_accounts(session, workspace_id)
today = app_today()
total = Decimal("0")
+ seen_shared: set[str] = set()
for acc in accounts:
+ # Cards on one consolidated credit line each carry the whole
+ # line's debt; count it once.
+ if acc.shared_balance_group and acc.type == "credit_card":
+ if acc.shared_balance_group in seen_shared:
+ continue
+ seen_shared.add(acc.shared_balance_group)
bal = Decimal(str(await _account_balance_at(session, acc, today)))
total += await _convert_amount(session, bal, acc.currency, goal_currency)
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.py
index 90663eb7..5e608ebb 100644
--- a/backend/app/services/report_service.py
+++ b/backend/app/services/report_service.py
@@ -153,8 +153,27 @@ async def _net_worth_at(
liabilities_total = 0.0
composition: list[ReportCompositionItem] = []
+ # Cards on one consolidated credit line (same shared_balance_group) each
+ # carry the whole line's debt, so they are summed as one item, the same way
+ # the dashboard's _total_balance_by_currency does. Only credit cards: an
+ # account retyped to checking keeps its group but no longer shares the debt.
+ grouped: dict[str, list[Account]] = {}
for account in accounts:
- bal = await _account_balance_at(session, account, cutoff)
+ shared = account.shared_balance_group if account.type == "credit_card" else None
+ grouped.setdefault(shared or str(account.id), []).append(account)
+
+ for key, group in grouped.items():
+ account = group[0]
+ bal = 0.0
+ for member in group:
+ bal += await _account_balance_at(session, member, cutoff)
+ if len(group) > 1 and account.shared_balance_group:
+ # Each card's balance at the cutoff is the shared debt today minus
+ # that card's own activity since, so the duplicates to strip are
+ # today's shared debt once per extra card.
+ current_shared = await _account_balance_at(session, account, app_today())
+ bal -= current_shared * (len(group) - 1)
+ label = " + ".join(get_account_name(member) for member in group)
converted, _ = await convert(
session, Decimal(str(abs(bal))), account.currency, primary_currency, cutoff
)
@@ -163,8 +182,8 @@ async def _net_worth_at(
liabilities_total += converted_val
if converted_val > 0:
composition.append(ReportCompositionItem(
- key=str(account.id),
- label=get_account_name(account),
+ key=key,
+ label=label,
value=round(converted_val, 2),
color=_ACCOUNT_TYPE_COLORS.get(account.type, "#6B7280"),
group="liabilities",
@@ -173,8 +192,8 @@ async def _net_worth_at(
accounts_total += converted_val
if converted_val > 0:
composition.append(ReportCompositionItem(
- key=str(account.id),
- label=get_account_name(account),
+ key=key,
+ label=label,
value=round(converted_val, 2),
color=_ACCOUNT_TYPE_COLORS.get(account.type, "#6B7280"),
group="accounts",
diff --git a/backend/tests/test_goal_service_coverage.py b/backend/tests/test_goal_service_coverage.py
index b0e42dcc..dd273262 100644
--- a/backend/tests/test_goal_service_coverage.py
+++ b/backend/tests/test_goal_service_coverage.py
@@ -16,6 +16,7 @@ from app.models.account import Account
from app.models.asset import Asset
from app.models.asset_group import AssetGroup
from app.models.asset_value import AssetValue
+from app.models.bank_connection import BankConnection
from app.models.fx_rate import FxRate
from app.models.goal import Goal
from app.models.transaction import Transaction
@@ -465,6 +466,34 @@ async def test_resolve_net_worth_same_currency(session, test_user, test_workspac
assert float(val) == pytest.approx(5000.0, abs=1.0)
+async def test_resolve_net_worth_counts_shared_credit_line_once(session, test_user, test_workspace):
+ acc = await _make_account(session, test_user.id, test_workspace.id, currency="BRL")
+ await _add_txn(session, test_user.id, acc.id, test_workspace.id, 2000, "credit", date.today())
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=test_user.id, provider="pluggy",
+ external_id="ext-goal-shared", institution_name="Shared line",
+ credentials={}, status="active", created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.flush()
+ for name in ("Shared Visa", "Shared Mastercard"):
+ session.add(Account(
+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ connection_id=conn.id, name=name, type="credit_card",
+ balance=Decimal("500"), currency="BRL",
+ shared_balance_group=f"{conn.id}:shared-credit",
+ ))
+ await session.commit()
+ goal = await _make_goal(
+ session, test_user.id, test_workspace.id,
+ tracking_type="net_worth", currency="BRL",
+ )
+ val = await _resolve_current_amount(session, goal, test_user.id)
+ # 2000 account - 500 shared credit line (not 1000)
+ assert float(val) == pytest.approx(1500.0, abs=1.0)
+
+
@pytest.mark.asyncio
async def test_resolve_net_worth_cross_currency(session, test_user, test_workspace):
today = date.today()
diff --git a/backend/tests/test_report_service.py b/backend/tests/test_report_service.py
index e7ad5a99..b5f2dc51 100644
--- a/backend/tests/test_report_service.py
+++ b/backend/tests/test_report_service.py
@@ -949,6 +949,80 @@ async def test_net_worth_with_credit_card(session: AsyncSession, test_user, test
assert dp.value == 4000.0
+async def _make_shared_credit_cards(session, user_id, workspace_id, balance):
+ conn = BankConnection(
+ id=uuid.uuid4(), user_id=user_id, provider="pluggy",
+ external_id="ext-shared-line", institution_name="Shared line",
+ credentials={}, status="active",
+ last_sync_at=datetime.now(timezone.utc),
+ created_at=datetime.now(timezone.utc),
+ )
+ session.add(conn)
+ await session.flush()
+ cards = []
+ for name in ("Shared Visa", "Shared Mastercard"):
+ card = Account(
+ id=uuid.uuid4(), user_id=user_id, workspace_id=workspace_id, connection_id=conn.id,
+ name=name, type="credit_card", balance=Decimal(balance), currency="BRL",
+ shared_balance_group=f"{conn.id}:shared-credit",
+ )
+ session.add(card)
+ cards.append(card)
+ await session.commit()
+ return cards
+
+
+async def test_net_worth_counts_shared_credit_line_once(
+ session: AsyncSession, test_user, test_workspace: User,
+):
+ checking = await _make_manual_account(session, test_user.id, "NW Shared Check")
+ await _add_txn(session, test_user.id, checking.id, 5000, "credit", date.today())
+ await _make_shared_credit_cards(session, test_user.id, test_workspace.id, "1000")
+
+ dp = await _net_worth_at(session, test_workspace.id, date.today(), "BRL")
+
+ assert dp.breakdowns["liabilities"] == 1000.0
+ assert dp.value == 4000.0
+ liabilities = [c for c in dp.composition if c.group == "liabilities"]
+ assert len(liabilities) == 1
+ assert liabilities[0].value == 1000.0
+ assert liabilities[0].label == "Shared Visa + Shared Mastercard"
+
+
+async def test_net_worth_backtracks_shared_credit_line_across_all_cards(
+ session: AsyncSession, test_user, test_workspace: User,
+):
+ first, second = await _make_shared_credit_cards(
+ session, test_user.id, test_workspace.id, "300"
+ )
+ # The line's debt today (300) includes 50 + 25 charged today on the two cards.
+ await _add_txn(session, test_user.id, first.id, 50, "debit", date.today())
+ await _add_txn(session, test_user.id, second.id, 25, "debit", date.today())
+
+ dp = await _net_worth_at(session, test_workspace.id, date.today() - timedelta(days=1), "BRL")
+
+ assert dp.breakdowns["liabilities"] == 225.0
+
+
+async def test_net_worth_does_not_merge_a_retyped_shared_card(
+ session: AsyncSession, test_user, test_workspace: User,
+):
+ first, second = await _make_shared_credit_cards(
+ session, test_user.id, test_workspace.id, "500"
+ )
+ second.type = "checking"
+ await session.commit()
+
+ dp = await _net_worth_at(session, test_workspace.id, date.today(), "BRL")
+
+ # The card owes 500; the retyped account reads as +500 checking.
+ assert dp.breakdowns["liabilities"] == 500.0
+ assert dp.breakdowns["accounts"] == 500.0
+
+
@pytest.mark.asyncio
async def test_net_worth_with_assets(session: AsyncSession, test_user, test_workspace: User):
checking = await _make_manual_account(session, test_user.id, "NW Assets Check")