Open-source personal finance manager. Self-hosted, privacy-first.
feat(transactions): filter the list to transfers only (#1009)
Tássio Noronha89fcdc5d89ec
diff --git a/backend/app/services/_query_filters.py b/backend/app/services/_query_filters.pyindex b4718bbe..842d3025 100644--- a/backend/app/services/_query_filters.py+++ b/backend/app/services/_query_filters.py@@ -118,6 +118,22 @@ def is_not_ignored():)+def is_transfer():+ """SQL filter: the row is a transfer rather than income or expense.++ Either both legs were matched (`transfer_pair_id` set), or the row sits+ in a category flagged `treat_as_transfer` (one-sided movements such as+ an investment application). Same reading the transactions calendar uses+ when it marks a day as having a transfer.+ """+ return or_(+ Transaction.transfer_pair_id.is_not(None),+ Transaction.category_id.in_(+ select(Category.id).where(Category.treat_as_transfer.is_(True))+ ),+ )++def counts_as_pnl():"""SQL filter: True when a transaction should contribute to income/expense totals.diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 642d1518..e869d5ce 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -30,6 +30,7 @@ from app.services._query_filters import (counts_as_pnl,counts_as_user_pnl,is_not_ignored,+ is_transfer,reporting_date_col,)from app.services.recurring_transaction_service import _advance_date@@ -269,7 +270,11 @@ async def get_transactions(# filtered set, so the totals a hidden list shows stay the totals of# what it is showing.base_query = base_query.where(is_not_ignored())- if txn_type:+ if txn_type == "transfer":+ # Not a value of the `type` column: a transfer is still stored as a+ # credit or a debit, so this narrows to the transfer family instead.+ base_query = base_query.where(is_transfer())+ elif txn_type:base_query = base_query.where(Transaction.type == txn_type)if status:base_query = base_query.where(Transaction.status == status)diff --git a/backend/tests/test_transactions_api_coverage.py b/backend/tests/test_transactions_api_coverage.pyindex b657345f..23bdd28e 100644--- a/backend/tests/test_transactions_api_coverage.py+++ b/backend/tests/test_transactions_api_coverage.py@@ -52,6 +52,89 @@ async def test_list_filter_by_type(client: AsyncClient, auth_headers, test_transassert all(t["type"] == "credit" for t in resp.json()["items"])+async def _seed_transfers(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_account: Account+) -> tuple[set[str], set[str]]:+ """A paired transfer plus a one-sided row in a `treat_as_transfer`+ category. Returns (transfer ids, transfer descriptions)."""+ other = await _manual_account(client, auth_headers, "Savings")+ resp = await client.post(+ "/api/transactions/transfer", headers=auth_headers,+ json={+ "from_account_id": str(test_account.id),+ "to_account_id": other,+ "amount": "300.00",+ "date": date.today().isoformat(),+ "description": "PAIRED TRANSFER",+ },+ )+ assert resp.status_code == 201, resp.text+ paired_ids = {resp.json()["debit"]["id"], resp.json()["credit"]["id"]}++ investments = Category(+ id=uuid.uuid4(), user_id=test_user.id, name="Investments",+ icon="trending-up", color="#0EA5E9", treat_as_transfer=True,+ )+ session.add(investments)+ await session.flush()+ one_sided = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=test_account.id,+ category_id=investments.id, description="BROKER APPLICATION",+ amount=500, currency="BRL", date=date.today(), type="debit", source="manual",+ )+ session.add(one_sided)+ await session.commit()+ return paired_ids | {str(one_sided.id)}, {"PAIRED TRANSFER", "BROKER APPLICATION"}+++async def test_list_filter_by_type_transfer(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+ test_account: Account, test_transactions,+):+ transfer_ids, _ = await _seed_transfers(client, auth_headers, session, test_user, test_account)++ resp = await client.get("/api/transactions?type=transfer&limit=500", headers=auth_headers)+ assert resp.status_code == 200+ items = resp.json()["items"]+ # Paired legs and the treat_as_transfer row, and none of the plain+ # income/expense fixtures.+ assert {t["id"] for t in items} == transfer_ids+++async def test_list_filter_by_income_expense_unchanged_by_transfers(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+ test_account: Account, test_transactions,+):+ transfer_ids, _ = await _seed_transfers(client, auth_headers, session, test_user, test_account)++ # Income/Expense stay a plain type filter, so a transfer leg of that+ # type still shows up there, exactly as before.+ for typ in ("credit", "debit"):+ resp = await client.get(f"/api/transactions?type={typ}&limit=500", headers=auth_headers)+ assert resp.status_code == 200+ items = resp.json()["items"]+ assert items and all(t["type"] == typ for t in items)+ assert any(t["id"] in transfer_ids for t in items)+++async def test_export_filter_by_type_transfer(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user,+ test_account: Account, test_transactions,+):+ _, descriptions = await _seed_transfers(client, auth_headers, session, test_user, test_account)++ resp = await client.get("/api/transactions/export?type=transfer", headers=auth_headers)+ assert resp.status_code == 200+ body = resp.text+ for desc in descriptions:+ assert desc in body+ for fixture_tx in test_transactions:+ assert fixture_tx.description not in body++@pytest.mark.asyncioasync def test_list_search_query(client: AsyncClient, auth_headers, test_transactions):resp = await client.get("/api/transactions?q=UBER", headers=auth_headers)diff --git a/frontend/src/components/mobile-transactions-filter-menu.tsx b/frontend/src/components/mobile-transactions-filter-menu.tsxindex 03fda1a5..c16e98b1 100644--- a/frontend/src/components/mobile-transactions-filter-menu.tsx+++ b/frontend/src/components/mobile-transactions-filter-menu.tsx@@ -486,7 +486,7 @@ function MobileFilterDetail({return <MobileSelectionView options={[allOption, ...menu.groups.map(({ id, name }) => ({ value: id, label: name }))]} selectedValue={menu.groupId} onChange={menu.onGroupIdChange} />}if (menu.view === 'type') {- const options = [allOption, { value: 'credit', label: t('transactions.income') }, { value: 'debit', label: t('transactions.expense') }]+ const options = [allOption, { value: 'credit', label: t('transactions.income') }, { value: 'debit', label: t('transactions.expense') }, { value: 'transfer', label: t('transactions.transfer') }]return <MobileSelectionView options={options} selectedValue={menu.type} onChange={menu.onTypeChange} />}if (menu.view === 'status') {diff --git a/frontend/src/components/transactions-filter-bar.tsx b/frontend/src/components/transactions-filter-bar.tsxindex 09f3bf96..8be1efa9 100644--- a/frontend/src/components/transactions-filter-bar.tsx+++ b/frontend/src/components/transactions-filter-bar.tsx@@ -221,7 +221,9 @@ export function TransactionsFilterBar({? t('transactions.income'): filterType === 'debit'? t('transactions.expense')- : ''+ : filterType === 'transfer'+ ? t('transactions.transfer')+ : ''const statusLabel =filterStatus === 'pending'@@ -721,7 +723,7 @@ export function TransactionsFilterBar({</DropdownMenuPortal></DropdownMenuSub>- {/* Type submenu (single — income vs expense) */}+ {/* Type submenu (single: income, expense or transfer) */}<DropdownMenuSub><DropdownMenuSubTrigger className="gap-2 text-[13px]"><ArrowUpDown size={14} className="text-muted-foreground" />@@ -741,6 +743,7 @@ export function TransactionsFilterBar({{ value: '', label: t('transactions.all') },{ value: 'credit', label: t('transactions.income') },{ value: 'debit', label: t('transactions.expense') },+ { value: 'transfer', label: t('transactions.transfer') },].map((opt) => (<DropdownMenuItemkey={opt.value || 'all'}