Skip to content

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

feat: add inter-account transfers with manual FX rate support (#49)

Tássio Noronha45677b25f28c
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index 5b89ad10..23ddf56a 100644
--- a/backend/app/api/transactions.py
+++ b/backend/app/api/transactions.py
@@ -12,7 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.auth import current_active_user
from app.core.database import get_async_session
from app.models.user import User
-from app.schemas.transaction import BulkCategorizeRequest, TransactionCreate, TransactionRead, TransactionUpdate
+from app.schemas.transaction import BulkCategorizeRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead
from app.services import transaction_service
router = APIRouter(prefix="/api/transactions", tags=["transactions"])
@@ -115,6 +115,26 @@ async def bulk_categorize(
return {"updated": count}
[email protected]("/transfer", response_model=TransferRead, status_code=status.HTTP_201_CREATED)
+async def create_transfer(
+ data: TransferCreate,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ try:
+ debit_tx, credit_tx = await transaction_service.create_transfer(session, user.id, data)
+ debit_full = await transaction_service.get_transaction(session, debit_tx.id, user.id)
+ credit_full = await transaction_service.get_transaction(session, credit_tx.id, user.id)
+ primary_currency = user.primary_currency
+ return TransferRead(
+ debit=_tag_fx_fallback(TransactionRead.model_validate(debit_full, from_attributes=True), primary_currency),
+ credit=_tag_fx_fallback(TransactionRead.model_validate(credit_full, from_attributes=True), primary_currency),
+ transfer_pair_id=debit_tx.transfer_pair_id,
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
+
+
@router.get("/{transaction_id}", response_model=TransactionRead)
async def get_transaction(
transaction_id: uuid.UUID,
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index 710d6028..538339f0 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -64,6 +64,22 @@ class BulkCategorizeRequest(BaseModel):
category_id: Optional[uuid.UUID] = None
+class TransferCreate(BaseModel):
+ from_account_id: uuid.UUID
+ to_account_id: uuid.UUID
+ amount: Decimal
+ date: _Date
+ description: str
+ notes: Optional[str] = None
+ fx_rate: Optional[Decimal] = None
+
+
+class TransferRead(BaseModel):
+ debit: TransactionRead
+ credit: TransactionRead
+ transfer_pair_id: uuid.UUID
+
+
class TransactionImportPreview(BaseModel):
transactions: list[TransactionBase]
detected_format: str
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index f8d9c5b6..55b7b96e 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -10,9 +10,9 @@ from app.models.transaction import Transaction
from app.models.transaction_attachment import TransactionAttachment
from app.models.account import Account
from app.models.bank_connection import BankConnection
-from app.schemas.transaction import TransactionCreate, TransactionUpdate
+from app.schemas.transaction import TransactionCreate, TransactionUpdate, TransferCreate
from app.services.rule_service import apply_rules_to_transaction
-from app.services.fx_rate_service import stamp_primary_amount
+from app.services.fx_rate_service import stamp_primary_amount, convert as fx_convert
def _apply_fx_override(transaction, amount, amount_primary=None, fx_rate_used=None):
@@ -209,6 +209,101 @@ async def create_transaction(
return transaction
+async def create_transfer(
+ session: AsyncSession, user_id: uuid.UUID, data: TransferCreate
+) -> tuple[Transaction, Transaction]:
+ if data.from_account_id == data.to_account_id:
+ raise ValueError("Cannot transfer to the same account")
+
+ # Verify both accounts belong to user
+ from_result = await session.execute(
+ select(Account)
+ .outerjoin(BankConnection)
+ .where(
+ Account.id == data.from_account_id,
+ or_(Account.user_id == user_id, BankConnection.user_id == user_id),
+ )
+ )
+ from_account = from_result.scalar_one_or_none()
+ if not from_account:
+ raise ValueError("Source account not found")
+
+ to_result = await session.execute(
+ select(Account)
+ .outerjoin(BankConnection)
+ .where(
+ Account.id == data.to_account_id,
+ or_(Account.user_id == user_id, BankConnection.user_id == user_id),
+ )
+ )
+ to_account = to_result.scalar_one_or_none()
+ if not to_account:
+ raise ValueError("Destination account not found")
+
+ transfer_pair_id = uuid.uuid4()
+ from decimal import Decimal
+
+ # Debit transaction (from account)
+ debit_tx = Transaction(
+ user_id=user_id,
+ account_id=data.from_account_id,
+ description=data.description,
+ amount=data.amount,
+ currency=from_account.currency,
+ date=data.date,
+ type="debit",
+ source="transfer",
+ notes=data.notes,
+ transfer_pair_id=transfer_pair_id,
+ )
+ session.add(debit_tx)
+
+ # Credit transaction (to account) — convert if cross-currency
+ if from_account.currency != to_account.currency:
+ if data.fx_rate is not None:
+ from decimal import ROUND_HALF_UP
+ credit_amount = (Decimal(str(data.amount)) * Decimal(str(data.fx_rate))).quantize(
+ Decimal("0.01"), rounding=ROUND_HALF_UP
+ )
+ else:
+ converted_amount, _ = await fx_convert(
+ session, Decimal(str(data.amount)), from_account.currency, to_account.currency, data.date
+ )
+ credit_amount = converted_amount
+ else:
+ credit_amount = data.amount
+
+ credit_tx = Transaction(
+ user_id=user_id,
+ account_id=data.to_account_id,
+ description=data.description,
+ amount=credit_amount,
+ currency=to_account.currency,
+ date=data.date,
+ type="credit",
+ source="transfer",
+ notes=data.notes,
+ transfer_pair_id=transfer_pair_id,
+ )
+ session.add(credit_tx)
+ await session.flush()
+
+ # Stamp primary amounts on both
+ await stamp_primary_amount(session, user_id, debit_tx)
+ await stamp_primary_amount(session, user_id, credit_tx)
+
+ # For cross-currency transfers, both sides should show the same primary amount
+ if from_account.currency != to_account.currency and debit_tx.amount_primary is not None:
+ credit_tx.amount_primary = debit_tx.amount_primary
+ if credit_tx.amount and Decimal(str(credit_tx.amount)):
+ credit_tx.fx_rate_used = debit_tx.amount_primary / Decimal(str(credit_tx.amount))
+
+ await session.commit()
+ await session.refresh(debit_tx, ["category"])
+ await session.refresh(credit_tx, ["category"])
+ return debit_tx, credit_tx
+
+
async def update_transaction(
session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID, data: TransactionUpdate
) -> Optional[Transaction]:
@@ -239,6 +334,31 @@ async def update_transaction(
elif needs_restamp:
await stamp_primary_amount(session, user_id, transaction)
+ # Cascade changes to paired transfer transaction
+ cascade_fields = {"amount", "date", "description", "notes"}
+ if transaction.transfer_pair_id and (cascade_fields & update_data.keys()):
+ paired = await session.execute(
+ select(Transaction).where(
+ Transaction.transfer_pair_id == transaction.transfer_pair_id,
+ Transaction.id != transaction.id,
+ )
+ )
+ paired_tx = paired.scalar_one_or_none()
+ if paired_tx:
+ for key in cascade_fields & update_data.keys():
+ if key == "amount" and paired_tx.currency != transaction.currency:
+ from decimal import Decimal
+ converted, _ = await fx_convert(
+ session, Decimal(str(transaction.amount)),
+ transaction.currency, paired_tx.currency, transaction.date,
+ )
+ paired_tx.amount = converted
+ elif key != "amount":
+ setattr(paired_tx, key, update_data[key])
+ else:
+ paired_tx.amount = update_data[key]
+ await stamp_primary_amount(session, user_id, paired_tx)
+
await session.commit()
await session.refresh(transaction)
return transaction
@@ -271,8 +391,26 @@ async def delete_transaction(
# Clean up attachment files from storage before ORM cascade deletes DB records
from app.services.attachment_service import cleanup_attachment_files
- await cleanup_attachment_files(session, [transaction_id])
+ tx_ids_to_cleanup = [transaction_id]
+
+ # Cascade delete paired transfer transaction
+ paired_tx = None
+ if transaction.transfer_pair_id:
+ paired_result = await session.execute(
+ select(Transaction).where(
+ Transaction.transfer_pair_id == transaction.transfer_pair_id,
+ Transaction.id != transaction.id,
+ )
+ )
+ paired_tx = paired_result.scalar_one_or_none()
+ if paired_tx:
+ tx_ids_to_cleanup.append(paired_tx.id)
+
+ await cleanup_attachment_files(session, tx_ids_to_cleanup)
+
+ if paired_tx:
+ await session.delete(paired_tx)
await session.delete(transaction)
await session.commit()
return True
diff --git a/backend/tests/test_transfer_api.py b/backend/tests/test_transfer_api.py
new file mode 100644
index 00000000..40c03c78
--- /dev/null
+++ b/backend/tests/test_transfer_api.py
@@ -0,0 +1,284 @@
+import uuid
+from datetime import date
+from decimal import Decimal
+
+import pytest
+import pytest_asyncio
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.bank_connection import BankConnection
+from app.models.user import User
+
+
+@pytest_asyncio.fixture
+async def second_account(session: AsyncSession, test_user: User, test_connection: BankConnection) -> Account:
+ """Create a second test account (same currency)."""
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ connection_id=test_connection.id,
+ external_id="acc-ext-456",
+ name="Poupança",
+ type="savings",
+ balance=Decimal("5000.00"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+@pytest_asyncio.fixture
+async def usd_account(session: AsyncSession, test_user: User, test_connection: BankConnection) -> Account:
+ """Create a USD test account for cross-currency tests."""
+ account = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ connection_id=test_connection.id,
+ external_id="acc-ext-usd",
+ name="USD Account",
+ type="checking",
+ balance=Decimal("1000.00"),
+ currency="USD",
+ )
+ session.add(account)
+ await session.commit()
+ await session.refresh(account)
+ return account
+
+
+async def test_create_same_currency_transfer(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 500.00,
+ "date": date.today().isoformat(),
+ "description": "Transfer to savings",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+
+ # Check structure
+ assert "debit" in data
+ assert "credit" in data
+ assert "transfer_pair_id" in data
+
+ # Check debit
+ assert data["debit"]["type"] == "debit"
+ assert data["debit"]["source"] == "transfer"
+ assert float(data["debit"]["amount"]) == 500.00
+ assert data["debit"]["account_id"] == str(test_account.id)
+ assert data["debit"]["transfer_pair_id"] == data["transfer_pair_id"]
+
+ # Check credit
+ assert data["credit"]["type"] == "credit"
+ assert data["credit"]["source"] == "transfer"
+ assert float(data["credit"]["amount"]) == 500.00
+ assert data["credit"]["account_id"] == str(second_account.id)
+ assert data["credit"]["transfer_pair_id"] == data["transfer_pair_id"]
+
+ # Both share the same transfer_pair_id
+ assert data["debit"]["transfer_pair_id"] == data["credit"]["transfer_pair_id"]
+
+
+async def test_create_cross_currency_transfer(
+ client: AsyncClient, auth_headers, test_account: Account, usd_account: Account
+):
+ """Cross-currency transfer should convert amount."""
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(usd_account.id),
+ "amount": 1000.00,
+ "date": date.today().isoformat(),
+ "description": "Transfer BRL to USD",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+
+ assert data["debit"]["currency"] == "BRL"
+ assert data["credit"]["currency"] == "USD"
+ assert float(data["debit"]["amount"]) == 1000.00
+ # Credit amount may differ due to FX conversion (or be 1000 if FX falls back to 1:1)
+ assert float(data["credit"]["amount"]) > 0
+
+
+async def test_create_cross_currency_transfer_with_manual_fx_rate(
+ client: AsyncClient, auth_headers, test_account: Account, usd_account: Account
+):
+ """Cross-currency transfer with manual FX rate should use provided rate."""
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(usd_account.id),
+ "amount": 1000.00,
+ "date": date.today().isoformat(),
+ "description": "Transfer BRL to USD with manual rate",
+ "fx_rate": 0.20,
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+
+ assert data["debit"]["currency"] == "BRL"
+ assert data["credit"]["currency"] == "USD"
+ assert float(data["debit"]["amount"]) == 1000.00
+ # 1000 * 0.20 = 200.00
+ assert float(data["credit"]["amount"]) == 200.00
+
+
+async def test_reject_same_account_transfer(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(test_account.id),
+ "amount": 100.00,
+ "date": date.today().isoformat(),
+ "description": "Self transfer",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 400
+ assert "same account" in response.json()["detail"].lower()
+
+
+async def test_reject_invalid_account_transfer(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ fake_id = str(uuid.uuid4())
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": fake_id,
+ "amount": 100.00,
+ "date": date.today().isoformat(),
+ "description": "Invalid transfer",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 400
+ assert "not found" in response.json()["detail"].lower()
+
+
+async def test_delete_cascades_to_paired_transaction(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ # Create transfer
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 200.00,
+ "date": date.today().isoformat(),
+ "description": "Transfer to delete",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ debit_id = data["debit"]["id"]
+ credit_id = data["credit"]["id"]
+
+ # Delete debit — should cascade to credit
+ del_response = await client.delete(
+ f"/api/transactions/{debit_id}", headers=auth_headers
+ )
+ assert del_response.status_code == 204
+
+ # Both should be gone
+ assert (await client.get(f"/api/transactions/{debit_id}", headers=auth_headers)).status_code == 404
+ assert (await client.get(f"/api/transactions/{credit_id}", headers=auth_headers)).status_code == 404
+
+
+async def test_update_cascades_to_paired_transaction(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ # Create transfer
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 300.00,
+ "date": date.today().isoformat(),
+ "description": "Original description",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ data = response.json()
+ debit_id = data["debit"]["id"]
+ credit_id = data["credit"]["id"]
+
+ # Update debit description and date
+ new_date = "2025-06-15"
+ update_response = await client.patch(
+ f"/api/transactions/{debit_id}",
+ json={"description": "Updated description", "date": new_date},
+ headers=auth_headers,
+ )
+ assert update_response.status_code == 200
+
+ # Check credit was also updated
+ credit_response = await client.get(
+ f"/api/transactions/{credit_id}", headers=auth_headers
+ )
+ assert credit_response.status_code == 200
+ credit_data = credit_response.json()
+ assert credit_data["description"] == "Updated description"
+ assert credit_data["date"] == new_date
+
+
+async def test_transfers_appear_in_transaction_list(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ # Create transfer
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 100.00,
+ "date": date.today().isoformat(),
+ "description": "Listed transfer",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ transfer_pair_id = response.json()["transfer_pair_id"]
+
+ # List transactions
+ list_response = await client.get("/api/transactions", headers=auth_headers)
+ assert list_response.status_code == 200
+ items = list_response.json()["items"]
+
+ transfer_txns = [tx for tx in items if tx.get("transfer_pair_id") == transfer_pair_id]
+ assert len(transfer_txns) == 2
+ assert {tx["type"] for tx in transfer_txns} == {"debit", "credit"}
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 4fba1e44..b7bad8a7 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -430,6 +430,11 @@ function TransactionForm({
{t('transactions.syncedInfo')}
</div>
)}
+ {!!transaction?.transfer_pair_id && (
+ <div className="flex items-center gap-2 p-3 text-sm bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md text-blue-700 dark:text-blue-300">
+ {t('transactions.transferInfo')}
+ </div>
+ )}
{recurringMatch && (
<div className="flex items-center gap-2 p-3 text-sm bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md">
<span>{t('transactions.recurringInfo', {
@@ -537,9 +542,10 @@ function TransactionForm({
<div className="space-y-2">
<Label>{t('transactions.category')}</Label>
<select
- className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
value={categoryId}
onChange={(e) => setCategoryId(e.target.value)}
+ disabled={!!transaction?.transfer_pair_id}
>
<option value="">{t('transactions.noCategory')}</option>
{categories.map((cat) => (
diff --git a/frontend/src/components/transfer-dialog.tsx b/frontend/src/components/transfer-dialog.tsx
new file mode 100644
index 00000000..579e8894
--- /dev/null
+++ b/frontend/src/components/transfer-dialog.tsx
@@ -0,0 +1,279 @@
+import { useState, useEffect, useCallback } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { DatePickerInput } from '@/components/ui/date-picker-input'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogFooter,
+} from '@/components/ui/dialog'
+import { ArrowRight, Info } from 'lucide-react'
+import type { Account } from '@/types'
+
+export function TransferDialog({
+ open,
+ onClose,
+ accounts,
+ onSave,
+ loading,
+ defaultFromAccountId,
+}: {
+ open: boolean
+ onClose: () => void
+ accounts: Account[]
+ onSave: (data: {
+ from_account_id: string
+ to_account_id: string
+ amount: number
+ date: string
+ description: string
+ notes?: string
+ fx_rate?: number
+ }) => void
+ loading: boolean
+ defaultFromAccountId?: string
+}) {
+ const { t } = useTranslation()
+ const [fromAccountId, setFromAccountId] = useState(defaultFromAccountId || (accounts[0]?.id ?? ''))
+ const [toAccountId, setToAccountId] = useState('')
+ const [amount, setAmount] = useState('')
+ const [date, setDate] = useState(new Date().toISOString().split('T')[0])
+ const [description, setDescription] = useState('')
+ const [notes, setNotes] = useState('')
+ const [fxRate, setFxRate] = useState('')
+ const [convertedAmount, setConvertedAmount] = useState('')
+
+ // Reset form when dialog opens
+ const resetForm = useCallback(() => {
+ setFromAccountId(defaultFromAccountId || (accounts[0]?.id ?? ''))
+ setToAccountId('')
+ setAmount('')
+ setDate(new Date().toISOString().split('T')[0])
+ setDescription('')
+ setNotes('')
+ setFxRate('')
+ setConvertedAmount('')
+ }, [defaultFromAccountId, accounts])
+
+ useEffect(() => {
+ if (open) resetForm()
+ }, [open, resetForm])
+
+ const fromAccount = accounts.find((a) => a.id === fromAccountId)
+ const toAccount = accounts.find((a) => a.id === toAccountId)
+ const isCrossCurrency = fromAccount && toAccount && fromAccount.currency !== toAccount.currency
+ const isSameAccount = fromAccountId && toAccountId && fromAccountId === toAccountId
+
+ const availableToAccounts = accounts.filter((a) => a.id !== fromAccountId)
+
+ // Sync fx_rate <-> converted amount when one changes
+ const handleFxRateChange = (val: string) => {
+ setFxRate(val)
+ if (val && amount) {
+ setConvertedAmount((parseFloat(amount) * parseFloat(val)).toFixed(2))
+ } else {
+ setConvertedAmount('')
+ }
+ }
+
+ const handleConvertedAmountChange = (val: string) => {
+ setConvertedAmount(val)
+ if (val && amount && parseFloat(amount) > 0) {
+ setFxRate((parseFloat(val) / parseFloat(amount)).toFixed(6))
+ } else {
+ setFxRate('')
+ }
+ }
+
+ const handleAmountChange = (val: string) => {
+ setAmount(val)
+ if (fxRate && val) {
+ setConvertedAmount((parseFloat(val) * parseFloat(fxRate)).toFixed(2))
+ } else if (convertedAmount && val && parseFloat(val) > 0) {
+ setFxRate((parseFloat(convertedAmount) / parseFloat(val)).toFixed(6))
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t('transactions.transferTitle')}</DialogTitle>
+ </DialogHeader>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault()
+ onSave({
+ from_account_id: fromAccountId,
+ to_account_id: toAccountId,
+ amount: parseFloat(amount),
+ date,
+ description,
+ notes: notes.trim() || undefined,
+ fx_rate: isCrossCurrency && fxRate ? parseFloat(fxRate) : undefined,
+ })
+ }}
+ className="space-y-4"
+ >
+ <div className="grid grid-cols-[1fr,auto,1fr] items-end gap-2">
+ <div className="space-y-2">
+ <Label>{t('transactions.transferFromAccount')}</Label>
+ <select
+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
+ value={fromAccountId}
+ onChange={(e) => {
+ setFromAccountId(e.target.value)
+ if (e.target.value === toAccountId) setToAccountId('')
+ setFxRate('')
+ setConvertedAmount('')
+ }}
+ required
+ >
+ <option value="" disabled>{t('transactions.account')}</option>
+ {accounts.map((acc) => (
+ <option key={acc.id} value={acc.id}>
+ {acc.name} ({acc.currency})
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="pb-2">
+ <ArrowRight size={18} className="text-muted-foreground" />
+ </div>
+ <div className="space-y-2">
+ <Label>{t('transactions.transferToAccount')}</Label>
+ <select
+ className="w-full border border-border rounded-md px-3 py-2 text-sm bg-background focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
+ value={toAccountId}
+ onChange={(e) => {
+ setToAccountId(e.target.value)
+ setFxRate('')
+ setConvertedAmount('')
+ }}
+ required
+ >
+ <option value="" disabled>{t('transactions.account')}</option>
+ {availableToAccounts.map((acc) => (
+ <option key={acc.id} value={acc.id}>
+ {acc.name} ({acc.currency})
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+
+ {isSameAccount && (
+ <div className="flex items-center gap-2 p-3 text-sm bg-destructive/10 text-destructive rounded-md">
+ {t('transactions.transferSameAccount')}
+ </div>
+ )}
+
+ {isCrossCurrency && (
+ <div className="flex items-center gap-2 p-3 text-sm bg-blue-50 dark:bg-blue-950 border border-blue-200 dark:border-blue-800 rounded-md text-blue-700 dark:text-blue-300">
+ <Info size={14} className="shrink-0" />
+ {t('transactions.transferCrossCurrency')}
+ </div>
+ )}
+
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <Label>
+ {t('transactions.transferAmount')}
+ {fromAccount && <span className="text-muted-foreground ml-1">({fromAccount.currency})</span>}
+ </Label>
+ <Input
+ type="number"
+ step="0.01"
+ min="0.01"
+ value={amount}
+ onChange={(e) => handleAmountChange(e.target.value)}
+ required
+ />
+ </div>
+ <div className="space-y-2">
+ <Label>{t('transactions.date')}</Label>
+ <DatePickerInput
+ value={date}
+ onChange={setDate}
+ className="w-full justify-start"
+ />
+ </div>
+ </div>
+
+ {isCrossCurrency && (
+ <div className="space-y-3 p-3 bg-muted/50 border border-border rounded-md">
+ <p className="text-xs font-medium text-muted-foreground">
+ {t('transactions.conversion')}{' '}
+ <span className="font-normal">({t('transactions.conversionHint')})</span>
+ </p>
+ <div className="grid grid-cols-2 gap-4">
+ <div className="space-y-2">
+ <Label className="text-xs">
+ {t('transactions.convertedAmount', { currency: toAccount?.currency })}
+ </Label>
+ <Input
+ type="number"
+ step="0.01"
+ min="0"
+ value={convertedAmount}
+ onChange={(e) => handleConvertedAmountChange(e.target.value)}
+ placeholder={t('transactions.autoCalculated')}
+ />
+ </div>
+ <div className="space-y-2">
+ <Label className="text-xs">{t('transactions.exchangeRate')}</Label>
+ <Input
+ type="number"
+ step="0.000001"
+ min="0"
+ value={fxRate}
+ onChange={(e) => handleFxRateChange(e.target.value)}
+ placeholder={t('transactions.autoCalculated')}
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ <div className="space-y-2">
+ <Label>{t('transactions.transferDescription')}</Label>
+ <Input
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ required
+ />
+ </div>
+
+ <div className="space-y-2">
+ <Label>
+ {t('transactions.transferNotes')}{' '}
+ <span className="text-muted-foreground font-normal text-xs">({t('transactions.notesHint')})</span>
+ </Label>
+ <textarea
+ className="w-full border border-input rounded-md px-3 py-2 text-sm bg-background resize-none focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-0"
+ rows={2}
+ value={notes}
+ onChange={(e) => setNotes(e.target.value)}
+ />
+ </div>
+
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="submit"
+ disabled={loading || !fromAccountId || !toAccountId || !!isSameAccount}
+ >
+ {loading ? t('common.loading') : t('common.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index e4c6e892..2b57d876 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -239,6 +239,18 @@ export const transactions = {
delete: async (id: string): Promise<void> => {
await api.delete(`/transactions/${id}`)
},
+ createTransfer: async (transfer: {
+ from_account_id: string
+ to_account_id: string
+ amount: number
+ date: string
+ description: string
+ notes?: string
+ fx_rate?: number
+ }): Promise<{ debit: Transaction; credit: Transaction; transfer_pair_id: string }> => {
+ const { data } = await api.post('/transactions/transfer', transfer)
+ return data
+ },
bulkCategorize: async (transactionIds: string[], categoryId: string | null): Promise<{ updated: number }> => {
const { data } = await api.patch('/transactions/bulk-categorize', {
transaction_ids: transactionIds,
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 906339c6..3b3a0a8c 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -149,7 +149,17 @@
"attachmentTypeNotAllowed": "File type not supported. Allowed: jpg, jpeg, png, webp, gif, heic, pdf",
"attachmentMaxReached": "Maximum number of attachments reached",
"attachmentRenamed": "Attachment renamed",
- "attachmentRename": "Rename"
+ "attachmentRename": "Rename",
+ "transferCreated": "Transfer created",
+ "transferTitle": "Transfer Between Accounts",
+ "transferFromAccount": "From account",
+ "transferToAccount": "To account",
+ "transferAmount": "Amount",
+ "transferCrossCurrency": "Currencies differ — amount will be converted automatically",
+ "transferSameAccount": "Source and destination must be different",
+ "transferDescription": "Description",
+ "transferNotes": "Notes",
+ "transferInfo": "This is a transfer — changes to description, date, and notes will apply to both sides"
},
"accounts": {
"title": "Accounts",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 4dca50ee..7b6dbe42 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -149,7 +149,17 @@
"attachmentTypeNotAllowed": "Tipo de arquivo não suportado. Permitidos: jpg, jpeg, png, webp, gif, heic, pdf",
"attachmentMaxReached": "Número máximo de anexos atingido",
"attachmentRenamed": "Anexo renomeado",
- "attachmentRename": "Renomear"
+ "attachmentRename": "Renomear",
+ "transferCreated": "Transferência criada",
+ "transferTitle": "Transferência Entre Contas",
+ "transferFromAccount": "Conta de origem",
+ "transferToAccount": "Conta de destino",
+ "transferAmount": "Valor",
+ "transferCrossCurrency": "Moedas diferentes — o valor será convertido automaticamente",
+ "transferSameAccount": "Origem e destino devem ser diferentes",
+ "transferDescription": "Descrição",
+ "transferNotes": "Notas",
+ "transferInfo": "Esta é uma transferência — alterações na descrição, data e notas serão aplicadas em ambos os lados"
},
"accounts": {
"title": "Contas",
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index ab12a907..010225bf 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -11,6 +11,7 @@ import { Button } from '@/components/ui/button'
import { ArrowLeft, ArrowLeftRight, Clock, Paperclip, X } from 'lucide-react'
import { CategoryIcon } from '@/components/category-icon'
import { TransactionDialog, extractApiError } from '@/components/transaction-dialog'
+import { TransferDialog } from '@/components/transfer-dialog'
import { DatePickerInput } from '@/components/ui/date-picker-input'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useAuth } from '@/contexts/auth-context'
@@ -52,6 +53,7 @@ export default function AccountDetailPage() {
const queryClient = useQueryClient()
const [dialogOpen, setDialogOpen] = useState(false)
const [editingTx, setEditingTx] = useState<Transaction | null>(null)
+ const [transferDialogOpen, setTransferDialogOpen] = useState(false)
const [filterFrom, setFilterFrom] = useState(defaultFrom)
const [filterTo, setFilterTo] = useState(defaultTo)
const [showPrimary, setShowPrimary] = useState(false)
@@ -137,6 +139,30 @@ export default function AccountDetailPage() {
onError: () => toast.error(t('common.error')),
})
+ const transferMutation = useMutation({
+ mutationFn: (data: {
+ from_account_id: string
+ to_account_id: string
+ amount: number
+ date: string
+ description: string
+ notes?: string
+ fx_rate?: number
+ }) => transactions.createTransfer(data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ queryClient.invalidateQueries({ queryKey: ['accounts'] })
+ queryClient.invalidateQueries({ queryKey: ['accounts', id, 'summary'] })
+ queryClient.invalidateQueries({ queryKey: ['accounts', id, 'balance-history'] })
+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })
+ setTransferDialogOpen(false)
+ toast.success(t('transactions.transferCreated'))
+ },
+ onError: (error) => {
+ toast.error(extractApiError(error))
+ },
+ })
+
// Whether to use primary currency amounts (for foreign-currency accounts with toggle, or domestic accounts with foreign txs)
const isCreditCard = account?.type === 'credit_card'
const isForeignCurrency = account ? account.currency !== userCurrency : false
@@ -212,6 +238,12 @@ export default function AccountDetailPage() {
<span className="text-xs font-medium bg-muted text-muted-foreground px-2.5 py-1 rounded-full capitalize">
{account.type}
</span>
+ {!account.is_closed && (
+ <Button variant="outline" size="sm" className="ml-auto" onClick={() => setTransferDialogOpen(true)}>
+ <ArrowLeftRight className="h-4 w-4 mr-1" />
+ {t('transactions.transfer')}
+ </Button>
+ )}
</div>
<div className="flex items-center gap-2 sm:gap-3 flex-wrap">
<div className="flex items-center gap-2">
@@ -505,6 +537,15 @@ export default function AccountDetailPage() {
error={updateMutation.error ? extractApiError(updateMutation.error) : null}
isSynced={editingTx?.source === 'sync'}
/>
+
+ <TransferDialog
+ open={transferDialogOpen}
+ onClose={() => setTransferDialogOpen(false)}
+ accounts={accountsList ?? []}
+ onSave={(data) => transferMutation.mutate(data)}
+ loading={transferMutation.isPending}
+ defaultFromAccountId={id}
+ />
</div>
)
}
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index 2f138436..66231262 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -14,11 +14,12 @@ import {
} from '@/components/ui/table'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
-import { AlertTriangle, Check, Download, Paperclip, Search, X } from 'lucide-react'
+import { AlertTriangle, ArrowLeftRight, Check, Download, Paperclip, Search, X } from 'lucide-react'
import type { Transaction } from '@/types'
import { PageHeader } from '@/components/page-header'
import { CategoryIcon } from '@/components/category-icon'
import { TransactionDialog, extractApiError } from '@/components/transaction-dialog'
+import { TransferDialog } from '@/components/transfer-dialog'
import { DatePickerInput } from '@/components/ui/date-picker-input'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useAuth } from '@/contexts/auth-context'
@@ -51,6 +52,7 @@ export default function TransactionsPage() {
const [editingTx, setEditingTx] = useState<Transaction | null>(null)
const [tagFilter, setTagFilter] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
+ const [transferDialogOpen, setTransferDialogOpen] = useState(false)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [bulkCategory, setBulkCategory] = useState<string>('')
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)
@@ -178,6 +180,28 @@ export default function TransactionsPage() {
},
})
+ const transferMutation = useMutation({
+ mutationFn: (data: {
+ from_account_id: string
+ to_account_id: string
+ amount: number
+ date: string
+ description: string
+ notes?: string
+ fx_rate?: number
+ }) => transactions.createTransfer(data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ queryClient.invalidateQueries({ queryKey: ['accounts'] })
+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })
+ setTransferDialogOpen(false)
+ toast.success(t('transactions.transferCreated'))
+ },
+ onError: (error) => {
+ toast.error(extractApiError(error))
+ },
+ })
+
const toggleSelect = (id: string) => {
setSelectedIds(prev => {
const next = new Set(prev)
@@ -241,6 +265,10 @@ export default function TransactionsPage() {
<Download size={16} className="mr-1.5" />
{exporting ? t('transactions.exporting') : t('transactions.exportCsv')}
</Button>
+ <Button variant="outline" onClick={() => setTransferDialogOpen(true)}>
+ <ArrowLeftRight size={16} className="mr-1.5" />
+ {t('transactions.transfer')}
+ </Button>
<Button onClick={() => { setEditingTx(null); setDialogOpen(true) }}>
+ {t('transactions.addManual')}
</Button>
@@ -375,6 +403,12 @@ export default function TransactionsPage() {
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="text-sm font-semibold text-foreground truncate">{tx.description}</p>
+ {!!tx.transfer_pair_id && (
+ <span className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-blue-600 bg-blue-50 border border-blue-200 px-1.5 py-0.5 rounded-full">
+ <ArrowLeftRight className="h-3 w-3" />
+ {t('transactions.transfer')}
+ </span>
+ )}
{recurringList?.some(r => r.description === tx.description && r.type === tx.type) && (
<span className="text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1.5 py-0.5 rounded-full">
{t('transactions.recurringBadge')}
@@ -519,6 +553,15 @@ export default function TransactionsPage() {
</div>
</div>
+ {/* Transfer Dialog */}
+ <TransferDialog
+ open={transferDialogOpen}
+ onClose={() => setTransferDialogOpen(false)}
+ accounts={accountsList ?? []}
+ onSave={(data) => transferMutation.mutate(data)}
+ loading={transferMutation.isPending}
+ />
+
{/* Add/Edit Dialog */}
<TransactionDialog
open={dialogOpen}