Open-source personal finance manager. Self-hosted, privacy-first.
feat(transactions): show Excluded total in summary footer (#242) (#297)
Tássio Noronha9d2f4cff587f
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 17bf9680..3e32ee7a 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -33,10 +33,16 @@ class TransactionsSummary(BaseModel):"""Income / expense / net totals across all rows matching the activefilters (issue #185). Amounts are in the user's primary currency.Floats (not Decimal) so the JSON payload matches `amount_primary`- and the frontend gets plain numbers."""+ and the frontend gets plain numbers.++ `excluded` (issue #242) is the absolute total of everything filtered+ out of income/expense for the same rows — paired transfers,+ `treat_as_transfer` categories (transfers, investments, custom) and+ ignored items — i.e. the complement of `counts_as_pnl()`."""income: floatexpense: floatnet: float+ excluded: floatcurrency: strdiff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 20bb5203..cef857de 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -4,7 +4,7 @@ from datetime import datefrom decimal import Decimalfrom typing import Optional-from sqlalchemy import select, func, or_, update+from sqlalchemy import select, func, or_, not_, updatefrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload@@ -21,6 +21,7 @@ from app.services import split_servicefrom app.services.credit_card_service import apply_effective_datefrom app.services.rule_service import apply_rules_to_transactionfrom app.services.fx_rate_service import stamp_primary_amount, convert as fx_convert+from app.services._query_filters import counts_as_pnldef _apply_fx_override(transaction, amount, amount_primary=None, fx_rate_used=None):@@ -362,14 +363,12 @@ async def get_transactions(# rows). Computed before pagination so it covers the whole result set.summary: Optional[dict] = Noneif include_summary:- ignored_category_ids = select(Category.id).where(Category.is_ignored == True)- pnl_subq = base_query.where(- Transaction.is_ignored == False,- or_(- Transaction.category_id.is_(None),- Transaction.category_id.not_in(ignored_category_ids),- ),- ).subquery()+ # Income / expense / net use the shared `counts_as_pnl()` definition+ # (issue #242) so the footer matches the dashboard & reports: paired+ # transfers, `treat_as_transfer` categories (transfers, investments,+ # custom) and ignored items are kept OUT of income/expense.+ pnl_filter = counts_as_pnl()+ pnl_subq = base_query.where(pnl_filter).subquery()amount_norm = func.coalesce(pnl_subq.c.amount_primary, pnl_subq.c.amount)@@ -386,10 +385,25 @@ async def get_transactions(income = Decimal(str(row_total or 0))elif row_type == "debit":expense = Decimal(str(row_total or 0))++ # Excluded: the absolute total of everything filtered out of P/L for+ # the same rows — the complement of `counts_as_pnl()`. Surfaces+ # transfer-like movement (e.g. how much was moved/invested) without+ # distorting income/expense/net.+ excl_subq = base_query.where(not_(pnl_filter)).subquery()+ excl_amount_norm = func.coalesce(+ excl_subq.c.amount_primary, excl_subq.c.amount+ )+ excluded_total = await session.scalar(+ select(func.coalesce(func.sum(func.abs(excl_amount_norm)), 0))+ )+ excluded = Decimal(str(excluded_total or 0))+summary = {"income": income,"expense": expense,"net": income - expense,+ "excluded": excluded,}# Apply ordering (and pagination unless skipped). Bill-view callersdiff --git a/backend/tests/test_transaction_service_coverage.py b/backend/tests/test_transaction_service_coverage.pyindex 47049104..02680cbc 100644--- a/backend/tests/test_transaction_service_coverage.py+++ b/backend/tests/test_transaction_service_coverage.py@@ -234,6 +234,8 @@ async def test_get_transactions_include_summary(session, test_user, test_workspaassert summary["income"] == Decimal("1000")assert summary["expense"] == Decimal("300")assert summary["net"] == Decimal("700")+ # Nothing transfer-like / ignored in range, so nothing is excluded (#242).+ assert summary["excluded"] == Decimal("0")async def test_get_transactions_summary_excludes_ignored(session, test_user, test_workspace, acct):@@ -246,6 +248,46 @@ async def test_get_transactions_summary_excludes_ignored(session, test_user, tessession, test_workspace.id, test_user.id, include_summary=True)assert summary["expense"] == Decimal("100")+ # The ignored row leaves income/expense but surfaces in `excluded` (#242).+ assert summary["excluded"] == Decimal("999")+++async def test_get_transactions_summary_excludes_transfers_and_treat_as_transfer(+ session, test_user, test_workspace, acct+):+ """income/expense use counts_as_pnl(); paired transfers and+ treat_as_transfer categories are kept out of P/L and surface in+ `excluded` instead (#242)."""+ from app.models.category import Category++ invest = Category(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Investments",+ treat_as_transfer=True,+ )+ session.add(invest)+ await session.commit()++ # Real P/L+ await _mk_txn(session, test_user, acct, description="Salary", amount=Decimal("2000"), type="credit")+ await _mk_txn(session, test_user, acct, description="Rent", amount=Decimal("800"), type="debit")+ # Paired transfer (both legs excluded from P/L, both counted in excluded)+ pair = uuid.uuid4()+ await _mk_txn(session, test_user, acct, description="Xfer out", amount=Decimal("500"), type="debit", transfer_pair_id=pair)+ await _mk_txn(session, test_user, acct, description="Xfer in", amount=Decimal("500"), type="credit", transfer_pair_id=pair)+ # treat_as_transfer category contribution (one-sided, excluded from P/L)+ await _mk_txn(session, test_user, acct, description="Buy ETF", amount=Decimal("300"), type="debit", category_id=invest.id)++ _, _, summary = await get_transactions(+ session, test_workspace.id, test_user.id, include_summary=True+ )+ assert summary["income"] == Decimal("2000")+ assert summary["expense"] == Decimal("800")+ assert summary["net"] == Decimal("1200")+ # 500 (out) + 500 (in) + 300 (investment) — absolute totals.+ assert summary["excluded"] == Decimal("1300")async def test_get_transactions_sorting(session, test_user, test_workspace, acct):diff --git a/backend/tests/test_transactions_api_coverage.py b/backend/tests/test_transactions_api_coverage.pyindex b02eb1e9..86bc67c0 100644--- a/backend/tests/test_transactions_api_coverage.py+++ b/backend/tests/test_transactions_api_coverage.py@@ -35,7 +35,7 @@ async def test_list_with_summary(client: AsyncClient, auth_headers, test_transacassert resp.status_code == 200data = resp.json()assert data["summary"] is not None- assert {"income", "expense", "net", "currency"} <= data["summary"].keys()+ assert {"income", "expense", "net", "excluded", "currency"} <= data["summary"].keys()@pytest.mark.asynciodiff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex db793781..c552e042 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -311,6 +311,7 @@"summaryIncome": "Income","summaryExpenses": "Expenses","summaryNet": "Net",+ "summaryExcluded": "Excluded","bulkCategorize": "Apply","bulkSuccess": "{{count}} transactions categorized","selectCategory": "Select category...",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 411bdd24..18bb4e38 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -309,6 +309,7 @@"summaryIncome": "Ingresos","summaryExpenses": "Gastos","summaryNet": "Neto",+ "summaryExcluded": "Excluido","bulkCategorize": "Aplicar","bulkSuccess": "{{count}} transacciones categorizadas","selectCategory": "Seleccionar categoría...",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 7b9ade2e..58d9f737 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -284,6 +284,7 @@"summaryIncome": "Entrate","summaryExpenses": "Spese","summaryNet": "Netto",+ "summaryExcluded": "Escluso","bulkCategorize": "Applica","bulkSuccess": "{{count}} transazioni categorizzate","selectCategory": "Seleziona categoria...",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 450ec78d..8343a52d 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -323,6 +323,7 @@"summaryIncome": "Przychody","summaryExpenses": "Wydatki","summaryNet": "Netto",+ "summaryExcluded": "Wykluczone","bulkCategorize": "Zastosuj","bulkSuccess_one": "Skategoryzowano {{count}} transakcję","bulkSuccess_few": "Skategoryzowano {{count}} transakcje",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex cc1cc287..b29c78cc 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -311,6 +311,7 @@"summaryIncome": "Receitas","summaryExpenses": "Despesas","summaryNet": "Saldo",+ "summaryExcluded": "Excluído","bulkCategorize": "Aplicar","bulkSuccess": "{{count}} transações categorizadas","selectCategory": "Selecionar categoria...",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex cb14cce3..ac4b1f4b 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -1363,6 +1363,16 @@ export default function TransactionsPage() {<span className="mr-auto text-xs text-muted-foreground">{t('transactions.summaryCount', { count: data.total })}</span>+ {/* Excluded (#242): transfers / investments / ignored, kept out of+ income/expense. Hidden when nothing was excluded in range. */}+ {data.summary.excluded > 0 && (+ <span className="flex items-baseline gap-1.5 text-xs">+ <span className="text-muted-foreground">{t('transactions.summaryExcluded')}</span>+ <span className="text-sm font-semibold tabular-nums text-muted-foreground">+ {mask(formatCurrency(data.summary.excluded, data.summary.currency, locale))}+ </span>+ </span>+ )}<span className="flex items-baseline gap-1.5 text-xs"><span className="text-muted-foreground">{t('transactions.summaryIncome')}</span><span className="text-sm font-semibold tabular-nums text-emerald-600">diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex cfc21338..f042db61 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -607,6 +607,9 @@ export interface TransactionsSummary {income: numberexpense: numbernet: number+ // Absolute total of everything excluded from income/expense for the same+ // rows — transfers, treat_as_transfer categories and ignored items (#242).+ excluded: numbercurrency: string}