Open-source personal finance manager. Self-hosted, privacy-first.
fix(transactions): badge transfer-category rows as transfers in every list (#1231)
Tássio Noronha735837eb9a72
diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.pyindex c27c1016..16e8a675 100644--- a/backend/app/schemas/dashboard.py+++ b/backend/app/schemas/dashboard.py@@ -76,3 +76,4 @@ class ProjectedTransaction(BaseModel):category_name: Optional[str]category_icon: Optional[str]category_color: Optional[str] = None+ category_treat_as_transfer: bool = Falsediff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex 4fdf546f..35281348 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -1137,14 +1137,20 @@ async def get_projected_transactions(# Pre-fetch categories for all recurring templates that have onecat_ids = {r.category_id for r in recurring_list if r.category_id}- cat_map: dict[uuid.UUID, tuple[str, str, str]] = {}+ cat_map: dict[uuid.UUID, tuple[str, str, str, bool]] = {}if cat_ids:cat_result = await session.execute(- select(Category.id, Category.name, Category.icon, Category.color)+ select(+ Category.id,+ Category.name,+ Category.icon,+ Category.color,+ Category.treat_as_transfer,+ ).where(Category.id.in_(cat_ids)))for row in cat_result.all():- cat_map[row[0]] = (row[1], row[2], row[3])+ cat_map[row[0]] = (row[1], row[2], row[3], bool(row[4]))projections: list[ProjectedTransaction] = []for rec in recurring_list:@@ -1157,7 +1163,11 @@ async def get_projected_transactions(intended_day=rec.day_of_month or rec.start_date.day,weekend_adjustment=rec.weekend_adjustment,)- cat_name, cat_icon, cat_color = cat_map.get(rec.category_id, (None, None, None)) if rec.category_id else (None, None, None)+ cat_name, cat_icon, cat_color, cat_is_transfer = (+ cat_map.get(rec.category_id, (None, None, None, False))+ if rec.category_id+ else (None, None, None, False)+ )# Convert to primary currency at the latest real rate. A missing rate# stays unknown; virtual projections must never manufacture a 1:1@@ -1188,6 +1198,7 @@ async def get_projected_transactions(category_name=cat_name,category_icon=cat_icon,category_color=cat_color,+ category_treat_as_transfer=cat_is_transfer,))return projectionsdiff --git a/backend/tests/test_dashboard_api.py b/backend/tests/test_dashboard_api.pyindex d65c1fd7..c8b8cdad 100644--- a/backend/tests/test_dashboard_api.py+++ b/backend/tests/test_dashboard_api.py@@ -669,6 +669,53 @@ async def test_projected_transactions_account_id_and_range(client, auth_headers,assert defaults.json() == []+async def test_projected_transactions_carry_category_transfer_flag(+ client, auth_headers, test_account, test_categories+):+ """Each projection says whether its category is a transfer category, so a+ projected row can be badged like a posted row in that category."""+ next_month = _next_month_str()++ cat_resp = await client.post(+ "/api/categories",+ json={"name": "Savings move", "icon": "piggy-bank", "color": "#000000", "treat_as_transfer": True},+ headers=auth_headers,+ )+ assert cat_resp.status_code == 201+ transfer_category_id = cat_resp.json()["id"]++ for desc, category_id in (+ ("Move to savings", transfer_category_id),+ ("Rent", str(test_categories[0].id)),+ ("No category", None),+ ):+ rec_resp = await client.post(+ "/api/recurring-transactions",+ json={+ "description": desc,+ "amount": 100.00,+ "currency": "BRL",+ "type": "debit",+ "frequency": "monthly",+ "start_date": next_month,+ "category_id": category_id,+ "account_id": str(test_account.id),+ },+ headers=auth_headers,+ )+ assert rec_resp.status_code == 201++ resp = await client.get(+ "/api/dashboard/projected-transactions",+ params={"from": next_month, "to": next_month},+ headers=auth_headers,+ )+ assert resp.status_code == 200+ flags = {p["description"]: p["category_treat_as_transfer"] for p in resp.json()}+ assert flags == {"Move to savings": True, "Rent": False, "No category": False}++@pytest.mark.asyncioasync def test_projected_transactions_range_excludes_outside_dates(client, auth_headers, test_account, test_categoriesdiff --git a/frontend/src/components/mobile-transaction-row.test.tsx b/frontend/src/components/mobile-transaction-row.test.tsxnew file mode 100644index 00000000..c556e9b3--- /dev/null+++ b/frontend/src/components/mobile-transaction-row.test.tsx@@ -0,0 +1,130 @@+import { describe, expect, it, vi } from 'vitest'+import { render, screen } from '@testing-library/react'+import { MobileTransactionRow } from './mobile-transaction-row'+import type { Account, Category, Transaction } from '@/types'++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),+}))++function makeCategory(overrides: Partial<Category> = {}): Category {+ return {+ id: 'cat-1',+ user_id: 'u-1',+ group_id: null,+ name: 'Transfers',+ icon: 'arrow-left-right',+ color: '#3b82f6',+ is_system: true,+ is_hidden: false,+ treat_as_transfer: false,+ is_ignored: false,+ ...overrides,+ }+}++function makeTx(overrides: Partial<Transaction> = {}): Transaction {+ return {+ id: 'tx-1',+ user_id: 'u-1',+ account_id: 'acc-1',+ category_id: null,+ category: null,+ external_id: null,+ description: 'STORE PURCHASE',+ original_description: null,+ amount: -42,+ currency: 'USD',+ date: '2026-10-20',+ type: 'debit',+ source: 'manual',+ status: 'posted',+ payee: 'Store A',+ payee_id: null,+ payee_name: null,+ notes: null,+ transfer_pair_id: 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,+ ...overrides,+ }+}++function makeAccount(): Account {+ return {+ id: 'acc-1',+ user_id: 'u-1',+ connection_id: null,+ external_id: null,+ name: 'Checking A',+ display_name: null,+ masked_number: null,+ institution_name: null,+ institution_logo_url: null,+ type: 'checking',+ balance: 100,+ current_balance: 100,+ previous_balance: null,+ balance_primary: 100,+ currency: 'USD',+ credit_limit: null,+ available_credit: null,+ statement_close_day: null,+ payment_due_day: null,+ next_close_date: null,+ next_due_date: null,+ minimum_payment: null,+ card_brand: null,+ card_level: null,+ shared_balance_group: null,+ is_closed: false,+ closed_at: null,+ }+}++function renderRow(tx: Transaction) {+ return render(+ <MobileTransactionRow+ tx={tx}+ account={makeAccount()}+ groupName={undefined}+ selected={false}+ selectable={false}+ canWrite={true}+ highlighted={false}+ locale="en"+ userCurrency="USD"+ onSelect={() => {}}+ onClick={() => {}}+ />,+ )+}++describe('MobileTransactionRow transfer indicator', () => {+ it('shows the transfer icon for a treat_as_transfer category without a pair (#993)', () => {+ const category = makeCategory({ treat_as_transfer: true })+ renderRow(makeTx({ category_id: category.id, category }))+ expect(screen.getByLabelText('transactions.transfer')).toBeInTheDocument()+ })++ it('shows the transfer icon for a linked transfer pair', () => {+ renderRow(makeTx({ transfer_pair_id: 'pair-1' }))+ expect(screen.getByLabelText('transactions.transfer')).toBeInTheDocument()+ })++ it('hides the transfer icon for a normal row', () => {+ const category = makeCategory({ treat_as_transfer: false })+ renderRow(makeTx({ category_id: category.id, category }))+ expect(screen.queryByLabelText('transactions.transfer')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/mobile-transaction-row.tsx b/frontend/src/components/mobile-transaction-row.tsxindex 8ceebce3..591b2df9 100644--- a/frontend/src/components/mobile-transaction-row.tsx+++ b/frontend/src/components/mobile-transaction-row.tsx@@ -7,6 +7,7 @@ import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useTranslation } from 'react-i18next'import { formatCurrency } from '@/lib/format'import { shouldShowPendingBadge } from '@/lib/transaction-status'+import { isTransferTransaction } from '@/lib/transaction-transfer'import { transactionDescription } from '@/lib/transaction-description'/** Keep long merchant references on one line when there are no word breaks. */@@ -117,8 +118,11 @@ export function MobileTransactionRow({{tx.is_shared && tx.parent_owner_name ? tx.parent_owner_name : t('splitGroups.ownerRowBadge', { group: groupName ?? '' })}</span>)}- {!!tx.transfer_pair_id && (- <ArrowLeftRight className="h-3 w-3 text-blue-600 shrink-0" />+ {isTransferTransaction(tx) && (+ <ArrowLeftRight+ className="h-3 w-3 text-blue-600 shrink-0"+ aria-label={t('transactions.transfer')}+ />)}{virtual && (<CalendarClock className="h-3 w-3 text-primary shrink-0" />diff --git a/frontend/src/lib/transaction-transfer.test.ts b/frontend/src/lib/transaction-transfer.test.tsnew file mode 100644index 00000000..70e60659--- /dev/null+++ b/frontend/src/lib/transaction-transfer.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from 'vitest'+import { isTransferTransaction } from './transaction-transfer'+import type { Category, Transaction } from '@/types'++function makeCategory(overrides: Partial<Category> = {}): Category {+ return {+ id: 'cat-1',+ user_id: 'u-1',+ group_id: null,+ name: 'Food',+ icon: 'utensils',+ color: '#f97316',+ is_system: false,+ is_hidden: false,+ treat_as_transfer: false,+ is_ignored: false,+ ...overrides,+ }+}++function makeTx(overrides: Partial<Transaction> = {}): Transaction {+ return {+ id: 'tx-1',+ user_id: 'u-1',+ account_id: 'acc-1',+ category_id: null,+ category: null,+ external_id: null,+ description: 'STORE PURCHASE',+ original_description: null,+ amount: -42,+ currency: 'USD',+ date: '2026-10-20',+ type: 'debit',+ source: 'manual',+ status: 'posted',+ payee: 'Store A',+ payee_id: null,+ payee_name: null,+ notes: null,+ transfer_pair_id: 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,+ ...overrides,+ }+}++describe('isTransferTransaction', () => {+ it('reads a linked transfer pair as a transfer', () => {+ expect(isTransferTransaction(makeTx({ transfer_pair_id: 'pair-1' }))).toBe(true)+ })++ it('reads a treat_as_transfer category as a transfer without a pair (#993)', () => {+ const category = makeCategory({ treat_as_transfer: true })+ expect(+ isTransferTransaction(makeTx({ category_id: category.id, category })),+ ).toBe(true)+ })++ it('does not read a normal category as a transfer', () => {+ const category = makeCategory({ treat_as_transfer: false })+ expect(+ isTransferTransaction(makeTx({ category_id: category.id, category })),+ ).toBe(false)+ })++ it('does not read an uncategorized row without a pair as a transfer', () => {+ expect(isTransferTransaction(makeTx())).toBe(false)+ })+})diff --git a/frontend/src/lib/transaction-transfer.ts b/frontend/src/lib/transaction-transfer.tsnew file mode 100644index 00000000..b82f020e--- /dev/null+++ b/frontend/src/lib/transaction-transfer.ts@@ -0,0 +1,18 @@+import type { Transaction } from '@/types'++/**+ * Whether a transaction reads as a transfer in row-level indicators.+ *+ * A transaction is a transfer when it is part of a linked transfer pair, or+ * when its category is flagged `treat_as_transfer`. The backend classifies+ * transfers the same way for profit and loss: the dashboard, the reports and+ * the list summary all keep these rows out of income and expense totals, and+ * the calendar marks each item with the same test. Row indicators must match,+ * so a row that the totals keep out reads as a transfer on every screen that+ * lists it (issue #993).+ */+export function isTransferTransaction(+ tx: Pick<Transaction, 'transfer_pair_id' | 'category'>,+): boolean {+ return !!tx.transfer_pair_id || !!tx.category?.treat_as_transfer+}diff --git a/frontend/src/pages/account-detail-projected-transfer.test.tsx b/frontend/src/pages/account-detail-projected-transfer.test.tsxnew file mode 100644index 00000000..78b15713--- /dev/null+++ b/frontend/src/pages/account-detail-projected-transfer.test.tsx@@ -0,0 +1,121 @@+/**+ * Projected rows in a transfer category (#993).+ *+ * A recurring transaction whose category is flagged treat_as_transfer shows+ * up in Account Detail as a projected row. That row must carry the flag so+ * it gets the same Transfer badge as a posted row in that category.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, within } from '@testing-library/react'++import AccountDetailPage from '@/pages/account-detail'+import { renderWithProviders } from '@/test/utils'+import type { Transaction } from '@/types'++const api = vi.hoisted(() => ({+ accounts: {+ get: vi.fn(),+ bills: vi.fn(),+ summary: vi.fn(),+ list: vi.fn(),+ update: vi.fn(),+ runningBalance: vi.fn(),+ },+ transactions: { list: vi.fn(), update: vi.fn(), delete: vi.fn(), create: vi.fn() },+ dashboard: { projectedTransactions: vi.fn() },+ categories: { list: vi.fn() },+ categoryGroups: { list: vi.fn() },+}))++vi.mock('@/lib/api', () => ({+ accounts: api.accounts,+ transactions: api.transactions,+ dashboard: api.dashboard,+ categories: api.categories,+ categoryGroups: api.categoryGroups,+}))+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: { preferences: { currency_display: 'BRL' } } }),+}))+vi.mock('@/contexts/workspace-context', () => ({+ useWorkspace: () => ({ canWrite: true }),+}))++const checking = {+ id: 'acc-1', name: 'Checking', type: 'checking', currency: 'BRL',+ balance: 9000, current_balance: 9000, is_active: true,+}++/** A R$1 debit. Its amount alone can never add up to the balances below,+ * so any balance on screen that matches them came from the server. */+function tx(index: number, date: string, runningBalance: number | null): Transaction {+ return {+ id: `tx-${index}`, user_id: 'user-1', account_id: 'acc-1', category_id: null,+ category: null, external_id: null, description: `Payment ${index}`,+ original_description: null, amount: 1, currency: 'BRL', date, type: 'debit',+ source: 'manual', status: 'posted', payee: null, payee_id: null,+ payee_name: null, notes: null, transfer_pair_id: 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,+ running_balance: runningBalance, running_balance_primary: null,+ }+}++function projection(description: string, treatAsTransfer: boolean) {+ return {+ recurring_id: `rec-${description}`, account_id: 'acc-1', description, amount: 500,+ amount_primary: null, currency: 'BRL', type: 'debit', date: '2026-09-28',+ category_id: 'cat-1', category_name: 'Savings', category_icon: 'piggy-bank',+ category_color: '#000000', category_treat_as_transfer: treatAsTransfer,+ }+}++function row(description: string) {+ return screen.getByText(description).closest('tr')!+}++beforeEach(() => {+ vi.clearAllMocks()+ vi.setSystemTime(new Date('2026-09-15T12:00:00'))+ api.accounts.get.mockResolvedValue(checking)+ api.accounts.list.mockResolvedValue([])+ api.accounts.bills.mockResolvedValue([])+ api.accounts.summary.mockResolvedValue({+ opening_balance: 0, current_balance: 9000, monthly_income: 0, monthly_expenses: 0,+ projected_income: 0, projected_expenses: 0,+ })+ api.accounts.runningBalance.mockResolvedValue([])+ api.categories.list.mockResolvedValue([])+ api.categoryGroups.list.mockResolvedValue([])+ api.transactions.list.mockResolvedValue({ items: [tx(0, '2026-09-10', 9000)], total: 1, page: 1, limit: 100 })+})++describe('a projected row', () => {+ it('shows the Transfer badge when its category is a transfer category', async () => {+ api.dashboard.projectedTransactions.mockResolvedValue([projection('Move to savings', true)])++ renderWithProviders(<AccountDetailPage />, { route: '/accounts/acc-1', path: '/accounts/:id' })++ expect(await screen.findByText('Move to savings')).toBeVisible()+ expect(within(row('Move to savings')).getByText('Transfer')).toBeVisible()+ })++ it('shows no Transfer badge for a normal category', async () => {+ api.dashboard.projectedTransactions.mockResolvedValue([projection('Rent', false)])++ renderWithProviders(<AccountDetailPage />, { route: '/accounts/acc-1', path: '/accounts/:id' })++ expect(await screen.findByText('Rent')).toBeVisible()+ expect(within(row('Rent')).queryByText('Transfer')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/pages/account-detail-running-balance.test.tsx b/frontend/src/pages/account-detail-running-balance.test.tsxindex 7683f0b2..1e4d3ef5 100644--- a/frontend/src/pages/account-detail-running-balance.test.tsx+++ b/frontend/src/pages/account-detail-running-balance.test.tsx@@ -127,6 +127,7 @@ describe('a non-credit-card account with more rows than one page', () => {recurring_id: 'rec-1', account_id: 'acc-1', description: 'Rent', amount: 500,amount_primary: null, currency: 'BRL', type: 'debit', date: '2026-09-28',category_id: null, category_name: null, category_icon: null, category_color: null,+ category_treat_as_transfer: false,}])})diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex 30f6deb9..90513d8a 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -10,6 +10,7 @@ import { localDateString } from '@/lib/date-utils'import { applyTransactionToBalance, excludeMaterializedProjections, mergeRunningBalances, runningBalanceChartFrom, transactionAmountForBalance } from '@/lib/account-detail-utils'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { shouldShowPendingBadge } from '@/lib/transaction-status'+import { isTransferTransaction } from '@/lib/transaction-transfer'import { closeDateForBill, isOpenCycleWindow } from '@/lib/credit-card-cycle'import { toast } from 'sonner'import type { CreditCardBill, ProjectedTransaction, Transaction } from '@/types'@@ -727,7 +728,7 @@ export default function AccountDetailPage() {color: p.category_color ?? '',is_system: false,is_hidden: false,- treat_as_transfer: false,+ treat_as_transfer: p.category_treat_as_transfer,is_ignored: false,}: null,@@ -1659,7 +1660,7 @@ export default function AccountDetailPage() {<tbody>{displayRows.map((tx) => {const isOpening = tx.source === 'opening_balance'- const isTransfer = !!tx.transfer_pair_id+ const isTransfer = isTransferTransaction(tx)const isIgnored = tx.is_ignoredconst isVirtual = tx.virtual === truereturn (diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 4ef5718f..cff1f8e3 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -80,6 +80,7 @@ import { useWorkspace } from '@/contexts/workspace-context'import { useCollectionFilter } from '@/contexts/collection-filter-context'import { formatCurrency } from '@/lib/format'import { shouldShowPendingBadge } from '@/lib/transaction-status'+import { isTransferTransaction } from '@/lib/transaction-transfer'type TransactionUpdatePayload = TransactionEditPayload & {apply_to_transfer_pair?: boolean@@ -1173,7 +1174,7 @@ export default function TransactionsPage() {: t('transactions.invoiceBadgeNoNumber')}</Link>))}- {!!tx.transfer_pair_id && (+ {isTransferTransaction(tx) && (<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')}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 5d192f5a..c36edc73 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -674,6 +674,7 @@ export interface ProjectedTransaction {category_name: string | nullcategory_icon: string | nullcategory_color: string | null+ category_treat_as_transfer: boolean}export interface TransactionCalendarItem {