Open-source personal finance manager. Self-hosted, privacy-first.
feat/fx multi currency support (#29)
Tássio Noronha3c5c791c2a6b
diff --git a/README.md b/README.mdindex 328b17f7..7f89ffd0 100644--- a/README.md+++ b/README.md@@ -48,6 +48,7 @@ Open [http://localhost:3000](http://localhost:3000) and create an account. That'- Reports: Net Worth and Income vs Expenses with category sparklines- Dashboard with spending analytics and projections- Bank sync via providers (Pluggy supported, extensible)+- Multi-currency support with automatic FX conversion- Dark/light theme, multi-language support, privacy mode## Bank Sync (Optional)@@ -61,6 +62,16 @@ PLUGGY_CLIENT_SECRET=your-client-secretThen restart: `docker compose up`+## Exchange Rates (Optional)++For automatic currency conversion, add a free [Open Exchange Rates](https://openexchangerates.org/) key to `.env`:++```+OPENEXCHANGERATES_APP_ID=your-app-id+```++Rates are fetched on-demand when foreign-currency transactions are created. Without a key, cross-currency amounts default to a 1:1 fallback rate with a visual warning.+## Tech Stack| Layer | Stack |diff --git a/backend/alembic/versions/016_fx_rates.py b/backend/alembic/versions/016_fx_rates.pynew file mode 100644index 00000000..84cadb23--- /dev/null+++ b/backend/alembic/versions/016_fx_rates.py@@ -0,0 +1,42 @@+"""add fx_rates table++Revision ID: 016+Revises: 015+Create Date: 2026-03-23+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "016"+down_revision: Union[str, None] = "015"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "fx_rates",+ sa.Column("id", sa.UUID(), nullable=False, primary_key=True),+ sa.Column("base_currency", sa.String(3), nullable=False),+ sa.Column("quote_currency", sa.String(3), nullable=False),+ sa.Column("date", sa.Date(), nullable=False),+ sa.Column("rate", sa.Numeric(precision=20, scale=10), nullable=False),+ sa.Column("source", sa.String(50), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now()),+ )+ op.create_unique_constraint(+ "uq_fx_rate_base_quote_date", "fx_rates",+ ["base_currency", "quote_currency", "date"],+ )+ op.create_index(+ "ix_fx_rates_quote_date", "fx_rates",+ ["quote_currency", "date"],+ )+++def downgrade() -> None:+ op.drop_index("ix_fx_rates_quote_date", table_name="fx_rates")+ op.drop_constraint("uq_fx_rate_base_quote_date", "fx_rates", type_="unique")+ op.drop_table("fx_rates")diff --git a/backend/alembic/versions/017_multi_currency_primary_amounts.py b/backend/alembic/versions/017_multi_currency_primary_amounts.pynew file mode 100644index 00000000..67cb8357--- /dev/null+++ b/backend/alembic/versions/017_multi_currency_primary_amounts.py@@ -0,0 +1,46 @@+"""add multi-currency primary amount columns++Revision ID: 017+Revises: 016+Create Date: 2026-03-23+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "017"+down_revision: Union[str, None] = "016"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # Transactions+ op.add_column("transactions", sa.Column("amount_primary", sa.Numeric(precision=15, scale=2), nullable=True))+ op.add_column("transactions", sa.Column("fx_rate_used", sa.Numeric(precision=20, scale=10), nullable=True))++ # Recurring transactions+ op.add_column("recurring_transactions", sa.Column("amount_primary", sa.Numeric(precision=15, scale=2), nullable=True))+ op.add_column("recurring_transactions", sa.Column("fx_rate_used", sa.Numeric(precision=20, scale=10), nullable=True))++ # Accounts+ op.add_column("accounts", sa.Column("balance_primary", sa.Numeric(precision=15, scale=2), nullable=True))++ # Assets+ op.add_column("assets", sa.Column("purchase_price_primary", sa.Numeric(precision=15, scale=2), nullable=True))++ # Budgets+ op.add_column("budgets", sa.Column("currency", sa.String(3), server_default="BRL", nullable=True))+ op.add_column("budgets", sa.Column("amount_primary", sa.Numeric(precision=15, scale=2), nullable=True))+++def downgrade() -> None:+ op.drop_column("budgets", "amount_primary")+ op.drop_column("budgets", "currency")+ op.drop_column("assets", "purchase_price_primary")+ op.drop_column("accounts", "balance_primary")+ op.drop_column("recurring_transactions", "fx_rate_used")+ op.drop_column("recurring_transactions", "amount_primary")+ op.drop_column("transactions", "fx_rate_used")+ op.drop_column("transactions", "amount_primary")diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.pyindex a79b0586..aa60166f 100644--- a/backend/app/api/accounts.py+++ b/backend/app/api/accounts.py@@ -1,5 +1,6 @@import uuidfrom datetime import date+from decimal import Decimalfrom typing import Optionalfrom fastapi import APIRouter, Depends, HTTPException, Query, status@@ -10,6 +11,7 @@ from app.core.database import get_async_sessionfrom app.models.user import Userfrom app.schemas.account import AccountCreate, AccountRead, AccountUpdate, AccountSummaryfrom app.services import account_service+from app.services.fx_rate_service import convertrouter = APIRouter(prefix="/api/accounts", tags=["accounts"])@@ -20,7 +22,15 @@ async def list_accounts(session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):- return await account_service.get_accounts(session, user.id, include_closed=include_closed)+ accounts = await account_service.get_accounts(session, user.id, include_closed=include_closed)+ primary_currency = user.primary_currency+ for 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)+ return accounts@router.get("/{account_id}/summary", response_model=AccountSummary)diff --git a/backend/app/api/assets.py b/backend/app/api/assets.pyindex c3bcd7ed..f8e28b91 100644--- a/backend/app/api/assets.py+++ b/backend/app/api/assets.py@@ -1,4 +1,5 @@import uuid+from decimal import Decimalfrom fastapi import APIRouter, Depends, HTTPException, Query, statusfrom sqlalchemy.ext.asyncio import AsyncSession@@ -8,6 +9,7 @@ from app.core.database import get_async_sessionfrom app.models.user import Userfrom app.schemas.asset import AssetCreate, AssetRead, AssetUpdate, AssetValueCreate, AssetValueReadfrom app.services import asset_service+from app.services.fx_rate_service import convertrouter = APIRouter(prefix="/api/assets", tags=["assets"])@@ -18,7 +20,20 @@ async def list_assets(session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):- return await asset_service.get_assets(session, user.id, include_archived=include_archived)+ assets = await asset_service.get_assets(session, user.id, include_archived=include_archived)+ primary_currency = user.primary_currency+ for asset in assets:+ if asset.currency != primary_currency and asset.current_value is not None:+ converted, _ = await convert(+ session, Decimal(str(asset.current_value)), asset.currency, primary_currency,+ )+ 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,+ )+ asset.gain_loss_primary = float(gl_converted)+ return assets@router.get("/portfolio-trend")diff --git a/backend/app/api/currencies.py b/backend/app/api/currencies.pynew file mode 100644index 00000000..c9e72a79--- /dev/null+++ b/backend/app/api/currencies.py@@ -0,0 +1,44 @@+from fastapi import APIRouter++from app.core.config import get_settings++router = APIRouter(prefix="/api/currencies", tags=["currencies"])++CURRENCY_META = {+ "BRL": {"symbol": "R$", "name": "Real Brasileiro", "flag": "\U0001F1E7\U0001F1F7"},+ "USD": {"symbol": "$", "name": "US Dollar", "flag": "\U0001F1FA\U0001F1F8"},+ "EUR": {"symbol": "\u20ac", "name": "Euro", "flag": "\U0001F1EA\U0001F1FA"},+ "GBP": {"symbol": "\u00a3", "name": "British Pound", "flag": "\U0001F1EC\U0001F1E7"},+ "JPY": {"symbol": "\u00a5", "name": "Japanese Yen", "flag": "\U0001F1EF\U0001F1F5"},+ "CAD": {"symbol": "C$", "name": "Canadian Dollar", "flag": "\U0001F1E8\U0001F1E6"},+ "AUD": {"symbol": "A$", "name": "Australian Dollar", "flag": "\U0001F1E6\U0001F1FA"},+ "CHF": {"symbol": "Fr", "name": "Swiss Franc", "flag": "\U0001F1E8\U0001F1ED"},+ "CNY": {"symbol": "\u00a5", "name": "Chinese Yuan", "flag": "\U0001F1E8\U0001F1F3"},+ "ARS": {"symbol": "$", "name": "Peso Argentino", "flag": "\U0001F1E6\U0001F1F7"},+ "MXN": {"symbol": "$", "name": "Peso Mexicano", "flag": "\U0001F1F2\U0001F1FD"},+ "CLP": {"symbol": "$", "name": "Peso Chileno", "flag": "\U0001F1E8\U0001F1F1"},+ "COP": {"symbol": "$", "name": "Peso Colombiano", "flag": "\U0001F1E8\U0001F1F4"},+ "PEN": {"symbol": "S/", "name": "Sol Peruano", "flag": "\U0001F1F5\U0001F1EA"},+ "UYU": {"symbol": "$U", "name": "Peso Uruguayo", "flag": "\U0001F1FA\U0001F1FE"},+ "INR": {"symbol": "\u20B9", "name": "Indian Rupee", "flag": "\U0001F1EE\U0001F1F3"},+ "SEK": {"symbol": "kr", "name": "Swedish Krona", "flag": "\U0001F1F8\U0001F1EA"},+}+++async def list_currencies():+ """Return the list of supported currencies configured for this instance."""+ settings = get_settings()+ codes = [c.strip() for c in settings.supported_currencies.split(",") if c.strip()]++ currencies = []+ for code in codes:+ meta = CURRENCY_META.get(code, {})+ currencies.append({+ "code": code,+ "symbol": meta.get("symbol", code),+ "name": meta.get("name", code),+ "flag": meta.get("flag", ""),+ })++ return currenciesdiff --git a/backend/app/api/fx_rates.py b/backend/app/api/fx_rates.pynew file mode 100644index 00000000..8173c5dc--- /dev/null+++ b/backend/app/api/fx_rates.py@@ -0,0 +1,45 @@+from datetime import date++from fastapi import APIRouter, Depends+from sqlalchemy import select, func+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.auth import current_active_user+from app.core.config import get_settings+from app.core.database import get_async_session+from app.models.fx_rate import FxRate+from app.models.user import User+from app.services.fx_rate_service import sync_rates++router = APIRouter(prefix="/api/fx-rates", tags=["fx-rates"])++[email protected]("/refresh")+async def refresh_rates(+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Trigger immediate FX rate sync."""+ count = await sync_rates(session, date.today())+ return {"synced": True, "rates_count": count, "date": date.today().isoformat()}++[email protected]("/status")+async def rates_status(+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Return last sync date and total stored rates."""+ last_date = await session.scalar(+ select(func.max(FxRate.date))+ )+ total = await session.scalar(+ select(func.count()).select_from(FxRate)+ ) or 0++ settings = get_settings()+ return {+ "last_sync_date": last_date.isoformat() if last_date else None,+ "total_rates": total,+ "fx_sync_mode": settings.fx_sync_mode,+ }diff --git a/backend/app/api/reports.py b/backend/app/api/reports.pyindex a17a0659..312f0ba1 100644--- a/backend/app/api/reports.py+++ b/backend/app/api/reports.py@@ -17,13 +17,8 @@ async def get_net_worth(session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):- currency = getattr(user, "preferences", None)- currency_display = "BRL"- if currency and isinstance(currency, dict):- currency_display = currency.get("currency_display", "BRL")-return await report_service.get_net_worth_report(- session, user.id, months, interval, currency_display+ session, user.id, months, interval, user.primary_currency)@@ -34,11 +29,6 @@ async def get_income_expenses(session: AsyncSession = Depends(get_async_session),user: User = Depends(current_active_user),):- currency = getattr(user, "preferences", None)- currency_display = "BRL"- if currency and isinstance(currency, dict):- currency_display = currency.get("currency_display", "BRL")-return await report_service.get_income_expenses_report(- session, user.id, months, interval, currency_display+ session, user.id, months, interval, user.primary_currency)diff --git a/backend/app/api/setup.py b/backend/app/api/setup.pyindex be652527..5bbb69b2 100644--- a/backend/app/api/setup.py+++ b/backend/app/api/setup.py@@ -20,7 +20,7 @@ class SetupStatus(BaseModel):class CreateAdminRequest(BaseModel):email: EmailStrpassword: str- currency: str = "BRL"+ currency: str = "USD"name: str = ""language: str = "pt-BR"diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex d3eea40d..5b89ad10 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -18,6 +18,13 @@ from app.services import transaction_servicerouter = APIRouter(prefix="/api/transactions", tags=["transactions"])+def _tag_fx_fallback(tx: TransactionRead, primary_currency: str) -> TransactionRead:+ """Set fx_fallback=True when a cross-currency tx used 1:1 fallback rate."""+ if tx.currency != primary_currency and tx.fx_rate_used is not None and tx.fx_rate_used == 1.0:+ tx.fx_fallback = True+ return tx++class PaginatedTransactions(BaseModel):items: list[TransactionRead]total: int@@ -44,7 +51,9 @@ async def list_transactions(session, user.id, account_id, category_id, from_date, to_date, page, limit,include_opening_balance, search=q, uncategorized=uncategorized, txn_type=type,)- return PaginatedTransactions(items=transactions, total=total, page=page, limit=limit)+ primary_currency = user.primary_currency+ items = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]+ return PaginatedTransactions(items=items, total=total, page=page, limit=limit)@router.get("/export")@@ -67,7 +76,7 @@ async def export_transactions(output = io.StringIO()output.write("\ufeff") # UTF-8 BOM for Excelwriter = csv.writer(output)- writer.writerow(["date", "description", "amount", "type", "currency", "category", "account", "payee", "notes", "status", "source"])+ writer.writerow(["date", "description", "amount", "type", "currency", "category", "account", "payee", "notes", "status", "source", "amount_primary", "fx_rate_used"])for tx in transactions:writer.writerow([tx.date.isoformat(),@@ -81,6 +90,8 @@ async def export_transactions(tx.notes or "",tx.status,tx.source,+ str(tx.amount_primary) if tx.amount_primary is not None else "",+ str(tx.fx_rate_used) if tx.fx_rate_used is not None else "",])output.seek(0)@@ -113,7 +124,8 @@ async def get_transaction(transaction = await transaction_service.get_transaction(session, transaction_id, user.id)if not transaction:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")- return transaction+ primary_currency = user.primary_currency+ return _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)@router.post("", response_model=TransactionRead, status_code=status.HTTP_201_CREATED)@@ -124,7 +136,9 @@ async def create_transaction():try:transaction = await transaction_service.create_transaction(session, user.id, data)- return await transaction_service.get_transaction(session, transaction.id, user.id)+ full_tx = await transaction_service.get_transaction(session, transaction.id, user.id)+ primary_currency = user.primary_currency+ return _tag_fx_fallback(TransactionRead.model_validate(full_tx, from_attributes=True), primary_currency)except ValueError as e:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))@@ -139,7 +153,8 @@ async def update_transaction(transaction = await transaction_service.update_transaction(session, transaction_id, user.id, data)if not transaction:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")- return transaction+ primary_currency = user.primary_currency+ return _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)@router.delete("/{transaction_id}", status_code=status.HTTP_204_NO_CONTENT)diff --git a/backend/app/cli.py b/backend/app/cli.pyindex 3b20a581..652bd933 100644--- a/backend/app/cli.py+++ b/backend/app/cli.py@@ -51,7 +51,7 @@ async def create_user(email: str, password: str) -> None:"language": "pt-BR","date_format": "DD/MM/YYYY","timezone": "America/Sao_Paulo",- "currency_display": "BRL",+ "currency_display": "USD",},)session.add(user)diff --git a/backend/app/core/auth.py b/backend/app/core/auth.pyindex 0f106a16..8756e5f2 100644--- a/backend/app/core/auth.py+++ b/backend/app/core/auth.py@@ -36,7 +36,7 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):# Create default wallet for users registered via /auth/register.from app.models.account import Accountsession = self.user_db.session- currency = (user.preferences or {}).get("currency_display", "BRL")+ currency = user.primary_currencylang = (user.preferences or {}).get("language", "en")wallet_name = "Carteira" if lang.startswith("pt") else "Wallet"wallet = Account(diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex a377f9df..5179a49a 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -23,6 +23,14 @@ class Settings(BaseSettings):# Frontendfrontend_url: str = "http://localhost:5173"+ # Defaults+ default_currency: str = "USD" # fallback currency when user preference is unavailable++ # FX Rates+ openexchangerates_app_id: str = ""+ supported_currencies: str = "USD,EUR,GBP,BRL,CAD,AUD,CHF,ARS,JPY,MXN,INR,SEK" # comma-separated list+ fx_sync_mode: str = "on_demand" # "on_demand" or "scheduled"+# Celeryredis_url: str = "redis://localhost:6379/0"diff --git a/backend/app/main.py b/backend/app/main.pyindex da3b9a45..d195db14 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -17,6 +17,8 @@ from app.api.rules import router as rules_routerfrom app.api.assets import router as assets_routerfrom app.api.reports import router as reports_routerfrom app.api.setup import router as setup_router+from app.api.currencies import router as currencies_router+from app.api.fx_rates import router as fx_rates_routerfrom app.api.transactions import router as transactions_routerfrom app.core.auth import auth_backend, fastapi_usersfrom app.core.config import get_settings@@ -91,6 +93,8 @@ app.include_router(assets_router)app.include_router(dashboard_router)app.include_router(reports_router)app.include_router(setup_router)+app.include_router(currencies_router)+app.include_router(fx_rates_router)@app.get("/api/health")diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 084c0e51..a081c9ab 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -10,6 +10,7 @@ from app.models.budget import Budgetfrom app.models.import_log import ImportLogfrom app.models.asset import Assetfrom app.models.asset_value import AssetValue+from app.models.fx_rate import FxRate__all__ = ["User",@@ -24,4 +25,5 @@ __all__ = ["ImportLog","Asset","AssetValue",+ "FxRate",]diff --git a/backend/app/models/account.py b/backend/app/models/account.pyindex 8443428b..bdaec594 100644--- a/backend/app/models/account.py+++ b/backend/app/models/account.py@@ -24,7 +24,8 @@ class Account(Base):name: Mapped[str] = mapped_column(String(255))type: Mapped[str] = mapped_column(String(50)) # checking, savings, credit_cardbalance: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))- currency: Mapped[str] = mapped_column(String(3), default="BRL")+ currency: Mapped[str] = mapped_column(String(3), default="USD")+ balance_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)is_closed: Mapped[bool] = mapped_column(Boolean, default=False)closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)diff --git a/backend/app/models/asset.py b/backend/app/models/asset.pyindex 6f6a140a..df4c1e89 100644--- a/backend/app/models/asset.py+++ b/backend/app/models/asset.py@@ -20,7 +20,7 @@ class Asset(Base):user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))name: Mapped[str] = mapped_column(String(255))type: Mapped[str] = mapped_column(String(50)) # real_estate, vehicle, valuable, investment, other- currency: Mapped[str] = mapped_column(String(3), default="BRL")+ currency: Mapped[str] = mapped_column(String(3), default="USD")units: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=6), nullable=True)valuation_method: Mapped[str] = mapped_column(String(20), default="manual") # manual, growth_rulepurchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)@@ -31,6 +31,7 @@ class Asset(Base):growth_rate: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=6), nullable=True)growth_frequency: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) # daily, weekly, monthly, yearlygrowth_start_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)+ purchase_price_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)is_archived: Mapped[bool] = mapped_column(Boolean, default=False)position: Mapped[int] = mapped_column(Integer, default=0)diff --git a/backend/app/models/budget.py b/backend/app/models/budget.pyindex 9dc0dc0a..f01b0165 100644--- a/backend/app/models/budget.py+++ b/backend/app/models/budget.py@@ -1,9 +1,9 @@import uuidfrom datetime import date, datetimefrom decimal import Decimal-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, Optional-from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Numeric, UniqueConstraint+from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Numeric, String, UniqueConstraintfrom sqlalchemy.dialects.postgresql import UUIDfrom sqlalchemy.orm import Mapped, mapped_column, relationshipfrom sqlalchemy.sql import func@@ -27,6 +27,8 @@ class Budget(Base):amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))month: Mapped[date] = mapped_column(Date) # First day of monthis_recurring: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")+ currency: Mapped[Optional[str]] = mapped_column(String(3), server_default="USD", nullable=True)+ amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())user: Mapped["User"] = relationship()diff --git a/backend/app/models/fx_rate.py b/backend/app/models/fx_rate.pynew file mode 100644index 00000000..bc29f917--- /dev/null+++ b/backend/app/models/fx_rate.py@@ -0,0 +1,25 @@+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++from sqlalchemy import Date, DateTime, Index, Numeric, String, UniqueConstraint+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column++from app.core.database import Base+++class FxRate(Base):+ __tablename__ = "fx_rates"+ __table_args__ = (+ UniqueConstraint("base_currency", "quote_currency", "date", name="uq_fx_rate_base_quote_date"),+ Index("ix_fx_rates_quote_date", "quote_currency", "date"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ base_currency: Mapped[str] = mapped_column(String(3)) # Always "USD" for OER+ quote_currency: Mapped[str] = mapped_column(String(3))+ date: Mapped[date] = mapped_column(Date)+ rate: Mapped[Decimal] = mapped_column(Numeric(precision=20, scale=10))+ source: Mapped[str] = mapped_column(String(50))+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))diff --git a/backend/app/models/recurring_transaction.py b/backend/app/models/recurring_transaction.pyindex e35ecb1d..2d6609bb 100644--- a/backend/app/models/recurring_transaction.py+++ b/backend/app/models/recurring_transaction.py@@ -28,7 +28,7 @@ class RecurringTransaction(Base):category_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("categories.id"), nullable=True)description: Mapped[str] = mapped_column(String(500))amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))- currency: Mapped[str] = mapped_column(String(3), default="BRL")+ currency: Mapped[str] = mapped_column(String(3), default="USD")type: Mapped[str] = mapped_column(String(10)) # debit, creditfrequency: Mapped[str] = mapped_column(String(20)) # monthly, weekly, yearlyday_of_month: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)@@ -36,6 +36,8 @@ class RecurringTransaction(Base):end_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)is_active: Mapped[bool] = mapped_column(Boolean, default=True)next_occurrence: Mapped[date] = mapped_column(Date)+ amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)+ fx_rate_used: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=20, scale=10), nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())user: Mapped["User"] = relationship()diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.pyindex 9f1c485e..edbcfbc7 100644--- a/backend/app/models/transaction.py+++ b/backend/app/models/transaction.py@@ -25,7 +25,7 @@ class Transaction(Base):external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # Provider's transaction IDdescription: Mapped[str] = mapped_column(String(500))amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))- currency: Mapped[str] = mapped_column(String(3), default="BRL")+ currency: Mapped[str] = mapped_column(String(3), default="USD")date: Mapped[date] = mapped_column(Date)type: Mapped[str] = mapped_column(String(10)) # debit, creditsource: Mapped[str] = mapped_column(String(20)) # sync, ofx, csv, manual@@ -35,6 +35,8 @@ class Transaction(Base):raw_data: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)import_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("import_logs.id"), nullable=True)transfer_pair_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)+ amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)+ fx_rate_used: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=20, scale=10), nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))account: Mapped["Account"] = relationship(back_populates="transactions")diff --git a/backend/app/models/user.py b/backend/app/models/user.pyindex db83b0ff..cb31f9a2 100644--- a/backend/app/models/user.py+++ b/backend/app/models/user.py@@ -18,13 +18,19 @@ class User(SQLAlchemyBaseUserTableUUID, Base):preferences: Mapped[Optional[dict]] = mapped_column(JSON,default=lambda: {- "language": "pt-BR",- "date_format": "DD/MM/YYYY",- "timezone": "America/Sao_Paulo",- "currency_display": "BRL",+ "language": "en",+ "date_format": "MM/DD/YYYY",+ "timezone": "UTC",+ "currency_display": "USD",},)categories: Mapped[list["Category"]] = relationship(back_populates="user", cascade="all, delete-orphan")category_groups: Mapped[list["CategoryGroup"]] = relationship(back_populates="user", cascade="all, delete-orphan")bank_connections: Mapped[list["BankConnection"]] = relationship(back_populates="user", cascade="all, delete-orphan")++ @property+ def primary_currency(self) -> str:+ """Return the user's configured primary currency."""+ from app.core.config import get_settings+ return (self.preferences or {}).get("currency_display", get_settings().default_currency)diff --git a/backend/app/providers/base.py b/backend/app/providers/base.pyindex 3a390c3a..8ad0e0de 100644--- a/backend/app/providers/base.py+++ b/backend/app/providers/base.py@@ -21,6 +21,8 @@ class TransactionData:amount: Decimaldate: datetype: str # debit, credit+ currency: Optional[str] = None # ISO currency code (e.g. BRL, USD)+ amount_in_account_currency: Optional[Decimal] = None # Bank-provided conversion for intl txnspluggy_category: Optional[str] = Nonestatus: str = "posted" # posted, pendingpayee: Optional[str] = None@@ -40,6 +42,26 @@ class ConnectTokenData:access_token: str+class FxRateProvider(ABC):+ """Abstract interface for FX rate providers."""++ @property+ @abstractmethod+ def name(self) -> str:+ """Unique provider identifier (e.g. 'openexchangerates')."""+ ...++ @abstractmethod+ async def fetch_latest(self) -> dict[str, Decimal]:+ """Return {currency_code: rate_vs_USD} for latest rates."""+ ...++ @abstractmethod+ async def fetch_historical(self, target_date: date) -> dict[str, Decimal]:+ """Return rates for a specific date."""+ ...++class BankProvider(ABC):"""Abstract interface for open finance integrations.diff --git a/backend/app/providers/openexchangerates.py b/backend/app/providers/openexchangerates.pynew file mode 100644index 00000000..08dcb080--- /dev/null+++ b/backend/app/providers/openexchangerates.py@@ -0,0 +1,50 @@+import logging+from datetime import date+from decimal import Decimal++import httpx++from app.core.config import get_settings+from app.providers.base import FxRateProvider++logger = logging.getLogger(__name__)++BASE_URL = "https://openexchangerates.org/api"+++class OpenExchangeRatesProvider(FxRateProvider):+ """FX rate provider using Open Exchange Rates API."""++ @property+ def name(self) -> str:+ return "openexchangerates"++ def _app_id(self) -> str:+ return get_settings().openexchangerates_app_id++ def _symbols(self) -> str:+ """Return comma-separated supported currencies for the OER `symbols` param."""+ return get_settings().supported_currencies++ async def fetch_latest(self) -> dict[str, Decimal]:+ app_id = self._app_id()+ if not app_id:+ raise ValueError("openexchangerates_app_id not configured")+ params = {"app_id": app_id, "symbols": self._symbols()}+ async with httpx.AsyncClient(timeout=30) as client:+ resp = await client.get(f"{BASE_URL}/latest.json", params=params)+ resp.raise_for_status()+ data = resp.json()+ return {code: Decimal(str(rate)) for code, rate in data.get("rates", {}).items()}++ async def fetch_historical(self, target_date: date) -> dict[str, Decimal]:+ app_id = self._app_id()+ if not app_id:+ raise ValueError("openexchangerates_app_id not configured")+ date_str = target_date.strftime("%Y-%m-%d")+ params = {"app_id": app_id, "symbols": self._symbols()}+ async with httpx.AsyncClient(timeout=30) as client:+ resp = await client.get(f"{BASE_URL}/historical/{date_str}.json", params=params)+ resp.raise_for_status()+ data = resp.json()+ return {code: Decimal(str(rate)) for code, rate in data.get("rates", {}).items()}diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.pyindex 4de60dbe..e3830833 100644--- a/backend/app/providers/pluggy.py+++ b/backend/app/providers/pluggy.py@@ -124,7 +124,7 @@ class PluggyProvider(BankProvider):name=acc["name"],type=self._map_account_type(acc.get("type", "")),balance=Decimal(str(acc.get("balance", 0))),- currency=acc.get("currencyCode", "BRL"),+ currency=acc.get("currencyCode", "USD"),))@@ -156,7 +156,7 @@ class PluggyProvider(BankProvider):name=acc["name"],type=self._map_account_type(acc.get("type", "")),balance=Decimal(str(acc.get("balance", 0))),- currency=acc.get("currencyCode", "BRL"),+ currency=acc.get("currencyCode", "USD"),))return accounts@@ -212,6 +212,12 @@ class PluggyProvider(BankProvider):# Smart payee extraction (merchant → payment data → None)payee = self._extract_payee(txn, txn_type, payee_source)+ # Bank-provided conversion for international transactions+ amt_in_acct = txn.get("amountInAccountCurrency")+ amount_in_account_currency = (+ Decimal(str(abs(amt_in_acct))) if amt_in_acct is not None else None+ )+all_transactions.append(TransactionData(external_id=txn["id"],@@ -219,6 +225,8 @@ class PluggyProvider(BankProvider):amount=amount,date=txn_date,type=txn_type,+ currency=txn.get("currencyCode"),+ amount_in_account_currency=amount_in_account_currency,pluggy_category=txn.get("category"),status=status,payee=payee,diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex 1ea0afe5..77ab62c4 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -10,7 +10,7 @@ class AccountBase(BaseModel):name: strtype: strbalance: Decimal- currency: str = "BRL"+ currency: str = "USD"class AccountCreate(BaseModel):@@ -18,7 +18,7 @@ class AccountCreate(BaseModel):type: strbalance: Decimal = Decimal("0.00")balance_date: Optional[date] = None- currency: str = "BRL"+ currency: str = "USD"class AccountUpdate(BaseModel):@@ -35,6 +35,7 @@ class AccountRead(AccountBase):external_id: Optional[str] = Nonecurrent_balance: float = 0.0previous_balance: Optional[float] = None+ balance_primary: Optional[float] = Noneis_closed: bool = Falseclosed_at: Optional[datetime] = Nonediff --git a/backend/app/schemas/asset.py b/backend/app/schemas/asset.pyindex 191d7488..d86529e9 100644--- a/backend/app/schemas/asset.py+++ b/backend/app/schemas/asset.py@@ -9,7 +9,7 @@ from pydantic import BaseModel, ConfigDictclass AssetCreate(BaseModel):name: strtype: str- currency: str = "BRL"+ currency: str = "USD"units: Optional[Decimal] = Nonevaluation_method: str = "manual"purchase_date: Optional[date] = None@@ -62,7 +62,9 @@ class AssetRead(BaseModel):is_archived: boolposition: intcurrent_value: Optional[float] = None+ current_value_primary: Optional[float] = Nonegain_loss: Optional[float] = None+ gain_loss_primary: Optional[float] = Nonevalue_count: int = 0model_config = ConfigDict(from_attributes=True)diff --git a/backend/app/schemas/dashboard.py b/backend/app/schemas/dashboard.pyindex 14919b2e..2df21432 100644--- a/backend/app/schemas/dashboard.py+++ b/backend/app/schemas/dashboard.py@@ -5,13 +5,18 @@ from pydantic import BaseModelclass DashboardSummary(BaseModel):total_balance: dict[str, float] # currency -> amount+ total_balance_primary: float = 0.0 # consolidated in primary currencybalance_date: str # ISO date string, e.g. "2026-03-02"monthly_income: floatmonthly_expenses: float+ monthly_income_primary: float = 0.0+ monthly_expenses_primary: float = 0.0accounts_count: intpending_categorization: intpending_categorization_amount: floatassets_value: dict[str, float] = {} # currency -> total asset value+ assets_value_primary: float = 0.0+ primary_currency: str = "USD"class SpendingByCategory(BaseModel):@@ -43,6 +48,7 @@ class ProjectedTransaction(BaseModel):recurring_id: strdescription: stramount: float+ amount_primary: Optional[float] = Nonecurrency: strtype: str # debit, creditdate: str # YYYY-MM-DDdiff --git a/backend/app/schemas/recurring_transaction.py b/backend/app/schemas/recurring_transaction.pyindex 95f5b8e7..e7e2e674 100644--- a/backend/app/schemas/recurring_transaction.py+++ b/backend/app/schemas/recurring_transaction.py@@ -9,7 +9,7 @@ from pydantic import BaseModel, ConfigDictclass RecurringTransactionCreate(BaseModel):description: stramount: Decimal- currency: str = "BRL"+ currency: str = "USD"type: str # debit, creditfrequency: str # monthly, weekly, yearlyday_of_month: Optional[int] = None@@ -49,5 +49,7 @@ class RecurringTransactionRead(BaseModel):end_date: Optional[_Date] = Noneis_active: boolnext_occurrence: _Date+ amount_primary: Optional[float] = None+ fx_rate_used: Optional[float] = Nonemodel_config = ConfigDict(from_attributes=True)diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex 9bd851d4..a8645ba0 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -14,13 +14,17 @@ class TransactionBase(BaseModel):date: _Datetype: str # debit, creditexternal_id: Optional[str] = None+ currency: Optional[str] = None+ fx_rate: Optional[Decimal] = Noneclass TransactionCreate(TransactionBase):account_id: uuid.UUIDcategory_id: Optional[uuid.UUID] = None- currency: str = "BRL"+ currency: Optional[str] = Nonenotes: Optional[str] = None+ amount_primary: Optional[Decimal] = None+ fx_rate_used: Optional[Decimal] = Noneclass TransactionUpdate(BaseModel):@@ -31,6 +35,8 @@ class TransactionUpdate(BaseModel):currency: Optional[str] = Nonecategory_id: Optional[uuid.UUID] = Nonenotes: Optional[str] = None+ amount_primary: Optional[Decimal] = None+ fx_rate_used: Optional[Decimal] = Noneclass TransactionRead(TransactionBase):@@ -39,12 +45,15 @@ class TransactionRead(TransactionBase):account_id: Optional[uuid.UUID] = Nonecategory_id: Optional[uuid.UUID] = Nonecategory: Optional[CategoryRead] = None- currency: str = "BRL"+ currency: str = "USD"source: strstatus: str = "posted"payee: Optional[str] = Nonenotes: Optional[str] = Nonetransfer_pair_id: Optional[uuid.UUID] = None+ amount_primary: Optional[float] = None+ fx_rate_used: Optional[float] = None+ fx_fallback: bool = Falsemodel_config = ConfigDict(from_attributes=True)diff --git a/backend/app/schemas/user.py b/backend/app/schemas/user.pyindex 4f7c5344..5d63ae7c 100644--- a/backend/app/schemas/user.py+++ b/backend/app/schemas/user.py@@ -6,10 +6,10 @@ from pydantic import BaseModelclass UserPreferences(BaseModel):- language: str = "pt-BR"- date_format: str = "DD/MM/YYYY"- timezone: str = "America/Sao_Paulo"- currency_display: str = "BRL"+ language: str = "en"+ date_format: str = "MM/DD/YYYY"+ timezone: str = "UTC"+ currency_display: str = "USD"onboarding_completed: bool = Falsediff --git a/backend/app/services/asset_service.py b/backend/app/services/asset_service.pyindex f17d8fd3..f7632f8f 100644--- a/backend/app/services/asset_service.py+++ b/backend/app/services/asset_service.py@@ -6,9 +6,12 @@ from typing import Optionalfrom sqlalchemy import select, func, descfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.config import get_settingsfrom app.models.asset import Assetfrom app.models.asset_value import AssetValue+from app.models.user import Userfrom app.schemas.asset import AssetCreate, AssetUpdate, AssetValueCreate, AssetRead, AssetValueRead+from app.services.fx_rate_service import convert, stamp_primary_amountdef _next_due_date(last_date: date, frequency: str) -> date:@@ -225,6 +228,16 @@ async def create_asset(for v in backfill:session.add(v)+ # Stamp purchase_price_primary+ if asset.purchase_price is not None:+ await stamp_primary_amount(+ session, user_id, asset,+ amount_field="purchase_price",+ primary_field="purchase_price_primary",+ rate_field="_no_rate", # Asset has no rate field+ date_field="purchase_date",+ )+await session.commit()await session.refresh(asset)latest = await _get_latest_value(session, asset.id)@@ -279,6 +292,17 @@ async def update_asset(for v in backfill:session.add(v)+ # Re-stamp purchase_price_primary if purchase_price or currency changed+ if "purchase_price" in update_data or "currency" in update_data:+ if asset.purchase_price is not None:+ await stamp_primary_amount(+ session, user_id, asset,+ amount_field="purchase_price",+ primary_field="purchase_price_primary",+ rate_field="_no_rate",+ date_field="purchase_date",+ )+await session.commit()await session.refresh(asset)latest = await _get_latest_value(session, asset.id)@@ -403,9 +427,17 @@ async def get_portfolio_trend(asset_values_map: dict[str, list[tuple[date, float]]] = {}all_dates: set[date] = set()+ # Get user's primary currency for conversion+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency++ # Map asset_id -> currency for conversion+ asset_currency: dict[str, str] = {}+for asset in active_assets:aid = str(asset.id)asset_meta.append({"id": aid, "name": asset.name, "type": asset.type})+ asset_currency[aid] = asset.currencyrows = await session.execute(select(AssetValue.date, AssetValue.amount)@@ -458,8 +490,18 @@ async def get_portfolio_trend(row["_total"] = round(date_total, 2)trend.append(row)- # Total = sum of last known values- total = sum(last_known[a["id"]] for a in asset_meta)+ # Total = sum of last known values, converted to primary currency+ total = 0.0+ for a in asset_meta:+ aid = a["id"]+ val = last_known[aid]+ if val and asset_currency[aid] != primary_currency:+ converted, _ = await convert(+ session, Decimal(str(val)), asset_currency[aid], primary_currency,+ )+ total += float(converted)+ else:+ total += valreturn {"assets": asset_meta, "trend": trend, "total": round(total, 2)}diff --git a/backend/app/services/budget_service.py b/backend/app/services/budget_service.pyindex 470df4e8..c71a1182 100644--- a/backend/app/services/budget_service.py+++ b/backend/app/services/budget_service.py@@ -10,8 +10,16 @@ from app.models.budget import Budgetfrom app.models.category import Categoryfrom app.models.category_group import CategoryGroupfrom app.models.transaction import Transaction+from app.models.user import Userfrom app.schemas.budget import BudgetCreate, BudgetUpdate, BudgetVsActualfrom app.services.dashboard_service import _get_recurring_projections+from app.services.fx_rate_service import convert+from app.core.config import get_settings+++def _primary_amount_expr():+ """Amount in primary currency: uses amount_primary when available, falls back to amount."""+ return func.coalesce(Transaction.amount_primary, Transaction.amount)async def _build_budget_map(@@ -232,11 +240,16 @@ async def get_budget_vs_actual(# Get budgets for this month (with recurring resolution)budget_map = await _build_budget_map(session, user_id, month_start)+ # Get user's primary currency for FX conversion+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency+# Get actual spending by category for this month (exclude transfer pairs)+ # Use amount_primary for multi-currency supportspending_result = await session.execute(select(Transaction.category_id,- func.sum(Transaction.amount),+ func.sum(_primary_amount_expr()),).where(Transaction.user_id == user_id,@@ -252,19 +265,23 @@ async def get_budget_vs_actual(for row in spending_result.all():spending_map[str(row[0])] = abs(row[1] or Decimal("0"))- # Add projected recurring transactions for this month+ # Add projected recurring transactions for this month (converted to primary currency)projections = await _get_recurring_projections(session, user_id, month_start, month_end)for proj in projections:if proj["type"] != "debit" or not proj["category_id"]:continuecat_id = str(proj["category_id"])- spending_map[cat_id] = spending_map.get(cat_id, Decimal("0")) + Decimal(str(proj["amount"]))+ converted, _ = await convert(+ session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,+ )+ spending_map[cat_id] = spending_map.get(cat_id, Decimal("0")) + converted# Get previous month spending by category (exclude transfer pairs)+ # Use amount_primary for multi-currency supportprev_spending_result = await session.execute(select(Transaction.category_id,- func.sum(Transaction.amount),+ func.sum(_primary_amount_expr()),).where(Transaction.user_id == user_id,@@ -280,13 +297,16 @@ async def get_budget_vs_actual(for row in prev_spending_result.all():prev_spending_map[str(row[0])] = abs(row[1] or Decimal("0"))- # Add projected recurring transactions for previous month+ # Add projected recurring transactions for previous month (converted to primary currency)prev_projections = await _get_recurring_projections(session, user_id, prev_month_start, prev_month_end)for proj in prev_projections:if proj["type"] != "debit" or not proj["category_id"]:continuecat_id = str(proj["category_id"])- prev_spending_map[cat_id] = prev_spending_map.get(cat_id, Decimal("0")) + Decimal(str(proj["amount"]))+ converted, _ = await convert(+ session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,+ )+ prev_spending_map[cat_id] = prev_spending_map.get(cat_id, Decimal("0")) + convertedcomparisons = []for category, group in all_categories:diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 3f782f6c..dd883d15 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -11,9 +11,11 @@ from app.models.bank_connection import BankConnectionfrom app.models.account import Accountfrom app.models.category import Categoryfrom app.models.transaction import Transaction+from app.models.user import Userfrom app.providers import get_providerfrom app.services.rule_service import apply_rules_to_transactionfrom app.services.transfer_detection_service import detect_transfer_pairs+from app.services.fx_rate_service import stamp_primary_amountsettings = get_settings()@@ -133,6 +135,8 @@ async def handle_oauth_callback(session.add(connection)await session.flush()+ user = await session.get(User, user_id)+ user_currency = user.primary_currency if user else get_settings().default_currencynew_tx_ids: list[uuid.UUID] = []for acc_data in connection_data.accounts:@@ -162,6 +166,7 @@ async def handle_oauth_callback(external_id=txn_data.external_id,description=txn_data.description,amount=txn_data.amount,+ currency=txn_data.currency or acc_data.currency or user_currency,date=txn_data.date,type=txn_data.type,source="sync",@@ -176,6 +181,19 @@ async def handle_oauth_callback(if not category_id:await apply_rules_to_transaction(session, user_id, transaction)+ # Prefer bank-provided conversion for international transactions+ acct_currency = acc_data.currency or user_currency+ if (+ txn_data.amount_in_account_currency is not None+ and txn_data.amount+ and acct_currency == user_currency+ and txn_data.currency != acct_currency+ ):+ transaction.amount_primary = txn_data.amount_in_account_currency+ transaction.fx_rate_used = txn_data.amount_in_account_currency / txn_data.amount+ else:+ await stamp_primary_amount(session, user_id, transaction)+# Detect transfer pairs among newly synced transactionsawait detect_transfer_pairs(session, user_id, candidate_ids=new_tx_ids)@@ -253,6 +271,8 @@ async def sync_connection(connection.credentials = credentials# Update accounts+ user = await session.get(User, user_id)+ user_currency = user.primary_currency if user else get_settings().default_currencynew_tx_ids: list[uuid.UUID] = []merged_count = 0accounts_data = await provider.get_accounts(credentials)@@ -326,6 +346,7 @@ async def sync_connection(external_id=txn_data.external_id,description=txn_data.description,amount=txn_data.amount,+ currency=txn_data.currency or acc_data.currency or user_currency,date=txn_data.date,type=txn_data.type,source="sync",@@ -340,6 +361,19 @@ async def sync_connection(if not category_id:await apply_rules_to_transaction(session, user_id, transaction)+ # Prefer bank-provided conversion for international transactions+ acct_currency = acc_data.currency or user_currency+ if (+ txn_data.amount_in_account_currency is not None+ and txn_data.amount+ and acct_currency == user_currency+ and txn_data.currency != acct_currency+ ):+ transaction.amount_primary = txn_data.amount_in_account_currency+ transaction.fx_rate_used = txn_data.amount_in_account_currency / txn_data.amount+ else:+ await stamp_primary_amount(session, user_id, transaction)+# Detect transfer pairs among newly synced transactionsif new_tx_ids:await detect_transfer_pairs(session, user_id, candidate_ids=new_tx_ids)diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.pyindex 9ef5b376..4b3d8014 100644--- a/backend/app/services/dashboard_service.py+++ b/backend/app/services/dashboard_service.py@@ -1,10 +1,12 @@import uuidfrom datetime import date, timedelta+from decimal import Decimalfrom typing import Optionalfrom sqlalchemy import select, func, case, or_from sqlalchemy.ext.asyncio import AsyncSession+from app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.models.transaction import Transaction@@ -13,6 +15,8 @@ from app.models.recurring_transaction import RecurringTransactionfrom app.schemas.dashboard import DashboardSummary, SpendingByCategory, MonthlyTrend, ProjectedTransaction, DailyBalance, BalanceHistoryfrom app.services.recurring_transaction_service import get_occurrences_in_rangefrom app.services.asset_service import get_total_asset_value+from app.services.fx_rate_service import convert+from app.models.user import Userdef _month_range(month: date) -> tuple[date, date]:@@ -115,6 +119,10 @@ async def get_summary(monthly_income = float(monthly_row[0] or 0)monthly_expenses = float(monthly_row[1] or 0)+ # Save real-only totals before adding projections (used for primary init)+ real_monthly_income = monthly_income+ real_monthly_expenses = monthly_expenses+# Add virtual recurring projectionsprojections = await _get_recurring_projections(session, user_id, month_start, month_end)for proj in projections:@@ -156,15 +164,75 @@ async def get_summary(for currency, amount in assets_value.items():total_balance[currency] = total_balance.get(currency, 0.0) + amount+ # Get user's primary currency+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency++ # 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)++ # Convert income/expenses to primary currency using amount_primary when available+ # Use real-only totals (without projections) to avoid double-counting;+ # projections are added separately below via convert().+ monthly_income_primary = real_monthly_income+ monthly_expenses_primary = abs(real_monthly_expenses)++ # Use amount_primary sums for more accurate multi-currency income/expenses+ primary_result = await session.execute(+ select(+ func.sum(case((Transaction.type == "credit", Transaction.amount_primary), else_=0)),+ func.sum(case((Transaction.type == "debit", Transaction.amount_primary), else_=0)),+ )+ .join(Account, Transaction.account_id == Account.id)+ .where(+ Transaction.user_id == user_id,+ Account.is_closed == False,+ Transaction.date >= month_start,+ Transaction.date < month_end,+ Transaction.source != "opening_balance",+ Transaction.transfer_pair_id.is_(None),+ Transaction.amount_primary.isnot(None),+ )+ )+ primary_row = primary_result.one()+ if primary_row[0] is not None or primary_row[1] is not None:+ monthly_income_primary = float(primary_row[0] or 0)+ monthly_expenses_primary = abs(float(primary_row[1] or 0))++ # Add recurring projections to primary totals (convert each)+ for proj in projections:+ proj_converted, _ = await convert(+ session, Decimal(str(proj["amount"])),+ proj["currency"], primary_currency,+ )+ if proj["type"] == "credit":+ monthly_income_primary += float(proj_converted)+ else:+ monthly_expenses_primary += float(proj_converted)++ # Convert asset values to primary currency+ assets_value_primary = 0.0+ for currency, amount in assets_value.items():+ converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency)+ assets_value_primary += float(converted)+return DashboardSummary(total_balance=total_balance,+ total_balance_primary=round(total_balance_primary, 2),balance_date=cutoff.isoformat(),monthly_income=monthly_income,monthly_expenses=abs(monthly_expenses),+ monthly_income_primary=round(monthly_income_primary, 2),+ monthly_expenses_primary=round(monthly_expenses_primary, 2),accounts_count=accounts_count,pending_categorization=pending_categorization,pending_categorization_amount=pending_categorization_amount,assets_value=assets_value,+ assets_value_primary=round(assets_value_primary, 2),+ primary_currency=primary_currency,)@@ -177,13 +245,14 @@ async def get_spending_by_category(month_start, month_end = _month_range(month)# Real transactions grouped by category (exclude transfer pairs and closed accounts)+ # Use amount_primary for multi-currency supportresult = await session.execute(select(Category.id,Category.name,Category.icon,Category.color,- func.sum(Transaction.amount),+ func.sum(_primary_amount_expr()),).select_from(Transaction).join(Account, Transaction.account_id == Account.id)@@ -197,7 +266,7 @@ async def get_spending_by_category(Transaction.transfer_pair_id.is_(None),).group_by(Category.id, Category.name, Category.icon, Category.color)- .order_by(func.sum(Transaction.amount).desc())+ .order_by(func.sum(_primary_amount_expr()).desc()))# Build a dict of category_id -> {name, icon, color, total}@@ -211,8 +280,10 @@ async def get_spending_by_category("total": abs(float(row[4] or 0)),}- # Add virtual recurring projections (debit only)+ # Add virtual recurring projections (debit only), converted to primary currencyprojections = await _get_recurring_projections(session, user_id, month_start, month_end)+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency# We need category info for recurring projections — fetch categoriescat_cache: dict[str, dict] = {}for proj in projections:@@ -231,15 +302,21 @@ async def get_spending_by_category(else:cat_cache[cat_id] = {"name": "Sem categoria", "icon": "circle-help", "color": "#6B7280"}+ # Convert projection amount to primary currency+ proj_amount, _ = await convert(+ session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,+ )+ proj_amount_float = float(proj_amount)+if cat_id in spending_map:- spending_map[cat_id]["total"] += proj["amount"]+ spending_map[cat_id]["total"] += proj_amount_floatelse:info = cat_cache.get(cat_id, {"name": "Sem categoria", "icon": "circle-help", "color": "#6B7280"})spending_map[cat_id] = {"name": info["name"],"icon": info["icon"],"color": info["color"],- "total": proj["amount"],+ "total": proj_amount_float,}# Convert to list and compute percentages@@ -262,11 +339,12 @@ async def get_monthly_trend(session: AsyncSession, user_id: uuid.UUID, months: int = 6) -> list[MonthlyTrend]:month_label = func.to_char(Transaction.date, 'YYYY-MM').label('month')+ primary_amt = _primary_amount_expr()result = await session.execute(select(month_label,- func.sum(case((Transaction.type == "credit", Transaction.amount), else_=0)),- func.sum(case((Transaction.type == "debit", Transaction.amount), else_=0)),+ func.sum(case((Transaction.type == "credit", primary_amt), else_=0)),+ func.sum(case((Transaction.type == "debit", primary_amt), else_=0)),).join(Account, Transaction.account_id == Account.id).where(@@ -301,6 +379,10 @@ async def get_projected_transactions(month_start, month_end = _month_range(month)+ # Get user's primary currency for live conversion+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency+result = await session.execute(select(RecurringTransaction).where(@@ -332,11 +414,21 @@ async def get_projected_transactions(range_end=month_end,)cat_name, cat_icon, cat_color = cat_map.get(rec.category_id, (None, None, None)) if rec.category_id else (None, None, None)++ # Convert to primary currency at current rate (consistent with summary)+ amt_primary = None+ if rec.currency != primary_currency:+ converted, _ = await convert(+ session, Decimal(str(rec.amount)), rec.currency, primary_currency,+ )+ amt_primary = float(converted)+for occ_date in occurrences:projections.append(ProjectedTransaction(recurring_id=str(rec.id),description=rec.description,amount=float(rec.amount),+ amount_primary=amt_primary,currency=rec.currency,type=rec.type,date=occ_date.isoformat(),@@ -350,13 +442,28 @@ async def get_projected_transactions(def _signed_balance_expr():- """Reusable SQL expression: credit → +amount, debit → −amount."""+ """Reusable SQL expression: credit → +amount, debit → −amount.+ Uses raw amount — suitable for single-account balance calculations."""return case((Transaction.type == "credit", Transaction.amount),else_=-Transaction.amount,)+def _primary_amount_expr():+ """Amount in primary currency: uses amount_primary when available, falls back to amount."""+ return func.coalesce(Transaction.amount_primary, Transaction.amount)+++def _signed_primary_expr():+ """Signed amount in primary currency: credit → +, debit → −."""+ amt = _primary_amount_expr()+ return case(+ (Transaction.type == "credit", amt),+ else_=-amt,+ )++async def _get_open_accounts(session: AsyncSession, user_id: uuid.UUID) -> list[Account]:@@ -441,19 +548,35 @@ async def _total_balance_by_currency(async def _balance_at(session: AsyncSession, user_id: uuid.UUID, cutoff: date) -> float:- """Get total balance across all open accounts at a specific date (single currency sum)."""+ """Get total balance across all open accounts at a specific date, converted to primary currency."""totals = await _total_balance_by_currency(session, user_id, cutoff)- return sum(totals.values())++ # If all same currency, just sum+ if len(totals) <= 1:+ return sum(totals.values())++ # Convert to primary currency+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency++ total = 0.0+ for currency, amount in totals.items():+ converted, _ = await convert(session, Decimal(str(amount)), currency, primary_currency, cutoff)+ total += float(converted)+ return totalasync def _daily_deltas(session: AsyncSession, user_id: uuid.UUID, start: date, end: date) -> dict[int, float]:- """Get daily balance deltas for a date range [start, end)."""+ """Get daily balance deltas for a date range [start, end).+ Uses amount_primary for multi-currency support.+ Excludes opening_balance transactions because they are already accounted+ for in the starting balance via _account_balance_at's carry-back logic."""result = await session.execute(select(func.extract("day", Transaction.date).label("day"),- func.sum(_signed_balance_expr()),+ func.sum(_signed_primary_expr()),).join(Account, Transaction.account_id == Account.id).where(@@ -461,6 +584,7 @@ async def _daily_deltas(Account.is_closed == False,Transaction.date >= start,Transaction.date < end,+ Transaction.source != "opening_balance",).group_by("day"))@@ -492,14 +616,20 @@ async def get_balance_history(current_deltas = await _daily_deltas(session, user_id, month_start, month_end)prev_deltas = await _daily_deltas(session, user_id, prev_month_start, prev_month_end)- # Recurring projections for future days of current month+ # Recurring projections for future days of current month (converted to primary currency)proj_deltas: dict[int, float] = {}if month_end > today:+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currencyproj_start = max(month_start, today + timedelta(days=1))projections = await _get_recurring_projections(session, user_id, proj_start, month_end)for proj in projections:day = proj["date"].day- signed = proj["amount"] if proj["type"] == "credit" else -proj["amount"]+ proj_converted, _ = await convert(+ session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,+ )+ amount = float(proj_converted)+ signed = amount if proj["type"] == "credit" else -amountproj_deltas[day] = proj_deltas.get(day, 0) + signed# Build current month daily balancesdiff --git a/backend/app/services/fx_rate_service.py b/backend/app/services/fx_rate_service.pynew file mode 100644index 00000000..164fa823--- /dev/null+++ b/backend/app/services/fx_rate_service.py@@ -0,0 +1,256 @@+import logging+import uuid+from datetime import date+from decimal import Decimal+from typing import Optional++from sqlalchemy import select, desc+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.dialects.postgresql import insert as pg_insert++from app.core.config import get_settings+from app.models.fx_rate import FxRate+from app.models.user import User+from app.providers.openexchangerates import OpenExchangeRatesProvider++logger = logging.getLogger(__name__)++_provider = OpenExchangeRatesProvider()+++async def sync_rates(+ session: AsyncSession, target_date: Optional[date] = None+) -> int:+ """Fetch rates from the provider for the given date and upsert into fx_rates.++ Only saves rates for currencies in `supported_currencies`.+ Idempotent — existing rates for the same date are updated.+ Returns the number of rates synced.+ """+ target = target_date or date.today()+ supported = set(get_settings().supported_currencies.split(","))++ if target == date.today():+ rates = await _provider.fetch_latest()+ else:+ rates = await _provider.fetch_historical(target)++ count = 0+ for currency_code, rate in rates.items():+ if currency_code not in supported:+ continue+ stmt = pg_insert(FxRate).values(+ base_currency="USD",+ quote_currency=currency_code,+ date=target,+ rate=rate,+ source=_provider.name,+ )+ stmt = stmt.on_conflict_do_update(+ constraint="uq_fx_rate_base_quote_date",+ set_={"rate": rate, "source": _provider.name},+ )+ await session.execute(stmt)+ count += 1++ await session.commit()+ logger.info("Synced %d FX rates for %s", count, target)+ return count+++async def get_rate(+ session: AsyncSession,+ from_currency: str,+ to_currency: str,+ target_date: Optional[date] = None,+) -> Decimal:+ """Get FX rate from from_currency to to_currency.++ Uses cross-rate through USD: rate = usd_to_target / usd_to_source.+ Priority: exact date → on-demand fetch → closest available → fallback 1:1.+ """+ if from_currency == to_currency:+ return Decimal("1")++ target = target_date or date.today()++ # Step 1: Try exact date+ usd_to_source = await _get_exact_date_rate(session, from_currency, target)+ usd_to_target = await _get_exact_date_rate(session, to_currency, target)++ # Step 2: If missing, fetch from provider for exact date+ if usd_to_source is None or usd_to_target is None:+ try:+ synced = await sync_rates(session, target)+ if synced > 0:+ logger.info("On-demand sync fetched %d rates for %s", synced, target)+ if usd_to_source is None:+ usd_to_source = await _get_exact_date_rate(session, from_currency, target)+ if usd_to_target is None:+ usd_to_target = await _get_exact_date_rate(session, to_currency, target)+ except Exception:+ logger.warning("On-demand FX rate sync failed for %s", target, exc_info=True)++ # Step 3: Fall back to closest available date+ if usd_to_source is None:+ usd_to_source = await _get_closest_rate(session, from_currency, target)+ if usd_to_target is None:+ usd_to_target = await _get_closest_rate(session, to_currency, target)++ if from_currency == "USD":+ usd_to_source = Decimal("1")+ if to_currency == "USD":+ usd_to_target = Decimal("1")++ if usd_to_source is None or usd_to_target is None:+ logger.warning(+ "No FX rate found for %s -> %s on %s, returning 1",+ from_currency, to_currency, target,+ )+ return Decimal("1")++ if usd_to_source == 0:+ return Decimal("1")++ return usd_to_target / usd_to_source+++async def _get_exact_date_rate(session: AsyncSession, currency: str, target: date) -> Optional[Decimal]:+ """Get the rate for an exact date."""+ if currency == "USD":+ return Decimal("1")+ result = await session.scalar(+ select(FxRate.rate)+ .where(+ FxRate.base_currency == "USD",+ FxRate.quote_currency == currency,+ FxRate.date == target,+ )+ )+ return result+++async def _get_closest_rate(session: AsyncSession, currency: str, target: date) -> Optional[Decimal]:+ """Get the closest available rate to a target date (preferring before, then after)."""+ if currency == "USD":+ return Decimal("1")+ # Try closest before or on target date+ result = await session.scalar(+ select(FxRate.rate)+ .where(+ FxRate.base_currency == "USD",+ FxRate.quote_currency == currency,+ FxRate.date <= target,+ )+ .order_by(desc(FxRate.date))+ .limit(1)+ )+ if result is not None:+ return result+ # Try closest after target date+ from sqlalchemy import asc+ result = await session.scalar(+ select(FxRate.rate)+ .where(+ FxRate.base_currency == "USD",+ FxRate.quote_currency == currency,+ FxRate.date > target,+ )+ .order_by(asc(FxRate.date))+ .limit(1)+ )+ return result+++async def _get_latest_rate(session: AsyncSession, currency: str) -> Optional[Decimal]:+ """Get the most recent rate for a currency vs USD."""+ if currency == "USD":+ return Decimal("1")+ result = await session.scalar(+ select(FxRate.rate)+ .where(+ FxRate.base_currency == "USD",+ FxRate.quote_currency == currency,+ )+ .order_by(desc(FxRate.date))+ .limit(1)+ )+ return result+++async def _get_month_closing_rate(+ session: AsyncSession, currency: str, target: date+) -> Optional[Decimal]:+ """Get the last available rate within the target's month."""+ if currency == "USD":+ return Decimal("1")+ month_start = target.replace(day=1)+ if month_start.month == 12:+ month_end = month_start.replace(year=month_start.year + 1, month=1)+ else:+ month_end = month_start.replace(month=month_start.month + 1)++ result = await session.scalar(+ select(FxRate.rate)+ .where(+ FxRate.base_currency == "USD",+ FxRate.quote_currency == currency,+ FxRate.date >= month_start,+ FxRate.date < month_end,+ )+ .order_by(desc(FxRate.date))+ .limit(1)+ )+ return result+++async def convert(+ session: AsyncSession,+ amount: Decimal,+ from_currency: str,+ to_currency: str,+ target_date: Optional[date] = None,+) -> tuple[Decimal, Decimal]:+ """Convert an amount from one currency to another.++ Returns (converted_amount, rate_used).+ """+ if from_currency == to_currency:+ return amount, Decimal("1")++ rate = await get_rate(session, from_currency, to_currency, target_date)+ converted = amount * rate+ return converted.quantize(Decimal("0.01")), rate+++async def stamp_primary_amount(+ session: AsyncSession,+ user_id: uuid.UUID,+ obj,+ amount_field: str = "amount",+ primary_field: str = "amount_primary",+ rate_field: str = "fx_rate_used",+ date_field: str = "date",+ currency_field: str = "currency",+) -> None:+ """Set obj's primary amount and fx_rate_used based on user's primary currency.++ Works for Transaction, RecurringTransaction, etc.+ """+ user = await session.get(User, user_id)+ if not user:+ return++ primary_currency = user.primary_currency+ obj_currency = getattr(obj, currency_field, get_settings().default_currency)+ obj_amount = getattr(obj, amount_field, None)++ if obj_amount is None:+ return++ obj_date = getattr(obj, date_field, None)+ converted, rate = await convert(session, Decimal(str(obj_amount)), obj_currency, primary_currency, obj_date)++ setattr(obj, primary_field, converted)+ if hasattr(obj, rate_field):+ setattr(obj, rate_field, rate)diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.pyindex 656989f1..dca9bf67 100644--- a/backend/app/services/import_service.py+++ b/backend/app/services/import_service.py@@ -10,9 +10,12 @@ from ofxparse import OfxParserfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.config import get_settings+from app.models.account import Accountfrom app.models.transaction import Transactionfrom app.schemas.transaction import TransactionBasefrom app.services.rule_service import apply_rules_to_transaction+from app.services.fx_rate_service import stamp_primary_amountdef parse_ofx(content: bytes) -> list[TransactionBase]:@@ -151,11 +154,15 @@ def parse_camt(content: bytes) -> list[TransactionBase]:or "Unknown")+ # Extract currency from Ccy attribute on Amt element+ txn_currency = amt_el.get('Ccy') or None+transactions.append(TransactionBase(description=description,amount=abs(amount),date=txn_date,type=txn_type,+ currency=txn_currency,))return transactions@@ -196,6 +203,8 @@ def parse_csv(date_cols = ['date', 'data', 'dt', 'transaction_date', 'data_transacao']desc_cols = ['description', 'descricao', 'desc', 'memo', 'historico', 'lancamento']amount_cols = ['amount', 'valor', 'value', 'quantia']+ currency_cols = ['currency', 'moeda', 'currency_code']+ fx_rate_cols = ['fx_rate', 'fx_rate_used', 'taxa_cambio', 'exchange_rate', 'taxa']def find_col(candidates):for c in candidates:@@ -218,6 +227,9 @@ def parse_csv(else:amount_col = find_col(amount_cols)+ currency_col = find_col(currency_cols)+ fx_rate_col = find_col(fx_rate_cols)+if not date_col or not desc_col:raise ValueError("Could not detect CSV columns. Expected: date, description, amount")if not use_split and not amount_col:@@ -283,11 +295,26 @@ def parse_csv(txn_type = "credit" if amount > 0 else "debit"amount = abs(amount)+ # Extract optional currency and fx_rate from CSV columns+ txn_currency = None+ txn_fx_rate = None+ if currency_col and row.get(currency_col):+ txn_currency = row[currency_col].strip().upper() or None+ if fx_rate_col and row.get(fx_rate_col):+ fx_str = normalize_amount(row[fx_rate_col].strip())+ if fx_str:+ try:+ txn_fx_rate = Decimal(fx_str)+ except Exception:+ pass+transactions.append(TransactionBase(description=row[desc_col].strip(),amount=abs(amount),date=txn_date,type=txn_type,+ currency=txn_currency,+ fx_rate=txn_fx_rate,))return transactions@@ -322,9 +349,19 @@ async def import_transactions(session.add(import_log)await session.flush() # Get the import_log.id+ # Look up account currency for fallback+ account_result = await session.execute(+ select(Account).where(Account.id == account_id)+ )+ account = account_result.scalar_one_or_none()+ account_currency = account.currency if account else get_settings().default_currency+imported = 0skipped = 0for txn_data in transactions:+ # Resolve currency: CSV value > account currency+ txn_currency = txn_data.currency or account_currency+# Duplicate detection: use external_id when available (OFX FITID),# fall back to field-based matching for formats without unique IDsif txn_data.external_id:@@ -358,10 +395,22 @@ async def import_transactions(source=source,import_id=import_log.id,external_id=txn_data.external_id,+ currency=txn_currency,)++ # If CSV provided an fx_rate, use it directly+ if txn_data.fx_rate:+ transaction.fx_rate_used = txn_data.fx_rate+ transaction.amount_primary = txn_data.amount * txn_data.fx_rate+session.add(transaction)await session.flush()await apply_rules_to_transaction(session, user_id, transaction)++ # Only auto-convert if no fx_rate was provided by the CSV+ if not txn_data.fx_rate:+ await stamp_primary_amount(session, user_id, transaction)+imported += 1# Update import log with actual imported countdiff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.pyindex 7e5ecf4e..80c586c3 100644--- a/backend/app/services/recurring_transaction_service.py+++ b/backend/app/services/recurring_transaction_service.py@@ -9,6 +9,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction import Transactionfrom app.schemas.recurring_transaction import RecurringTransactionCreate, RecurringTransactionUpdate+from app.services.fx_rate_service import stamp_primary_amountasync def get_recurring_transactions(@@ -53,6 +54,11 @@ async def create_recurring_transaction(next_occurrence=next_occ,)session.add(recurring)+ await session.flush()+ await stamp_primary_amount(+ session, user_id, recurring,+ date_field="start_date",+ )await session.commit()await session.refresh(recurring)return recurring@@ -175,6 +181,8 @@ async def generate_pending(source="recurring",)session.add(transaction)+ await session.flush()+ await stamp_primary_amount(session, user_id, transaction)count += 1# Advance to next occurrencediff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.pyindex 23c84772..901923b3 100644--- a/backend/app/services/report_service.py+++ b/backend/app/services/report_service.py@@ -1,14 +1,18 @@import uuidfrom datetime import date, timedelta+from decimal import Decimalfrom sqlalchemy import String, select, desc, func, casefrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.config import get_settingsfrom app.models.account import Accountfrom app.models.asset import Assetfrom app.models.asset_value import AssetValuefrom app.models.transaction import Transactionfrom app.models.category import Category+from app.models.user import User+from app.services.fx_rate_service import convertfrom app.schemas.report import (CategoryTrendItem,ReportBreakdown,@@ -22,9 +26,11 @@ from app.services.dashboard_service import _get_open_accounts, _account_balance_async def _asset_value_at(- session: AsyncSession, user_id: uuid.UUID, cutoff: date+ session: AsyncSession, user_id: uuid.UUID, cutoff: date,+ primary_currency: str = "USD",) -> float:- """Sum of all active (non-archived, non-sold) asset values at a given date.+ """Sum of all active (non-archived, non-sold) asset values at a given date,+ converted to primary currency.For each asset, finds the most recent AssetValue with date <= cutoff.Falls back to purchase_price if no value entries exist before the cutoff@@ -52,20 +58,27 @@ async def _asset_value_at(.limit(1))row = val_result.scalar_one_or_none()+ amount = 0.0if row is not None:- total += float(row)+ amount = float(row)elif asset.purchase_price is not None:- # Fall back to purchase_price if the asset existed by cutoffif asset.purchase_date is None or asset.purchase_date <= cutoff:- total += float(asset.purchase_price)+ amount = float(asset.purchase_price)++ if amount != 0.0:+ converted, _ = await convert(+ session, Decimal(str(amount)), asset.currency, primary_currency, cutoff+ )+ total += float(converted)return totalasync def _net_worth_at(- session: AsyncSession, user_id: uuid.UUID, cutoff: date+ session: AsyncSession, user_id: uuid.UUID, cutoff: date,+ primary_currency: str = "USD",) -> ReportDataPoint:- """Compute a single net worth snapshot at a given date."""+ """Compute a single net worth snapshot at a given date, converted to primary currency."""accounts = await _get_open_accounts(session, user_id)accounts_total = 0.0@@ -73,13 +86,20 @@ async def _net_worth_at(for account in accounts:bal = await _account_balance_at(session, account, cutoff)+ # Convert to primary currency+ converted, _ = await convert(+ session, Decimal(str(abs(bal))), account.currency, primary_currency, cutoff+ )+ converted_val = float(converted)if account.type == "credit_card":- # _account_balance_at already negates credit_card; show as positive liability- liabilities_total += abs(bal)+ liabilities_total += converted_valelse:- accounts_total += bal+ if bal < 0:+ accounts_total -= converted_val+ else:+ accounts_total += converted_val- assets_total = await _asset_value_at(session, user_id, cutoff)+ assets_total = await _asset_value_at(session, user_id, cutoff, primary_currency)net_worth = accounts_total + assets_total - liabilities_totalreturn ReportDataPoint(@@ -158,19 +178,23 @@ async def get_net_worth_report(user_id: uuid.UUID,months: int = 12,interval: str = "monthly",- currency: str = "BRL",+ currency: str = "USD",) -> ReportResponse:"""Build a full ReportResponse for net worth over time."""today = date.today()start = date(today.year, today.month, 1) - timedelta(days=months * 30)start = start.replace(day=1) # Align to month start+ # Get user's primary currency+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency+points = _date_points(start, today, interval)# Compute snapshot at each date pointtrend: list[ReportDataPoint] = []for point in points:- dp = await _net_worth_at(session, user_id, point)+ dp = await _net_worth_at(session, user_id, point, primary_currency)dp.date = _format_date_label(point, interval)trend.append(dp)@@ -216,7 +240,7 @@ async def get_net_worth_report(meta = ReportMeta(type="net_worth",series_keys=["accounts", "assets", "liabilities"],- currency=currency,+ currency=primary_currency,interval=interval,)@@ -239,11 +263,15 @@ async def get_net_worth_report(accounts = await _get_open_accounts(session, user_id)for account in accounts:bal = await _account_balance_at(session, account, today)+ converted, _ = await convert(+ session, Decimal(str(abs(bal))), account.currency, primary_currency, today+ )+ converted_val = float(converted)if account.type == "credit_card":composition.append(ReportCompositionItem(key=str(account.id),label=account.name,- value=round(abs(bal), 2),+ value=round(converted_val, 2),color=account_type_colors.get(account.type, "#6B7280"),group="liabilities",))@@ -252,7 +280,7 @@ async def get_net_worth_report(composition.append(ReportCompositionItem(key=str(account.id),label=account.name,- value=round(bal, 2),+ value=round(converted_val, 2),color=account_type_colors.get(account.type, "#6B7280"),group="accounts",))@@ -282,10 +310,13 @@ async def get_net_worth_report(else:amount = 0.0if amount > 0:+ converted, _ = await convert(+ session, Decimal(str(amount)), asset.currency, primary_currency, today+ )composition.append(ReportCompositionItem(key=str(asset.id),label=asset.name,- value=round(amount, 2),+ value=round(float(converted), 2),color=asset_type_colors.get(asset.type, "#6B7280"),group="assets",))@@ -314,20 +345,27 @@ async def get_income_expenses_report(user_id: uuid.UUID,months: int = 12,interval: str = "monthly",- currency: str = "BRL",+ currency: str = "USD",) -> ReportResponse:"""Build a ReportResponse for income vs expenses over time."""today = date.today()start = date(today.year, today.month, 1) - timedelta(days=months * 30)start = start.replace(day=1)+ # Get user's primary currency+ user = await session.get(User, user_id)+ primary_currency = user.primary_currency if user else get_settings().default_currency+label_expr = _interval_label_expr(interval).label('period')+ # Use amount_primary when available, fall back to amount+ amount_expr = func.coalesce(Transaction.amount_primary, Transaction.amount)+result = await session.execute(select(label_expr,- func.sum(case((Transaction.type == "credit", Transaction.amount), else_=0)),- func.sum(case((Transaction.type == "debit", Transaction.amount), else_=0)),+ func.sum(case((Transaction.type == "credit", amount_expr), else_=0)),+ func.sum(case((Transaction.type == "debit", amount_expr), else_=0)),).join(Account, Transaction.account_id == Account.id).where(@@ -349,6 +387,32 @@ async def get_income_expenses_report(expenses = abs(float(row[2] or 0))data_map[row[0]] = (income, expenses)+ # Add recurring projections for each month in the range (consistent with dashboard)+ from app.services.dashboard_service import _month_range, _get_recurring_projections+ from app.services.fx_rate_service import convert as fx_convert++ cursor = start+ while cursor <= today:+ m_start, m_end = _month_range(cursor)+ projections = await _get_recurring_projections(session, user_id, m_start, m_end)+ for proj in projections:+ # Convert to primary currency+ converted, _ = await fx_convert(+ session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,+ )+ proj_amount = float(converted)+ label = _format_date_label(cursor, interval)+ existing_income, existing_expenses = data_map.get(label, (0.0, 0.0))+ if proj["type"] == "credit":+ data_map[label] = (existing_income + proj_amount, existing_expenses)+ else:+ data_map[label] = (existing_income, existing_expenses + proj_amount)+ # Advance to next month+ if cursor.month == 12:+ cursor = date(cursor.year + 1, 1, 1)+ else:+ cursor = date(cursor.year, cursor.month + 1, 1)+# Generate all expected date points and map to resultspoints = _date_points(start, today, interval)trend: list[ReportDataPoint] = []@@ -411,7 +475,7 @@ async def get_income_expenses_report(meta = ReportMeta(type="income_expenses",series_keys=["income", "expenses"],- currency=currency,+ currency=primary_currency,interval=interval,)@@ -422,7 +486,7 @@ async def get_income_expenses_report(Category.name,Category.color,Transaction.type,- func.sum(Transaction.amount),+ func.sum(amount_expr),).select_from(Transaction).join(Account, Transaction.account_id == Account.id)@@ -437,19 +501,22 @@ async def get_income_expenses_report().group_by(Category.id, Category.name, Category.color, Transaction.type))- composition: list[ReportCompositionItem] = []++ # Collect composition into a mutable map so projections can be added+ # Key: (cat_key, group) -> {label, color, value}+ comp_map: dict[tuple[str, str], dict] = {}for row in cat_result.all():cat_id, cat_name, cat_color, txn_type, total_amount = rowamount = abs(float(total_amount or 0))if amount <= 0:continue- composition.append(ReportCompositionItem(- key=str(cat_id) if cat_id else "uncategorized",- label=cat_name if cat_name else "Uncategorized",- value=round(amount, 2),- color=cat_color if cat_color else "#6B7280",- group="income" if txn_type == "credit" else "expenses",- ))+ cat_key = str(cat_id) if cat_id else "uncategorized"+ group = "income" if txn_type == "credit" else "expenses"+ comp_map[(cat_key, group)] = {+ "label": cat_name if cat_name else "Uncategorized",+ "color": cat_color if cat_color else "#6B7280",+ "value": amount,+ }# Build per-category trend (sparklines) for the full date rangecat_trend_result = await session.execute(@@ -459,7 +526,7 @@ async def get_income_expenses_report(Category.name,Category.color,Transaction.type,- func.sum(Transaction.amount),+ func.sum(amount_expr),).select_from(Transaction).join(Account, Transaction.account_id == Account.id)@@ -497,6 +564,79 @@ async def get_income_expenses_report(cat_trend_map[map_key]["periods"].get(period_label, 0.0) + amount)+ # Add recurring projections to composition and category trend+ cat_cache: dict[str, dict] = {}+ cursor2 = start+ while cursor2 <= today:+ m_start, m_end = _month_range(cursor2)+ projections = await _get_recurring_projections(session, user_id, m_start, m_end)+ period_label = _format_date_label(cursor2, interval)+ for proj in projections:+ cat_id_str = str(proj["category_id"]) if proj["category_id"] else "uncategorized"+ group = "income" if proj["type"] == "credit" else "expenses"++ # Fetch category info if needed+ if cat_id_str != "uncategorized" and cat_id_str not in cat_cache:+ cat_row = await session.execute(+ select(Category.name, Category.color)+ .where(Category.id == proj["category_id"])+ )+ row = cat_row.one_or_none()+ cat_cache[cat_id_str] = {+ "label": row[0] if row else "Uncategorized",+ "color": row[1] if row else "#6B7280",+ }++ info = cat_cache.get(cat_id_str, {"label": "Uncategorized", "color": "#6B7280"})++ # Convert projection amount to primary currency+ converted, _ = await fx_convert(+ session, Decimal(str(proj["amount"])), proj["currency"], primary_currency,+ )+ proj_amount = float(converted)++ # Add to composition map+ comp_key = (cat_id_str, group)+ if comp_key in comp_map:+ comp_map[comp_key]["value"] += proj_amount+ else:+ comp_map[comp_key] = {+ "label": info["label"],+ "color": info["color"],+ "value": proj_amount,+ }++ # Add to category trend map+ if comp_key not in cat_trend_map:+ cat_trend_map[comp_key] = {+ "label": info["label"],+ "color": info["color"],+ "total": 0.0,+ "periods": {},+ }+ cat_trend_map[comp_key]["total"] += proj_amount+ cat_trend_map[comp_key]["periods"][period_label] = (+ cat_trend_map[comp_key]["periods"].get(period_label, 0.0) + proj_amount+ )++ if cursor2.month == 12:+ cursor2 = date(cursor2.year + 1, 1, 1)+ else:+ cursor2 = date(cursor2.year, cursor2.month + 1, 1)++ # Build final composition list from map+ composition: list[ReportCompositionItem] = []+ for (cat_key, group), info in comp_map.items():+ if info["value"] <= 0:+ continue+ composition.append(ReportCompositionItem(+ key=cat_key,+ label=info["label"],+ value=round(info["value"], 2),+ color=info["color"],+ group=group,+ ))+# Build period labels from the same points used by the trendperiod_labels = [_format_date_label(p, interval) for p in points]diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 9389c12d..9178e75a 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -11,6 +11,33 @@ from app.models.account import Accountfrom app.models.bank_connection import BankConnectionfrom app.schemas.transaction import TransactionCreate, TransactionUpdatefrom app.services.rule_service import apply_rules_to_transaction+from app.services.fx_rate_service import stamp_primary_amount+++def _apply_fx_override(transaction, amount, amount_primary=None, fx_rate_used=None):+ """Apply manual FX override values to a transaction.++ - Both provided → use as-is+ - Only amount_primary → derive rate = amount_primary / amount+ - Only fx_rate_used → derive amount_primary = amount * fx_rate_used+ """+ from decimal import Decimal, ROUND_HALF_UP++ amount = Decimal(str(amount))+ if amount_primary is not None and fx_rate_used is not None:+ transaction.amount_primary = Decimal(str(amount_primary))+ transaction.fx_rate_used = Decimal(str(fx_rate_used))+ elif amount_primary is not None:+ transaction.amount_primary = Decimal(str(amount_primary))+ if amount:+ transaction.fx_rate_used = (Decimal(str(amount_primary)) / amount)+ else:+ transaction.fx_rate_used = Decimal("1")+ elif fx_rate_used is not None:+ transaction.fx_rate_used = Decimal(str(fx_rate_used))+ transaction.amount_primary = (amount * Decimal(str(fx_rate_used))).quantize(+ Decimal("0.01"), rounding=ROUND_HALF_UP+ )async def get_transactions(@@ -125,13 +152,16 @@ async def create_transaction(if not account:raise ValueError("Account not found")+ # Resolve currency: explicit value > account currency+ currency = data.currency or account.currency+transaction = Transaction(user_id=user_id,account_id=data.account_id,category_id=data.category_id, # use provided category if givendescription=data.description,amount=data.amount,- currency=data.currency,+ currency=currency,date=data.date,type=data.type,source="manual",@@ -144,6 +174,12 @@ async def create_transaction(if not data.category_id:await apply_rules_to_transaction(session, user_id, transaction)+ # Stamp primary currency amount (manual override or auto)+ if data.amount_primary is not None or data.fx_rate_used is not None:+ _apply_fx_override(transaction, data.amount, data.amount_primary, data.fx_rate_used)+ else:+ await stamp_primary_amount(session, user_id, transaction)+await session.commit()await session.refresh(transaction, ["category"])return transaction@@ -156,9 +192,29 @@ async def update_transaction(if not transaction:return None- for key, value in data.model_dump(exclude_unset=True).items():+ update_data = data.model_dump(exclude_unset=True)++ # Pop FX override fields before generic setattr loop+ override_amount_primary = update_data.pop("amount_primary", None)+ override_fx_rate = update_data.pop("fx_rate_used", None)+ has_fx_override = override_amount_primary is not None or override_fx_rate is not None++ restamp_fields = {"amount", "currency", "date"}+ needs_restamp = bool(restamp_fields & update_data.keys())++ for key, value in update_data.items():setattr(transaction, key, value)+ if has_fx_override:+ _apply_fx_override(+ transaction,+ transaction.amount,+ override_amount_primary,+ override_fx_rate,+ )+ elif needs_restamp:+ await stamp_primary_amount(session, user_id, transaction)+await session.commit()await session.refresh(transaction)return transactiondiff --git a/backend/app/tasks/fx_backfill_tasks.py b/backend/app/tasks/fx_backfill_tasks.pynew file mode 100644index 00000000..8f696084--- /dev/null+++ b/backend/app/tasks/fx_backfill_tasks.py@@ -0,0 +1,126 @@+import asyncio+import logging+from datetime import date+from decimal import Decimal++from sqlalchemy import select, func, distinct+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker++from app.worker import celery_app+from app.core.config import get_settings+from app.models.transaction import Transaction+from app.models.recurring_transaction import RecurringTransaction+from app.models.asset import Asset+from app.models.user import User++logger = logging.getLogger(__name__)+++def _make_session_maker():+ settings = get_settings()+ engine = create_async_engine(settings.database_url)+ return async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)+++async def _backfill_primary_amounts() -> dict:+ """One-time backfill: stamp amount_primary on all rows where it's NULL."""+ from app.services.fx_rate_service import sync_rates, convert++ session_maker = _make_session_maker()+ stats = {"transactions": 0, "recurring": 0, "assets": 0, "rates_synced": 0}++ async with session_maker() as session:+ # 1. Collect all unique (year, month) pairs from transactions needing backfill+ month_result = await session.execute(+ select(+ distinct(func.to_char(Transaction.date, 'YYYY-MM'))+ ).where(Transaction.amount_primary.is_(None))+ )+ months = [row[0] for row in month_result.all()]++ # Sync historical rates for each month+ for month_str in months:+ try:+ year, mon = month_str.split("-")+ # Use last day of month for historical rate+ if int(mon) == 12:+ target = date(int(year) + 1, 1, 1)+ else:+ target = date(int(year), int(mon) + 1, 1)+ from datetime import timedelta+ target = target - timedelta(days=1)+ count = await sync_rates(session, target)+ stats["rates_synced"] += count+ except Exception:+ logger.exception("Failed to sync rates for %s", month_str)++ # 2. Get all users+ users_result = await session.execute(select(User))+ settings = get_settings()+ users = {u.id: (u.preferences or {}).get("currency_display", settings.default_currency) for u in users_result.scalars().all()}++ # 3. Backfill transactions+ tx_result = await session.execute(+ select(Transaction).where(Transaction.amount_primary.is_(None))+ )+ for tx in tx_result.scalars().all():+ primary_currency = users.get(tx.user_id, settings.default_currency)+ try:+ converted, rate = await convert(+ session, Decimal(str(tx.amount)),+ tx.currency, primary_currency, tx.date,+ )+ tx.amount_primary = converted+ tx.fx_rate_used = rate+ stats["transactions"] += 1+ except Exception:+ logger.exception("Failed to backfill tx %s", tx.id)+ await session.commit()++ # 4. Backfill recurring transactions+ rec_result = await session.execute(+ select(RecurringTransaction).where(RecurringTransaction.amount_primary.is_(None))+ )+ for rec in rec_result.scalars().all():+ primary_currency = users.get(rec.user_id, settings.default_currency)+ try:+ converted, rate = await convert(+ session, Decimal(str(rec.amount)),+ rec.currency, primary_currency, rec.start_date,+ )+ rec.amount_primary = converted+ rec.fx_rate_used = rate+ stats["recurring"] += 1+ except Exception:+ logger.exception("Failed to backfill recurring %s", rec.id)+ await session.commit()++ # 5. Backfill assets+ asset_result = await session.execute(+ select(Asset).where(+ Asset.purchase_price.isnot(None),+ Asset.purchase_price_primary.is_(None),+ )+ )+ for asset in asset_result.scalars().all():+ primary_currency = users.get(asset.user_id, settings.default_currency)+ try:+ converted, _ = await convert(+ session, Decimal(str(asset.purchase_price)),+ asset.currency, primary_currency, asset.purchase_date,+ )+ asset.purchase_price_primary = converted+ stats["assets"] += 1+ except Exception:+ logger.exception("Failed to backfill asset %s", asset.id)+ await session.commit()++ return stats+++@celery_app.task(name="app.tasks.fx_backfill_tasks.backfill_primary_amounts")+def backfill_primary_amounts() -> dict:+ """Celery task: one-time backfill of amount_primary for all existing records."""+ stats = asyncio.run(_backfill_primary_amounts())+ logger.info("Backfill complete: %s", stats)+ return statsdiff --git a/backend/app/tasks/fx_rate_tasks.py b/backend/app/tasks/fx_rate_tasks.pynew file mode 100644index 00000000..cab2a62d--- /dev/null+++ b/backend/app/tasks/fx_rate_tasks.py@@ -0,0 +1,80 @@+import asyncio+import logging++from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker++from app.worker import celery_app+from app.core.config import get_settings++logger = logging.getLogger(__name__)+++def _make_session_maker():+ """Create a fresh engine+session for the Celery worker event loop."""+ settings = get_settings()+ engine = create_async_engine(settings.database_url)+ return async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)+++async def _sync_fx_rates() -> int:+ """Fetch latest FX rates and store them."""+ from app.services.fx_rate_service import sync_rates++ session_maker = _make_session_maker()+ async with session_maker() as session:+ count = await sync_rates(session)+ return count+++async def _restamp_recurring_fx() -> int:+ """Re-stamp active recurring transactions with latest FX rates."""+ from sqlalchemy import select++ from app.models.recurring_transaction import RecurringTransaction+ from app.models.user import User+ from app.services.fx_rate_service import stamp_primary_amount++ session_maker = _make_session_maker()+ async with session_maker() as session:+ users = (await session.execute(select(User))).scalars().all()+ count = 0+ for user in users:+ primary = user.primary_currency+ result = await session.execute(+ select(RecurringTransaction).where(+ RecurringTransaction.user_id == user.id,+ RecurringTransaction.is_active == True,+ RecurringTransaction.currency != primary,+ )+ )+ for rec in result.scalars().all():+ await stamp_primary_amount(+ session, user.id, rec, date_field="start_date",+ )+ count += 1+ await session.commit()+ return count+++@celery_app.task(name="app.tasks.fx_rate_tasks.sync_fx_rates")+def sync_fx_rates() -> dict:+ """Celery task: sync latest FX rates from provider. Skips if fx_sync_mode != scheduled."""+ settings = get_settings()+ if settings.fx_sync_mode != "scheduled":+ logger.debug("FX sync skipped (fx_sync_mode=%s)", settings.fx_sync_mode)+ return {"skipped": True, "reason": "fx_sync_mode is not scheduled"}+ count = asyncio.run(_sync_fx_rates())+ logger.info("FX rate sync complete: %d rates synced", count)+ return {"synced": count}+++@celery_app.task(name="app.tasks.fx_rate_tasks.restamp_recurring_fx")+def restamp_recurring_fx() -> dict:+ """Celery task: re-stamp recurring transactions with latest FX rates. Skips if fx_sync_mode != scheduled."""+ settings = get_settings()+ if settings.fx_sync_mode != "scheduled":+ logger.debug("Recurring FX re-stamp skipped (fx_sync_mode=%s)", settings.fx_sync_mode)+ return {"skipped": True, "reason": "fx_sync_mode is not scheduled"}+ count = asyncio.run(_restamp_recurring_fx())+ logger.info("Recurring FX re-stamp complete: %d records updated", count)+ return {"restamped": count}diff --git a/backend/app/worker.py b/backend/app/worker.pyindex 3bcf5888..e467602f 100644--- a/backend/app/worker.py+++ b/backend/app/worker.py@@ -31,6 +31,19 @@ celery_app.conf.beat_schedule = {"task": "app.tasks.asset_tasks.apply_asset_growth_rules","schedule": 60 * 60, # every hour; idempotent (checks last value date)},+ "sync-fx-rates-daily": {+ "task": "app.tasks.fx_rate_tasks.sync_fx_rates",+ "schedule": 60 * 60 * 12, # twice daily (~60 API calls/month)+ },+ "restamp-recurring-fx-daily": {+ "task": "app.tasks.fx_rate_tasks.restamp_recurring_fx",+ "schedule": 60 * 60 * 12, # twice daily, after FX rate sync+ },}-celery_app.conf.include = ["app.tasks.sync_tasks", "app.tasks.recurring_tasks", "app.tasks.asset_tasks"]+celery_app.conf.include = [+ "app.tasks.sync_tasks",+ "app.tasks.recurring_tasks",+ "app.tasks.asset_tasks",+ "app.tasks.fx_rate_tasks",+]diff --git a/backend/tests/test_fx_rates.py b/backend/tests/test_fx_rates.pynew file mode 100644index 00000000..a3f32e78--- /dev/null+++ b/backend/tests/test_fx_rates.py@@ -0,0 +1,1410 @@+"""Tests for FX rate service, API endpoints, and multi-currency integration."""++import uuid+from datetime import date, timedelta+from decimal import Decimal+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.fx_rate import FxRate+from app.models.transaction import Transaction+from app.models.user import User+++# ─── helpers ────────────────────────────────────────────────────────────────+++async def _insert_rate(+ session: AsyncSession,+ quote_currency: str,+ rate: Decimal,+ rate_date: date | None = None,+) -> FxRate:+ """Insert a single FxRate record (base=USD)."""+ fx = FxRate(+ base_currency="USD",+ quote_currency=quote_currency,+ date=rate_date or date.today(),+ rate=rate,+ source="test",+ )+ session.add(fx)+ await session.commit()+ await session.refresh(fx)+ return fx+++async def _make_account(+ session: AsyncSession,+ user: User,+ currency: str = "USD",+ balance: Decimal = Decimal("1000.00"),+ name: str = "Test USD Account",+) -> Account:+ """Create an account in a specific currency."""+ acct = Account(+ user_id=user.id,+ name=name,+ currency=currency,+ balance=balance,+ type="checking",+ )+ session.add(acct)+ await session.commit()+ await session.refresh(acct)+ return acct+++# ─── fixtures ───────────────────────────────────────────────────────────────+++@pytest_asyncio.fixture+async def fx_rates(session: AsyncSession, clean_db) -> list[FxRate]:+ """Insert a realistic set of FX rates for testing."""+ today = date.today()+ rates_data = [+ ("BRL", Decimal("5.0000000000"), today),+ ("EUR", Decimal("0.9200000000"), today),+ ("GBP", Decimal("0.7900000000"), today),+ ]+ rates = []+ for currency, rate, dt in rates_data:+ fx = await _insert_rate(session, currency, rate, dt)+ rates.append(fx)+ return rates+++@pytest_asyncio.fixture+async def historical_fx_rates(session: AsyncSession, clean_db) -> list[FxRate]:+ """Insert historical FX rates for a past month."""+ past_date = date(2025, 6, 15)+ rates_data = [+ ("BRL", Decimal("4.8000000000"), past_date),+ ("EUR", Decimal("0.8800000000"), past_date),+ ]+ rates = []+ for currency, rate, dt in rates_data:+ fx = await _insert_rate(session, currency, rate, dt)+ rates.append(fx)+ return rates+++# ═══════════════════════════════════════════════════════════════════════════+# 1. FX RATE SERVICE — UNIT TESTS+# ═══════════════════════════════════════════════════════════════════════════+++class TestGetRate:+ """Tests for fx_rate_service.get_rate()."""++ @pytest.mark.asyncio+ async def test_same_currency_returns_one(self, session: AsyncSession):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "BRL", "BRL")+ assert rate == Decimal("1")++ @pytest.mark.asyncio+ async def test_same_currency_no_rates_needed(self, session: AsyncSession):+ """Same currency should return 1 even without any FxRate records."""+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "USD", "USD")+ assert rate == Decimal("1")++ @pytest.mark.asyncio+ async def test_usd_to_brl(self, session: AsyncSession, fx_rates):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "USD", "BRL")+ assert rate == Decimal("5.0000000000")++ @pytest.mark.asyncio+ async def test_brl_to_usd(self, session: AsyncSession, fx_rates):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "BRL", "USD")+ # BRL→USD: usd_to_target(USD)=1 / usd_to_source(BRL)=5 = 0.2+ expected = Decimal("1") / Decimal("5.0000000000")+ assert rate == expected++ @pytest.mark.asyncio+ async def test_cross_currency_eur_to_brl(self, session: AsyncSession, fx_rates):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "EUR", "BRL")+ # EUR→BRL: usd_to_BRL / usd_to_EUR = 5.0 / 0.92+ expected = Decimal("5.0000000000") / Decimal("0.9200000000")+ assert rate == expected++ @pytest.mark.asyncio+ async def test_cross_currency_gbp_to_eur(self, session: AsyncSession, fx_rates):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "GBP", "EUR")+ # GBP→EUR: usd_to_EUR / usd_to_GBP = 0.92 / 0.79+ expected = Decimal("0.9200000000") / Decimal("0.7900000000")+ assert rate == expected++ @pytest.mark.asyncio+ async def test_no_rates_returns_one_as_fallback(self, session: AsyncSession):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "JPY", "CHF")+ assert rate == Decimal("1")++ @pytest.mark.asyncio+ async def test_historical_month_uses_closing_rate(+ self, session: AsyncSession, historical_fx_rates+ ):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "USD", "BRL", target_date=date(2025, 6, 20))+ # Should find the June 2025 rate (4.8)+ assert rate == Decimal("4.8000000000")++ @pytest.mark.asyncio+ async def test_historical_cross_currency(+ self, session: AsyncSession, historical_fx_rates+ ):+ from app.services.fx_rate_service import get_rate++ rate = await get_rate(session, "EUR", "BRL", target_date=date(2025, 6, 20))+ expected = Decimal("4.8000000000") / Decimal("0.8800000000")+ assert rate == expected+++class TestConvert:+ """Tests for fx_rate_service.convert()."""++ @pytest.mark.asyncio+ async def test_same_currency(self, session: AsyncSession):+ from app.services.fx_rate_service import convert++ converted, rate = await convert(session, Decimal("100.00"), "BRL", "BRL")+ assert converted == Decimal("100.00")+ assert rate == Decimal("1")++ @pytest.mark.asyncio+ async def test_usd_to_brl(self, session: AsyncSession, fx_rates):+ from app.services.fx_rate_service import convert++ converted, rate = await convert(session, Decimal("100.00"), "USD", "BRL")+ assert converted == Decimal("500.00")+ assert rate == Decimal("5.0000000000")++ @pytest.mark.asyncio+ async def test_brl_to_usd(self, session: AsyncSession, fx_rates):+ from app.services.fx_rate_service import convert++ converted, rate = await convert(session, Decimal("500.00"), "BRL", "USD")+ assert converted == Decimal("100.00")++ @pytest.mark.asyncio+ async def test_cross_currency_rounds_to_two_decimals(+ self, session: AsyncSession, fx_rates+ ):+ from app.services.fx_rate_service import convert++ converted, rate = await convert(session, Decimal("100.00"), "EUR", "BRL")+ # 100 * (5.0 / 0.92) = 543.478... → rounded to 543.48+ assert converted == Decimal("543.48")+++class TestStampPrimaryAmount:+ """Tests for fx_rate_service.stamp_primary_amount()."""++ @pytest.mark.asyncio+ async def test_stamps_transaction_same_currency(+ self, session: AsyncSession, test_user: User, test_account: Account+ ):+ """Transaction in BRL (user primary=BRL) → amount_primary = amount."""+ from app.services.fx_rate_service import stamp_primary_amount++ txn = Transaction(+ user_id=test_user.id,+ account_id=test_account.id,+ description="Test BRL",+ amount=Decimal("100.00"),+ currency="BRL",+ date=date.today(),+ type="debit",+ source="manual",+ )+ session.add(txn)+ await session.flush()++ await stamp_primary_amount(session, test_user.id, txn)+ assert txn.amount_primary == Decimal("100.00")+ assert txn.fx_rate_used == Decimal("1")++ @pytest.mark.asyncio+ async def test_stamps_transaction_different_currency(+ self, session: AsyncSession, test_user: User, test_account: Account, fx_rates+ ):+ """Transaction in USD (user primary=BRL) → converts using FX rate."""+ from app.services.fx_rate_service import stamp_primary_amount++ txn = Transaction(+ user_id=test_user.id,+ account_id=test_account.id,+ description="Test USD",+ amount=Decimal("50.00"),+ currency="USD",+ date=date.today(),+ type="debit",+ source="manual",+ )+ session.add(txn)+ await session.flush()++ await stamp_primary_amount(session, test_user.id, txn)+ assert txn.amount_primary == Decimal("250.00") # 50 * 5.0+ assert txn.fx_rate_used == Decimal("5.0000000000")++ @pytest.mark.asyncio+ async def test_stamps_with_no_user_returns_early(self, session: AsyncSession):+ """Non-existent user → does nothing."""+ from app.services.fx_rate_service import stamp_primary_amount++ class FakeObj:+ amount = Decimal("100")+ amount_primary = None+ fx_rate_used = None+ currency = "USD"+ date = date.today()++ obj = FakeObj()+ await stamp_primary_amount(session, uuid.uuid4(), obj)+ assert obj.amount_primary is None+++# ═══════════════════════════════════════════════════════════════════════════+# 2. FX RATE API ENDPOINT TESTS+# ═══════════════════════════════════════════════════════════════════════════+++class TestFxRatesAPI:+ """Tests for /api/fx-rates endpoints."""++ @pytest.mark.asyncio+ async def test_status_empty(+ self, client: AsyncClient, auth_headers+ ):+ response = await client.get("/api/fx-rates/status", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()+ assert data["last_sync_date"] is None+ assert data["total_rates"] == 0++ @pytest.mark.asyncio+ async def test_status_with_rates(+ self, client: AsyncClient, auth_headers, fx_rates+ ):+ response = await client.get("/api/fx-rates/status", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()+ assert data["last_sync_date"] == date.today().isoformat()+ assert data["total_rates"] == 3++ @pytest.mark.asyncio+ async def test_refresh_calls_sync(+ self, client: AsyncClient, auth_headers+ ):+ mock_sync = AsyncMock(return_value=150)+ with patch("app.api.fx_rates.sync_rates", mock_sync):+ response = await client.post(+ "/api/fx-rates/refresh", headers=auth_headers+ )+ assert response.status_code == 200+ data = response.json()+ assert data["synced"] is True+ assert data["rates_count"] == 150+ assert data["date"] == date.today().isoformat()+ mock_sync.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_status_unauthenticated(self, client: AsyncClient):+ response = await client.get("/api/fx-rates/status")+ assert response.status_code == 401++ @pytest.mark.asyncio+ async def test_refresh_unauthenticated(self, client: AsyncClient):+ response = await client.post("/api/fx-rates/refresh")+ assert response.status_code == 401+++# ═══════════════════════════════════════════════════════════════════════════+# 3. INTEGRATION: TRANSACTION CREATION WITH FX STAMPING+# ═══════════════════════════════════════════════════════════════════════════+++class TestTransactionFxIntegration:+ """Test that creating transactions via API stamps amount_primary."""++ @pytest.mark.asyncio+ async def test_create_transaction_stamps_primary_same_currency(+ self,+ client: AsyncClient,+ auth_headers,+ test_account: Account,+ ):+ """Creating a BRL transaction for a BRL-preference user stamps amount_primary = amount."""+ response = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(test_account.id),+ "description": "Almoço",+ "amount": "32.50",+ "date": date.today().isoformat(),+ "type": "debit",+ },+ )+ assert response.status_code == 201+ data = response.json()+ assert data["amount_primary"] == 32.50+ assert data["fx_rate_used"] == 1.0++ @pytest.mark.asyncio+ async def test_create_transaction_stamps_primary_different_currency(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ """Creating a USD transaction converts to BRL using FX rates."""+ # Create a USD account+ usd_account = await _make_account(session, test_user, currency="USD")++ response = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Amazon purchase",+ "amount": "20.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ },+ )+ assert response.status_code == 201+ data = response.json()+ # USD→BRL at rate 5.0 → 20 * 5 = 100+ assert data["amount_primary"] == 100.00+ assert data["fx_rate_used"] is not None+++# ═══════════════════════════════════════════════════════════════════════════+# 4. DASHBOARD MULTI-CURRENCY TOTALS+# ═══════════════════════════════════════════════════════════════════════════+++class TestDashboardMultiCurrency:+ """Test that dashboard consolidates multi-currency balances."""++ @pytest.mark.asyncio+ async def test_dashboard_summary_with_multi_currency(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ fx_rates,+ ):+ """total_balance_primary sums all currencies into primary (BRL)."""+ from app.services.dashboard_service import get_summary++ # test_account is BRL (manual, balance from transactions)+ # Create a USD account with an opening balance transaction+ usd_account = await _make_account(+ session, test_user, currency="USD", balance=Decimal("200.00")+ )+ # Manual accounts compute balance from transactions, so add one+ txn = Transaction(+ user_id=test_user.id,+ account_id=usd_account.id,+ description="Opening balance",+ amount=Decimal("200.00"),+ currency="USD",+ date=date.today(),+ type="credit",+ source="opening_balance",+ )+ session.add(txn)+ await session.commit()++ summary = await get_summary(session, test_user.id)++ assert summary.primary_currency == "BRL"+ # USD balance: 200 * 5.0 = 1000 in BRL+ # BRL balance from test_account transactions (may be 0 if no txns)+ # Key assertion: USD portion is converted correctly+ assert summary.total_balance_primary >= 1000.0+ assert "USD" in summary.total_balance++ @pytest.mark.asyncio+ async def test_dashboard_summary_single_currency(+ self,+ client: AsyncClient,+ auth_headers,+ test_account: Account,+ ):+ """Single-currency dashboard still returns primary fields."""+ response = await client.get("/api/dashboard/summary", headers=auth_headers)+ assert response.status_code == 200+ data = response.json()++ assert data["primary_currency"] == "BRL"+ assert "total_balance_primary" in data+ # Single BRL account → primary equals the BRL total+ assert data["total_balance_primary"] == pytest.approx(1500.00, abs=1.0)+++# ═══════════════════════════════════════════════════════════════════════════+# 5. OPEN EXCHANGE RATES PROVIDER+# ═══════════════════════════════════════════════════════════════════════════+++class TestOpenExchangeRatesProvider:+ """Tests for the OER provider (mocked HTTP calls)."""++ @pytest.mark.asyncio+ async def test_fetch_latest(self):+ from app.providers.openexchangerates import OpenExchangeRatesProvider++ provider = OpenExchangeRatesProvider()+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "base": "USD",+ "rates": {"BRL": 5.1, "EUR": 0.93},+ }+ mock_response.raise_for_status = MagicMock()++ mock_client = MagicMock()+ mock_client.get = AsyncMock(return_value=mock_response)+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=False)++ with patch("app.providers.openexchangerates.get_settings") as mock_settings, \+ patch("app.providers.openexchangerates.httpx.AsyncClient", return_value=mock_client):+ mock_settings.return_value.openexchangerates_app_id = "test-key"+ rates = await provider.fetch_latest()++ assert "BRL" in rates+ assert rates["BRL"] == Decimal("5.1")+ assert "EUR" in rates+ assert rates["EUR"] == Decimal("0.93")++ @pytest.mark.asyncio+ async def test_fetch_latest_no_api_key_raises(self):+ from app.providers.openexchangerates import OpenExchangeRatesProvider++ provider = OpenExchangeRatesProvider()+ with patch("app.providers.openexchangerates.get_settings") as mock_settings:+ mock_settings.return_value.openexchangerates_app_id = ""+ with pytest.raises(ValueError, match="not configured"):+ await provider.fetch_latest()++ @pytest.mark.asyncio+ async def test_fetch_historical(self):+ from app.providers.openexchangerates import OpenExchangeRatesProvider++ provider = OpenExchangeRatesProvider()+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "base": "USD",+ "rates": {"BRL": 4.9, "GBP": 0.78},+ }+ mock_response.raise_for_status = MagicMock()++ mock_client = MagicMock()+ mock_client.get = AsyncMock(return_value=mock_response)+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)+ mock_client.__aexit__ = AsyncMock(return_value=False)++ with patch("app.providers.openexchangerates.get_settings") as mock_settings, \+ patch("app.providers.openexchangerates.httpx.AsyncClient", return_value=mock_client):+ mock_settings.return_value.openexchangerates_app_id = "test-key"+ rates = await provider.fetch_historical(date(2025, 6, 15))++ assert rates["BRL"] == Decimal("4.9")+ assert rates["GBP"] == Decimal("0.78")+ # Verify the correct URL was called+ call_args = mock_client.get.call_args+ assert "2025-06-15" in call_args[0][0]+++# ═══════════════════════════════════════════════════════════════════════════+# 6. SYNC RATES (mocked provider — pg_insert incompatible with SQLite)+# ═══════════════════════════════════════════════════════════════════════════+++class TestSyncRates:+ """Tests for fx_rate_service.sync_rates() with mocked provider."""++ @pytest.mark.asyncio+ async def test_sync_rates_calls_provider_latest(self):+ from app.services.fx_rate_service import sync_rates++ mock_provider = MagicMock()+ mock_provider.name = "test_provider"+ mock_provider.fetch_latest = AsyncMock(return_value={+ "BRL": Decimal("5.0"),+ "EUR": Decimal("0.92"),+ })++ mock_session = AsyncMock()+ mock_session.execute = AsyncMock()+ mock_session.commit = AsyncMock()++ with patch("app.services.fx_rate_service._provider", mock_provider):+ count = await sync_rates(mock_session, date.today())++ mock_provider.fetch_latest.assert_awaited_once()+ assert count == 2+ assert mock_session.execute.await_count == 2+ mock_session.commit.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_sync_rates_calls_provider_historical(self):+ from app.services.fx_rate_service import sync_rates++ target = date(2025, 6, 15)+ mock_provider = MagicMock()+ mock_provider.name = "test_provider"+ mock_provider.fetch_historical = AsyncMock(return_value={+ "BRL": Decimal("4.8"),+ })++ mock_session = AsyncMock()+ mock_session.execute = AsyncMock()+ mock_session.commit = AsyncMock()++ with patch("app.services.fx_rate_service._provider", mock_provider):+ count = await sync_rates(mock_session, target)++ mock_provider.fetch_historical.assert_awaited_once_with(target)+ assert count == 1++ @pytest.mark.asyncio+ async def test_sync_rates_defaults_to_today(self):+ from app.services.fx_rate_service import sync_rates++ mock_provider = MagicMock()+ mock_provider.name = "test_provider"+ mock_provider.fetch_latest = AsyncMock(return_value={"BRL": Decimal("5.0")})++ mock_session = AsyncMock()+ mock_session.execute = AsyncMock()+ mock_session.commit = AsyncMock()++ with patch("app.services.fx_rate_service._provider", mock_provider):+ await sync_rates(mock_session)++ # Should call fetch_latest (not fetch_historical) when no date given+ mock_provider.fetch_latest.assert_awaited_once()+++# ═══════════════════════════════════════════════════════════════════════════+# 7. STAMP_PRIMARY_AMOUNT EDGE CASES+# ═══════════════════════════════════════════════════════════════════════════+++class TestStampEdgeCases:+ """Edge cases for stamp_primary_amount."""++ @pytest.mark.asyncio+ async def test_null_amount_returns_early(+ self, session: AsyncSession, test_user: User+ ):+ """Object with None amount → does nothing."""+ from app.services.fx_rate_service import stamp_primary_amount++ class FakeObj:+ amount = None+ amount_primary = None+ fx_rate_used = None+ currency = "USD"+ date = date.today()++ obj = FakeObj()+ await stamp_primary_amount(session, test_user.id, obj)+ assert obj.amount_primary is None++ @pytest.mark.asyncio+ async def test_custom_field_names(+ self, session: AsyncSession, test_user: User, test_account: Account, fx_rates+ ):+ """stamp_primary_amount works with custom field names (e.g. for assets)."""+ from app.services.fx_rate_service import stamp_primary_amount++ class FakeAsset:+ purchase_price = Decimal("100.00")+ purchase_price_primary = None+ currency = "USD"+ purchase_date = date.today()++ obj = FakeAsset()+ await stamp_primary_amount(+ session, test_user.id, obj,+ amount_field="purchase_price",+ primary_field="purchase_price_primary",+ rate_field="fx_rate_used",+ date_field="purchase_date",+ )+ assert obj.purchase_price_primary == Decimal("500.00")++ @pytest.mark.asyncio+ async def test_missing_currency_field_defaults_brl(+ self, session: AsyncSession, test_user: User+ ):+ """Object without currency field defaults to BRL (user primary=BRL → rate 1)."""+ from app.services.fx_rate_service import stamp_primary_amount++ class FakeObj:+ amount = Decimal("100.00")+ amount_primary = None+ fx_rate_used = None+ date = date.today()+ # No 'currency' attribute++ obj = FakeObj()+ await stamp_primary_amount(session, test_user.id, obj)+ assert obj.amount_primary == Decimal("100.00")+ assert obj.fx_rate_used == Decimal("1")+++# ═══════════════════════════════════════════════════════════════════════════+# 8. TRANSACTION UPDATE RE-STAMPING+# ═══════════════════════════════════════════════════════════════════════════+++class TestTransactionUpdateRestamp:+ """Test that updating a transaction re-stamps amount_primary when needed."""++ @pytest.mark.asyncio+ async def test_update_amount_restamps(+ self, client: AsyncClient, auth_headers, test_account: Account+ ):+ """Changing amount triggers re-stamp."""+ # Create a BRL transaction+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(test_account.id),+ "description": "Test",+ "amount": "50.00",+ "date": date.today().isoformat(),+ "type": "debit",+ },+ )+ txn_id = resp.json()["id"]+ assert resp.json()["amount_primary"] == 50.0++ # Update the amount+ resp2 = await client.patch(+ f"/api/transactions/{txn_id}",+ headers=auth_headers,+ json={"amount": "75.00"},+ )+ assert resp2.status_code == 200+ assert resp2.json()["amount_primary"] == 75.0++ @pytest.mark.asyncio+ async def test_update_category_does_not_restamp(+ self, client: AsyncClient, auth_headers, test_account: Account, test_categories+ ):+ """Changing only category does NOT trigger re-stamp."""+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(test_account.id),+ "description": "Test",+ "amount": "50.00",+ "date": date.today().isoformat(),+ "type": "debit",+ },+ )+ txn_id = resp.json()["id"]+ original_rate = resp.json()["fx_rate_used"]++ # Update only category — should not re-stamp+ resp2 = await client.patch(+ f"/api/transactions/{txn_id}",+ headers=auth_headers,+ json={"category_id": str(test_categories[0].id)},+ )+ assert resp2.status_code == 200+ assert resp2.json()["fx_rate_used"] == original_rate++ @pytest.mark.asyncio+ async def test_update_currency_restamps(+ self,+ client: AsyncClient,+ auth_headers,+ test_account: Account,+ fx_rates,+ ):+ """Changing currency triggers re-stamp with new FX rate."""+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(test_account.id),+ "description": "Test",+ "amount": "100.00",+ "date": date.today().isoformat(),+ "type": "debit",+ },+ )+ txn_id = resp.json()["id"]+ assert resp.json()["amount_primary"] == 100.0 # BRL→BRL = 1:1++ # Change currency to USD — should re-stamp with USD→BRL rate+ resp2 = await client.patch(+ f"/api/transactions/{txn_id}",+ headers=auth_headers,+ json={"currency": "USD"},+ )+ assert resp2.status_code == 200+ # 100 USD * 5.0 = 500 BRL+ assert resp2.json()["amount_primary"] == 500.0+++# ═══════════════════════════════════════════════════════════════════════════+# 9. REPORT SERVICE — NET WORTH WITH MULTI-CURRENCY+# ═══════════════════════════════════════════════════════════════════════════+++class TestReportNetWorthMultiCurrency:+ """Test that net worth report converts multi-currency accounts."""++ @pytest.mark.asyncio+ async def test_net_worth_at_converts_currencies(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ fx_rates,+ ):+ """_net_worth_at converts each account balance to primary currency."""+ from app.services.report_service import _net_worth_at++ # Create USD account with a transaction+ usd_account = await _make_account(+ session, test_user, currency="USD", balance=Decimal("300.00")+ )+ txn = Transaction(+ user_id=test_user.id,+ account_id=usd_account.id,+ description="Opening",+ amount=Decimal("300.00"),+ currency="USD",+ date=date.today(),+ type="credit",+ source="opening_balance",+ )+ session.add(txn)+ await session.commit()++ dp = await _net_worth_at(session, test_user.id, date.today(), "BRL")++ # USD: 300 * 5.0 = 1500 BRL+ # Total should include the USD portion+ assert dp.value >= 1500.0+ assert dp.breakdowns["accounts"] >= 1500.0++ @pytest.mark.asyncio+ async def test_net_worth_report_uses_user_primary_currency(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ ):+ """get_net_worth_report reads the user's currency preference."""+ from app.services.report_service import get_net_worth_report++ report = await get_net_worth_report(session, test_user.id, months=1)++ # test_user has currency_display=BRL+ assert report is not None+ assert len(report.trend) >= 1+++# ═══════════════════════════════════════════════════════════════════════════+# 10. RECURRING TRANSACTION STAMPING+# ═══════════════════════════════════════════════════════════════════════════+++class TestRecurringTransactionStamping:+ """Test that recurring transactions get FX stamping."""++ @pytest.mark.asyncio+ async def test_create_recurring_stamps_primary(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ fx_rates,+ ):+ """Creating a recurring transaction in USD stamps amount_primary in BRL."""+ from app.schemas.recurring_transaction import RecurringTransactionCreate+ from app.services.recurring_transaction_service import create_recurring_transaction++ data = RecurringTransactionCreate(+ description="Monthly subscription",+ amount=Decimal("10.00"),+ type="debit",+ frequency="monthly",+ start_date=date.today(),+ account_id=test_account.id,+ currency="USD",+ )+ rec = await create_recurring_transaction(session, test_user.id, data)++ assert rec.amount_primary is not None+ # USD→BRL: 10 * 5.0 = 50+ assert rec.amount_primary == Decimal("50.00")+ assert rec.fx_rate_used == Decimal("5.0000000000")++ @pytest.mark.asyncio+ async def test_create_recurring_same_currency(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ ):+ """Recurring in BRL (user primary=BRL) → rate = 1."""+ from app.schemas.recurring_transaction import RecurringTransactionCreate+ from app.services.recurring_transaction_service import create_recurring_transaction++ data = RecurringTransactionCreate(+ description="Rent",+ amount=Decimal("2000.00"),+ type="debit",+ frequency="monthly",+ start_date=date.today(),+ account_id=test_account.id,+ currency="BRL",+ )+ rec = await create_recurring_transaction(session, test_user.id, data)++ assert rec.amount_primary == Decimal("2000.00")+ assert rec.fx_rate_used == Decimal("1")++ @pytest.mark.asyncio+ async def test_generate_pending_stamps_transactions(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ ):+ """generate_pending creates transactions with amount_primary stamped."""+ from sqlalchemy import select as sa_select++ from app.schemas.recurring_transaction import RecurringTransactionCreate+ from app.services.recurring_transaction_service import (+ create_recurring_transaction,+ generate_pending,+ )++ start = date.today() - timedelta(days=35)+ data = RecurringTransactionCreate(+ description="Weekly sub",+ amount=Decimal("15.00"),+ type="debit",+ frequency="weekly",+ start_date=start,+ account_id=test_account.id,+ currency="BRL",+ )+ await create_recurring_transaction(session, test_user.id, data)++ count = await generate_pending(session, test_user.id, up_to=date.today())+ assert count >= 1++ # Verify generated transactions have amount_primary stamped+ result = await session.execute(+ sa_select(Transaction).where(+ Transaction.user_id == test_user.id,+ Transaction.source == "recurring",+ )+ )+ txns = result.scalars().all()+ assert len(txns) >= 1+ for txn in txns:+ assert txn.amount_primary is not None+ assert txn.amount_primary == Decimal("15.00")+++# ═══════════════════════════════════════════════════════════════════════════+# 11. BACKFILL TASK (core logic, mocked session)+# ═══════════════════════════════════════════════════════════════════════════+++class TestBackfillTask:+ """Test the backfill logic with mocked infrastructure."""++ @pytest.mark.asyncio+ async def test_backfill_stamps_null_transactions(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ fx_rates,+ ):+ """Transactions with amount_primary=NULL get backfilled."""+ from app.services.fx_rate_service import convert++ # Create transaction with NULL amount_primary (simulating pre-migration data)+ txn = Transaction(+ user_id=test_user.id,+ account_id=test_account.id,+ description="Old transaction",+ amount=Decimal("100.00"),+ currency="USD",+ date=date.today(),+ type="debit",+ source="manual",+ amount_primary=None,+ fx_rate_used=None,+ )+ session.add(txn)+ await session.commit()+ await session.refresh(txn)++ assert txn.amount_primary is None++ # Simulate what backfill does: convert and stamp+ primary_currency = (test_user.preferences or {}).get("currency_display", "BRL")+ converted, rate = await convert(+ session, Decimal(str(txn.amount)),+ txn.currency, primary_currency, txn.date,+ )+ txn.amount_primary = converted+ txn.fx_rate_used = rate+ await session.commit()++ assert txn.amount_primary == Decimal("500.00") # 100 USD * 5.0+ assert txn.fx_rate_used == Decimal("5.0000000000")++ @pytest.mark.asyncio+ async def test_backfill_skips_already_stamped(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ ):+ """Transactions with existing amount_primary should not be re-stamped by backfill query."""+ from sqlalchemy import select++ txn = Transaction(+ user_id=test_user.id,+ account_id=test_account.id,+ description="Already stamped",+ amount=Decimal("50.00"),+ currency="BRL",+ date=date.today(),+ type="debit",+ source="manual",+ amount_primary=Decimal("50.00"),+ fx_rate_used=Decimal("1"),+ )+ session.add(txn)+ await session.commit()++ # The backfill query filters amount_primary IS NULL+ result = await session.execute(+ select(Transaction).where(+ Transaction.amount_primary.is_(None),+ Transaction.user_id == test_user.id,+ )+ )+ null_txns = result.scalars().all()++ # Our stamped transaction should not appear+ assert txn.id not in [t.id for t in null_txns]+++# ═══════════════════════════════════════════════════════════════════════════+# 12. RECURRING FX RE-STAMP+# ═══════════════════════════════════════════════════════════════════════════+++class TestRecurringFxRestamp:+ """Test that recurring transactions get re-stamped with latest FX rates."""++ @pytest.mark.asyncio+ async def test_restamp_updates_with_new_rate(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ fx_rates,+ ):+ """Re-stamping a USD recurring transaction updates amount_primary with latest rate."""+ from app.schemas.recurring_transaction import RecurringTransactionCreate+ from app.services.recurring_transaction_service import create_recurring_transaction+ from app.services.fx_rate_service import stamp_primary_amount++ data = RecurringTransactionCreate(+ description="USD subscription",+ amount=Decimal("10.00"),+ type="debit",+ frequency="monthly",+ start_date=date.today(),+ account_id=test_account.id,+ currency="USD",+ )+ rec = await create_recurring_transaction(session, test_user.id, data)+ assert rec.amount_primary == Decimal("50.00") # 10 * 5.0++ # Simulate rate change: update the USD rate to 5.5+ from sqlalchemy import update as sa_update++ await session.execute(+ sa_update(FxRate).where(+ FxRate.quote_currency == "BRL",+ ).values(rate=Decimal("5.5000000000"))+ )+ await session.commit()++ # Re-stamp+ await stamp_primary_amount(session, test_user.id, rec, date_field="start_date")+ await session.commit()++ assert rec.amount_primary == Decimal("55.00") # 10 * 5.5+ assert rec.fx_rate_used == Decimal("5.5000000000")++ @pytest.mark.asyncio+ async def test_restamp_skips_same_currency(+ self,+ session: AsyncSession,+ test_user: User,+ test_account: Account,+ ):+ """BRL recurring transaction is not affected by re-stamp (rate stays 1)."""+ from app.schemas.recurring_transaction import RecurringTransactionCreate+ from app.services.recurring_transaction_service import create_recurring_transaction++ data = RecurringTransactionCreate(+ description="BRL rent",+ amount=Decimal("2000.00"),+ type="debit",+ frequency="monthly",+ start_date=date.today(),+ account_id=test_account.id,+ currency="BRL",+ )+ rec = await create_recurring_transaction(session, test_user.id, data)+ assert rec.amount_primary == Decimal("2000.00")+ assert rec.fx_rate_used == Decimal("1")+++# ═══════════════════════════════════════════════════════════════════════════+# 13. MANUAL FX OVERRIDE+# ═══════════════════════════════════════════════════════════════════════════+++class TestManualFxOverride:+ """Test manual FX override on create and update."""++ @pytest.mark.asyncio+ async def test_create_with_both_overrides(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ """Providing both amount_primary and fx_rate_used uses exact values."""+ usd_account = await _make_account(session, test_user, currency="USD")+ response = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Manual FX both",+ "amount": "100.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ "amount_primary": "520.00",+ "fx_rate_used": "5.2",+ },+ )+ assert response.status_code == 201+ data = response.json()+ assert data["amount_primary"] == 520.0+ assert data["fx_rate_used"] == 5.2++ @pytest.mark.asyncio+ async def test_create_with_only_fx_rate(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ """Providing only fx_rate_used derives amount_primary."""+ usd_account = await _make_account(session, test_user, currency="USD")+ response = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Manual FX rate only",+ "amount": "50.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ "fx_rate_used": "5.3",+ },+ )+ assert response.status_code == 201+ data = response.json()+ # 50 * 5.3 = 265.00+ assert data["amount_primary"] == 265.0+ assert data["fx_rate_used"] == 5.3++ @pytest.mark.asyncio+ async def test_create_with_only_amount_primary(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ """Providing only amount_primary derives fx_rate_used."""+ usd_account = await _make_account(session, test_user, currency="USD")+ response = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Manual FX amount only",+ "amount": "80.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ "amount_primary": "400.00",+ },+ )+ assert response.status_code == 201+ data = response.json()+ assert data["amount_primary"] == 400.0+ # 400 / 80 = 5.0+ assert data["fx_rate_used"] == 5.0++ @pytest.mark.asyncio+ async def test_update_with_fx_override_skips_auto_stamp(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ """Update with FX override uses manual values, not auto-stamp."""+ usd_account = await _make_account(session, test_user, currency="USD")+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Will override",+ "amount": "100.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ },+ )+ txn_id = resp.json()["id"]++ # Update with manual FX override+ resp2 = await client.patch(+ f"/api/transactions/{txn_id}",+ headers=auth_headers,+ json={+ "amount_primary": "550.00",+ "fx_rate_used": "5.5",+ },+ )+ assert resp2.status_code == 200+ data = resp2.json()+ assert data["amount_primary"] == 550.0+ assert data["fx_rate_used"] == 5.5++ @pytest.mark.asyncio+ async def test_update_without_fx_override_auto_stamps(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ """Update without FX override still auto-stamps (backward compat)."""+ usd_account = await _make_account(session, test_user, currency="USD")+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Auto stamp test",+ "amount": "100.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ },+ )+ txn_id = resp.json()["id"]++ # Update amount without FX override → should auto re-stamp+ resp2 = await client.patch(+ f"/api/transactions/{txn_id}",+ headers=auth_headers,+ json={"amount": "200.00"},+ )+ assert resp2.status_code == 200+ data = resp2.json()+ # 200 * 5.0 = 1000+ assert data["amount_primary"] == 1000.0+++class TestFxFallbackFlag:+ """Test that fx_fallback is set correctly in API responses."""++ @pytest.mark.asyncio+ async def test_foreign_currency_no_rates_returns_fx_fallback_true(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ ):+ """Cross-currency transaction with no FX rates → fx_fallback=True."""+ usd_account = await _make_account(session, test_user, currency="USD")++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "No FX rate available",+ "amount": "50.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ },+ )+ assert resp.status_code == 201+ data = resp.json()+ # No FX rates in DB → falls back to 1:1+ assert data["fx_rate_used"] == 1.0+ assert data["fx_fallback"] is True++ @pytest.mark.asyncio+ async def test_foreign_currency_with_rates_returns_fx_fallback_false(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ fx_rates,+ ):+ """Cross-currency transaction with valid FX rates → fx_fallback=False."""+ usd_account = await _make_account(session, test_user, currency="USD")++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Has FX rate",+ "amount": "20.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ },+ )+ assert resp.status_code == 201+ data = resp.json()+ assert data["fx_rate_used"] == 5.0+ assert data["fx_fallback"] is False++ @pytest.mark.asyncio+ async def test_same_currency_returns_fx_fallback_false(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ ):+ """Same-currency transaction → fx_fallback=False (not applicable)."""+ brl_account = await _make_account(+ session, test_user, currency="BRL", name="BRL Account",+ )++ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(brl_account.id),+ "description": "Same currency",+ "amount": "100.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "BRL",+ },+ )+ assert resp.status_code == 201+ data = resp.json()+ assert data["fx_fallback"] is False++ @pytest.mark.asyncio+ async def test_list_endpoint_tags_fx_fallback(+ self,+ client: AsyncClient,+ auth_headers,+ test_user: User,+ session: AsyncSession,+ ):+ """GET /api/transactions tags fx_fallback on listed items."""+ usd_account = await _make_account(session, test_user, currency="USD")++ # Create a transaction that will fall back to 1:1 (no rates)+ resp = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": str(usd_account.id),+ "description": "Fallback in list",+ "amount": "10.00",+ "date": date.today().isoformat(),+ "type": "debit",+ "currency": "USD",+ },+ )+ assert resp.status_code == 201++ # List transactions+ resp2 = await client.get("/api/transactions", headers=auth_headers)+ assert resp2.status_code == 200+ items = resp2.json()["items"]+ fallback_items = [i for i in items if i["description"] == "Fallback in list"]+ assert len(fallback_items) == 1+ assert fallback_items[0]["fx_fallback"] is Truediff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.pyindex 5376758e..e63b3a11 100644--- a/backend/tests/test_import_service.py+++ b/backend/tests/test_import_service.py@@ -1,9 +1,15 @@+import uuidfrom datetime import datefrom decimal import Decimal+from unittest.mock import AsyncMock, patchimport pytest+from sqlalchemy.ext.asyncio import AsyncSession-from app.services.import_service import parse_csv, parse_ofx, parse_qif, parse_camt+from app.models.account import Account+from app.models.fx_rate import FxRate+from app.models.user import User+from app.services.import_service import parse_csv, parse_ofx, parse_qif, parse_camt, import_transactionsclass TestParseCsv:@@ -516,3 +522,361 @@ class TestParseOfx:assert transactions[1].external_id == "FITID_002"assert transactions[0].amount == transactions[1].amountassert transactions[0].description == transactions[1].description+++# ═══════════════════════════════════════════════════════════════════════════+# MULTI-CURRENCY PARSING TESTS+# ═══════════════════════════════════════════════════════════════════════════+++class TestCsvCurrencyParsing:+ """Tests for CSV parsing with currency and fx_rate columns."""++ def test_parse_csv_with_currency_column(self):+ """CSV with a 'currency' column should populate the currency field."""+ csv_content = (+ "date,description,amount,currency\n"+ "2026-01-10,Amazon Purchase,-120.50,USD\n"+ "2026-01-11,Local Store,-45.00,BRL\n"+ "2026-01-12,Euro Payment,-80.00,EUR\n"+ )+ transactions = parse_csv(csv_content.encode("utf-8"))++ assert len(transactions) == 3+ assert transactions[0].currency == "USD"+ assert transactions[1].currency == "BRL"+ assert transactions[2].currency == "EUR"++ def test_parse_csv_with_moeda_column(self):+ """CSV with Portuguese 'moeda' column should detect currency."""+ csv_content = (+ "data,descricao,valor,moeda\n"+ "10/01/2026,AMAZON,-120.50,USD\n"+ "11/01/2026,PIX RECEBIDO,500.00,BRL\n"+ )+ transactions = parse_csv(csv_content.encode("utf-8"))++ assert len(transactions) == 2+ assert transactions[0].currency == "USD"+ assert transactions[1].currency == "BRL"++ def test_parse_csv_with_fx_rate_column(self):+ """CSV with 'fx_rate' column should populate the fx_rate field."""+ csv_content = (+ "date,description,amount,currency,fx_rate\n"+ "2026-01-10,Amazon Purchase,-120.50,USD,5.25\n"+ "2026-01-11,Local Store,-45.00,BRL,\n"+ )+ transactions = parse_csv(csv_content.encode("utf-8"))++ assert len(transactions) == 2+ assert transactions[0].currency == "USD"+ assert transactions[0].fx_rate == Decimal("5.25")+ assert transactions[1].currency == "BRL"+ assert transactions[1].fx_rate is None++ def test_parse_csv_with_taxa_cambio_column(self):+ """CSV with Portuguese 'taxa_cambio' column should detect fx_rate."""+ csv_content = (+ "data,descricao,valor,moeda,taxa_cambio\n"+ '10/01/2026,COMPRA EXTERIOR,-200.00,USD,"5,30"\n'+ )+ transactions = parse_csv(csv_content.encode("utf-8"))++ assert len(transactions) == 1+ assert transactions[0].fx_rate == Decimal("5.30")++ def test_parse_csv_without_currency_column(self):+ """CSV without currency column should leave currency as None."""+ csv_content = (+ "date,description,amount\n"+ "2026-01-10,GROCERY,-50.00\n"+ )+ transactions = parse_csv(csv_content.encode("utf-8"))++ assert len(transactions) == 1+ assert transactions[0].currency is None+ assert transactions[0].fx_rate is None+++class TestCamtCurrencyParsing:+ """Tests for CAMT parsing with currency extraction."""++ def _make_camt_xml(self, entries_xml: str) -> bytes:+ return (+ '<?xml version="1.0" encoding="UTF-8"?>'+ '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.02">'+ '<BkToCstmrStmt><Stmt>'+ f'{entries_xml}'+ '</Stmt></BkToCstmrStmt>'+ '</Document>'+ ).encode('utf-8')++ def test_parse_camt_extracts_currency(self):+ """CAMT parser should extract currency from Ccy attribute on Amt element."""+ entries = (+ '<Ntry>'+ '<Amt Ccy="USD">500.00</Amt>'+ '<CdtDbtInd>DBIT</CdtDbtInd>'+ '<BookgDt><Dt>2026-01-15</Dt></BookgDt>'+ '<NtryDtls><TxDtls><RmtInf><Ustrd>Wire Transfer</Ustrd></RmtInf></TxDtls></NtryDtls>'+ '</Ntry>'+ '<Ntry>'+ '<Amt Ccy="EUR">300.00</Amt>'+ '<CdtDbtInd>CRDT</CdtDbtInd>'+ '<BookgDt><Dt>2026-01-16</Dt></BookgDt>'+ '<NtryDtls><TxDtls><RmtInf><Ustrd>Euro Payment</Ustrd></RmtInf></TxDtls></NtryDtls>'+ '</Ntry>'+ )+ transactions = parse_camt(self._make_camt_xml(entries))++ assert len(transactions) == 2+ assert transactions[0].currency == "USD"+ assert transactions[1].currency == "EUR"++ def test_parse_camt_no_ccy_attribute(self):+ """CAMT entries without Ccy attribute should have currency=None."""+ entries = (+ '<Ntry>'+ '<Amt>100.00</Amt>'+ '<CdtDbtInd>DBIT</CdtDbtInd>'+ '<BookgDt><Dt>2026-01-15</Dt></BookgDt>'+ '<NtryDtls><TxDtls><RmtInf><Ustrd>Test</Ustrd></RmtInf></TxDtls></NtryDtls>'+ '</Ntry>'+ )+ transactions = parse_camt(self._make_camt_xml(entries))++ assert len(transactions) == 1+ assert transactions[0].currency is None+++# ═══════════════════════════════════════════════════════════════════════════+# IMPORT TRANSACTIONS WITH FX — INTEGRATION TESTS (mocked FX provider)+# ═══════════════════════════════════════════════════════════════════════════+++async def _insert_fx_rate(session: AsyncSession, quote_currency: str, rate: Decimal, rate_date: date) -> None:+ """Insert a test FX rate (base=USD)."""+ fx = FxRate(base_currency="USD", quote_currency=quote_currency, date=rate_date, rate=rate, source="test")+ session.add(fx)+ await session.commit()+++class TestImportTransactionsFx:+ """Tests for import_transactions with multi-currency and FX rate handling.++ All tests mock the external OER provider to avoid real API calls.+ """++ @pytest.mark.asyncio+ @patch("app.services.fx_rate_service._provider")+ async def test_import_with_fx_rate_from_csv(self, mock_provider, session: AsyncSession, test_user: User, test_account: Account):+ """When CSV provides fx_rate, it should be used directly without calling FX service."""+ from app.schemas.transaction import TransactionBase+ from app.models.transaction import Transaction+ from sqlalchemy import select++ txns = [+ TransactionBase(+ description="Amazon US",+ amount=Decimal("100.00"),+ date=date(2026, 1, 15),+ type="debit",+ currency="USD",+ fx_rate=Decimal("5.25"),+ ),+ ]++ imported, skipped, _ = await import_transactions(+ session, test_user.id, test_account.id, txns, "csv",+ )++ assert imported == 1+ assert skipped == 0++ # Verify the transaction was saved with correct FX fields+ result = await session.execute(+ select(Transaction).where(Transaction.description == "Amazon US")+ )+ tx = result.scalar_one()+ assert tx.currency == "USD"+ assert tx.fx_rate_used == Decimal("5.25")+ assert tx.amount_primary == Decimal("525.00") # 100 * 5.25++ # Provider should NOT have been called since fx_rate was provided+ mock_provider.fetch_latest.assert_not_called()+ mock_provider.fetch_historical.assert_not_called()++ @pytest.mark.asyncio+ @patch("app.services.fx_rate_service._provider")+ async def test_import_foreign_currency_without_fx_rate_auto_converts(+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ ):+ """When no fx_rate is provided, stamp_primary_amount should auto-convert using DB rates."""+ from app.schemas.transaction import TransactionBase+ from app.models.transaction import Transaction+ from sqlalchemy import select++ # Insert known FX rates so stamp_primary_amount can convert+ await _insert_fx_rate(session, "BRL", Decimal("5.0000"), date(2026, 1, 15))+ await _insert_fx_rate(session, "EUR", Decimal("0.9200"), date(2026, 1, 15))++ # Mock the provider to prevent real API calls during on-demand sync+ mock_provider.fetch_latest = AsyncMock(return_value={})+ mock_provider.fetch_historical = AsyncMock(return_value={})++ txns = [+ TransactionBase(+ description="Euro Store",+ amount=Decimal("100.00"),+ date=date(2026, 1, 15),+ type="debit",+ currency="EUR",+ ),+ ]++ imported, _, _ = await import_transactions(+ session, test_user.id, test_account.id, txns, "csv",+ )++ assert imported == 1++ result = await session.execute(+ select(Transaction).where(Transaction.description == "Euro Store")+ )+ tx = result.scalar_one()+ assert tx.currency == "EUR"+ # stamp_primary_amount should have converted EUR -> BRL+ # Rate: EUR/USD = 0.92, BRL/USD = 5.00 => EUR->BRL = 5.00/0.92 ≈ 5.4348+ assert tx.amount_primary is not None+ assert float(tx.amount_primary) > 500 # 100 EUR * ~5.43 = ~543++ @pytest.mark.asyncio+ @patch("app.services.fx_rate_service._provider")+ async def test_import_uses_account_currency_as_default(+ self, mock_provider, session: AsyncSession, test_user: User,+ ):+ """When transaction has no currency, the account's currency should be used."""+ from app.schemas.transaction import TransactionBase+ from app.models.transaction import Transaction+ from sqlalchemy import select++ # Create a USD account+ usd_account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="USD Checking",+ type="checking",+ balance=Decimal("5000.00"),+ currency="USD",+ )+ session.add(usd_account)+ await session.commit()+ await session.refresh(usd_account)++ # Insert FX rates for conversion+ await _insert_fx_rate(session, "BRL", Decimal("5.0000"), date(2026, 2, 10))++ mock_provider.fetch_latest = AsyncMock(return_value={})+ mock_provider.fetch_historical = AsyncMock(return_value={})++ txns = [+ TransactionBase(+ description="ATM Withdrawal",+ amount=Decimal("200.00"),+ date=date(2026, 2, 10),+ type="debit",+ # No currency set — should inherit from account+ ),+ ]++ imported, _, _ = await import_transactions(+ session, test_user.id, usd_account.id, txns, "csv",+ )++ assert imported == 1++ result = await session.execute(+ select(Transaction).where(Transaction.description == "ATM Withdrawal")+ )+ tx = result.scalar_one()+ # Should have inherited USD from the account+ assert tx.currency == "USD"++ @pytest.mark.asyncio+ @patch("app.services.fx_rate_service._provider")+ async def test_import_brl_into_brl_account_no_fx(+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ ):+ """Importing BRL transactions into a BRL account should not trigger FX conversion."""+ from app.schemas.transaction import TransactionBase+ from app.models.transaction import Transaction+ from sqlalchemy import select++ txns = [+ TransactionBase(+ description="Supermercado",+ amount=Decimal("150.00"),+ date=date(2026, 3, 1),+ type="debit",+ # No currency — account is BRL, user primary is BRL+ ),+ ]++ imported, _, _ = await import_transactions(+ session, test_user.id, test_account.id, txns, "csv",+ )++ assert imported == 1++ result = await session.execute(+ select(Transaction).where(Transaction.description == "Supermercado")+ )+ tx = result.scalar_one()+ assert tx.currency == "BRL"+ # For same-currency (BRL->BRL), amount_primary should equal amount+ # (stamp_primary_amount returns 1:1 for same currency)++ # Provider should NOT have been called for same-currency import+ mock_provider.fetch_latest.assert_not_called()+ mock_provider.fetch_historical.assert_not_called()++ @pytest.mark.asyncio+ @patch("app.services.fx_rate_service._provider")+ async def test_import_csv_currency_overrides_account_currency(+ self, mock_provider, session: AsyncSession, test_user: User, test_account: Account,+ ):+ """CSV-provided currency should take priority over account currency."""+ from app.schemas.transaction import TransactionBase+ from app.models.transaction import Transaction+ from sqlalchemy import select++ await _insert_fx_rate(session, "BRL", Decimal("5.0000"), date(2026, 3, 5))+ await _insert_fx_rate(session, "GBP", Decimal("0.7900"), date(2026, 3, 5))++ mock_provider.fetch_latest = AsyncMock(return_value={})+ mock_provider.fetch_historical = AsyncMock(return_value={})++ txns = [+ TransactionBase(+ description="London Hotel",+ amount=Decimal("300.00"),+ date=date(2026, 3, 5),+ type="debit",+ currency="GBP", # Explicit currency from CSV, account is BRL+ ),+ ]++ imported, _, _ = await import_transactions(+ session, test_user.id, test_account.id, txns, "csv",+ )++ assert imported == 1++ result = await session.execute(+ select(Transaction).where(Transaction.description == "London Hotel")+ )+ tx = result.scalar_one()+ # Currency from CSV should override account currency+ assert tx.currency == "GBP"+ assert tx.amount_primary is not Nonediff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.pyindex b62edf50..e8139514 100644--- a/backend/tests/test_new_rules_api.py+++ b/backend/tests/test_new_rules_api.py@@ -65,7 +65,7 @@ async def test_apply_all_rules(client: AsyncClient, auth_headers, test_rules, teassert response.status_code == 200data = response.json()assert "applied" in data- assert data["applied"] >= 3 # 3 of 5 transactions match test rules (UBER, IFOOD, SALARIO)+ assert data["applied"] >= 3 # 3 of 5 transactions match rules# --- Integration tests: category assignment, tags, priority, isolation ---diff --git a/docker-compose.yml b/docker-compose.ymlindex 0a01b368..6d037b82 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -9,6 +9,8 @@ x-backend-env: &backend-envPLUGGY_CLIENT_SECRET: ${PLUGGY_CLIENT_SECRET:-}PLUGGY_OAUTH_REDIRECT_URI: http://localhost:3000/oauth/callbackREDIS_URL: redis://redis:6379/0+ OPENEXCHANGERATES_APP_ID: ${OPENEXCHANGERATES_APP_ID:-}+ FX_SYNC_MODE: ${FX_SYNC_MODE:-on_demand}x-backend-base: &backend-basebuild: ./backenddiff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 8c52f3ee..0b963688 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -54,14 +54,14 @@ const navItems = [{ key: 'import', path: '/import', icon: Upload },] as const-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}export function AppLayout() {const { t, i18n } = useTranslation()const { user, logout, updateUser } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { theme, setTheme } = useTheme()const location = useLocation()diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex 7372f9e7..d1faf87b 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -1,6 +1,8 @@import { useState } from 'react'import { useTranslation } from 'react-i18next'+import { useQuery } from '@tanstack/react-query'import { useAuth } from '@/contexts/auth-context'+import { currencies as currenciesApi } from '@/lib/api'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'@@ -12,6 +14,7 @@ import {DialogTitle,DialogFooter,} from '@/components/ui/dialog'+import { AlertTriangle } from 'lucide-react'import type { Transaction, RecurringTransaction } from '@/types'export function extractApiError(error: unknown): string {@@ -116,8 +119,13 @@ function TransactionForm({}) {const { t, i18n } = useTranslation()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.language+ const { data: supportedCurrencies } = useQuery({+ queryKey: ['currencies'],+ queryFn: currenciesApi.list,+ staleTime: Infinity,+ })const [description, setDescription] = useState(transaction?.description ?? '')const [amount, setAmount] = useState(transaction?.amount?.toString() ?? '')const [date, setDate] = useState(transaction?.date ?? new Date().toISOString().split('T')[0])@@ -126,15 +134,68 @@ function TransactionForm({const [categoryId, setCategoryId] = useState(transaction?.category_id ?? '')const [accountId, setAccountId] = useState(transaction?.account_id ?? accounts[0]?.id ?? '')const [notes, setNotes] = useState(transaction?.notes ?? '')+ const [convertedAmount, setConvertedAmount] = useState(+ transaction?.amount_primary != null ? transaction.amount_primary.toString() : ''+ )+ const [fxRate, setFxRate] = useState(+ transaction?.fx_rate_used != null ? transaction.fx_rate_used.toString() : ''+ )const [isRecurring, setIsRecurring] = useState(false)const [frequency, setFrequency] = useState<'monthly' | 'weekly' | 'yearly'>('monthly')const [endDate, setEndDate] = useState('')const isCreating = !transaction+ const showConversion = currency !== userCurrency && !isSynced++ const handleConvertedAmountChange = (val: string) => {+ setConvertedAmount(val)+ const numVal = parseFloat(val)+ const numAmount = parseFloat(amount)+ if (numVal && numAmount) {+ setFxRate((numVal / numAmount).toString())+ } else if (!val) {+ setFxRate('')+ }+ }++ const handleFxRateChange = (val: string) => {+ setFxRate(val)+ const numRate = parseFloat(val)+ const numAmount = parseFloat(amount)+ if (numRate && numAmount) {+ setConvertedAmount((numAmount * numRate).toFixed(2))+ } else if (!val) {+ setConvertedAmount('')+ }+ }++ const handleAmountChange = (val: string) => {+ setAmount(val)+ const numAmount = parseFloat(val)+ const numRate = parseFloat(fxRate)+ if (numRate && numAmount) {+ setConvertedAmount((numAmount * numRate).toFixed(2))+ }+ }++ const handleCurrencyChange = (val: string) => {+ setCurrency(val)+ if (val === userCurrency) {+ setConvertedAmount('')+ setFxRate('')+ }+ }return (<formonSubmit={(e) => {e.preventDefault()+ const fxFields: Partial<Transaction> = {}+ if (showConversion && convertedAmount) {+ fxFields.amount_primary = parseFloat(convertedAmount)+ }+ if (showConversion && fxRate) {+ fxFields.fx_rate_used = parseFloat(fxRate)+ }const txData = isSynced? {category_id: categoryId || undefined,@@ -149,6 +210,7 @@ function TransactionForm({category_id: categoryId || undefined,account_id: accountId || undefined,notes: notes.trim() || undefined,+ ...fxFields,} as Partial<Transaction>const recurringData = isCreating && isRecurring? { frequency, end_date: endDate || undefined }@@ -194,7 +256,7 @@ function TransactionForm({type="number"step="0.01"value={amount}- onChange={(e) => setAmount(e.target.value)}+ onChange={(e) => handleAmountChange(e.target.value)}requireddisabled={isSynced}/>@@ -204,10 +266,12 @@ function TransactionForm({<selectclassName="w-full border border-border rounded-md px-3 py-2 text-sm bg-background h-9 disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"value={currency}- onChange={(e) => setCurrency(e.target.value)}+ onChange={(e) => handleCurrencyChange(e.target.value)}disabled={isSynced}>- <option value={userCurrency}>{userCurrency} ({({ BRL: 'R$', USD: '$', EUR: '€', GBP: '£' } as Record<string, string>)[userCurrency] ?? userCurrency})</option>+ {(supportedCurrencies ?? [{ code: userCurrency, symbol: userCurrency, name: userCurrency, flag: '' }]).map((c) => (+ <option key={c.code} value={c.code}>{c.flag} {c.name}</option>+ ))}</select></div><div className="space-y-2">@@ -220,6 +284,42 @@ function TransactionForm({/></div></div>+ {showConversion && (+ <div className="border border-border rounded-md p-3 space-y-2">+ {transaction?.fx_fallback && (+ <div className="flex items-start gap-2 p-2 rounded-md bg-amber-50 dark:bg-amber-950/30 text-amber-700 dark:text-amber-400">+ <AlertTriangle size={14} className="mt-0.5 shrink-0" />+ <span className="text-xs">{t('transactions.fxFallbackBanner')}</span>+ </div>+ )}+ <div>+ <span className="text-sm font-medium">{t('transactions.conversion')}</span>+ <span className="text-xs text-muted-foreground ml-2">({t('transactions.conversionHint')})</span>+ </div>+ <div className="grid grid-cols-2 gap-4">+ <div className="space-y-1">+ <Label className="text-xs">{t('transactions.convertedAmount', { currency: userCurrency })}</Label>+ <Input+ type="number"+ step="0.01"+ value={convertedAmount}+ onChange={(e) => handleConvertedAmountChange(e.target.value)}+ placeholder={t('transactions.autoCalculated')}+ />+ </div>+ <div className="space-y-1">+ <Label className="text-xs">{t('transactions.exchangeRate')}</Label>+ <Input+ type="number"+ step="0.0001"+ value={fxRate}+ onChange={(e) => handleFxRateChange(e.target.value)}+ placeholder={t('transactions.autoCalculated')}+ />+ </div>+ </div>+ </div>+ )}<div className="grid grid-cols-2 gap-4"><div className="space-y-2"><Label>{t('transactions.type')}</Label>diff --git a/frontend/src/components/transaction-drill-down.tsx b/frontend/src/components/transaction-drill-down.tsxindex a67fb73e..34805bca 100644--- a/frontend/src/components/transaction-drill-down.tsx+++ b/frontend/src/components/transaction-drill-down.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useQuery } from '@tanstack/react-query'import { transactions as transactionsApi, dashboard } from '@/lib/api'-import { X } from 'lucide-react'+import { AlertTriangle, X } from 'lucide-react'import { CategoryIcon } from '@/components/category-icon'import { useAuth } from '@/contexts/auth-context'import type { Transaction } from '@/types'@@ -23,6 +23,7 @@ type DisplayItem = {date: stringtype: 'debit' | 'credit'amount: number+ amountPrimary: number | nullcurrency: stringcategoryIcon: string | nullcategoryName: string | null@@ -31,7 +32,7 @@ type DisplayItem = {transaction: Transaction | null}-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -46,7 +47,7 @@ export function TransactionDrillDown({}) {const { t, i18n } = useTranslation()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst panelRef = useRef<HTMLDivElement>(null)@@ -85,6 +86,7 @@ export function TransactionDrillDown({date: tx.date,type: tx.type as 'debit' | 'credit',amount: Number(tx.amount),+ amountPrimary: tx.amount_primary != null ? Number(tx.amount_primary) : null,currency: tx.currency,categoryIcon: tx.category?.icon ?? null,categoryName: tx.category?.name ?? null,@@ -108,6 +110,7 @@ export function TransactionDrillDown({date: pt.date,type: pt.type,amount: pt.amount,+ amountPrimary: pt.amount_primary ?? null,currency: pt.currency,categoryIcon: pt.category_icon,categoryName: pt.category_name,@@ -149,7 +152,13 @@ export function TransactionDrillDown({}}, [filter, onClose])- const absTotal = displayItems.reduce((sum, item) => sum + Math.abs(item.amount), 0)+ const absTotal = displayItems.reduce((sum, item) => {+ // Use amount_primary for foreign currency transactions, fall back to amount+ const effectiveAmount = (item.currency !== userCurrency && item.amountPrimary != null)+ ? item.amountPrimary+ : item.amount+ return sum + Math.abs(effectiveAmount)+ }, 0)return (<>@@ -223,14 +232,26 @@ export function TransactionDrillDown({{item.categoryName && ` · ${item.categoryName}`}</p></div>- <span- className={`text-sm font-semibold tabular-nums shrink-0 ${- item.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'- }`}- >- {item.type === 'credit' ? '+' : '-'}- {formatCurrency(Math.abs(item.amount), item.currency ?? userCurrency, locale)}- </span>+ <div className="text-right shrink-0">+ <span+ className={`text-sm font-semibold tabular-nums ${+ item.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'+ }`}+ >+ {item.type === 'credit' ? '+' : '-'}+ {formatCurrency(Math.abs(item.amount), item.currency ?? userCurrency, locale)}+ </span>+ {item.currency !== userCurrency && item.amountPrimary != null && (+ <div className="flex items-center justify-end gap-1">+ {item.transaction?.fx_fallback && (+ <span title={t('transactions.fxFallbackTooltip')}><AlertTriangle size={11} className="text-amber-500 shrink-0" /></span>+ )}+ <span className="text-[10px] text-muted-foreground tabular-nums">+ {formatCurrency(Math.abs(item.amountPrimary), userCurrency, locale)}+ </span>+ </div>+ )}+ </div></div>))}</div>diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 114c79a5..9dd804bf 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -55,7 +55,7 @@ export const setup = {const { data } = await api.get('/setup/status')return data},- createAdmin: async (email: string, password: string, currency = 'BRL', name = '', language = 'pt-BR'): Promise<{ access_token: string }> => {+ createAdmin: async (email: string, password: string, currency = 'USD', name = '', language = 'en'): Promise<{ access_token: string }> => {const { data } = await api.post('/setup/create-admin', { email, password, currency, name, language })return data},@@ -443,6 +443,26 @@ export const reports = {},}+// Currencies+export const currencies = {+ list: async (): Promise<{ code: string; symbol: string; name: string; flag: string }[]> => {+ const { data } = await api.get('/currencies')+ return data+ },+}++// FX Rates+export const fxRates = {+ refresh: async (): Promise<{ synced: boolean; rates_count: number; date: string }> => {+ const { data } = await api.post('/fx-rates/refresh')+ return data+ },+ status: async (): Promise<{ last_sync_date: string | null; total_rates: number }> => {+ const { data } = await api.get('/fx-rates/status')+ return data+ },+}+// Import Logsexport const importLogs = {list: async (): Promise<ImportLog[]> => {diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.tsnew file mode 100644index 00000000..c4521500--- /dev/null+++ b/frontend/src/lib/format.ts@@ -0,0 +1,16 @@+/**+ * Format a numeric value as currency using Intl.NumberFormat.+ */+export function formatCurrency(+ value: number | null | undefined,+ currency = 'USD',+ locale = 'en-US',+): string {+ if (value == null) return '—'+ return new Intl.NumberFormat(locale, {+ style: 'currency',+ currency,+ minimumFractionDigits: 2,+ maximumFractionDigits: 2,+ }).format(value)+}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex f1ce05ba..1768874a 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -76,7 +76,13 @@"categorizeNow": "Categorize now","allCategorized": "All caught up!","allCategorizedDesc": "All transactions are categorized",- "assetsValue": "Assets"+ "assetsValue": "Assets",+ "currencyBreakdown": "Per-currency breakdown",+ "convertedFrom": "Converted from {{currency}}",+ "fxRateUsed": "FX rate: {{rate}}",+ "refreshRates": "Refresh FX rates",+ "ratesRefreshed": "FX rates updated",+ "ratesError": "Failed to update FX rates"},"transactions": {"title": "Transactions",@@ -121,7 +127,14 @@"income": "Income","notes": "Notes","notesHint": "optional — use #tags to categorize",- "notesPlaceholder": "E.g.: business dinner #work #reimbursable"+ "notesPlaceholder": "E.g.: business dinner #work #reimbursable",+ "conversion": "Conversion",+ "conversionHint": "optional — leave blank for auto rate",+ "convertedAmount": "Amount in {{currency}}",+ "exchangeRate": "Exchange rate",+ "autoCalculated": "auto",+ "fxFallbackTooltip": "Rate unavailable — using 1:1 fallback. Edit to set manually.",+ "fxFallbackBanner": "Exchange rate unavailable — using fallback (1:1). Set the rate manually or check your FX provider settings."},"accounts": {"title": "Accounts",@@ -248,7 +261,8 @@"updated": "Recurring transaction updated","deleted": "Recurring transaction deleted","generated": "{{count}} transactions generated",- "generatePending": "Generate Pending"+ "generatePending": "Generate Pending",+ "fxEstimate": "Estimate based on latest exchange rate ({{rate}}). Final amount may change."},"rules": {"section": "Automation",@@ -475,7 +489,8 @@"error": "Error","success": "Success","searchIcon": "Search icon...",- "noIconsFound": "No icons found"+ "noIconsFound": "No icons found",+ "primaryCurrency": "Primary Currency"},"privacy": {"hide": "Hide values",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 8ea31df6..90d41179 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -76,7 +76,13 @@"categorizeNow": "Categorizar agora","allCategorized": "Tudo em dia!","allCategorizedDesc": "Todas as transações estão categorizadas",- "assetsValue": "Patrimônio"+ "assetsValue": "Patrimônio",+ "currencyBreakdown": "Detalhamento por moeda",+ "convertedFrom": "Convertido de {{currency}}",+ "fxRateUsed": "Taxa de câmbio: {{rate}}",+ "refreshRates": "Atualizar taxas de câmbio",+ "ratesRefreshed": "Taxas de câmbio atualizadas",+ "ratesError": "Erro ao atualizar taxas de câmbio"},"transactions": {"title": "Transações",@@ -121,7 +127,14 @@"income": "Receita","notes": "Notas","notesHint": "opcional — use #tags para categorizar",- "notesPlaceholder": "Ex: jantar de negócios #work #reimbursable"+ "notesPlaceholder": "Ex: jantar de negócios #work #reimbursable",+ "conversion": "Conversão",+ "conversionHint": "opcional — deixe em branco para taxa automática",+ "convertedAmount": "Valor em {{currency}}",+ "exchangeRate": "Taxa de câmbio",+ "autoCalculated": "automático",+ "fxFallbackTooltip": "Taxa indisponível — usando fallback 1:1. Edite para definir manualmente.",+ "fxFallbackBanner": "Taxa de câmbio indisponível — usando fallback (1:1). Defina manualmente ou verifique as configurações do provedor de câmbio."},"accounts": {"title": "Contas",@@ -248,7 +261,8 @@"updated": "Transação recorrente atualizada","deleted": "Transação recorrente excluída","generated": "{{count}} transações geradas",- "generatePending": "Gerar Pendentes"+ "generatePending": "Gerar Pendentes",+ "fxEstimate": "Estimativa baseada na última taxa de câmbio ({{rate}}). O valor final pode mudar."},"rules": {"section": "Automação",@@ -475,7 +489,8 @@"error": "Erro","success": "Sucesso","searchIcon": "Buscar ícone...",- "noIconsFound": "Nenhum ícone encontrado"+ "noIconsFound": "Nenhum ícone encontrado",+ "primaryCurrency": "Moeda Principal"},"privacy": {"hide": "Ocultar valores",diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex ab4fafa4..3871ead9 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -32,7 +32,7 @@ function defaultTo() {return format(new Date(), 'yyyy-MM-dd')}-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -47,7 +47,7 @@ export default function AccountDetailPage() {const { t, i18n } = useTranslation()const { mask, privacyMode, MASK } = usePrivacyMode()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst queryClient = useQueryClient()const [dialogOpen, setDialogOpen] = useState(false)diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex 8f6b96d9..a7007001 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'import { Link } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { accounts, connections } from '@/lib/api'+import { accounts, connections, currencies } from '@/lib/api'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -39,7 +39,7 @@ import { ConnectionSettingsDialog } from '@/components/connection-settings-dialoimport { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -59,6 +59,8 @@ export default function AccountsPage() {const { t, i18n } = useTranslation()const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()+ const { user } = useAuth()+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()const [dialogOpen, setDialogOpen] = useState(false)const [editingAccount, setEditingAccount] = useState<Account | null>(null)@@ -242,9 +244,16 @@ export default function AccountsPage() {<Trash2 size={13} /></button></div>- <p className={`text-xs sm:text-sm font-semibold tabular-nums text-right ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>- {mask(formatCurrency(bal, acc.currency, locale))}- </p>+ <div className="text-right">+ <p className={`text-xs sm:text-sm font-semibold tabular-nums ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>+ {mask(formatCurrency(bal, acc.currency, locale))}+ </p>+ {acc.balance_primary != null && acc.currency !== userCurrency && (+ <p className="text-[10px] text-muted-foreground tabular-nums">+ {mask(formatCurrency(acc.balance_primary, userCurrency, locale))}+ </p>+ )}+ </div></div>)})}@@ -360,9 +369,16 @@ export default function AccountsPage() {><Archive size={13} /></button>- <p className={`text-xs sm:text-sm font-semibold tabular-nums text-right ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>- {mask(formatCurrency(bal, acc.currency, locale))}- </p>+ <div className="text-right">+ <p className={`text-xs sm:text-sm font-semibold tabular-nums ${(acc.type === 'credit_card' ? bal > 0 : bal < 0) ? 'text-rose-500' : 'text-foreground'}`}>+ {mask(formatCurrency(bal, acc.currency, locale))}+ </p>+ {acc.balance_primary != null && acc.currency !== userCurrency && (+ <p className="text-[10px] text-muted-foreground tabular-nums">+ {mask(formatCurrency(acc.balance_primary, userCurrency, locale))}+ </p>+ )}+ </div></div>)})}@@ -536,7 +552,12 @@ function AccountDialog({}) {const { t } = useTranslation()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'+ const { data: supportedCurrencies } = useQuery({+ queryKey: ['currencies'],+ queryFn: currencies.list,+ staleTime: Infinity,+ })const [name, setName] = useState(account?.name ?? '')const [type, setType] = useState(account?.type ?? 'checking')const [balance, setBalance] = useState(account?.balance?.toString() ?? '0')@@ -593,7 +614,9 @@ function AccountDialog({value={currency}onChange={(e) => setCurrency(e.target.value)}>- <option value={userCurrency}>{userCurrency} ({({ BRL: 'R$', USD: '$', EUR: '€', GBP: '£' } as Record<string, string>)[userCurrency] ?? userCurrency})</option>+ {(supportedCurrencies ?? [{ code: userCurrency, symbol: userCurrency, name: userCurrency, flag: '' }]).map((c) => (+ <option key={c.code} value={c.code}>{c.flag} {c.name}</option>+ ))}</select></div></div>diff --git a/frontend/src/pages/assets.tsx b/frontend/src/pages/assets.tsxindex d93f12c5..0562436f 100644--- a/frontend/src/pages/assets.tsx+++ b/frontend/src/pages/assets.tsx@@ -1,7 +1,7 @@import { useState, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { assets } from '@/lib/api'+import { assets, currencies as currenciesApi } from '@/lib/api'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -42,11 +42,11 @@ import { PageHeader } from '@/components/page-header'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {try {- return new Intl.NumberFormat(locale, { style: 'currency', currency: currency || 'BRL' }).format(value)+ return new Intl.NumberFormat(locale, { style: 'currency', currency: currency || 'USD' }).format(value)} catch {- return new Intl.NumberFormat(locale, { style: 'currency', currency: 'BRL' }).format(value)+ return new Intl.NumberFormat(locale, { style: 'currency', currency: 'USD' }).format(value)}}@@ -72,9 +72,15 @@ export default function AssetsPage() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()+ const { data: supportedCurrencies } = useQuery({+ queryKey: ['currencies'],+ queryFn: currenciesApi.list,+ staleTime: Infinity,+ })+const [dialogOpen, setDialogOpen] = useState(false)const [editingAsset, setEditingAsset] = useState<Asset | null>(null)const [deletingId, setDeletingId] = useState<string | null>(null)@@ -318,10 +324,20 @@ export default function AssetsPage() {<><p className="text-sm font-bold tabular-nums text-foreground">{mask(formatCurrency(asset.current_value, asset.currency, locale))}+ {asset.current_value_primary != null && (+ <span className="text-[10px] font-medium text-muted-foreground ml-1">+ ({mask(formatCurrency(asset.current_value_primary, userCurrency, locale))})+ </span>+ )}</p>{asset.gain_loss != null && (<p className={`text-xs font-medium tabular-nums ${asset.gain_loss >= 0 ? 'text-emerald-600' : 'text-rose-500'}`}>{mask(`${asset.gain_loss >= 0 ? '+' : ''}${formatCurrency(asset.gain_loss, asset.currency, locale)}`)}+ {asset.gain_loss_primary != null && (+ <span className="text-[10px] text-muted-foreground ml-1">+ ({mask(formatCurrency(asset.gain_loss_primary, userCurrency, locale))})+ </span>+ )}</p>)}</>@@ -449,7 +465,9 @@ export default function AssetsPage() {value={formCurrency}onChange={e => setFormCurrency(e.target.value)}>- <option value={userCurrency}>{userCurrency} ({({ BRL: 'R$', USD: '$', EUR: '€', GBP: '£' } as Record<string, string>)[userCurrency] ?? userCurrency})</option>+ {(supportedCurrencies ?? [{ code: userCurrency, symbol: userCurrency, name: userCurrency, flag: '' }]).map((c) => (+ <option key={c.code} value={c.code}>{c.flag} {c.name}</option>+ ))}</select></div></div>diff --git a/frontend/src/pages/budgets.tsx b/frontend/src/pages/budgets.tsxindex a4af009f..96ef9574 100644--- a/frontend/src/pages/budgets.tsx+++ b/frontend/src/pages/budgets.tsx@@ -24,7 +24,7 @@ import { CategoryIcon } from '@/components/category-icon'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -55,7 +55,7 @@ export default function BudgetsPage() {const { t, i18n } = useTranslation()const { mask } = usePrivacyMode()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst queryClient = useQueryClient()const [selectedMonth, setSelectedMonth] = useState(currentMonth)diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsxindex 3476fa6a..8c54aad7 100644--- a/frontend/src/pages/dashboard.tsx+++ b/frontend/src/pages/dashboard.tsx@@ -34,7 +34,7 @@ import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'import type { Transaction } from '@/types'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -68,7 +68,7 @@ export default function DashboardPage() {const { t, i18n } = useTranslation()const { mask, privacyMode, MASK } = usePrivacyMode()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const displayName = user?.preferences?.display_name || ''const locale = i18n.language === 'en' ? 'en-US' : i18n.language@@ -79,14 +79,12 @@ export default function DashboardPage() {return displayName ? `${base}, ${displayName}` : base})()const [selectedMonth, setSelectedMonth] = useState(currentMonth)- const [balanceDate, setBalanceDate] = useState<string | undefined>()const [drillDown, setDrillDown] = useState<DrillDownFilter | null>(null)const [editingTx, setEditingTx] = useState<Transaction | null>(null)const [dialogOpen, setDialogOpen] = useState(false)const queryClient = useQueryClient()const [headerCalOpen, setHeaderCalOpen] = useState(false)const [hoveredDay, setHoveredDay] = useState<number | null>(null)- const [balanceCalOpen, setBalanceCalOpen] = useState(false)const dateFnsLocale = i18n.language === 'pt-BR' ? ptBR : enUSconst monthParam = `${selectedMonth}-01`const monthStart = `${selectedMonth}-01`@@ -95,12 +93,11 @@ export default function DashboardPage() {const handleMonthChange = (newMonth: string) => {setSelectedMonth(newMonth)- setBalanceDate(undefined)- }+}const { data: summary, isLoading: summaryLoading } = useQuery({- queryKey: ['dashboard', 'summary', selectedMonth, balanceDate],- queryFn: () => dashboard.summary(monthParam, balanceDate),+ queryKey: ['dashboard', 'summary', selectedMonth],+ queryFn: () => dashboard.summary(monthParam),})const { data: spending, isLoading: spendingLoading } = useQuery({@@ -169,6 +166,7 @@ export default function DashboardPage() {},})+const cumulativeData = useMemo(() => {if (!balanceHistory) return []const daysInMonth = monthLastDay(selectedMonth)@@ -191,12 +189,13 @@ export default function DashboardPage() {const currentLatestBalance = lastCurrentPoint?.current ?? 0const monthVariation = currentLatestBalance - currentStartBalance- const totalBalance = Object.values(summary?.total_balance ?? {}).reduce((a, b) => a + Number(b), 0)+ const primaryCurrency = summary?.primary_currency ?? userCurrency+ const totalBalance = summary?.total_balance_primary ?? Object.values(summary?.total_balance ?? {}).reduce((a, b) => a + Number(b), 0)// Savings rate & projection- const income = Number(summary?.monthly_income ?? 0)- const expenses = Number(summary?.monthly_expenses ?? 0)+ const income = Number(summary?.monthly_income_primary ?? summary?.monthly_income ?? 0)+ const expenses = Number(summary?.monthly_expenses_primary ?? summary?.monthly_expenses ?? 0)const savingsRate = income > 0 ? ((income - expenses) / income) * 100 : 0const isCurrentMonth = selectedMonth === currentMonth()const daysElapsed = isCurrentMonth ? new Date().getDate() : monthLastDay(selectedMonth)@@ -253,6 +252,7 @@ export default function DashboardPage() {date: stringtype: 'debit' | 'credit'amount: number+ amountPrimary: number | nullcurrency: stringcategoryIcon: string | nullcategoryName: string | null@@ -270,6 +270,7 @@ export default function DashboardPage() {date: tx.date,type: tx.type,amount: Number(tx.amount),+ amountPrimary: tx.amount_primary != null ? Number(tx.amount_primary) : null,currency: tx.currency,categoryIcon: tx.category?.icon ?? null,categoryName: tx.category?.name ?? null,@@ -284,6 +285,7 @@ export default function DashboardPage() {date: pt.date,type: pt.type,amount: pt.amount,+ amountPrimary: pt.amount_primary ?? null,currency: pt.currency,categoryIcon: pt.category_icon,categoryName: pt.category_name,@@ -338,13 +340,12 @@ export default function DashboardPage() {<Calendarmode="single"locale={dateFnsLocale}- selected={new Date((balanceDate ?? `${selectedMonth}-01`) + 'T00:00:00')}+ selected={new Date(`${selectedMonth}-01T00:00:00`)}defaultMonth={new Date(`${selectedMonth}-01T00:00:00`)}onSelect={(date) => {if (!date) returnconst newMonth = format(date, 'yyyy-MM')setSelectedMonth(newMonth)- setBalanceDate(format(date, 'yyyy-MM-dd'))setHeaderCalOpen(false)}}/>@@ -385,36 +386,18 @@ export default function DashboardPage() {) : (<div><p className={`text-lg font-bold tabular-nums ${totalBalance < 0 ? 'text-rose-500' : 'text-foreground'}`}>- {mask(formatCurrency(totalBalance, userCurrency, locale))}+ {mask(formatCurrency(totalBalance, primaryCurrency, locale))}</p>- <Popover open={balanceCalOpen} onOpenChange={setBalanceCalOpen}>- <PopoverTrigger asChild>- <button className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-primary transition-colors cursor-pointer p-0 bg-transparent border-none outline-none">- <CalendarIcon className="size-3" />- {(() => {- const dateStr = balanceDate ?? summary?.balance_date ?? ''- if (!dateStr) return ''- return new Date(dateStr + 'T00:00:00').toLocaleDateString(locale)- })()}- </button>- </PopoverTrigger>- <PopoverContent align="start" className="w-auto p-0">- <Calendar- mode="single"- locale={dateFnsLocale}- selected={(() => {- const dateStr = balanceDate ?? summary?.balance_date ?? ''- return dateStr ? new Date(dateStr + 'T00:00:00') : undefined- })()}- defaultMonth={new Date(`${selectedMonth}-01T00:00:00`)}- onSelect={(date) => {- if (!date) return- setBalanceDate(format(date, 'yyyy-MM-dd'))- setBalanceCalOpen(false)- }}- />- </PopoverContent>- </Popover>+ {/* Per-currency breakdown when multiple currencies */}+ {summary?.total_balance && Object.keys(summary.total_balance).length > 1 && (+ <div className="flex flex-wrap gap-x-2 mt-0.5">+ {Object.entries(summary.total_balance).map(([cur, val]) => (+ <span key={cur} className="text-[10px] text-muted-foreground tabular-nums">+ {mask(formatCurrency(val, cur, locale))}+ </span>+ ))}+ </div>+ )}</div>)}</div>@@ -434,7 +417,7 @@ export default function DashboardPage() {<Skeleton className="h-7 w-24" />) : (<p className="text-lg font-bold tabular-nums text-emerald-600">- +{mask(formatCurrency(income, userCurrency, locale))}+ +{mask(formatCurrency(income, primaryCurrency, locale))}</p>)}</div>@@ -454,7 +437,7 @@ export default function DashboardPage() {<Skeleton className="h-7 w-24" />) : (<p className="text-lg font-bold tabular-nums text-rose-500">- -{mask(formatCurrency(expenses, userCurrency, locale))}+ -{mask(formatCurrency(expenses, primaryCurrency, locale))}</p>)}</div>@@ -464,7 +447,7 @@ export default function DashboardPage() {<div className="min-w-0"><p className="text-xs font-medium text-muted-foreground mb-0.5">{t('dashboard.assetsValue')}</p><p className="text-lg font-bold tabular-nums text-blue-600">- {mask(formatCurrency(Object.values(summary.assets_value).reduce((a, b) => a + b, 0), userCurrency, locale))}+ {mask(formatCurrency(summary.assets_value_primary ?? Object.values(summary.assets_value).reduce((a, b) => a + b, 0), primaryCurrency, locale))}</p></div>)}@@ -473,7 +456,7 @@ export default function DashboardPage() {{/* Spending projection */}{projectedSpend !== null && !summaryLoading && (<p className="text-xs text-muted-foreground mt-2">- {t('dashboard.spendingProjection', { amount: mask(formatCurrency(projectedSpend, userCurrency, locale)) })}+ {t('dashboard.spendingProjection', { amount: mask(formatCurrency(projectedSpend, primaryCurrency, locale)) })}</p>)}</div>@@ -792,6 +775,11 @@ export default function DashboardPage() {<span className={`text-sm font-semibold tabular-nums ${row.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>{mask(`${row.type === 'credit' ? '+' : '-'}${formatCurrency(Math.abs(row.amount), row.currency, locale)}`)}</span>+ {row.currency !== userCurrency && row.amountPrimary != null && (+ <span className="block text-[10px] text-muted-foreground tabular-nums">+ {mask(formatCurrency(Math.abs(row.amountPrimary), userCurrency, locale))}+ </span>+ )}</TableCell></TableRow>))}diff --git a/frontend/src/pages/import.tsx b/frontend/src/pages/import.tsxindex c767fa4c..9b7e71c1 100644--- a/frontend/src/pages/import.tsx+++ b/frontend/src/pages/import.tsx@@ -19,14 +19,14 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, Diimport { PageHeader } from '@/components/page-header'import { useAuth } from '@/contexts/auth-context'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}export default function ImportPage() {const { t, i18n } = useTranslation()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst queryClient = useQueryClient()const fileInputRef = useRef<HTMLInputElement>(null)diff --git a/frontend/src/pages/recurring.tsx b/frontend/src/pages/recurring.tsxindex 991f4231..61c72f62 100644--- a/frontend/src/pages/recurring.tsx+++ b/frontend/src/pages/recurring.tsx@@ -1,7 +1,7 @@import React, { useState } from 'react'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { categories as categoriesApi, recurring as recurringApi, accounts as accountsApi } from '@/lib/api'+import { categories as categoriesApi, recurring as recurringApi, accounts as accountsApi, currencies as currenciesApi } from '@/lib/api'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -14,14 +14,14 @@ import {DialogFooter,} from '@/components/ui/dialog'import type { Category, RecurringTransaction } from '@/types'-import { Pencil, Trash2, Plus, RefreshCw } from 'lucide-react'+import { Pencil, Trash2, Plus, RefreshCw, Info } from 'lucide-react'import { cn } from '@/lib/utils'import { PageHeader } from '@/components/page-header'import { DatePickerInput } from '@/components/ui/date-picker-input'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -59,6 +59,8 @@ function RecurringTab() {const { t, i18n } = useTranslation()const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()+ const { user } = useAuth()+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()const [dialogOpen, setDialogOpen] = useState(false)const [editing, setEditing] = useState<RecurringTransaction | null>(null)@@ -164,6 +166,14 @@ function RecurringTab() {<td className="py-3 pl-4 sm:pl-5 text-sm font-medium text-foreground">{rt.description}</td><td className={`py-3 text-xs sm:text-sm font-bold tabular-nums ${rt.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>{mask(`${rt.type === 'credit' ? '+' : '−'}${formatCurrency(rt.amount, rt.currency, locale)}`)}+ {rt.currency !== userCurrency && rt.amount_primary != null && (+ <div className="flex items-center gap-1 text-[11px] font-normal text-muted-foreground">+ <span>{mask(formatCurrency(rt.amount_primary, userCurrency, locale))}</span>+ <span title={t('recurring.fxEstimate', { rate: rt.fx_rate_used?.toFixed(4) ?? '–' })}>+ <Info size={11} className="inline opacity-60" />+ </span>+ </div>+ )}</td><td className="py-3 hidden md:table-cell"><span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full font-medium">@@ -252,7 +262,12 @@ function RecurringForm({}) {const { t } = useTranslation()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'+ const { data: supportedCurrencies } = useQuery({+ queryKey: ['currencies'],+ queryFn: currenciesApi.list,+ staleTime: Infinity,+ })const [description, setDescription] = useState(recurring?.description ?? '')const [amount, setAmount] = useState(recurring?.amount?.toString() ?? '')const [currency, setCurrency] = useState(recurring?.currency ?? userCurrency)@@ -299,7 +314,9 @@ function RecurringForm({<div className="space-y-2"><Label>{t('recurring.currency')}</Label><select className={selectClass} value={currency} onChange={(e) => setCurrency(e.target.value)}>- <option value={userCurrency}>{userCurrency} ({({ BRL: 'R$', USD: '$', EUR: '€', GBP: '£' } as Record<string, string>)[userCurrency] ?? userCurrency})</option>+ {(supportedCurrencies ?? [{ code: userCurrency, symbol: userCurrency, name: userCurrency, flag: '' }]).map((c) => (+ <option key={c.code} value={c.code}>{c.flag} {c.name}</option>+ ))}</select></div><div className="space-y-2">diff --git a/frontend/src/pages/reports.tsx b/frontend/src/pages/reports.tsxindex e6dd5aae..cf21332c 100644--- a/frontend/src/pages/reports.tsx+++ b/frontend/src/pages/reports.tsx@@ -25,11 +25,11 @@ import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'import type { ReportResponse, CategoryTrendItem } from '@/types'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}-function formatCompact(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCompact(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, {style: 'currency',currency,@@ -81,7 +81,7 @@ export default function ReportsPage() {const { t, i18n } = useTranslation()const { mask, privacyMode, MASK } = usePrivacyMode()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst [months, setMonths] = useState(12)diff --git a/frontend/src/pages/setup.tsx b/frontend/src/pages/setup.tsxindex bfdb48d0..14af447e 100644--- a/frontend/src/pages/setup.tsx+++ b/frontend/src/pages/setup.tsx@@ -22,7 +22,7 @@ export default function SetupPage() {const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [confirmPassword, setConfirmPassword] = useState('')- const [currency, setCurrency] = useState('BRL')+ const [currency, setCurrency] = useState('USD')const [error, setError] = useState('')const [isLoading, setIsLoading] = useState(false)const [checking, setChecking] = useState(true)@@ -144,10 +144,14 @@ export default function SetupPage() {<Label className="text-[13px] font-medium">{t('setup.currency')}</Label><div className="grid grid-cols-4 gap-2">{([- { code: 'BRL', flag: '\u{1F1E7}\u{1F1F7}', symbol: 'R$' },{ code: 'USD', flag: '\u{1F1FA}\u{1F1F8}', symbol: '$' },{ code: 'EUR', flag: '\u{1F1EA}\u{1F1FA}', symbol: '\u20AC' },{ code: 'GBP', flag: '\u{1F1EC}\u{1F1E7}', symbol: '\u00A3' },+ { code: 'BRL', flag: '\u{1F1E7}\u{1F1F7}', symbol: 'R$' },+ { code: 'CAD', flag: '\u{1F1E8}\u{1F1E6}', symbol: 'C$' },+ { code: 'AUD', flag: '\u{1F1E6}\u{1F1FA}', symbol: 'A$' },+ { code: 'CHF', flag: '\u{1F1E8}\u{1F1ED}', symbol: 'Fr' },+ { code: 'ARS', flag: '\u{1F1E6}\u{1F1F7}', symbol: '$' },] as const).map(({ code, flag, symbol }) => (<buttonkey={code}diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex a617c553..062f6f9d 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -14,7 +14,7 @@ import {} from '@/components/ui/table'import { Input } from '@/components/ui/input'import { Skeleton } from '@/components/ui/skeleton'-import { Check, Download, Search, X } from 'lucide-react'+import { AlertTriangle, Check, Download, Search, X } from 'lucide-react'import type { Transaction } from '@/types'import { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'@@ -23,7 +23,7 @@ import { DatePickerInput } from '@/components/ui/date-picker-input'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useAuth } from '@/contexts/auth-context'-function formatCurrency(value: number, currency = 'BRL', locale = 'pt-BR') {+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)}@@ -38,7 +38,7 @@ export default function TransactionsPage() {const locale = i18n.language === 'en' ? 'en-US' : i18n.languageconst { mask } = usePrivacyMode()const { user } = useAuth()- const userCurrency = user?.preferences?.currency_display ?? 'BRL'+ const userCurrency = user?.preferences?.currency_display ?? 'USD'const queryClient = useQueryClient()const [page, setPage] = useState(1)const [filterAccount, setFilterAccount] = useState<string>('')@@ -418,6 +418,16 @@ export default function TransactionsPage() {<span className={`text-xs md:text-sm font-bold tabular-nums ${tx.type === 'credit' ? 'text-emerald-600' : 'text-rose-500'}`}>{mask(`${tx.type === 'credit' ? '+' : '−'}${formatCurrency(Math.abs(Number(tx.amount)), tx.currency, locale)}`)}</span>+ {tx.amount_primary != null && tx.currency !== userCurrency && (+ <div className="flex items-center justify-end gap-1">+ {tx.fx_fallback && (+ <span title={t('transactions.fxFallbackTooltip')}><AlertTriangle size={11} className="text-amber-500 shrink-0" /></span>+ )}+ <span className="text-[10px] text-muted-foreground tabular-nums">+ {mask(formatCurrency(Math.abs(tx.amount_primary), userCurrency, locale))}+ </span>+ </div>+ )}</TableCell></TableRow>))}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 3ebf7595..66f63a8a 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -61,6 +61,7 @@ export interface Account {balance: numbercurrent_balance: numberprevious_balance: number | null+ balance_primary: number | nullcurrency: stringis_closed: booleanclosed_at: string | null@@ -90,6 +91,9 @@ export interface Transaction {payee: string | nullnotes: string | nulltransfer_pair_id: string | null+ amount_primary: number | null+ fx_rate_used: number | null+ fx_fallback: boolean}export interface RuleCondition {@@ -142,12 +146,15 @@ export interface RecurringTransaction {end_date: string | nullis_active: booleannext_occurrence: string+ amount_primary: number | null+ fx_rate_used: number | null}export interface ProjectedTransaction {recurring_id: stringdescription: stringamount: number+ amount_primary: number | nullcurrency: stringtype: 'debit' | 'credit'date: string@@ -159,13 +166,18 @@ export interface ProjectedTransaction {export interface DashboardSummary {total_balance: Record<string, number>+ total_balance_primary: numberbalance_date: stringmonthly_income: numbermonthly_expenses: number+ monthly_income_primary: number+ monthly_expenses_primary: numberaccounts_count: numberpending_categorization: numberpending_categorization_amount: numberassets_value: Record<string, number>+ assets_value_primary: number+ primary_currency: string}export interface SpendingByCategory {@@ -235,7 +247,9 @@ export interface Asset {is_archived: booleanposition: numbercurrent_value: number | null+ current_value_primary: number | nullgain_loss: number | null+ gain_loss_primary: number | nullvalue_count: number}