Open-source personal finance manager. Self-hosted, privacy-first.
fix(accounts): keep credit-card bill totals off the reporting filter (#815)
Tássio Noronhaae7bf49f8a55
diff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.pyindex 7b252584..96047ec0 100644--- a/backend/app/services/_query_filters.py+++ b/backend/app/services/_query_filters.py@@ -157,6 +157,47 @@ def counts_as_pnl():)+def counts_on_bill():+ """SQL filter: True when a transaction belongs on a credit-card bill.++ A bill total is an *amount owed*, not a reporting figure, and the two+ answer to different authorities: the bill has to match what the bank+ says you owe, while P/L answers to how the user chose to categorize+ their spending. So the card's cycle total cannot reuse+ `counts_as_pnl` — every judgment that helper makes about what counts+ as *spending* is a judgment the bank never made.++ Kept out, because they are genuinely not charges on this bill:+ - paired transfers (the bill *payment* is not a purchase),+ - settlement debits (a repayment of a share already booked),+ - rows the user flagged `is_ignored`, on the transaction or its+ category — those leave the account balance too, so dropping them+ from the bill keeps the card's two numbers telling one story.++ Kept in, and this is the whole point of the helper:+ - `treat_as_transfer` categories. Buying an investment with the+ card still lands on the statement; the category says how to+ report the purchase, not whether the bank billed for it.++ Deliberately spelled out rather than defined as "`counts_as_pnl`+ minus a clause": a filter for what a *report* excludes will keep+ growing as the product learns new ways to say "don't count this",+ and a bill total must not inherit those. Every clause here is one+ somebody chose for the bill.+ """+ return and_(+ Transaction.transfer_pair_id.is_(None),+ Transaction.is_ignored.is_(False),+ ~and_(Transaction.source == "settlement", Transaction.type == "debit"),+ or_(+ Transaction.category_id.is_(None),+ Transaction.category_id.not_in(+ select(Category.id).where(Category.is_ignored.is_(True))+ ),+ ),+ )++def counts_as_user_pnl():"""SQL filter for *user-level* P/L (dashboard, reports, budgets).diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex b1d6a2d6..6efeee50 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -15,6 +15,7 @@ from app.schemas.account import AccountCreate, AccountUpdatefrom app.services._query_filters import (counts_as_pnl,counts_in_current_balance,+ counts_on_bill,is_confirmed,is_inside_provider_snapshot,is_not_future,@@ -795,8 +796,18 @@ async def get_account_summary()return query.where(bucket_date >= date_from, bucket_date <= date_to)- # Income = SUM of credit transactions in window (excluding opening_balance,- # paired transfers, and transfer-like categories).+ # Which exclusions these totals answer to. A credit card's four summary+ # numbers are all bill-side — they describe what the bank put on the+ # statement, so they keep purchases in `treat_as_transfer` categories+ # that the reporting filter drops. Every other account type keeps the+ # reporting view. See `counts_on_bill` for why the bill cannot simply+ # reuse `counts_as_pnl`.+ summary_filter = (+ counts_on_bill() if account.type == "credit_card" else counts_as_pnl()+ )++ # Income = SUM of credit transactions in window (excluding opening_balance+ # and paired transfers).income_result = await session.execute(_scope(select(func.coalesce(func.sum(effective_amount), 0)).where(Transaction.account_id == account_id,@@ -804,7 +815,7 @@ async def get_account_summary(Transaction.source != "opening_balance",bucket_date <= today,Transaction.status == "posted",- counts_as_pnl(),+ summary_filter,)))monthly_income = float(income_result.scalar())@@ -812,8 +823,8 @@ async def get_account_summary(# Expenses = SUM of debit transactions in window (same exclusions).# For credit-card accounts, NET refund credits against debits so the# cycle's "Total da fatura" matches the bank's bill (refunds reduce the- # invoice amount). counts_as_pnl already excludes paired transfers and- # transfer-like categories, so bill payments are not double-counted.+ # invoice amount). `summary_filter` already excludes paired transfers,+ # so bill payments are not double-counted.if account.type == "credit_card":signed_for_bill = case((Transaction.type == "credit", -func.abs(effective_amount)),@@ -825,7 +836,7 @@ async def get_account_summary(Transaction.source != "opening_balance",bucket_date <= today,Transaction.status == "posted",- counts_as_pnl(),+ summary_filter,)))else:@@ -835,7 +846,7 @@ async def get_account_summary(Transaction.type == "debit",bucket_date <= today,Transaction.status == "posted",- counts_as_pnl(),+ summary_filter,)))monthly_expenses = float(expenses_result.scalar())@@ -855,7 +866,7 @@ async def get_account_summary(Transaction.type == "credit",Transaction.source != "opening_balance",forecast_condition,- counts_as_pnl(),+ summary_filter,)))forecast_income = float(forecast_income_result.scalar() or 0)@@ -866,7 +877,7 @@ async def get_account_summary(Transaction.account_id == account_id,Transaction.source != "opening_balance",forecast_condition,- counts_as_pnl(),+ summary_filter,)))else:@@ -875,7 +886,7 @@ async def get_account_summary(Transaction.account_id == account_id,Transaction.type == "debit",forecast_condition,- counts_as_pnl(),+ summary_filter,)))forecast_expenses = float(forecast_expense_result.scalar() or 0)diff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.pyindex f0a2cc96..c9220160 100644--- a/backend/tests/test_credit_card_accounting_mode.py+++ b/backend/tests/test_credit_card_accounting_mode.py@@ -23,6 +23,7 @@ import pytest_asynciofrom sqlalchemy import selectfrom app.models.account import Account+from app.models.category import Categoryfrom app.models.transaction import Transactionfrom app.services import (account_service,@@ -1803,3 +1804,195 @@ class TestEffectiveBillDateFiltersList:assert summary is not Noneassert summary["monthly_expenses"] == 59.90+++# ---------------------------------------------------------------------------+# Bill totals answer to the bank, not to the reporting filters.+# ---------------------------------------------------------------------------+++class TestBillTotalIgnoresReportingExclusions:+ """A credit-card bill total is an amount *owed*, so it does not inherit+ the judgments `counts_as_pnl` makes about what counts as spending.++ The card's own numbers used to disagree: a purchase in a+ `treat_as_transfer` category (Investimentos ships as one) dropped out+ of the cycle total while still moving the card's balance, so the bill+ card matched neither the bank's statement nor the running balance+ rendered beside it.+ """++ @pytest_asyncio.fixture+ async def transfer_category(self, session, test_user):+ cat = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Investimentos",+ icon="trending-up",+ color="#0EA5E9",+ treat_as_transfer=True,+ )+ session.add(cat)+ await session.commit()+ await session.refresh(cat)+ return cat++ @pytest.mark.asyncio+ async def test_treat_as_transfer_purchase_stays_on_the_bill(+ self, session, test_user, test_workspace, cc_account, transfer_category+ ):+ """The bank billed for it, so the cycle total has to show it."""+ await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 3), Decimal("100"), tx_type="debit",+ )+ await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 8), Decimal("200"), tx_type="debit",+ category_id=transfer_category.id,+ )+ await session.commit()++ summary = await account_service.get_account_summary(+ session, cc_account.id, test_workspace.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )++ assert summary is not None+ assert summary["monthly_expenses"] == 300.0++ @pytest.mark.asyncio+ async def test_treat_as_transfer_still_leaves_pnl_on_a_regular_account(+ self, session, test_user, test_workspace, test_account, transfer_category+ ):+ """The contrast that makes the rule readable: the same category on a+ checking account is still a transfer-like flow, not spending."""+ await _make_tx(+ session, test_user.id, test_account.id,+ date(2026, 4, 3), Decimal("100"), tx_type="debit",+ )+ await _make_tx(+ session, test_user.id, test_account.id,+ date(2026, 4, 8), Decimal("200"), tx_type="debit",+ category_id=transfer_category.id,+ )+ await session.commit()++ summary = await account_service.get_account_summary(+ session, test_account.id, test_workspace.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )++ assert summary is not None+ assert summary["monthly_expenses"] == 100.0++ @pytest.mark.asyncio+ async def test_treat_as_transfer_purchase_stays_in_the_forecast_total(+ self, session, test_user, test_workspace, cc_account, transfer_category+ ):+ """The payable shown on the bill card follows the same rule."""+ pending = await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 8), Decimal("200"), tx_type="debit",+ category_id=transfer_category.id,+ )+ pending.status = "pending"+ await session.commit()++ summary = await account_service.get_account_summary(+ session, cc_account.id, test_workspace.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )++ assert summary is not None+ assert summary["projected_expenses"] == 200.0++ @pytest.mark.asyncio+ async def test_ignored_purchase_still_leaves_the_bill(+ self, session, test_user, test_workspace, cc_account+ ):+ """Regression guard on the clause that must NOT change: `is_ignored`+ leaves the account balance too, so dropping it from the bill keeps+ the card's two numbers telling one story."""+ await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 3), Decimal("100"), tx_type="debit",+ )+ ignored = await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 8), Decimal("200"), tx_type="debit",+ )+ ignored.is_ignored = True+ await session.commit()++ summary = await account_service.get_account_summary(+ session, cc_account.id, test_workspace.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )++ assert summary is not None+ assert summary["monthly_expenses"] == 100.0++ @pytest.mark.asyncio+ async def test_transfer_like_refund_shows_in_both_card_numbers(+ self, session, test_user, test_workspace, cc_account, transfer_category+ ):+ """The card's four totals answer to one rule, so a refund the bank+ credited nets against the bill *and* surfaces as income. Splitting+ the rule between them would let the two disagree."""+ await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 3), Decimal("100"), tx_type="debit",+ )+ await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 8), Decimal("50"), tx_type="credit",+ category_id=transfer_category.id,+ )+ await session.commit()++ summary = await account_service.get_account_summary(+ session, cc_account.id, test_workspace.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )++ assert summary is not None+ assert summary["monthly_income"] == 50.0+ assert summary["monthly_expenses"] == 50.0++ @pytest.mark.asyncio+ async def test_ignored_category_purchase_also_leaves_the_bill(+ self, session, test_user, test_workspace, cc_account+ ):+ """The ignore signal counts from either side. A category the user+ ignored leaves the account balance exactly like a row-level ignore,+ so the bill has to drop it too or the card's numbers split apart."""+ ignored_category = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="Reembolsáveis",+ icon="receipt",+ color="#94A3B8",+ is_ignored=True,+ )+ session.add(ignored_category)+ await session.flush()++ await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 3), Decimal("100"), tx_type="debit",+ )+ await _make_tx(+ session, test_user.id, cc_account.id,+ date(2026, 4, 8), Decimal("200"), tx_type="debit",+ category_id=ignored_category.id,+ )+ await session.commit()++ summary = await account_service.get_account_summary(+ session, cc_account.id, test_workspace.id,+ date_from=date(2026, 4, 1), date_to=date(2026, 4, 30),+ )++ assert summary is not None+ assert summary["monthly_expenses"] == 100.0