Open-source personal finance manager. Self-hosted, privacy-first.
fix(accounts): don't let category flags shrink a credit card's bill total (#649)
Victor Hugo dos Santos9f7c5fbfa04d
diff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.pyindex 9abbb079..b4718bbe 100644--- a/backend/app/services/_query_filters.py+++ b/backend/app/services/_query_filters.py@@ -177,16 +177,25 @@ def counts_on_bill():category — those leave the account balance too, so dropping themfrom 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.- - rows flagged `exclude_from_pnl`. Its canonical use is a work- expense paid on a personal card and reimbursed later — and the- bank bills the whole card either way.-- The rule both share: a bill honors "make this disappear" and- ignores "report this differently".+ `treat_as_transfer` categories are handled asymmetrically, and this is+ the whole point of the helper:+ - kept in for *debits*: buying an investment or paying a consortium+ installment with the card still lands on the statement, so a+ charge doesn't stop being owed to the bank because of how it was+ tagged afterwards (issue #647).+ - dropped for *credits*: an unpaired card payment (the payer's+ account isn't connected, the amount doesn't match exactly, or it+ was a partial payment) is normally filed under a transfer-like+ category, and letting it through here would net it against new+ debt instead of being a repayment of it.++ Neither reading is exactly right — there's no field today that tells+ a genuine merchant refund apart from an unpaired bill payment once+ both land as a credit in a transfer-like category, so this is a+ judgment call, not a derived fact. Dropping transfer-tagged credits+ errs toward the more common case (an unmatched payment silently+ shrinking the bill every cycle) over the rarer one (a refund of a+ transfer-tagged purchase failing to shrink it back).Deliberately spelled out rather than defined as "`counts_as_pnl`minus a clause": a filter for what a *report* excludes will keep@@ -194,16 +203,18 @@ def counts_on_bill():and a bill total must not inherit those. Every clause here is onesomebody chose for the bill."""+ ignored_category = Transaction.category_id.in_(+ select(Category.id).where(Category.is_ignored.is_(True))+ )+ transfer_category = Transaction.category_id.in_(+ select(Category.id).where(Category.treat_as_transfer.is_(True))+ )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))- ),- ),+ or_(Transaction.category_id.is_(None), ~ignored_category),+ or_(Transaction.type == "debit", Transaction.category_id.is_(None), ~transfer_category),)diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex 6efeee50..f8a6889a 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -823,8 +823,10 @@ 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). `summary_filter` already excludes paired transfers,- # so bill payments are not double-counted.+ # invoice amount). Paired transfers are dropped by `transfer_pair_id`;+ # unpaired card payments are dropped by the credit-side `treat_as_transfer`+ # exclusion in `counts_on_bill` (see its docstring for why that's+ # asymmetric with the debit side).if account.type == "credit_card":signed_for_bill = case((Transaction.type == "credit", -func.abs(effective_amount)),diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.pyindex 9388289e..7d307e2a 100644--- a/backend/tests/test_account_service.py+++ b/backend/tests/test_account_service.py@@ -17,6 +17,7 @@ import pytestfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Account+from app.models.category import Categoryfrom app.models.goal import Goalfrom app.models.import_log import ImportLogfrom app.models.recurring_transaction import RecurringTransaction@@ -69,7 +70,7 @@ async def _add_txn(session: AsyncSession, user_id: uuid.UUID, account_id: uuid.UUID,amount: float, txn_type: str, txn_date: date,source: str = "manual", transfer_pair_id: uuid.UUID | None = None,- status: str = "posted",+ status: str = "posted", category_id: uuid.UUID | None = None,) -> Transaction:from datetime import datetime, timezonetxn = Transaction(@@ -84,6 +85,7 @@ async def _add_txn(status=status,currency="BRL",transfer_pair_id=transfer_pair_id,+ category_id=category_id,created_at=datetime.now(timezone.utc),)session.add(txn)@@ -92,6 +94,23 @@ async def _add_txn(return txn+async def _make_category(+ session: AsyncSession, user_id: uuid.UUID,+ treat_as_transfer: bool = False, is_ignored: bool = False,+) -> Category:+ category = Category(+ id=uuid.uuid4(),+ user_id=user_id,+ name="Test Category",+ treat_as_transfer=treat_as_transfer,+ is_ignored=is_ignored,+ )+ session.add(category)+ await session.commit()+ await session.refresh(category)+ return category++# ---------------------------------------------------------------------------# create_account# ---------------------------------------------------------------------------@@ -842,6 +861,87 @@ async def test_get_account_summary_keeps_pending_for_credit_card(session: AsyncSassert summary["projected_expenses"] == pytest.approx(20.0)+async def test_get_account_summary_bill_charge_ignores_transfer_category(session: AsyncSession, test_user, test_workspace):+ """A charge tagged `treat_as_transfer` for budgeting purposes still+ counts toward the bill total: the bank doesn't care how the user+ categorized it later (issue #647)."""+ account = await _make_account(session, test_user.id, "CC Bill Debit", acc_type="credit_card")+ today = date.today()+ transfer_cat = await _make_category(session, test_user.id, treat_as_transfer=True)++ await _add_txn(session, test_user.id, account.id, 100, "debit", today)+ await _add_txn(session, test_user.id, account.id, 300, "debit", today, category_id=transfer_cat.id)++ summary = await get_account_summary(session, account.id, test_workspace.id)+ assert summary is not None+ assert summary["monthly_expenses"] == pytest.approx(400.0)+++async def test_get_account_summary_bill_pending_charge_with_transfer_category_counts(+ session: AsyncSession, test_user, test_workspace+):+ """The in-progress cycle's projected bill total must also stop+ excluding transfer-tagged charges while they're still pending, not+ just once they post — otherwise the total jumps the moment the charge+ settles."""+ account = await _make_account(session, test_user.id, "CC Bill Pending", acc_type="credit_card")+ today = date.today()+ transfer_cat = await _make_category(session, test_user.id, treat_as_transfer=True)++ await _add_txn(session, test_user.id, account.id, 100, "debit", today)+ await _add_txn(+ session, test_user.id, account.id, 300, "debit", today,+ status="pending", category_id=transfer_cat.id,+ )++ summary = await get_account_summary(session, account.id, test_workspace.id)+ assert summary is not None+ assert summary["projected_expenses"] == pytest.approx(400.0)+++async def test_get_account_summary_bill_unpaired_payment_credit_still_nets_out(+ session: AsyncSession, test_user, test_workspace+):+ """An unpaired card payment (no matching transfer leg — the paying+ account isn't connected, or the amount doesn't match exactly) is+ normally filed under a transfer-like category. That category tag must+ keep netting it against the bill, or a real repayment would count as+ new debt."""+ account = await _make_account(session, test_user.id, "CC Bill Payment", acc_type="credit_card")+ today = date.today()+ transfer_cat = await _make_category(session, test_user.id, treat_as_transfer=True)++ await _add_txn(session, test_user.id, account.id, 100, "debit", today)+ await _add_txn(session, test_user.id, account.id, 80, "credit", today, category_id=transfer_cat.id)++ summary = await get_account_summary(session, account.id, test_workspace.id)+ assert summary is not None+ assert summary["monthly_expenses"] == pytest.approx(100.0)+++async def test_get_account_summary_bill_excludes_ignored_category_charge(+ session: AsyncSession, test_user, test_workspace+):+ """Unlike `treat_as_transfer`, a category the user explicitly marked+ `is_ignored` is a direct "don't count this" — those rows still render+ with an ignored badge elsewhere, so they should keep shrinking the+ bill total too."""+ account = await _make_account(session, test_user.id, "CC Bill Ignored", acc_type="credit_card")+ today = date.today()+ ignored_cat = await _make_category(session, test_user.id, is_ignored=True)++ await _add_txn(session, test_user.id, account.id, 100, "debit", today)+ await _add_txn(session, test_user.id, account.id, 50, "debit", today, category_id=ignored_cat.id)++ summary = await get_account_summary(session, account.id, test_workspace.id)+ assert summary is not None+ assert summary["monthly_expenses"] == pytest.approx(100.0)++@pytest.mark.asyncioasync def test_get_account_summary_opening_balance_connected_excludes_period_pending(session, test_user, test_workspace, test_connectiondiff --git a/backend/tests/test_credit_card_accounting_mode.py b/backend/tests/test_credit_card_accounting_mode.pyindex 179f57d9..2d379101 100644--- a/backend/tests/test_credit_card_accounting_mode.py+++ b/backend/tests/test_credit_card_accounting_mode.py@@ -1934,12 +1934,13 @@ class TestBillTotalIgnoresReportingExclusions:assert summary["monthly_expenses"] == 100.0@pytest.mark.asyncio- async def test_transfer_like_refund_shows_in_both_card_numbers(+ async def test_transfer_like_credit_does_not_shrink_the_bill(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."""+ """An unpaired card payment (no matching transfer leg) is normally+ filed under a transfer-like category. Unlike a debit in that same+ category, the credit must not net against the bill or an ordinary+ repayment would read as new debt shrinking, cycle after cycle."""await _make_tx(session, test_user.id, cc_account.id,date(2026, 4, 3), Decimal("100"), tx_type="debit",@@ -1957,8 +1958,8 @@ class TestBillTotalIgnoresReportingExclusions:)assert summary is not None- assert summary["monthly_income"] == 50.0- assert summary["monthly_expenses"] == 50.0+ assert summary["monthly_income"] == 0.0+ assert summary["monthly_expenses"] == 100.0@pytest.mark.asyncioasync def test_ignored_category_purchase_also_leaves_the_bill(