Open-source personal finance manager. Self-hosted, privacy-first.
fix(accounts): stop presenting 1:1 fallback balances as converted across accounts and dashboard (#1195)
Vijay Misal7c7fffa284c0
diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.pyindex a4268f1d..ab0f8302 100644--- a/backend/app/api/accounts.py+++ b/backend/app/api/accounts.py@@ -20,7 +20,7 @@ from app.schemas.account import (CreditCardBillRead,)from app.services import account_service-from app.services.fx_rate_service import convert+from app.services.fx_rate_service import _resolve_raterouter = APIRouter(prefix="/api/accounts", tags=["accounts"])@@ -35,10 +35,15 @@ async def list_accounts(primary_currency = ctx.user.primary_currencyfor acc in accounts:if acc["currency"] != primary_currency:- converted, _ = await convert(- session, Decimal(str(acc["current_balance"])), acc["currency"], primary_currency,- )- acc["balance_primary"] = float(converted)+ # Use the real rate only: the 1:1 fallback would present a foreign+ # balance as already converted (issue #1165). Leaving it unset makes+ # the UI show the native currency and flag the missing rate.+ rate = await _resolve_rate(session, acc["currency"], primary_currency)+ if rate is None:+ acc["fx_fallback"] = True+ else:+ converted = Decimal(str(acc["current_balance"])) * rate+ acc["balance_primary"] = float(converted.quantize(Decimal("0.01")))return accounts@@ -64,18 +69,18 @@ async def get_account_summary(account = await account_service.get_account(session, account_id, ctx.workspace.id)primary_currency = ctx.user.primary_currencyif account and account.currency != primary_currency:- bal, _ = await convert(session, Decimal(str(summary["current_balance"])), account.currency, primary_currency)- opening, _ = await convert(session, Decimal(str(summary["opening_balance"])), account.currency, primary_currency)- inc, _ = await convert(session, Decimal(str(summary["monthly_income"])), account.currency, primary_currency)- exp, _ = await convert(session, Decimal(str(summary["monthly_expenses"])), account.currency, primary_currency)- projected_inc, _ = await convert(session, Decimal(str(summary["projected_income"])), account.currency, primary_currency)- projected_exp, _ = await convert(session, Decimal(str(summary["projected_expenses"])), account.currency, primary_currency)- summary["current_balance_primary"] = float(bal)- summary["opening_balance_primary"] = float(opening)- summary["monthly_income_primary"] = float(inc)- summary["monthly_expenses_primary"] = float(exp)- summary["projected_income_primary"] = float(projected_inc)- summary["projected_expenses_primary"] = float(projected_exp)+ # Same rule as list_accounts: without a real rate, leave the *_primary+ # fields unset instead of returning 1:1 values as if converted (#1165).+ rate = await _resolve_rate(session, account.currency, primary_currency)+ if rate is None:+ summary["fx_fallback"] = True+ else:+ for field in (+ "current_balance", "opening_balance", "monthly_income",+ "monthly_expenses", "projected_income", "projected_expenses",+ ):+ converted = Decimal(str(summary[field])) * rate+ summary[f"{field}_primary"] = float(converted.quantize(Decimal("0.01")))return summary@@ -101,10 +106,12 @@ async def get_account_balance_history(if account and account.currency != primary_currency:for point in history:point_date = date.fromisoformat(point["date"])- converted, _ = await convert(- session, Decimal(str(point["balance"])), account.currency, primary_currency, target_date=point_date,- )- point["balance_primary"] = float(converted)+ rate = await _resolve_rate(session, account.currency, primary_currency, point_date)+ if rate is None:+ point["fx_fallback"] = True+ else:+ converted = Decimal(str(point["balance"])) * rate+ point["balance_primary"] = float(converted.quantize(Decimal("0.01")))return historydiff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex 045e34a4..2224822c 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -58,6 +58,9 @@ class AccountRead(AccountBase):current_balance: float = 0.0previous_balance: Optional[float] = Nonebalance_primary: Optional[float] = None+ # True when the account is in a foreign currency and no real FX rate is+ # available, so balance_primary is left unset rather than a 1:1 guess.+ fx_fallback: bool = Falsecredit_limit: Optional[float] = Noneavailable_credit: Optional[float] = Nonestatement_close_day: Optional[int] = None@@ -106,3 +109,6 @@ class AccountSummary(BaseModel):monthly_expenses_primary: Optional[float] = Noneprojected_income_primary: Optional[float] = Noneprojected_expenses_primary: Optional[float] = None+ # True when no real FX rate is available, so the *_primary fields are+ # left unset rather than a 1:1 guess.+ fx_fallback: bool = Falsediff --git a/backend/tests/test_accounts_api_coverage.py b/backend/tests/test_accounts_api_coverage.pyindex f03bfc81..fd190483 100644--- a/backend/tests/test_accounts_api_coverage.py+++ b/backend/tests/test_accounts_api_coverage.py@@ -5,10 +5,15 @@ balance-history and bills endpoints, plus 404/400 error branches and thenon-primary-currency conversion path."""+from decimal import Decimal+import pytestfrom httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.models.account import Account+from app.models.fx_rate import FxRateNONEXISTENT = "00000000-0000-0000-0000-000000000000"@@ -40,9 +45,14 @@ async def test_list_accounts_include_closed(client: AsyncClient, auth_headers):@pytest.mark.asyncioasync def test_list_accounts_foreign_currency_conversion(- client: AsyncClient, auth_headers+ client: AsyncClient, auth_headers, session: AsyncSession):- """A non-primary-currency account triggers the convert() balance_primary path."""+ """A non-primary-currency account is converted with the stored rate."""+ session.add(FxRate(+ base_currency="USD", quote_currency="BRL", date=app_today(),+ rate=Decimal("5.0"), source="test",+ ))+ await session.commit()await client.post("/api/accounts", headers=auth_headers,json={"name": "USD Wallet", "type": "checking", "balance": "100.00", "currency": "USD"},@@ -50,7 +60,39 @@ async def test_list_accounts_foreign_currency_conversion(resp = await client.get("/api/accounts", headers=auth_headers)assert resp.status_code == 200usd = next(a for a in resp.json() if a["name"] == "USD Wallet")- assert "balance_primary" in usd+ assert usd["balance_primary"] == pytest.approx(500.0)+ assert usd["fx_fallback"] is False+++async def test_list_accounts_foreign_currency_without_rate(+ client: AsyncClient, auth_headers+):+ """Without a real rate the balance is not presented as converted (#1165).++ The 1:1 fallback used to come back as balance_primary, so the dashboard+ showed a EUR balance with the primary currency's symbol and summed it as+ if it were already converted.+ """+ await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "EUR Wallet", "type": "checking", "balance": "100.00", "currency": "EUR"},+ )+ resp = await client.get("/api/accounts", headers=auth_headers)+ assert resp.status_code == 200+ eur = next(a for a in resp.json() if a["name"] == "EUR Wallet")+ assert eur["balance_primary"] is None+ assert eur["fx_fallback"] is True+++async def test_list_accounts_primary_currency_has_no_fallback_flag(+ client: AsyncClient, auth_headers, test_account: Account+):+ resp = await client.get("/api/accounts", headers=auth_headers)+ brl = next(a for a in resp.json() if a["id"] == str(test_account.id))+ assert brl["balance_primary"] is None+ assert brl["fx_fallback"] is False# ---------------------------------------------------------------------------@@ -225,6 +267,53 @@ async def test_account_summary_not_found(client: AsyncClient, auth_headers, testassert resp.status_code == 404+async def test_account_summary_foreign_currency_conversion(+ client: AsyncClient, auth_headers, session: AsyncSession+):+ """The summary converts a foreign account with the stored rate."""+ session.add(FxRate(+ base_currency="USD", quote_currency="BRL", date=app_today(),+ rate=Decimal("5.0"), source="test",+ ))+ await session.commit()+ created = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "USD Wallet", "type": "checking", "balance": "100.00", "currency": "USD"},+ )+ resp = await client.get(+ f"/api/accounts/{created.json()['id']}/summary", headers=auth_headers+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["current_balance_primary"] == pytest.approx(500.0)+ assert data["fx_fallback"] is False+++async def test_account_summary_foreign_currency_without_rate(+ client: AsyncClient, auth_headers+):+ """Without a real rate the summary does not return 1:1 values (#1165).++ Otherwise the detail page would show a converted balance for an account+ the accounts list shows in its native currency.+ """+ created = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "EUR Wallet", "type": "checking", "balance": "100.00", "currency": "EUR"},+ )+ resp = await client.get(+ f"/api/accounts/{created.json()['id']}/summary", headers=auth_headers+ )+ assert resp.status_code == 200+ data = resp.json()+ assert data["current_balance"] == pytest.approx(100.0)+ assert data["current_balance_primary"] is None+ assert data["opening_balance_primary"] is None+ assert data["fx_fallback"] is True++# ---------------------------------------------------------------------------# balance-history# ---------------------------------------------------------------------------@@ -248,6 +337,51 @@ async def test_balance_history_not_found(client: AsyncClient, auth_headers, testassert resp.status_code == 404+async def test_balance_history_foreign_currency_conversion(+ client: AsyncClient, auth_headers, session: AsyncSession+):+ """Each history point is converted with the stored rate."""+ session.add(FxRate(+ base_currency="USD", quote_currency="BRL", date=app_today(),+ rate=Decimal("5.0"), source="test",+ ))+ await session.commit()+ created = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "USD Wallet", "type": "checking", "balance": "100.00", "currency": "USD"},+ )+ resp = await client.get(+ f"/api/accounts/{created.json()['id']}/balance-history", headers=auth_headers+ )+ assert resp.status_code == 200+ points = resp.json()+ assert points+ for point in points:+ assert point["balance_primary"] == pytest.approx(point["balance"] * 5)+ assert "fx_fallback" not in point+++async def test_balance_history_foreign_currency_without_rate(+ client: AsyncClient, auth_headers+):+ """Without a real rate no point carries a 1:1 balance_primary (#1165)."""+ created = await client.post(+ "/api/accounts", headers=auth_headers,+ json={"name": "EUR Wallet", "type": "checking", "balance": "100.00", "currency": "EUR"},+ )+ resp = await client.get(+ f"/api/accounts/{created.json()['id']}/balance-history", headers=auth_headers+ )+ assert resp.status_code == 200+ points = resp.json()+ assert points+ for point in points:+ assert "balance_primary" not in point+ assert point["fx_fallback"] is True++# ---------------------------------------------------------------------------# bills# ---------------------------------------------------------------------------diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex bbdbfbaa..6be66d2a 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -483,7 +483,7 @@ export const accounts = {const { data } = await api.get(`/accounts/${id}/summary`, { params: { from, to, bill_id: billId, unbilled_only: unbilledOnly || undefined } })return data},- balanceHistory: async (id: string, from?: string, to?: string): Promise<{ date: string; balance: number; balance_primary?: number }[]> => {+ balanceHistory: async (id: string, from?: string, to?: string): Promise<{ date: string; balance: number; balance_primary?: number; fx_fallback?: boolean }[]> => {const { data } = await api.get(`/accounts/${id}/balance-history`, { params: { from, to } })return data},diff --git a/frontend/src/pages/account-detail-fx-fallback.test.tsx b/frontend/src/pages/account-detail-fx-fallback.test.tsxnew file mode 100644index 00000000..a3ffad6e--- /dev/null+++ b/frontend/src/pages/account-detail-fx-fallback.test.tsx@@ -0,0 +1,86 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'++import AccountDetailPage from '@/pages/account-detail'+import { i18n, renderWithProviders } from '@/test/utils'++const api = vi.hoisted(() => ({+ accounts: { get: vi.fn(), bills: vi.fn(), summary: vi.fn(), list: vi.fn(), update: 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 account = {+ id: 'acc-eur', name: 'EUR Wallet', type: 'checking', currency: 'EUR',+ balance: 100, current_balance: 100, is_active: true,+}+const nativeSummary = {+ opening_balance: 100, current_balance: 100, monthly_income: 0, monthly_expenses: 0,+ projected_income: 0, projected_expenses: 0,+}++beforeEach(async () => {+ vi.clearAllMocks()+ await i18n.changeLanguage('en')+ api.accounts.get.mockResolvedValue(account)+ api.accounts.list.mockResolvedValue([account])+ api.transactions.list.mockResolvedValue({ items: [], total: 0 })+ api.dashboard.projectedTransactions.mockResolvedValue([])+ api.categories.list.mockResolvedValue([])+ api.categoryGroups.list.mockResolvedValue([])+})++function renderPage() {+ renderWithProviders(<AccountDetailPage />, {+ route: `/accounts/${account.id}`, path: '/accounts/:id',+ })+}++describe('account-detail FX fallback (#1165)', () => {+ it('keeps the primary-currency toggle off when the summary has no real rate', async () => {+ api.accounts.summary.mockResolvedValue({ ...nativeSummary, fx_fallback: true })+ renderPage()++ const primary = await screen.findByRole('button', { name: 'BRL' })+ await waitFor(() => expect(primary).toBeDisabled())+ expect(primary).toHaveAttribute('title', i18n.t('transactions.fxFallbackBanner'))+ expect(screen.getByRole('button', { name: 'EUR' })).toBeEnabled()+ })++ it('allows the primary-currency toggle when the summary is converted', async () => {+ api.accounts.summary.mockResolvedValue({+ ...nativeSummary, current_balance_primary: 600, opening_balance_primary: 600,+ monthly_income_primary: 0, monthly_expenses_primary: 0, fx_fallback: false,+ })+ renderPage()++ const primary = await screen.findByRole('button', { name: 'BRL' })+ await waitFor(() => expect(api.accounts.summary).toHaveBeenCalled())+ expect(primary).toBeEnabled()+ expect(primary).not.toHaveAttribute('title')+ })+})diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex ff57968a..1dc2fbfa 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -634,8 +634,12 @@ export default function AccountDetailPage() {// Whether to use primary currency amounts (for foreign-currency accounts with toggle, or domestic accounts with foreign txs)const isCreditCard = account?.type === 'credit_card'const isForeignCurrency = account ? account.currency !== userCurrency : false- const usePrimary = !isForeignCurrency || showPrimary- const displayCurrency = (isForeignCurrency && !showPrimary) ? (account?.currency || userCurrency) : userCurrency+ // No real FX rate: the summary leaves the *_primary fields unset, so stay on+ // the account's own currency instead of labelling native amounts as converted.+ const fxFallback = summary?.fx_fallback === true+ const primaryShown = showPrimary && !fxFallback+ const usePrimary = !isForeignCurrency || primaryShown+ const displayCurrency = (isForeignCurrency && !primaryShown) ? (account?.currency || userCurrency) : userCurrency// Pseudo-transaction rows for non-materialized recurring projections.// Virtual: rendered with a "Previsão" badge, non-clickable, and merged@@ -1049,13 +1053,15 @@ export default function AccountDetailPage() {<div className="ml-auto inline-flex rounded-lg border border-border bg-muted p-0.5 text-xs font-medium"><buttononClick={() => setShowPrimary(false)}- className={`px-3 py-1.5 rounded-md transition-colors ${!showPrimary ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}+ className={`px-3 py-1.5 rounded-md transition-colors ${!primaryShown ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}>{account.currency}</button><buttononClick={() => setShowPrimary(true)}- className={`px-3 py-1.5 rounded-md transition-colors ${showPrimary ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}+ disabled={fxFallback}+ title={fxFallback ? t('transactions.fxFallbackBanner') : undefined}+ className={`px-3 py-1.5 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${primaryShown ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`}>{userCurrency}</button>@@ -1151,7 +1157,7 @@ export default function AccountDetailPage() {// can lag any charges added since the last sync). Otherwise use the// summary endpoint's monthly_expenses now nets refund credits against// debits for CC accounts (matches the bank's bill total).- const billTotal = (showPrimary ? summary?.projected_expenses_primary : undefined) ?? summary?.projected_expenses ?? summary?.monthly_expenses ?? 0+ const billTotal = (primaryShown ? summary?.projected_expenses_primary : undefined) ?? summary?.projected_expenses ?? summary?.monthly_expenses ?? 0// "Default cycle" = the bill the user is here to pay (next due). The// AGORA tag on Limite disponível only shows when viewing a different cycle.const isDefaultCycle =@@ -1312,7 +1318,7 @@ export default function AccountDetailPage() {// currently being viewed. For the current cycle this matches the "current// open balance" since nothing has been paid yet; for past cycles it shows// that month's burn rate against the (current) limit.- const cycleBillTotal = (showPrimary ? summary?.projected_expenses_primary : undefined) ?? summary?.projected_expenses ?? summary?.monthly_expenses ?? 0+ const cycleBillTotal = (primaryShown ? summary?.projected_expenses_primary : undefined) ?? summary?.projected_expenses ?? summary?.monthly_expenses ?? 0const utilized = limit != null ? cycleBillTotal : nullconst rawPct = limit != null && limit > 0 && utilized != null ? (utilized / limit) * 100 : nullconst pct = rawPct != null ? Math.min(100, rawPct) : nulldiff --git a/frontend/src/pages/dashboard.test.tsx b/frontend/src/pages/dashboard.test.tsxindex 44c4d367..5d25d607 100644--- a/frontend/src/pages/dashboard.test.tsx+++ b/frontend/src/pages/dashboard.test.tsx@@ -136,3 +136,30 @@ describe('Dashboard net worth breakdown', () => {expect(cardRow).toHaveTextContent(formatCurrency(-500, 'USD', 'en-US'))})})++describe('Dashboard available balance without an FX rate', () => {+ const renderDashboard = () => renderWithProviders(+ <TooltipProvider delayDuration={0}>+ <DashboardPage />+ </TooltipProvider>,+ )++ it('shows an unconverted account in its own currency and flags the total', async () => {+ api.accounts.list.mockResolvedValue([+ account({ id: 'checking', name: 'Checking', current_balance: 1000 }),+ account({ id: 'eur', name: 'Euro Savings', type: 'savings', currency: 'EUR', current_balance: 100, fx_fallback: true }),+ ])+ renderDashboard()++ const chip = (await screen.findByText('Euro Savings')).closest('a')!+ expect(chip).toHaveTextContent(formatCurrency(100, 'EUR', 'en-US'))+ expect(screen.getByText(t('transactions.fxFallbackBanner'))).toBeInTheDocument()+ })++ it('does not flag the total when every account is converted', async () => {+ renderDashboard()++ await screen.findByText('Checking')+ expect(screen.queryByText(t('transactions.fxFallbackBanner'))).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex b1a68ca2..18e359f2 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -405,6 +405,9 @@ export default function DashboardPage() {const availableBalance = availableBalanceAccounts.reduce((sum, a) => sum + Number(a.balance_primary ?? a.current_balance), 0,)+ // A foreign account without a real FX rate is summed at its native amount,+ // so the headline total is an estimate; say so instead of hiding it (#1165).+ const availableBalanceHasFxFallback = availableBalanceAccounts.some((a) => a.fx_fallback)const sortedAvailableBalanceAccounts = useMemo(() => sortAccountsByAbsoluteBalance(availableBalanceAccounts, (a) => a.balance_primary ?? a.current_balance),[availableBalanceAccounts],@@ -673,6 +676,13 @@ export default function DashboardPage() {<p className={`text-3xl font-bold tabular-nums leading-tight ${availableBalance < 0 ? 'text-rose-500' : 'text-foreground'}`}>{mask(formatCurrency(availableBalance, primaryCurrency, locale))}</p>+ {/* Visible text, not a hover title, so touch users can read it. */}+ {availableBalanceHasFxFallback && (+ <p className="flex items-start gap-1.5 mt-1 text-xs text-amber-700 dark:text-amber-400">+ <AlertCircle size={14} className="mt-0.5 shrink-0" />+ <span>{t('transactions.fxFallbackBanner')}</span>+ </p>+ )}{sortedAvailableBalanceAccounts.length > 0 && (<div className="flex flex-wrap gap-1.5 mt-3">{sortedAvailableBalanceAccounts.map((acc) => {diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex e020def3..c81786f8 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -174,6 +174,8 @@ export interface Account {current_balance: numberprevious_balance: number | nullbalance_primary: number | null+ // No real FX rate: balance_primary is unset and totals use the native amount.+ fx_fallback?: booleancurrency: stringcredit_limit: number | nullavailable_credit: number | null@@ -226,6 +228,7 @@ export interface AccountSummary {projected_expenses?: numberprojected_income_primary?: number | nullprojected_expenses_primary?: number | null+ fx_fallback?: boolean}/** Set when this transaction settles an invoice. Absent in workspaces