Open-source personal finance manager. Self-hosted, privacy-first.
fix(assets): exclude unconvertible assets from primary-currency totals (#1266)
Tássio Noronha3aebfdb2fe45
diff --git a/backend/app/api/assets.py b/backend/app/api/assets.pyindex fca83045..5d6a04a4 100644--- a/backend/app/api/assets.py+++ b/backend/app/api/assets.py@@ -39,7 +39,7 @@ from app.schemas.asset import (MarketSymbolQuote,)from app.services import asset_import_service, asset_service, asset_transaction_service-from app.services.fx_rate_service import convert+from app.services.fx_rate_service import convert_or_nonelogger = logging.getLogger(__name__)@@ -157,20 +157,25 @@ async def refresh_asset_price(# Stamp the primary-currency fields so the refresh response has the same# shape as the list endpoint — the React Query cache update needs them- # to keep the row rendering consistent (BRL rollup, gain/loss).+ # to keep the row rendering consistent (BRL rollup, gain/loss). When no+ # FX rate can be resolved the fields stay NULL: the UI then shows the+ # native value flagged as unconverted instead of a fake 1:1 number+ # (issue #574).primary_currency = ctx.user.primary_currencyif refreshed.currency != primary_currency and refreshed.current_value is not None:- converted, _ = await convert(+ converted, _ = await convert_or_none(session, Decimal(str(refreshed.current_value)), refreshed.currency, primary_currency,decimals=ASSET_PRICE_DECIMALS,)- refreshed.current_value_primary = float(converted)- if refreshed.gain_loss is not None:- gl_converted, _ = await convert(- session, Decimal(str(refreshed.gain_loss)), refreshed.currency, primary_currency,- decimals=ASSET_PRICE_DECIMALS,- )- refreshed.gain_loss_primary = float(gl_converted)+ if converted is not None:+ refreshed.current_value_primary = float(converted)+ if refreshed.gain_loss is not None:+ gl_converted, _ = await convert_or_none(+ session, Decimal(str(refreshed.gain_loss)), refreshed.currency, primary_currency,+ decimals=ASSET_PRICE_DECIMALS,+ )+ if gl_converted is not None:+ refreshed.gain_loss_primary = float(gl_converted)return refreshed@@ -183,18 +188,24 @@ async def list_assets(assets = await asset_service.get_assets(session, ctx.workspace.id, include_archived=include_archived)primary_currency = ctx.user.primary_currencyfor asset in assets:+ # convert_or_none leaves current_value_primary NULL when no FX rate+ # can be resolved, instead of stamping a fake 1:1 value. The UI+ # shows the native amount flagged as unconverted and keeps it out+ # of primary-currency totals (issue #574).if asset.currency != primary_currency and asset.current_value is not None:- converted, _ = await convert(+ converted, _ = await convert_or_none(session, Decimal(str(asset.current_value)), asset.currency, primary_currency,decimals=ASSET_PRICE_DECIMALS,)- asset.current_value_primary = float(converted)- if asset.gain_loss is not None:- gl_converted, _ = await convert(- session, Decimal(str(asset.gain_loss)), asset.currency, primary_currency,- decimals=ASSET_PRICE_DECIMALS,- )- asset.gain_loss_primary = float(gl_converted)+ if converted is not None:+ asset.current_value_primary = float(converted)+ if asset.gain_loss is not None:+ gl_converted, _ = await convert_or_none(+ session, Decimal(str(asset.gain_loss)), asset.currency, primary_currency,+ decimals=ASSET_PRICE_DECIMALS,+ )+ if gl_converted is not None:+ asset.gain_loss_primary = float(gl_converted)return assetsdiff --git a/backend/app/services/asset_group_service.py b/backend/app/services/asset_group_service.pyindex bdcfbb08..f5e7f932 100644--- a/backend/app/services/asset_group_service.py+++ b/backend/app/services/asset_group_service.py@@ -14,7 +14,7 @@ from app.models.asset_value import AssetValuefrom app.models.bank_connection import BankConnectionfrom app.models.user import Userfrom app.schemas.asset_group import AssetGroupCreate, AssetGroupRead, AssetGroupUpdate-from app.services.fx_rate_service import convert+from app.services.fx_rate_service import convert_or_noneasync def ensure_group_in_workspace(@@ -106,11 +106,12 @@ async def _rollup(if asset.currency == primary_currency:current_value_primary += latestelse:- converted, _ = await convert(+ converted, _ = await convert_or_none(session, latest, asset.currency, primary_currency,decimals=ASSET_PRICE_DECIMALS,)- current_value_primary += converted+ if converted is not None:+ current_value_primary += convertedreturn asset_count, current_value, current_value_primarydiff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex 3163cbd4..be1347e7 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -23,7 +23,7 @@ from app.providers.market_price import ()from app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate, AssetRead, AssetValueReadfrom app.services.asset_group_service import ensure_group_in_workspace-from app.services.fx_rate_service import convert, stamp_primary_amount+from app.services.fx_rate_service import convert, has_rate, stamp_primary_amountlogger = logging.getLogger(__name__)@@ -890,6 +890,24 @@ async def get_portfolio_trend(user = await session.get(User, user_id) if user_id is not None else Noneprimary_currency = user.primary_currency if user else get_settings().default_currency+ # Assets whose currency has no resolvable FX rate cannot be expressed in+ # the primary currency. Excluding them keeps the chart's total honest+ # instead of summing raw foreign amounts at a fake 1:1 rate (issue+ # #574); the holdings table still shows them in their original currency+ # flagged as unconverted.+ # One lookup per distinct currency: a missing rate can trigger a+ # provider sync, which must not repeat for every asset in it.+ convertible_currencies = {primary_currency}+ for currency in {asset.currency for asset in active_assets} - {primary_currency}:+ if await has_rate(session, currency, primary_currency):+ convertible_currencies.add(currency)+ convertible_assets = [+ asset for asset in active_assets if asset.currency in convertible_currencies+ ]+ if not convertible_assets:+ return {"assets": [], "trend": [], "total": 0.0}+ active_assets = convertible_assets+values_map = await _load_asset_native_values(session, active_assets)asset_meta: list[dict[str, Any]] = []diff --git a/backend/app/services/fx_rate_service.py b/backend/app/services/fx_rate_service.pyindex f21c1f1d..134c7bfc 100644--- a/backend/app/services/fx_rate_service.py+++ b/backend/app/services/fx_rate_service.py@@ -197,6 +197,56 @@ async def _get_closest_rate(session: AsyncSession, currency: str, target: date)return result+async def has_rate(+ session: AsyncSession,+ from_currency: str,+ to_currency: str,+ target_date: Optional[date] = None,+ *,+ allow_fetch: bool = True,+) -> bool:+ """Whether a real FX rate can be resolved between two currencies.++ Same resolution chain as :func:`get_rate` (exact date, on-demand fetch,+ closest stored date), but reports availability instead of falling back+ to 1:1. Callers use this to tell a genuine conversion apart from an+ unresolvable one (issue #574).+ """+ rate = await _resolve_rate(+ session, from_currency, to_currency, target_date, allow_fetch=allow_fetch+ )+ return rate is not None+++async def convert_or_none(+ session: AsyncSession,+ amount: Decimal,+ from_currency: str,+ to_currency: str,+ target_date: Optional[date] = None,+ *,+ allow_fetch: bool = True,+ decimals: int = 2,+) -> tuple[Optional[Decimal], Optional[Decimal]]:+ """Convert an amount, or return (None, None) when no rate can be resolved.++ Same precision rules as :func:`convert`, but never falls back to 1:1.+ Callers keep the primary-currency value NULL instead of displaying a+ fake amount, so mixed-currency totals never silently sum raw foreign+ values (issue #574).+ """+ if from_currency == to_currency:+ return amount, Decimal("1")++ rate = await _resolve_rate(+ session, from_currency, to_currency, target_date, allow_fetch=allow_fetch+ )+ if rate is None:+ return None, None+ converted = amount * rate+ return converted.quantize(Decimal(1).scaleb(-decimals)), rate++async def convert(session: AsyncSession,amount: Decimal,diff --git a/backend/tests/test_asset_group_service.py b/backend/tests/test_asset_group_service.pyindex c1ed4749..1875484d 100644--- a/backend/tests/test_asset_group_service.py+++ b/backend/tests/test_asset_group_service.py@@ -128,3 +128,87 @@ async def test_rollup_keeps_sub_cent_market_prices_in_primary_currency(assert read.asset_count == 30assert read.current_value == pytest.approx(0.06)assert read.current_value_primary == pytest.approx(0.06)+async def test_rollup_excludes_assets_without_fx_rate(+ session: AsyncSession, test_user, test_workspace+):+ """issue #574: a wallet holding a foreign-currency asset without a+ resolvable FX rate must not add the raw amount to the primary-currency+ total at a fake 1:1 rate. The asset still counts toward the wallet size;+ its primary contribution is 0. A sibling asset whose currency has a rate+ still converts."""+ test_user.preferences = {**(test_user.preferences or {}), "currency_display": "USD"}+ session.add(+ FxRate(+ id=uuid.uuid4(),+ base_currency="USD",+ quote_currency="EUR",+ date=date.today(),+ rate=Decimal("0.9200000000"),+ source="test",+ )+ )+ wallet = AssetGroup(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="Mixed Wallet",+ )+ session.add(wallet)+ await session.commit()++ eur_asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ group_id=wallet.id,+ name="Fund",+ type="investment",+ currency="EUR",+ units=Decimal("1000"),+ valuation_method="manual",+ purchase_price=Decimal("1000"),+ position=0,+ )+ gbp_asset = Asset(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ group_id=wallet.id,+ name="Cash",+ type="cash",+ currency="GBP",+ units=Decimal("500"),+ valuation_method="manual",+ purchase_price=Decimal("500"),+ position=1,+ )+ session.add_all([eur_asset, gbp_asset])+ await session.commit()+ session.add_all([+ AssetValue(+ id=uuid.uuid4(),+ asset_id=eur_asset.id,+ workspace_id=test_workspace.id,+ amount=Decimal("1000"),+ date=date.today(),+ source="manual",+ ),+ AssetValue(+ id=uuid.uuid4(),+ asset_id=gbp_asset.id,+ workspace_id=test_workspace.id,+ amount=Decimal("500"),+ date=date.today(),+ source="manual",+ ),+ ])+ await session.commit()++ read = await get_group(session, wallet.id, test_workspace.id, test_user.id)++ # 1000 EUR -> 1086.956522 USD at 1/0.92, shown at two decimals. The 500+ # GBP is left out of the primary total instead of being added as 500.0.+ assert read is not None+ assert read.asset_count == 2+ assert read.current_value_primary == pytest.approx(1086.96, abs=0.005)diff --git a/backend/tests/test_asset_group_service_coverage.py b/backend/tests/test_asset_group_service_coverage.pyindex e7e459d1..721edfe8 100644--- a/backend/tests/test_asset_group_service_coverage.py+++ b/backend/tests/test_asset_group_service_coverage.py@@ -113,10 +113,10 @@ async def test_get_groups_converts_foreign_currency(session: AsyncSession, test_currency="USD", value_amount=Decimal("10"))await session.commit()- async def _fake_convert(session, amount, frm, to, *args, **kwargs):+ async def _fake_convert_or_none(session, amount, frm, to, *args, **kwargs):return Decimal(amount) * Decimal("5"), Decimal("5")- monkeypatch.setattr(svc, "convert", _fake_convert)+ monkeypatch.setattr(svc, "convert_or_none", _fake_convert_or_none)groups = await svc.get_groups(session, test_workspace.id, test_user.id)read = {x.name: x for x in groups}["FX"]diff --git a/backend/tests/test_asset_service.py b/backend/tests/test_asset_service.pyindex d8d2ec11..666f0b29 100644--- a/backend/tests/test_asset_service.py+++ b/backend/tests/test_asset_service.py@@ -1056,3 +1056,86 @@ async def test_portfolio_trend_total_keeps_sub_cent_foreign_assets(assert result["trend"][-1]["_total"] == pytest.approx(0.02)assert result["total"] == pytest.approx(0.02)+async def test_portfolio_trend_excludes_assets_without_fx_rate(+ session: AsyncSession, test_user: User, test_workspace,+):+ """issue #574: an asset whose currency has no resolvable FX rate cannot+ be expressed in the user's primary currency, so it is excluded from the+ chart series and the total instead of being summed at a fake 1:1 rate.+ The BRL asset (the test user's primary currency) still appears and+ defines the total."""+ today = date.today()+ session.add(FxRate(+ id=uuid.uuid4(), base_currency="USD", quote_currency="BRL",+ date=today, rate=Decimal("5.0"), source="test",+ ))+ brl_asset = Asset(+ id=uuid.uuid4(), user_id=test_user.id, name="House",+ type="real_estate", currency="BRL", valuation_method="manual",+ purchase_date=today - timedelta(days=1), purchase_price=Decimal("1000"),+ position=0,+ )+ session.add(brl_asset)+ await session.flush()+ session.add(AssetValue(+ id=uuid.uuid4(), asset_id=brl_asset.id,+ amount=Decimal("1000"), date=today, source="manual",+ ))+ gbp_asset = Asset(+ id=uuid.uuid4(), user_id=test_user.id, name="Cash",+ type="cash", currency="GBP", valuation_method="manual",+ purchase_date=today, purchase_price=Decimal("500"), position=1,+ )+ session.add(gbp_asset)+ await session.flush()+ session.add(AssetValue(+ id=uuid.uuid4(), asset_id=gbp_asset.id,+ amount=Decimal("500"), date=today, source="manual",+ ))+ await session.commit()++ result = await get_portfolio_trend(session, test_workspace.id, test_user.id)++ # Only the BRL asset is in the chart; the 500 GBP is not summed at 1:1.+ assert [a["id"] for a in result["assets"]] == [str(brl_asset.id)]+ assert str(gbp_asset.id) not in result["trend"][-1]+ assert result["total"] == pytest.approx(1000.0)+++async def test_portfolio_trend_checks_each_missing_currency_once(+ session: AsyncSession, test_user: User, test_workspace, monkeypatch,+):+ """issue #574: a missing rate can trigger a provider sync, so several+ assets in the same unconvertible currency must cost one lookup, not+ one per asset."""+ import app.services.asset_service as svc++ today = date.today()+ for position in range(3):+ asset = Asset(+ id=uuid.uuid4(), user_id=test_user.id, name=f"Cash {position}",+ type="cash", currency="GBP", valuation_method="manual",+ purchase_date=today, purchase_price=Decimal("100"), position=position,+ )+ session.add(asset)+ await session.flush()+ session.add(AssetValue(+ id=uuid.uuid4(), asset_id=asset.id,+ amount=Decimal("100"), date=today, source="manual",+ ))+ await session.commit()++ calls: list[tuple[str, str]] = []++ async def fake_has_rate(_session, from_currency, to_currency, *args, **kwargs):+ calls.append((from_currency, to_currency))+ return False++ monkeypatch.setattr(svc, "has_rate", fake_has_rate)++ result = await get_portfolio_trend(session, test_workspace.id, test_user.id)++ assert result["total"] == 0.0+ assert calls == [("GBP", "BRL")]diff --git a/backend/tests/test_assets_api.py b/backend/tests/test_assets_api.pyindex bedcbcf9..722cbfa1 100644--- a/backend/tests/test_assets_api.py+++ b/backend/tests/test_assets_api.py@@ -427,3 +427,131 @@ class TestAssetValuePrecision:assert totals["USD"] == pytest.approx(0.004174)assert primary_total == pytest.approx(0.00384)+class TestAssetListMissingFxRate:+ """issue #574: an asset held in a currency with no resolvable FX rate+ must not be stamped with a fake 1:1 primary value. The row keeps its+ native amount, current_value_primary stays NULL, and the frontend keeps+ the asset out of primary-currency totals instead of summing raw foreign+ amounts. A sibling asset whose currency has a rate still converts, so+ the list endpoint stays one consistent view."""++ @pytest_asyncio.fixture+ async def usd_user(+ self, session: AsyncSession, test_user: User+ ) -> User:+ """The test user reads the portfolio in USD, not BRL."""+ test_user.preferences = {**(test_user.preferences or {}), "currency_display": "USD"}+ await session.commit()+ return test_user++ @pytest.mark.asyncio+ async def test_list_converts_only_assets_that_have_a_rate(+ self,+ client: AsyncClient,+ auth_headers: dict,+ session: AsyncSession,+ usd_user: User,+ test_workspace: Workspace,+ ):+ session.add(FxRate(+ id=uuid.uuid4(),+ base_currency="USD",+ quote_currency="EUR",+ date=date.today(),+ rate=Decimal("0.9200000000"),+ source="test",+ ))+ eur_asset = Asset(+ id=uuid.uuid4(),+ user_id=usd_user.id,+ workspace_id=test_workspace.id,+ name="Fund",+ type="investment",+ currency="EUR",+ units=Decimal("1000"),+ valuation_method="manual",+ purchase_price=Decimal("1000"),+ position=0,+ )+ gbp_asset = Asset(+ id=uuid.uuid4(),+ user_id=usd_user.id,+ workspace_id=test_workspace.id,+ name="Cash",+ type="cash",+ currency="GBP",+ units=Decimal("500"),+ valuation_method="manual",+ purchase_price=Decimal("500"),+ position=1,+ )+ session.add_all([eur_asset, gbp_asset])+ await session.commit()++ headers = {**auth_headers, "X-Workspace-Id": str(test_workspace.id)}+ response = await client.get("/api/assets", headers=headers)++ assert response.status_code == 200+ entries = {a["id"]: a for a in response.json()}+ # With a rate (USD -> EUR 0.92, so EUR -> USD 1/0.92): converted at+ # price precision, 1000 / 0.92 = 1086.956522.+ eur = entries[str(eur_asset.id)]+ assert eur["current_value_primary"] == pytest.approx(1086.956522, rel=1e-6)+ # Without a rate for GBP: left NULL instead of the raw 500.0 the old+ # code stamped at a fake 1:1 rate.+ gbp = entries[str(gbp_asset.id)]+ assert gbp["current_value"] == pytest.approx(500.0)+ assert gbp["current_value_primary"] is None+ assert gbp["gain_loss_primary"] is None++ @pytest.mark.asyncio+ async def test_refresh_price_leaves_primary_null_without_a_rate(+ self,+ client: AsyncClient,+ auth_headers: dict,+ session: AsyncSession,+ usd_user: User,+ test_workspace: Workspace,+ ):+ """The refresh endpoint stamps the primary fields on its own, so it+ must apply the same rule as the list: no GBP rate, no fake value."""+ asset = Asset(+ id=uuid.uuid4(),+ user_id=usd_user.id,+ workspace_id=test_workspace.id,+ name="Listed",+ type="stock",+ currency="GBP",+ ticker="LSE",+ units=Decimal("10"),+ valuation_method="market_price",+ purchase_price=Decimal("40"),+ position=0,+ )+ session.add(asset)+ session.add(AssetValue(+ id=uuid.uuid4(),+ asset_id=asset.id,+ workspace_id=test_workspace.id,+ amount=Decimal("500"),+ price=Decimal("50"),+ date=date.today(),+ source="sync",+ ))+ await session.commit()++ headers = {**auth_headers, "X-Workspace-Id": str(test_workspace.id)}+ with patch(+ "app.services.asset_service.refresh_market_price_asset",+ new=AsyncMock(return_value=True),+ ):+ response = await client.post(+ f"/api/assets/{asset.id}/refresh-price", headers=headers+ )++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["current_value"] is not None+ assert body["gain_loss"] is not None+ assert body["current_value_primary"] is None+ assert body["gain_loss_primary"] is Nonediff --git a/frontend/src/components/property-equity-summary.test.tsx b/frontend/src/components/property-equity-summary.test.tsxindex 4ff13775..20602c14 100644--- a/frontend/src/components/property-equity-summary.test.tsx+++ b/frontend/src/components/property-equity-summary.test.tsx@@ -6,7 +6,7 @@ import { formatCurrency } from '@/lib/format'import { renderWithProviders, t } from '@/test/utils'import type { Account, Asset } from '@/types'-const home = { id: 'home', type: 'real_estate', current_value: 500000, current_value_primary: null } as Asset+const home = { id: 'home', type: 'real_estate', currency: 'EUR', current_value: 500000, current_value_primary: null } as Assetfunction loan(id: string, name: string, balance: number, securedTo: string | null = 'home') {return {@@ -44,4 +44,15 @@ describe('PropertyEquitySummary', () => {expect(container).toBeEmptyDOMElement()})++ it('still lists the linked loans when the property has no FX rate', () => {+ const abroad = { ...home, currency: 'GBP' } as Asset+ renderWithProviders(+ <PropertyEquitySummary asset={abroad} loans={[loan('a', 'Part A', -200000)]} {...props} />,+ )++ expect(screen.getByText('Part A')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Part A' })).toHaveAttribute('href', '/accounts/a')+ expect(screen.queryByText(/equity/i)).not.toBeInTheDocument()+ })})diff --git a/frontend/src/components/property-equity-summary.tsx b/frontend/src/components/property-equity-summary.tsxindex c15aa0c3..477c4fac 100644--- a/frontend/src/components/property-equity-summary.tsx+++ b/frontend/src/components/property-equity-summary.tsx@@ -7,7 +7,9 @@ import type { Account, Asset } from '@/types'/*** The loans secured against a property, with its value, debt and equity.- * Renders nothing for a property without a linked loan.+ * Renders nothing for a property without a linked loan. When the property+ * has no value in the display currency (no FX rate), the loans are still+ * listed and only the equity line is left out.*/export function PropertyEquitySummary({asset,@@ -24,8 +26,8 @@ export function PropertyEquitySummary({}) {const { t } = useTranslation()const linked = loans.filter(loan => loan.type === 'loan' && loan.secured_asset_id === asset.id)- const equity = getPropertyEquity(asset, linked)- if (linked.length === 0 || !equity) return null+ const equity = getPropertyEquity(asset, linked, currency)+ if (linked.length === 0) return nullreturn (<div className="px-4 py-3 border-t border-border bg-muted/20 space-y-2">@@ -42,13 +44,15 @@ export function PropertyEquitySummary({</div>))}</div>- <p className="pt-2 border-t border-border text-xs font-medium">- {t('assets.propertyEquity', {- value: mask(formatCurrency(equity.value, currency, locale)),- debt: mask(formatCurrency(equity.debt, currency, locale)),- equity: mask(formatCurrency(equity.equity, currency, locale)),- })}- </p>+ {equity && (+ <p className="pt-2 border-t border-border text-xs font-medium">+ {t('assets.propertyEquity', {+ value: mask(formatCurrency(equity.value, currency, locale)),+ debt: mask(formatCurrency(equity.debt, currency, locale)),+ equity: mask(formatCurrency(equity.equity, currency, locale)),+ })}+ </p>+ )}</div>)}diff --git a/frontend/src/lib/asset-portfolio-share.test.ts b/frontend/src/lib/asset-portfolio-share.test.tsindex 2eb1676d..f55a0fa2 100644--- a/frontend/src/lib/asset-portfolio-share.test.ts+++ b/frontend/src/lib/asset-portfolio-share.test.ts@@ -7,26 +7,30 @@ import {} from '@/lib/asset-portfolio-share'describe('asset portfolio share', () => {- const inPrimary = { current_value: 600, current_value_primary: null }- const foreign = { current_value: 100, current_value_primary: 400 }- const unvalued = { current_value: null, current_value_primary: null }+ const inPrimary = { currency: 'USD', current_value: 600, current_value_primary: null }+ const foreign = { currency: 'EUR', current_value: 100, current_value_primary: 400 }+ // Foreign asset the backend could not convert: no FX rate available.+ const unconverted = { currency: 'EUR', current_value: 100, current_value_primary: null }+ const unvalued = { currency: 'USD', current_value: null, current_value_primary: null }- it('falls back to current_value for assets in the primary currency', () => {- expect(getAssetValuePrimary(inPrimary)).toBe(600)- expect(getAssetValuePrimary(foreign)).toBe(400)- expect(getAssetValuePrimary(unvalued)).toBeNull()+ it('falls back to current_value only for assets in the display currency', () => {+ expect(getAssetValuePrimary(inPrimary, 'USD')).toBe(600)+ expect(getAssetValuePrimary(foreign, 'USD')).toBe(400)+ expect(getAssetValuePrimary(unconverted, 'USD')).toBeNull()+ expect(getAssetValuePrimary(unvalued, 'USD')).toBeNull()})- it('computes shares on the same basis as the total so they sum to 100', () => {- const assets = [inPrimary, foreign, unvalued]- const total = getPortfolioTotalPrimary(assets)+ it('excludes foreign assets without an FX rate from total and shares', () => {+ const assets = [inPrimary, foreign, unconverted, unvalued]+ const total = getPortfolioTotalPrimary(assets, 'USD')expect(total).toBe(1000)- expect(getPortfolioShare(inPrimary, total)).toBe(60)- expect(getPortfolioShare(foreign, total)).toBe(40)- expect(getPortfolioShare(unvalued, total)).toBeNull()+ expect(getPortfolioShare(inPrimary, total, 'USD')).toBe(60)+ expect(getPortfolioShare(foreign, total, 'USD')).toBe(40)+ expect(getPortfolioShare(unconverted, total, 'USD')).toBeNull()+ expect(getPortfolioShare(unvalued, total, 'USD')).toBeNull()})it('returns null when the portfolio total is zero', () => {- expect(getPortfolioShare(inPrimary, 0)).toBeNull()+ expect(getPortfolioShare(inPrimary, 0, 'USD')).toBeNull()})})diff --git a/frontend/src/lib/asset-portfolio-share.ts b/frontend/src/lib/asset-portfolio-share.tsindex 9ad583bf..29347920 100644--- a/frontend/src/lib/asset-portfolio-share.ts+++ b/frontend/src/lib/asset-portfolio-share.ts@@ -1,21 +1,30 @@import type { Asset } from '@/types'-type ValuedAsset = Pick<Asset, 'current_value' | 'current_value_primary'>+type ValuedAsset = Pick<Asset, 'currency' | 'current_value' | 'current_value_primary'>-// The API only fills current_value_primary when the asset is held in a-// currency other than the user's primary one, so fall back to current_value-// for assets already in the primary currency.-export function getAssetValuePrimary(asset: ValuedAsset): number | null {- const value = asset.current_value_primary ?? asset.current_value- return value == null ? null : Number(value)+// The API fills current_value_primary only for assets held in a currency+// other than the user's display one, and only when an FX rate could be+// resolved. A foreign asset with a NULL primary value has no available+// rate, so it must not fall back to its raw current_value: doing so would+// silently sum unconverted amounts into the display-currency total+// (issue #574).+export function getAssetValuePrimary(asset: ValuedAsset, displayCurrency: string): number | null {+ if (asset.current_value_primary != null) return Number(asset.current_value_primary)+ if (asset.current_value == null) return null+ if (asset.currency === displayCurrency) return Number(asset.current_value)+ return null}-export function getPortfolioTotalPrimary(assets: ValuedAsset[]): number {- return assets.reduce((acc, a) => acc + (getAssetValuePrimary(a) ?? 0), 0)+export function getPortfolioTotalPrimary(assets: ValuedAsset[], displayCurrency: string): number {+ return assets.reduce((acc, a) => acc + (getAssetValuePrimary(a, displayCurrency) ?? 0), 0)}-export function getPortfolioShare(asset: ValuedAsset, totalPrimary: number): number | null {- const value = getAssetValuePrimary(asset)+export function getPortfolioShare(+ asset: ValuedAsset,+ totalPrimary: number,+ displayCurrency: string,+): number | null {+ const value = getAssetValuePrimary(asset, displayCurrency)if (value == null || !(totalPrimary > 0)) return nullreturn (value / totalPrimary) * 100}diff --git a/frontend/src/lib/property-equity.test.ts b/frontend/src/lib/property-equity.test.tsindex 3e346dc6..52e1b9cd 100644--- a/frontend/src/lib/property-equity.test.ts+++ b/frontend/src/lib/property-equity.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'import { getLoanDebtPrimary, getPropertyEquity } from '@/lib/property-equity'describe('property equity', () => {- const property = { id: 'home', current_value: 593000, current_value_primary: null }+ const property = { id: 'home', currency: 'USD', current_value: 593000, current_value_primary: null }const loans = [{ type: 'loan', secured_asset_id: 'home', current_balance: -194723.17, balance_primary: null },{ type: 'loan', secured_asset_id: 'home', current_balance: -23556.84, balance_primary: null },@@ -11,7 +11,7 @@ describe('property equity', () => {]it('deducts every loan linked to the property once', () => {- const result = getPropertyEquity(property, loans)+ const result = getPropertyEquity(property, loans, 'USD')expect(result?.debt).toBeCloseTo(218280.01, 2)expect(result?.equity).toBeCloseTo(374719.99, 2)})@@ -20,6 +20,7 @@ describe('property equity', () => {const result = getPropertyEquity({ ...property, current_value_primary: 600000 },[{ ...loans[0], balance_primary: -200000 }],+ 'USD',)expect(result).toEqual({ value: 600000, debt: 200000, equity: 400000 })})@@ -29,6 +30,11 @@ describe('property equity', () => {})it('has no equity to show for a property without a value', () => {- expect(getPropertyEquity({ ...property, current_value: null }, loans)).toBeNull()+ expect(getPropertyEquity({ ...property, current_value: null }, loans, 'USD')).toBeNull()+ })++ it('does not fabricate equity for a foreign property without an FX rate', () => {+ const foreignProperty = { ...property, currency: 'EUR' }+ expect(getPropertyEquity(foreignProperty, loans, 'USD')).toBeNull()})})diff --git a/frontend/src/lib/property-equity.ts b/frontend/src/lib/property-equity.tsindex 63a41a05..b8acb7e0 100644--- a/frontend/src/lib/property-equity.ts+++ b/frontend/src/lib/property-equity.ts@@ -4,7 +4,7 @@ import { getAssetValuePrimary } from '@/lib/asset-portfolio-share'/** Asset types a loan can be secured against (a mortgage, a car financing). */export const LOAN_COLLATERAL_TYPES: readonly string[] = ['real_estate', 'vehicle']-type ValuedProperty = Pick<Asset, 'id' | 'current_value' | 'current_value_primary'>+type ValuedProperty = Pick<Asset, 'id' | 'currency' | 'current_value' | 'current_value_primary'>type SecuredLoan = Pick<Account, 'type' | 'secured_asset_id' | 'current_balance' | 'balance_primary'>/** Loan debt in the user's primary currency. An overpaid loan owes nothing. */@@ -16,8 +16,9 @@ export function getLoanDebtPrimary(loan: Pick<Account, 'current_balance' | 'balaexport function getPropertyEquity(property: ValuedProperty,accounts: SecuredLoan[],+ displayCurrency: string,): { value: number; debt: number; equity: number } | null {- const value = getAssetValuePrimary(property)+ const value = getAssetValuePrimary(property, displayCurrency)if (value == null) return nullconst debt = accounts.filter(account => account.type === 'loan' && account.secured_asset_id === property.id)diff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.jsonindex b2fd50f6..565ef9d4 100644--- a/frontend/src/locales/cs.json+++ b/frontend/src/locales/cs.json@@ -2020,6 +2020,9 @@"oversellWarning": "Máte jen {{available}} ks — krátké pozice nejsou podporovány.","noPriceBadge": "bez ceny","noPriceWarning": "Přidáno bez nákupní ceny — doplňte nákupy, aby se sledovala průměrná cena a výnos.",+ "noFxRate": "nemá kurz",+ "noFxRateTitle": "Pro tuto měnu není k dispozici kurz měny. Aktiva se zobrazují v původní měně a jsou vynečány z celků.",+ "fxRateMissing": "Pro {{currencies}} není k dispozici kurz měny. Tyto aktiva se zobrazují v původní měně a jsou vynečány z celků.","colAsset": "Aktivum","colQuantity": "Množ.","colAvgPrice": "Prům. cena",diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 8ca360ba..9cd14a51 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -1887,6 +1887,9 @@"oversellWarning": "Du besitzt nur {{available}} Einheiten — Leerverkäufe werden nicht unterstützt.","noPriceBadge": "ohne Kosten","noPriceWarning": "Ohne Kaufpreis hinzugefügt — trage deine Käufe ein, um den durchschnittlichen Einstandspreis und die Rendite zu verfolgen.",+ "noFxRate": "kein Wechselkurs",+ "noFxRateTitle": "Für diese Währung steht kein Wechselkurs zur Verfügung. Das Asset wird in seiner Originalwährung angezeigt und bleibt aus den Summen ausgeschlossen.",+ "fxRateMissing": "Für {{currencies}} steht kein Wechselkurs zur Verfügung. Diese Assets werden in ihrer Originalwährung angezeigt und bleiben aus den Summen ausgeschlossen.","colAsset": "Vermögenswert","colQuantity": "Menge","colAvgPrice": "Einstandspreis",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex 8dbcf3ef..72a74e26 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -1886,6 +1886,9 @@"oversellWarning": "Κατέχετε μόνο {{available}} μονάδες — οι ανοικτές πωλήσεις (short) δεν υποστηρίζονται.","noPriceBadge": "χωρίς κόστος","noPriceWarning": "Προστέθηκε χωρίς τιμή αγοράς — προσθέστε τις αγορές σας για να παρακολουθείτε τη μέση τιμή και την απόδοση.",+ "noFxRate": "χωρίς ισοτιμία",+ "noFxRateTitle": "Δεν υπάρχει διαθέσιμη ισοτιμία για αυτό το νόμισμα. Το ενεργητικό εμφανίζεται στο αρχικό του νόμισμα και εξαιρείται από τα σύνολα.",+ "fxRateMissing": "Δεν υπάρχει διαθέσιμη ισοτιμία για τα {{currencies}}. Αυτά τα ενεργητικά εμφανίζονται στο αρχικό τους νόμισμα και εξαιρούνται από τα σύνολα.","colAsset": "Περιουσιακό στοιχείο","colQuantity": "Ποσότητα","colAvgPrice": "Μέση τιμή",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 72b91edd..8e816418 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1886,6 +1886,9 @@"oversellWarning": "You only hold {{available}} units — short positions aren’t supported.","noPriceBadge": "no cost","noPriceWarning": "Added without a purchase price — add your buys to track average price and return.",+ "noFxRate": "no FX rate",+ "noFxRateTitle": "No exchange rate is available for this currency. The asset is shown in its original currency and excluded from the totals.",+ "fxRateMissing": "No exchange rate is available for {{currencies}}. Those assets are shown in their original currency and left out of the totals.","colAsset": "Asset","colQuantity": "Qty","colAvgPrice": "Avg price",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex e35e8cd5..69db973b 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1890,6 +1890,9 @@"oversellWarning": "Solo tienes {{available}} unidades — no se admiten posiciones cortas.","noPriceBadge": "sin precio","noPriceWarning": "Añadido sin precio de compra — añade tus compras para seguir el precio medio y la rentabilidad.",+ "noFxRate": "sin tipo de cambio",+ "noFxRateTitle": "No hay tipo de cambio disponible para esta moneda. El activo se muestra en su moneda original y queda fuera de los totales.",+ "fxRateMissing": "No hay tipo de cambio disponible para {{currencies}}. Esos activos se muestran en su moneda original y quedan fuera de los totales.","colAsset": "Activo","colQuantity": "Cant.","colAvgPrice": "Precio medio",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex d1fbd472..edc34a6d 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -1890,6 +1890,9 @@"oversellWarning": "Vous ne détenez que {{available}} unités — les positions à découvert ne sont pas prises en charge.","noPriceBadge": "sans coût","noPriceWarning": "Ajouté sans prix d'achat — ajoutez vos achats pour suivre le prix moyen et le rendement.",+ "noFxRate": "pas de taux de change",+ "noFxRateTitle": "Aucun taux de change n'est disponible pour cette devise. L'actif est affiché dans sa devise d'origine et exclu des totaux.",+ "fxRateMissing": "Aucun taux de change n'est disponible pour {{currencies}}. Ces actifs sont affichés dans leur devise d'origine et exclus des totaux.","colAsset": "Actif","colQuantity": "Qté","colAvgPrice": "Prix moyen",diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex af4fd0c4..04276065 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -1886,6 +1886,9 @@"oversellWarning": "आपके पास केवल {{available}} इकाइयाँ हैं — शॉर्ट पोज़िशन समर्थित नहीं हैं।","noPriceBadge": "कोई लागत नहीं","noPriceWarning": "खरीद मूल्य के बिना जोड़ी गई — औसत मूल्य और रिटर्न ट्रैक करने के लिए अपनी खरीद जोड़ें।",+ "noFxRate": "कोई विनिमय भाव नहीं",+ "noFxRateTitle": "इस मुद्रा के लिए कोई विनिमय भाव उपलब्ध नहीं है। परिसंपत्ति अपनी मूल मुद्रा में दिखाई जाती है और कुलों से बाहर रहती है।",+ "fxRateMissing": "{{currencies}} के लिए कोई विनिमय भाव उपलब्ध नहीं है। ये परिसंपत्तियाँ अपनी मूल मुद्रा में दिखाई जाती हैं और कुलों से बाहर रहती हैं।","colAsset": "संपत्ति","colQuantity": "मात्रा","colAvgPrice": "औसत मूल्य",diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.jsonindex 19b8f10c..3f878b98 100644--- a/frontend/src/locales/hu.json+++ b/frontend/src/locales/hu.json@@ -1888,6 +1888,9 @@"oversellWarning": "Csak {{available}} egységed van — short pozíció nem támogatott.","noPriceBadge": "nincs bekerülési ár","noPriceWarning": "Vételár nélkül hozzáadva — add meg a vételeidet az átlagár és a hozam követéséhez.",+ "noFxRate": "nincs árfolyam",+ "noFxRateTitle": "Ehhez a pénznemhez nincs elérhető árfolyam. Az eszköz az eredeti pénznemében jelenik meg, és kimarad az összesítőkből.",+ "fxRateMissing": "{{currencies}} esetén nincs elérhető árfolyam. Ezek az eszközök az eredeti pénznemükben jelennek meg, és kimaradnak az összesítőkből.","colAsset": "Eszköz","colQuantity": "Menny.","colAvgPrice": "Átlagár",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 66a92a74..792ed303 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1890,6 +1890,9 @@"oversellWarning": "Possiedi solo {{available}} unità — le posizioni corte non sono supportate.","noPriceBadge": "senza prezzo","noPriceWarning": "Aggiunto senza prezzo di acquisto — aggiungi i tuoi acquisti per tracciare prezzo medio e rendimento.",+ "noFxRate": "nessun tasso di cambio",+ "noFxRateTitle": "Non è disponibile un tasso di cambio per questa valuta. L'attivo viene mostrato nella valuta originale e escluso dai totali.",+ "fxRateMissing": "Non è disponibile un tasso di cambio per {{currencies}}. Questi attivi sono mostrati nella valuta originale e esclusi dai totali.","colAsset": "Attività","colQuantity": "Qtà","colAvgPrice": "Prezzo medio",diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex 6ffae2e4..b6197db0 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -1886,6 +1886,9 @@"oversellWarning": "保有は{{available}}単位のみです — 空売りは対応していません。","noPriceBadge": "取得価額なし","noPriceWarning": "取得価格なしで追加されました — 平均取得単価とリターンを追跡するには買付を追加してください。",+ "noFxRate": "為替レートなし",+ "noFxRateTitle": "この通貨の為替レートが利用できません。資産は元通貨で表示され、合計から除外されます。",+ "fxRateMissing": "{{currencies}} の為替レートが利用できません。これらの資産は元通貨で表示され、合計から除外されます。","colAsset": "資産","colQuantity": "数量","colAvgPrice": "平均単価",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 3a759367..5b624cb0 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -1888,6 +1888,9 @@"oversellWarning": "U bezit alleen {{available}} eenheden; shortposities worden niet ondersteund.","noPriceBadge": "geen kosten","noPriceWarning": "Toegevoegd zonder aankoopprijs: voeg uw aankopen toe om de gemiddelde prijs en het rendement bij te houden.",+ "noFxRate": "geen wisselkoers",+ "noFxRateTitle": "Voor deze munt is geen wisselkoers beschikbaar. Het vermogen wordt in de oorspronkelijke munt getoond en blijft buiten de totalen.",+ "fxRateMissing": "Voor {{currencies}} is geen wisselkoers beschikbaar. Deze activa worden in de oorspronkelijke munt getoond en blijven buiten de totalen.","colAsset": "Aanwinst","colQuantity": "Aantal","colAvgPrice": "Gem. prijs",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 860681a3..38e0cbb5 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1975,6 +1975,9 @@"oversellWarning": "Masz tylko {{available}} jednostek — pozycje krótkie nie są obsługiwane.","noPriceBadge": "bez ceny","noPriceWarning": "Dodano bez ceny zakupu — dodaj swoje zakupy, aby śledzić średnią cenę i zwrot.",+ "noFxRate": "brak kursu",+ "noFxRateTitle": "Dla tej waluty nie ma dostępnego kursu wymiany. Aktywo jest wyświetlane w oryginalnej walucie i pomijane w sumach.",+ "fxRateMissing": "Dla {{currencies}} nie ma dostępnego kursu wymiany. Te aktywa są wyświetlane w oryginalnej walucie i pomijane w sumach.","colAsset": "Aktywo","colQuantity": "Ilość","colAvgPrice": "Śr. cena",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex e5b89220..69019dc0 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1890,6 +1890,9 @@"oversellWarning": "Você só possui {{available}} unidades — posições vendidas (short) não são suportadas.","noPriceBadge": "sem preço","noPriceWarning": "Adicionado sem preço de compra — adicione suas compras para acompanhar o preço médio e a rentabilidade.",+ "noFxRate": "sem cotação",+ "noFxRateTitle": "Não há cotação disponível para esta moeda. O ativo aparece na moeda original e fica de fora dos totais.",+ "fxRateMissing": "Não há cotação disponível para {{currencies}}. Esses ativos aparecem na moeda original e ficam de fora dos totais.","colAsset": "Ativo","colQuantity": "Qtd.","colAvgPrice": "Preço médio",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 9d96ba40..d02ea1dd 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -1890,6 +1890,9 @@"oversellWarning": "Só tens {{available}} unidades — posições vendidas (short) não são suportadas.","noPriceBadge": "sem preço","noPriceWarning": "Adicionado sem preço de compra — adiciona as tuas compras para acompanhar o preço médio e a rentabilidade.",+ "noFxRate": "sem cotação",+ "noFxRateTitle": "Não existe cotação disponível para esta moeda. O ativo é mostrado na moeda original e fica fora dos totais.",+ "fxRateMissing": "Não existe cotação disponível para {{currencies}}. Estes ativos são mostrados na moeda original e ficam fora dos totais.","colAsset": "Ativo","colQuantity": "Qtd.","colAvgPrice": "Preço médio",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 74f7b210..165c5ed1 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -1903,6 +1903,9 @@"oversellWarning": "У вас всего {{available}} единиц — короткие позиции не поддерживаются.","noPriceBadge": "без цены","noPriceWarning": "Добавлено без цены покупки — добавляйте покупки, чтобы отслеживать среднюю цену и доходность.",+ "noFxRate": "нет курса",+ "noFxRateTitle": "Для этой валюты нет доступного обменного курса. Актив отображается в исходной валюте и исключается из итогов.",+ "fxRateMissing": "Для {{currencies}} нет доступного обменного курса. Эти активы отображаются в исходной валюте и исключаются из итогов.","colAsset": "Актив","colQuantity": "Кол-во","colAvgPrice": "Средняя цена",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex c76b31dd..95daf776 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -2002,6 +2002,9 @@"oversellWarning": "Máš len {{available}} ks — krátke pozície nie sú podporované.","noPriceBadge": "bez ceny","noPriceWarning": "Pridané bez nákupnej ceny — doplň nákupy, aby sa sledovala priemerná cena a výnos.",+ "noFxRate": "chýba kurz",+ "noFxRateTitle": "Pre túto menu nie je k dispozícii kurz. Aktívum sa zobrazuje v pôvodnej mene a je vynechané z celkov.",+ "fxRateMissing": "Pre {{currencies}} nie je k dispozícii kurz. Tieto aktíva sa zobrazujú v pôvodnej mene a sú vynechané z celkov.","colAsset": "Aktívum","colQuantity": "Množ.","colAvgPrice": "Priem. cena",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 018a30e1..487c4847 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -1903,6 +1903,9 @@"oversellWarning": "У вас усього {{available}} одиниць — короткі позиції не підтримуються.","noPriceBadge": "без ціни","noPriceWarning": "Додано без ціни купівлі — додавайте купівлі, щоб відстежувати середню ціну та дохідність.",+ "noFxRate": "немає курсу",+ "noFxRateTitle": "Для цієї валюти немає доступного обмінного курсу. Актив відображається в початковій валюті та виключається з ітогів.",+ "fxRateMissing": "Для {{currencies}} немає доступного обмінного курсу. Ці активи відображаються в початковій валюті та виключаються з ітогів.","colAsset": "Актив","colQuantity": "К-сть","colAvgPrice": "Середня ціна",diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex 1ead45b0..12ab2df5 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -60,7 +60,7 @@ import { useAuth } from '@/contexts/auth-context'import { useWorkspace } from '@/contexts/workspace-context'import { useCollectionFilter } from '@/contexts/collection-filter-context'import { getAssetProfit } from '@/lib/asset-profit'-import { getPortfolioShare, getPortfolioTotalPrimary } from '@/lib/asset-portfolio-share'+import { getAssetValuePrimary, getPortfolioShare, getPortfolioTotalPrimary } from '@/lib/asset-portfolio-share'import { formatTransactionTotal, getTransactionTotalCurrency } from '@/lib/asset-transaction-total'import { formatCurrency } from '@/lib/format'@@ -501,8 +501,22 @@ export default function AssetsPage() {const activeAssets = useMemo(() => assetsList?.filter(a => !a.sell_date && !a.is_archived) ?? [], [assetsList])const soldAssets = assetsList?.filter(a => a.sell_date) ?? []// Denominator for the "% of portfolio" column: current holdings only, in the- // user's primary currency, so the active rows add up to 100%.- const portfolioTotalPrimary = getPortfolioTotalPrimary(activeAssets)+ // user's primary currency, so the active rows add up to 100%. Assets with+ // no resolvable FX rate are left out of the denominator (their rows show+ // a dash) instead of being summed at a fake 1:1 rate (issue #574).+ const portfolioTotalPrimary = getPortfolioTotalPrimary(activeAssets, userCurrency)++ // Currencies of active assets that cannot be converted to the user's+ // display currency: shown in a page-level banner and kept out of totals.+ const unconvertedCurrencies = useMemo(() => {+ const currencies = new Set<string>()+ for (const a of activeAssets) {+ if (a.current_value != null && a.currency !== userCurrency && a.current_value_primary == null) {+ currencies.add(a.currency)+ }+ }+ return [...currencies].sort()+ }, [activeAssets, userCurrency])// Debounced ticker search. Runs only when the market-price method is// selected and the query is non-trivial — keeps the autocomplete snappy@@ -745,7 +759,14 @@ export default function AssetsPage() {const isProviderOwned = isSynced && !isMarketPricedconst hasCost = asset.average_price != null && asset.total_invested != nullconst profit = getAssetProfit(asset)- const pctOfPortfolio = asset.sell_date ? null : getPortfolioShare(asset, portfolioTotalPrimary)+ // Foreign-currency asset the backend could not convert (no FX rate):+ // keep it out of primary-currency totals and flag it instead.+ const unconverted =+ !asset.sell_date &&+ asset.current_value != null &&+ asset.currency !== userCurrency &&+ asset.current_value_primary == null+ const pctOfPortfolio = asset.sell_date ? null : getPortfolioShare(asset, portfolioTotalPrimary, userCurrency)const needsBuys = isMarketPriced && !hasCost && !asset.sell_datereturn (@@ -771,6 +792,16 @@ export default function AssetsPage() {{t('assets.noPriceBadge')}</Badge>)}+ {unconverted && (+ <Badge+ variant="outline"+ className="text-[9px] px-1 py-0 text-amber-600 border-amber-300 bg-amber-50 dark:bg-amber-950/30 gap-0.5 shrink-0"+ title={t('assets.noFxRateTitle')}+ >+ <AlertTriangle size={9} />+ {t('assets.noFxRate')}+ </Badge>+ )}{asset.sell_date && (<Badge variant="outline" className="text-[9px] px-1 py-0 text-rose-600 border-rose-200">{t('assets.sold')}</Badge>)}@@ -825,6 +856,9 @@ export default function AssetsPage() {{asset.current_value_primary != null && asset.currency !== userCurrency && (<span className="block text-[10px] text-muted-foreground">{mask(formatCurrency(asset.current_value_primary, userCurrency, locale))}</span>)}+ {unconverted && (+ <span className="block text-[10px] text-amber-600 dark:text-amber-400">{t('assets.noFxRate')}</span>+ )}</>) : <span className="text-muted-foreground">—</span>}</div>@@ -972,9 +1006,23 @@ export default function AssetsPage() {function renderWalletSection(wallet: AssetGroup, walletAssets: Asset[]) {const isCollapsed = collapsedWallets.has(wallet.id)const isSynced = wallet.source !== 'manual'- // Sum in wallet's reported current_value (already computed by backend).- // Fall back to per-asset sum if the rollup is stale after a move.- const total = walletAssets.reduce((s, a) => s + (a.current_value_primary ?? a.current_value ?? 0), 0) || wallet.current_value_primary || wallet.current_value+ // Sum in the user's primary currency. Fall back to the wallet's own+ // rollup if the per-asset sum is empty (rollup already excludes+ // unconvertible assets, so it agrees with this one).+ const total =+ walletAssets.reduce((s, a) => s + (getAssetValuePrimary(a, userCurrency) ?? 0), 0) ||+ wallet.current_value_primary ||+ 0+ // Native values of assets the backend could not convert (no FX rate),+ // grouped by currency and listed below the total. They are deliberately+ // NOT added to the number above: that would mix unconverted currencies+ // (issue #574).+ const unconvertedSums = new Map<string, number>()+ for (const a of walletAssets) {+ if (getAssetValuePrimary(a, userCurrency) == null && a.current_value != null && a.currency !== userCurrency) {+ unconvertedSums.set(a.currency, (unconvertedSums.get(a.currency) ?? 0) + Number(a.current_value))+ }+ }// Only show the institution as a subtitle when it's actually// additional information — if the user hasn't renamed the wallet,@@ -1016,9 +1064,16 @@ export default function AssetsPage() {)}</div></button>- <span className="text-sm font-bold tabular-nums text-foreground shrink-0">- {mask(formatCurrency(total, userCurrency, locale))}- </span>+ <div className="flex flex-col items-end shrink-0">+ <span className="text-sm font-bold tabular-nums text-foreground">+ {mask(formatCurrency(total, userCurrency, locale))}+ </span>+ {[...unconvertedSums.entries()].map(([currency, amount]) => (+ <span key={currency} className="text-[10px] text-amber-600 dark:text-amber-400 tabular-nums">+ + {mask(formatCurrency(amount, currency, locale))} {currency} · {t('assets.noFxRate')}+ </span>+ ))}+ </div>{canWrite && (<><button@@ -1107,6 +1162,15 @@ export default function AssetsPage() {/>) : (<>+ {/* Assets that have no resolvable FX rate are left out of the totals+ below; explain that so the numbers do not look wrong (issue #574). */}+ {unconvertedCurrencies.length > 0 && (+ <div className="flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2.5 text-xs text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-200">+ <AlertTriangle size={14} className="mt-0.5 shrink-0" />+ <span>{t('assets.fxRateMissing', { currencies: unconvertedCurrencies.join(', ') })}</span>+ </div>+ )}+{/* Portfolio Chart */}{portfolioData && portfolioData.trend.length > 0 && (<PortfolioChart