Open-source personal finance manager. Self-hosted, privacy-first.
feat(transactions): name the linked account on the transfer badge (#1270)
Tássio Noronha1602b70a0f1c
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex c0e1dece..f501c4cd 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -7,6 +7,7 @@ from typing import List, Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel+from sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.app_clock import app_today@@ -16,7 +17,9 @@ from app.core.workspace_context import (current_workspace,current_writable_workspace,)-from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, DescriptionSuggestion, BulkTagsRequest, CreateCounterpartRequest, InstallmentSeriesCreate, LinkTransferRequest, TransactionBulkDeleteRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead+from app.models.account import Account+from app.models.transaction import Transaction+from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, DescriptionSuggestion, BulkTagsRequest, CreateCounterpartRequest, InstallmentSeriesCreate, LinkTransferRequest, TransactionBulkDeleteRequest, TransactionCreate, TransactionRead, TransactionTransferCounterpart, TransactionUpdate, TransferCreate, TransferReadfrom app.schemas.transaction_calendar import TransactionCalendarResponsefrom app.services import transaction_servicefrom app.services.admin_service import get_credit_card_accounting_mode@@ -54,6 +57,52 @@ async def _attach_invoice_links(session, ctx, items: list) -> None:]+async def _attach_transfer_counterparts(+ session: AsyncSession, workspace_id: uuid.UUID, items: list[TransactionRead]+) -> None:+ """Name the account each transfer row is linked to, for the badge.++ The list marks transfer rows with a badge but said nothing about what+ the row is connected to (issue #810). Both legs of a pair share+ ``transfer_pair_id``, so one query over the page's pair ids fetches+ every other leg in the workspace. The other leg is found even when+ the account filter keeps it off the page, and a page without+ transfers costs nothing: no query, no field change.+ """+ pair_ids = {item.transfer_pair_id for item in items if item.transfer_pair_id}+ if not pair_ids:+ return++ result = await session.execute(+ select(+ Transaction.id,+ Transaction.transfer_pair_id,+ Transaction.account_id,+ # The name the rest of the UI shows: the user's override, or+ # the provider's name when there is none.+ func.coalesce(Account.display_name, Account.name),+ )+ .join(Account, Account.id == Transaction.account_id)+ .where(+ Transaction.workspace_id == workspace_id,+ Transaction.transfer_pair_id.in_(pair_ids),+ )+ )+ legs: dict[uuid.UUID, list[tuple[uuid.UUID, uuid.UUID, str]]] = {}+ for tx_id, pair_id, account_id, account_name in result:+ legs.setdefault(pair_id, []).append((tx_id, account_id, account_name))++ for item in items:+ if item.transfer_pair_id is None:+ continue+ for tx_id, account_id, account_name in legs.get(item.transfer_pair_id, []):+ if tx_id != item.id:+ item.transfer_counterpart = TransactionTransferCounterpart(+ account_id=account_id, account_name=account_name+ )+ break++def _tag_fx_fallback(tx: TransactionRead, primary_currency: str) -> TransactionRead:"""Set fx_fallback=True when a cross-currency tx isn't backed by a real rate.@@ -165,6 +214,7 @@ async def list_transactions(primary_currency = ctx.user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]await _attach_invoice_links(session, ctx, items)+ await _attach_transfer_counterparts(session, ctx.workspace.id, items)summary_out = (TransactionsSummary(**summary, currency=primary_currency)if summary is not Nonediff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex aae2e8ea..0abbe3a7 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -156,6 +156,19 @@ class TransactionInvoiceLink(BaseModel):amount: Decimal+class TransactionTransferCounterpart(BaseModel):+ """The other leg of a linked transfer, as seen from a list row.++ Filled only by the paginated list, one query per page (issue #810),+ so the badge on a row can name the account the transfer is linked+ to without a per-row request. The dialog keeps using the dedicated+ transfer-pair endpoint, which carries date and amount too.+ """++ account_id: uuid.UUID+ account_name: str++class TransactionRead(TransactionBase):id: uuid.UUIDuser_id: uuid.UUID@@ -175,6 +188,10 @@ class TransactionRead(TransactionBase):payee_name: Optional[str] = Nonenotes: Optional[str] = Nonetransfer_pair_id: Optional[uuid.UUID] = None+ # Other leg of the transfer this row belongs to, when it is one.+ # The paginated list fills it per page (issue #810); other endpoints+ # leave it null.+ transfer_counterpart: Optional[TransactionTransferCounterpart] = Noneamount_primary: Optional[float] = Nonefx_rate_used: Optional[float] = Nonefx_fallback: bool = Falsediff --git a/backend/tests/test_transactions_transfer_counterpart.py b/backend/tests/test_transactions_transfer_counterpart.pynew file mode 100644index 00000000..b837ae45--- /dev/null+++ b/backend/tests/test_transactions_transfer_counterpart.py@@ -0,0 +1,208 @@+"""The transfer badge in the transactions list names the linked account.++Issue #810: the list marks transfer rows with a "Transfer" badge but says+nothing about what the row is connected to. The paginated list enriches+each transfer row with ``transfer_counterpart`` (the other leg's+account), one query per page.+"""++import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.models.user import User+++async def _register(client: AsyncClient, email: str, password: str) -> dict:+ resp = await client.post(+ "/api/auth/register",+ json={"email": email, "password": password},+ )+ assert resp.status_code in (200, 201), resp.text+ return resp.json()+++async def _login(client: AsyncClient, email: str, password: str) -> dict:+ resp = await client.post(+ "/api/auth/login",+ data={"username": email, "password": password},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert resp.status_code == 200, resp.text+ return {"Authorization": f"Bearer {resp.json()['access_token']}"}+++def _tx(+ user: User,+ account: Account,+ description: str,+ amount: Decimal,+ txn_type: str,+ pair_id: uuid.UUID | None,+ user_id=None,+) -> Transaction:+ return Transaction(+ id=uuid.uuid4(),+ user_id=user_id or user.id,+ account_id=account.id,+ description=description,+ amount=amount,+ date=date.today(),+ type=txn_type,+ source="transfer" if pair_id else "manual",+ transfer_pair_id=pair_id,+ created_at=datetime.now(timezone.utc),+ )+++@pytest_asyncio.fixture+async def transfer_accounts(+ session: AsyncSession, test_user: User, test_account: Account, test_connection+) -> tuple[Account, Account]:+ """The default account plus a savings account in the same workspace."""+ savings = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ connection_id=test_connection.id,+ external_id="acc-ext-savings",+ name="Conta Poupanca",+ type="savings",+ balance=Decimal("1000.00"),+ currency="BRL",+ )+ session.add(savings)+ await session.commit()+ await session.refresh(savings)+ return test_account, savings+++@pytest_asyncio.fixture+async def transfer_pair(+ session: AsyncSession,+ test_user: User,+ transfer_accounts: tuple[Account, Account],+) -> tuple[Transaction, Transaction, Transaction]:+ """A pair across the two accounts, plus a regular row."""+ checking, savings = transfer_accounts+ pair_id = uuid.uuid4()+ leg_out = _tx(test_user, checking, "Transfer out", Decimal("200.00"), "debit", pair_id)+ leg_in = _tx(test_user, savings, "Transfer in", Decimal("200.00"), "credit", pair_id)+ regular = _tx(test_user, checking, "GROCERIES", Decimal("50.00"), "debit", None)+ for t in (leg_out, leg_in, regular):+ session.add(t)+ await session.commit()+ for t in (leg_out, leg_in, regular):+ await session.refresh(t)+ return leg_out, leg_in, regular+++async def test_transfer_rows_name_the_counterpart_account(+ client: AsyncClient, auth_headers, transfer_pair+):+ leg_out, leg_in, regular = transfer_pair+ resp = await client.get("/api/transactions", headers=auth_headers)+ assert resp.status_code == 200+ by_id = {t["id"]: t for t in resp.json()["items"]}++ out = by_id[str(leg_out.id)]+ assert out["transfer_pair_id"] is not None+ assert out["transfer_counterpart"] is not None+ assert out["transfer_counterpart"]["account_name"] == "Conta Poupanca"+ # The counterpart is the other leg's account, never the row's own.+ assert out["transfer_counterpart"]["account_id"] != out["account_id"]++ inn = by_id[str(leg_in.id)]+ assert inn["transfer_counterpart"]["account_name"] == "Conta Corrente"+ assert inn["transfer_counterpart"]["account_id"] != inn["account_id"]++ assert by_id[str(regular.id)]["transfer_counterpart"] is None+++async def test_counterpart_found_when_other_leg_filtered_off_page(+ client: AsyncClient, auth_headers, transfer_pair, transfer_accounts+):+ """Filtering to one account keeps its leg on the page but not the+ other one; the badge still names the linked account."""+ leg_out, _, _ = transfer_pair+ checking, _ = transfer_accounts+ resp = await client.get(+ f"/api/transactions?account_id={checking.id}", headers=auth_headers+ )+ assert resp.status_code == 200+ items = resp.json()["items"]+ row = next(t for t in items if t["id"] == str(leg_out.id))+ assert row["transfer_counterpart"]["account_name"] == "Conta Poupanca"+++async def test_transfer_counterpart_stays_inside_the_workspace(+ client: AsyncClient, auth_headers, session: AsyncSession,+ test_user: User, transfer_pair, transfer_accounts,+):+ """A second workspace holding a row with the same pair id must not+ leak into the first workspace's badge."""+ leg_out, leg_in, _ = transfer_pair+ _, savings = transfer_accounts+ friend_email = "[email protected]"+ await _register(client, friend_email, "friendpassword12")+ friend_headers = await _login(client, friend_email, "friendpassword12")++ result = await session.execute(select(User).where(User.email == friend_email))+ friend = result.scalar_one()+ other = Account(+ id=uuid.uuid4(),+ user_id=friend.id,+ external_id="acc-ext-other-ws",+ name="Outra Conta",+ type="checking",+ balance=Decimal("0.00"),+ currency="BRL",+ )+ session.add(other)+ await session.commit()+ await session.refresh(other)++ pair_id = leg_out.transfer_pair_id+ intruder = _tx(friend, other, "Same pair id", Decimal("200.00"), "debit", pair_id, user_id=friend.id)+ session.add(intruder)+ await session.commit()++ resp = await client.get("/api/transactions", headers=auth_headers)+ assert resp.status_code == 200+ by_id = {t["id"]: t for t in resp.json()["items"]}+ assert by_id[str(leg_out.id)]["transfer_counterpart"]["account_name"] == "Conta Poupanca"+ assert by_id[str(leg_in.id)]["transfer_counterpart"]["account_name"] == "Conta Corrente"++ # And the friend's list resolves its leg within its own workspace only.+ resp2 = await client.get("/api/transactions", headers=friend_headers)+ assert resp2.status_code == 200+ friend_rows = {t["id"]: t for t in resp2.json()["items"]}+ assert friend_rows[str(intruder.id)]["transfer_counterpart"] is None+++async def test_counterpart_uses_the_account_display_name(+ client: AsyncClient, auth_headers, session: AsyncSession, transfer_pair, transfer_accounts+):+ """The badge shows the same name as the rest of the UI: the user's+ display name when set, the account name otherwise."""+ leg_out, leg_in, _ = transfer_pair+ _, savings = transfer_accounts+ savings.display_name = "Reserva"+ await session.commit()++ resp = await client.get("/api/transactions", headers=auth_headers)+ assert resp.status_code == 200+ by_id = {t["id"]: t for t in resp.json()["items"]}+ assert by_id[str(leg_out.id)]["transfer_counterpart"]["account_name"] == "Reserva"+ assert by_id[str(leg_in.id)]["transfer_counterpart"]["account_name"] == "Conta Corrente"diff --git a/frontend/src/components/mobile-transaction-row.tsx b/frontend/src/components/mobile-transaction-row.tsxindex 4e92ed5b..8ceebce3 100644--- a/frontend/src/components/mobile-transaction-row.tsx+++ b/frontend/src/components/mobile-transaction-row.tsx@@ -169,6 +169,14 @@ export function MobileTransactionRow({<span className="text-xs text-muted-foreground truncate">{getAccountName(account)}</span>+ {tx.transfer_counterpart && (+ <>+ <ArrowLeftRight className="h-3 w-3 text-blue-600 shrink-0" aria-hidden="true" />+ <span className="text-xs text-muted-foreground truncate">+ {tx.transfer_counterpart.account_name}+ </span>+ </>+ )}</div>))}diff --git a/frontend/src/pages/transactions-transfer-badge.test.tsx b/frontend/src/pages/transactions-transfer-badge.test.tsxnew file mode 100644index 00000000..0f09cfbc--- /dev/null+++ b/frontend/src/pages/transactions-transfer-badge.test.tsx@@ -0,0 +1,181 @@+/**+ * The transfer badge in the transactions list names the linked account+ * (#810).+ *+ * The list marked every transfer row with a bare "Transfer" badge, so a+ * page full of transfers said nothing about what each row is connected+ * to. The list API now fills `transfer_counterpart` on each transfer+ * row, and the badge adds the other leg's account, as a link to it.+ * Rows whose counterpart the server could not resolve keep the plain badge.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'++import TransactionsPage from '@/pages/transactions'+import { MobileTransactionRow } from '@/components/mobile-transaction-row'+import { renderWithProviders } from '@/test/utils'+import type { Account, Transaction } from '@/types'++const api = vi.hoisted(() => ({+ transactions: { list: vi.fn(), update: vi.fn(), delete: vi.fn(), create: vi.fn() },+ categories: { list: vi.fn(), listIncludingHidden: vi.fn() },+ categoryGroups: { list: vi.fn() },+ accounts: {+ get: vi.fn(), list: vi.fn(), bills: vi.fn(), summary: vi.fn(),+ update: vi.fn(), runningBalance: vi.fn(),+ },+ recurring: { list: vi.fn() },+ payees: { list: vi.fn() },+ admin: { accountingMode: vi.fn() },+ groups: { get: vi.fn(), list: vi.fn() },+ rules: { create: vi.fn() },+ reconciliation: { suggestions: vi.fn() },+ currencies: { list: vi.fn() },+ settings: { attachments: vi.fn() },+}))++vi.mock('@/lib/api', () => ({+ transactions: api.transactions,+ categories: api.categories,+ categoryGroups: api.categoryGroups,+ accounts: api.accounts,+ recurring: api.recurring,+ payees: api.payees,+ admin: api.admin,+ groups: api.groups,+ rules: api.rules,+ reconciliation: api.reconciliation,+ currencies: api.currencies,+ settings: api.settings,+}))+vi.mock('@/hooks/use-mobile', () => ({ useIsMobile: () => false }))+vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))+vi.mock('@/hooks/use-privacy-mode', () => ({+ usePrivacyMode: () => ({ mask: (value: string) => value, privacyMode: false, MASK: '***' }),+}))+vi.mock('@/contexts/auth-context', () => ({+ useAuth: () => ({ user: { id: 'user-1', preferences: { currency_display: 'BRL' } } }),+}))+vi.mock('@/contexts/workspace-context', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/contexts/workspace-context')>()+ return { ...actual, useWorkspace: () => ({ canWrite: true, hasModule: () => true }) }+})+vi.mock('@/contexts/collection-filter-context', () => ({+ useCollectionFilter: () => ({+ collections: [], activeCollectionId: null, activeCollection: null,+ setActiveCollectionId: () => {}, activeAccountIds: null, activeWalletIds: null,+ }),+}))++const TOOLTIP = 'Transfers are excluded from report and dashboard totals'++function tx(over: Partial<Transaction> & { id: string; description: string }): Transaction {+ return {+ user_id: 'user-1', account_id: 'acc-1', category_id: null, category: null,+ external_id: null, original_description: null, amount: 1, currency: 'BRL',+ date: '2026-10-08', type: 'debit', source: 'manual', status: 'posted',+ payee: null, payee_id: null, payee_name: null, notes: null,+ transfer_pair_id: null, transfer_counterpart: null, amount_primary: null,+ fx_rate_used: null, fx_fallback: false, installment_number: null,+ total_installments: null, installment_total_amount: null,+ installment_purchase_date: null, installment_series_id: null, bill_id: null,+ effective_bill_date: null, splits: [], is_ignored: false,+ ...over,+ }+}++const pair = 'pair-1'+const rows: Transaction[] = [+ tx({+ id: 'tx-out', description: 'Transfer out', transfer_pair_id: pair,+ transfer_counterpart: { account_id: 'acc-2', account_name: 'Savings' },+ }),+ tx({+ id: 'tx-in', description: 'Transfer in', type: 'credit',+ transfer_pair_id: pair,+ transfer_counterpart: { account_id: 'acc-1', account_name: 'Checking' },+ }),+ // The server could not resolve this leg's counterpart: old badge stays.+ tx({ id: 'tx-plain', description: 'Transfer plain', transfer_pair_id: 'pair-2' }),+ tx({ id: 'tx-groceries', description: 'GROCERIES' }),+]++async function renderPage() {+ return renderWithProviders(<TransactionsPage />, { route: '/transactions', path: '/transactions' })+}++beforeEach(() => {+ vi.clearAllMocks()+ vi.setSystemTime(new Date('2026-10-20T12:00:00'))+ api.transactions.list.mockResolvedValue({ items: rows, total: rows.length, page: 1, limit: 50 })+ api.categories.list.mockResolvedValue([])+ api.categories.listIncludingHidden.mockResolvedValue([])+ api.categoryGroups.list.mockResolvedValue([])+ api.accounts.list.mockResolvedValue([])+ api.recurring.list.mockResolvedValue([])+ api.payees.list.mockResolvedValue([])+ api.admin.accountingMode.mockResolvedValue(false)+ api.groups.list.mockResolvedValue([])+ api.reconciliation.suggestions.mockResolvedValue([])+ api.currencies.list.mockResolvedValue([])+ api.settings.attachments.mockResolvedValue(false)+})++describe('transfer rows in the transactions list', () => {+ it('names the account each row is linked to', async () => {+ await renderPage()++ const outLink = await screen.findByRole('link', { name: 'Savings' })+ expect(outLink).toHaveAttribute('href', '/accounts/acc-2')+ const inLink = await screen.findByRole('link', { name: 'Checking' })+ expect(inLink).toHaveAttribute('href', '/accounts/acc-1')+ // The name sits inside the existing "Transfer" badge, which keeps its+ // label and its explanation tooltip.+ const outBadge = outLink.parentElement!+ expect(outBadge).toHaveTextContent('Transfer')+ expect(outBadge.querySelector(`[title="${TOOLTIP}"]`)).not.toBeNull()++ // A row whose counterpart the server could not resolve keeps the plain+ // badge: the "Transfer" word, no name, no link to follow.+ const plainRow = (await screen.findByText('Transfer plain')).closest('div[class*="flex"]')!+ expect(plainRow).toHaveTextContent('Transfer')+ expect(plainRow.querySelector('a[href^="/accounts/"]')).toBeNull()+ })++ it('opens the linked account from the badge', async () => {+ const { user } = await renderPage()++ await user.click(await screen.findByRole('link', { name: 'Savings' }))++ // The click navigates to /accounts/acc-2; this test mounts the page+ // only under /transactions, so the list unmounts with the route.+ await waitFor(() => expect(screen.queryByText('Transfer out')).not.toBeInTheDocument())+ })++ it('names the linked account next to the account on the mobile row', () => {+ const checking = { id: 'acc-1', name: 'Checking', display_name: null, type: 'checking' } as unknown as Account+ renderWithProviders(+ <MobileTransactionRow+ tx={rows[0]}+ account={checking}+ groupName={undefined}+ selected={false}+ selectable={false}+ canWrite={true}+ highlighted={false}+ locale="en-US"+ userCurrency="BRL"+ onSelect={() => {}}+ onClick={() => {}}+ />,+ )++ // rows[0] is linked to 'Savings': the name is visible text on the row,+ // so it works on touch, not only as a hover tooltip.+ expect(screen.getByText('Checking')).toBeInTheDocument()+ expect(screen.getByText('Savings')).toBeInTheDocument()+ })+})diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex aaacb7c3..4ef5718f 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -1177,6 +1177,16 @@ export default function TransactionsPage() {<span className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-blue-600 bg-blue-50 border border-blue-200 px-1.5 py-0.5 rounded-full"><ArrowLeftRight className="h-3 w-3" />{t('transactions.transfer')}+ {tx.transfer_counterpart && (+ <Link+ to={`/accounts/${tx.transfer_counterpart.account_id}`}+ onClick={(e) => e.stopPropagation()}+ title={tx.transfer_counterpart.account_name}+ className="normal-case tracking-normal font-medium max-w-[180px] truncate hover:underline"+ >+ {tx.transfer_counterpart.account_name}+ </Link>+ )}<span title={t('transactions.transferTooltip')}><HelpCircle className="h-3 w-3 text-blue-400" /></span></span>)}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 50b2ab18..5d192f5a 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -290,6 +290,12 @@ export interface Transaction {payee_name: string | nullnotes: string | nulltransfer_pair_id: string | null+ /**+ * The other leg of the transfer this row belongs to, when it is one.+ * The paginated list fills it so the badge can name the account the+ * transfer is linked to (issue #810); other endpoints leave it null.+ */+ transfer_counterpart?: { account_id: string; account_name: string } | nullamount_primary: number | nullfx_rate_used: number | nullfx_fallback: boolean