Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix(dashboard): flag mixed-currency net worth when FX rates are missing (#1265)

Tássio Noronhaceadb3ed68d1
diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.py
index 5f6aa0ff..c27c1016 100644
--- a/backend/app/schemas/dashboard.py
+++ b/backend/app/schemas/dashboard.py
@@ -23,6 +23,10 @@ class DashboardSummary(BaseModel):
assets_value: dict[str, float] = Field(default_factory=dict) # currency -> total asset value
assets_value_primary: float = 0.0
primary_currency: str = "USD"
+ # No real FX rate for at least one currency bucket: the *_primary totals
+ # sum that bucket at 1:1, so they are an estimate, not a conversion.
+ # Same flag the account list carries (issue #1165).
+ fx_fallback: bool = False
# Net pending balance from group splits (in primary currency).
# Negative = the user is a net debtor (others paid for them, debt
# owed). Positive = the user is a net creditor (paid for others,
diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py
index 369d6502..4fdf546f 100644
--- a/backend/app/services/dashboard_service.py
+++ b/backend/app/services/dashboard_service.py
@@ -210,6 +210,37 @@ def _counts_as_user_pnl_row(tx: Transaction) -> bool:
)
+async def _sum_to_primary(
+ session: AsyncSession,
+ buckets: dict[str, float],
+ primary_currency: str,
+ target_date: Optional[date],
+) -> tuple[float, bool]:
+ """Sum per-currency buckets in the primary currency, real rates only.
+
+ A bucket without a real rate is kept at its native amount (1:1) and the
+ returned flag reports the estimate, so the UI can surface it instead of
+ a foreign balance passing as converted (issue #1165, same rule as the
+ account list in app/api/accounts.py).
+ """
+ total = 0.0
+ fx_fallback = False
+ for currency, amount in buckets.items():
+ if currency == primary_currency:
+ total += float(amount)
+ continue
+ if not amount:
+ # Zero is zero in any currency: no rate needed, nothing estimated.
+ continue
+ rate = await _resolve_rate(session, currency, primary_currency, target_date)
+ if rate is None:
+ fx_fallback = True
+ total += float(amount)
+ continue
+ total += float((Decimal(str(amount)) * rate).quantize(Decimal("0.01")))
+ return total, fx_fallback
+
+
async def get_summary(
session: AsyncSession,
workspace_id: uuid.UUID,
@@ -465,16 +496,16 @@ async def get_summary(
total_balance[currency] = total_balance.get(currency, 0.0) + amount
projected_balance[currency] = projected_balance.get(currency, 0.0) + amount
- # Convert totals to primary currency
- total_balance_primary = 0.0
- for currency, amount in total_balance.items():
- converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency, cutoff)
- total_balance_primary += float(converted)
-
- projected_balance_primary = 0.0
- for currency, amount in projected_balance.items():
- converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency, cutoff)
- projected_balance_primary += float(converted)
+ # Convert totals to primary currency. A currency bucket without a real
+ # rate stays at its native amount and sets the flag, so the estimate is
+ # visible instead of foreign money passing as converted (issue #1165).
+ total_balance_primary, fx_fallback = await _sum_to_primary(
+ session, total_balance, primary_currency, cutoff
+ )
+ projected_balance_primary, projected_fx_fallback = await _sum_to_primary(
+ session, projected_balance, primary_currency, cutoff
+ )
+ fx_fallback = fx_fallback or projected_fx_fallback
# Convert income/expenses to primary currency using amount_primary when available
# Use real-only totals (without projections) to avoid double-counting;
@@ -637,6 +668,7 @@ async def get_summary(
assets_value=assets_value,
assets_value_primary=round(assets_value_primary, 2),
primary_currency=primary_currency,
+ fx_fallback=fx_fallback,
pending_shares_net=round(pending_shares_net, 2),
)
diff --git a/backend/tests/test_dashboard_service.py b/backend/tests/test_dashboard_service.py
index 8b985906..92756b12 100644
--- a/backend/tests/test_dashboard_service.py
+++ b/backend/tests/test_dashboard_service.py
@@ -5,6 +5,7 @@ from decimal import Decimal
import pytest
from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.app_clock import app_today
from app.models.account import Account
from app.models.category import Category
from app.models.recurring_transaction import RecurringTransaction
@@ -378,6 +379,118 @@ async def test_get_summary_basic(session: AsyncSession, test_user, test_workspac
assert summary.accounts_count >= 1
+# ---------------------------------------------------------------------------
+# get_summary: mixed currencies and the FX fallback flag (issue #1165)
+# ---------------------------------------------------------------------------
+
+
+async def _fund_manual(
+ session: AsyncSession, user_id: uuid.UUID, account_id: uuid.UUID,
+ amount: float, currency: str,
+) -> Transaction:
+ """Opening credit for a manual account, in the account's own currency.
+
+ Manual account totals count transactions, not the balance field.
+ """
+ txn = Transaction(
+ id=uuid.uuid4(), user_id=user_id, account_id=account_id,
+ description="Opening balance", amount=Decimal(str(amount)),
+ date=app_today(), type="credit", source="opening_balance",
+ currency=currency, status="posted",
+ )
+ session.add(txn)
+ await session.commit()
+ return txn
+
+
+async def test_get_summary_mixed_currency_missing_rate_flags_fallback(
+ session: AsyncSession, test_user, test_workspace, monkeypatch
+):
+ """No FX rate: foreign buckets stay at 1:1 and the summary is flagged.
+
+ The total keeps the native amounts (same rule as the available balance
+ headline) but must carry fx_fallback, so the UI shows the estimate
+ instead of presenting foreign money as converted (issue #1165).
+ """
+ from unittest.mock import AsyncMock
+ import app.services.fx_rate_service as fx
+
+ # Hermetic: never touch the network, even if a provider API key is set.
+ monkeypatch.setattr(fx, "sync_rates", AsyncMock(return_value=0))
+
+ home = await _make_account(session, test_user.id, "Home", currency="BRL")
+ abroad = await _make_account(session, test_user.id, "Abroad", currency="EUR")
+ await _fund_manual(session, test_user.id, home.id, 100.0, "BRL")
+ await _fund_manual(session, test_user.id, abroad.id, 50.0, "EUR")
+
+ summary = await get_summary(session, test_workspace.id, test_user.id)
+
+ assert summary.primary_currency == "BRL"
+ assert summary.total_balance == {"BRL": 100.0, "EUR": 50.0}
+ # Summed at 1:1 (not silently converted) and flagged as an estimate.
+ assert summary.total_balance_primary == pytest.approx(150.0)
+ assert summary.fx_fallback is True
+
+
+async def test_get_summary_zero_foreign_balance_without_rate_is_not_flagged(
+ session: AsyncSession, test_user, test_workspace, monkeypatch
+):
+ """A foreign account at zero needs no rate: the total is exact, so the
+ summary must not be flagged as an estimate (issue #1165)."""
+ from unittest.mock import AsyncMock
+ import app.services.fx_rate_service as fx
+
+ monkeypatch.setattr(fx, "sync_rates", AsyncMock(return_value=0))
+
+ home = await _make_account(session, test_user.id, "Home", currency="BRL")
+ abroad = await _make_account(session, test_user.id, "Abroad", currency="EUR")
+ await _fund_manual(session, test_user.id, home.id, 100.0, "BRL")
+ await _fund_manual(session, test_user.id, abroad.id, 50.0, "EUR")
+ session.add(Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, account_id=abroad.id,
+ description="Spent it all", amount=Decimal("50"), date=app_today(),
+ type="debit", source="manual", currency="EUR", status="posted",
+ ))
+ await session.commit()
+
+ summary = await get_summary(session, test_workspace.id, test_user.id)
+
+ assert summary.total_balance_primary == pytest.approx(100.0)
+ assert summary.fx_fallback is False
+
+
+async def test_get_summary_mixed_currency_with_rate_converts(
+ session: AsyncSession, test_user, test_workspace, monkeypatch
+):
+ """A real stored rate converts the bucket and no fallback flag is set."""
+ from unittest.mock import AsyncMock
+ import app.core.app_clock as clock
+ import app.services.fx_rate_service as fx
+ from app.models.fx_rate import FxRate
+
+ # Hermetic: never touch the network, even if a provider API key is set.
+ monkeypatch.setattr(fx, "sync_rates", AsyncMock(return_value=0))
+
+ home = await _make_account(session, test_user.id, "Home", currency="BRL")
+ abroad = await _make_account(session, test_user.id, "Abroad", currency="EUR")
+ await _fund_manual(session, test_user.id, home.id, 100.0, "BRL")
+ await _fund_manual(session, test_user.id, abroad.id, 50.0, "EUR")
+
+ today = clock.app_today()
+ session.add(FxRate(base_currency="USD", quote_currency="EUR", date=today, rate=Decimal("1.10"), source="test"))
+ session.add(FxRate(base_currency="USD", quote_currency="BRL", date=today, rate=Decimal("5.50"), source="test"))
+ await session.commit()
+
+ summary = await get_summary(session, test_workspace.id, test_user.id)
+
+ # EUR -> BRL cross rate = 5.50 / 1.10 = 5.00, so 50 EUR counts as 250 BRL.
+ assert summary.total_balance_primary == pytest.approx(350.0)
+ assert summary.fx_fallback is False
+
+
@pytest.mark.asyncio
async def test_summary_keeps_closed_account_history_and_matches_drilldown(
session: AsyncSession, test_user, test_workspace
diff --git a/frontend/src/pages/dashboard.test.tsx b/frontend/src/pages/dashboard.test.tsx
index 21c560d1..61682bde 100644
--- a/frontend/src/pages/dashboard.test.tsx
+++ b/frontend/src/pages/dashboard.test.tsx
@@ -185,6 +185,29 @@ describe('Dashboard available balance without an FX rate', () => {
})
})
+describe('Dashboard net worth without an FX rate', () => {
+ const renderDashboard = () => renderWithProviders(
+ <TooltipProvider delayDuration={0}>
+ <DashboardPage />
+ </TooltipProvider>,
+ )
+
+ it('flags the net worth total when the summary carried a fallback', async () => {
+ api.dashboard.summary.mockResolvedValue({ ...summary, fx_fallback: true })
+ renderDashboard()
+
+ await screen.findByText(formatCurrency(500, 'USD', 'en-US'))
+ expect(screen.getByText(t('transactions.fxFallbackBanner'))).toBeInTheDocument()
+ })
+
+ it('keeps the net worth quiet when every bucket was converted', async () => {
+ renderDashboard()
+
+ await screen.findByText('Checking')
+ expect(screen.queryByText(t('transactions.fxFallbackBanner'))).not.toBeInTheDocument()
+ })
+})
+
describe('Dashboard refresh button', () => {
it('refetches page data when the refresh button is clicked', async () => {
const { user, queryClient } = renderWithProviders(
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index b4a95367..c4052727 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -860,9 +860,18 @@ export default function DashboardPage() {
{summaryLoading || accountsUnavailable ? (
<Skeleton className="h-6 w-24" />
) : (
- <p className={`text-lg sm:text-xl font-bold tabular-nums ${totalBalance < 0 ? 'text-rose-500' : 'text-foreground'}`}>
- {mask(formatCurrency(totalBalance, primaryCurrency, locale))}
- </p>
+ <>
+ <p className={`text-lg sm:text-xl font-bold tabular-nums ${totalBalance < 0 ? 'text-rose-500' : 'text-foreground'}`}>
+ {mask(formatCurrency(totalBalance, primaryCurrency, locale))}
+ </p>
+ {/* Visible text, not a hover title, so touch users can read it. */}
+ {summary?.fx_fallback === true && (
+ <p className="mt-1 flex items-start gap-1.5 text-xs text-amber-700 dark:text-amber-400">
+ <AlertCircle size={14} className="mt-0.5 shrink-0" />
+ <span>{t('transactions.fxFallbackBanner')}</span>
+ </p>
+ )}
+ </>
)}
</div>
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 93e9aee7..50b2ab18 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -743,6 +743,9 @@ export interface DashboardSummary {
assets_value: Record<string, number>
assets_value_primary: number
primary_currency: string
+ // At least one currency bucket had no real FX rate, so the *_primary
+ // totals sum it at 1:1 and are an estimate, not a conversion (issue #1165).
+ fx_fallback?: boolean
// Net pending balance from group splits in primary currency.
// Negative = net liability, positive = net receivable. Already
// accounts for partial settlements.