Skip to content

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

feat: adding manual inter-account transfers

Tássio Noronha59c9104dbc36
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index 630b4fb9..0356a9eb 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, TransferCreate, TransferRead
+from app.schemas.transaction import BulkCategorizeRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead
from app.services import transaction_service
router = APIRouter(prefix="/api/transactions", tags=["transactions"])
@@ -162,6 +162,51 @@ async def create_transfer(
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
[email protected]("/link-transfer", response_model=TransferRead)
+async def link_transfer(
+ data: LinkTransferRequest,
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ """Link two existing transactions as an inter-account transfer pair."""
+ try:
+ debit_tx, credit_tx = await transaction_service.link_existing_as_transfer(
+ session, user.id, data.transaction_ids
+ )
+ 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))
+
+
[email protected]("/{transaction_id}/transfer-candidates", response_model=list[TransactionRead])
+async def get_transfer_candidates(
+ transaction_id: uuid.UUID,
+ limit: int = Query(10, ge=1, le=50),
+ window_days: int = Query(30, ge=1, le=365),
+ session: AsyncSession = Depends(get_async_session),
+ user: User = Depends(current_active_user),
+):
+ """Return ranked candidate transactions to link as a transfer counterpart."""
+ anchor = await transaction_service.get_transaction(session, transaction_id, user.id)
+ if not anchor:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")
+ candidates = await transaction_service.get_transfer_candidates(
+ session, user.id, transaction_id, limit=limit, window_days=window_days
+ )
+ primary_currency = user.primary_currency
+ return [
+ _tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency)
+ for tx in candidates
+ ]
+
+
@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 65b550a8..c4e55a4e 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -79,6 +79,10 @@ class TransferCreate(BaseModel):
fx_rate: Optional[Decimal] = None
+class LinkTransferRequest(BaseModel):
+ transaction_ids: list[uuid.UUID]
+
+
class TransferRead(BaseModel):
debit: TransactionRead
credit: TransactionRead
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index 8085c9fa..8c64c61d 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -323,6 +323,152 @@ async def create_transfer(
return debit_tx, credit_tx
+async def get_transfer_candidates(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ transaction_id: uuid.UUID,
+ limit: int = 10,
+ window_days: int = 30,
+) -> list[Transaction]:
+ """Return ranked transfer-pair candidates for the given anchor transaction.
+
+ Filters: different account, opposing type, not already linked, within
+ ``window_days`` of the anchor's date. Ranked by date proximity, then
+ primary-currency amount closeness (so cross-currency pairs match well).
+ """
+ from datetime import timedelta
+ from decimal import Decimal
+
+ anchor = await get_transaction(session, transaction_id, user_id)
+ if not anchor:
+ return []
+ if anchor.transfer_pair_id is not None:
+ return []
+
+ opposing_type = "credit" if anchor.type == "debit" else "debit"
+ from_date = anchor.date - timedelta(days=window_days)
+ to_date = anchor.date + timedelta(days=window_days)
+
+ result = await session.execute(
+ select(Transaction)
+ .outerjoin(Account)
+ .outerjoin(BankConnection)
+ .where(
+ or_(
+ Transaction.user_id == user_id,
+ BankConnection.user_id == user_id,
+ ),
+ Transaction.id != anchor.id,
+ Transaction.account_id != anchor.account_id,
+ Transaction.type == opposing_type,
+ Transaction.transfer_pair_id.is_(None),
+ Transaction.source != "opening_balance",
+ Transaction.date >= from_date,
+ Transaction.date <= to_date,
+ )
+ .options(
+ selectinload(Transaction.category),
+ selectinload(Transaction.account),
+ selectinload(Transaction.payee_entity),
+ )
+ )
+ candidates = list(result.scalars().all())
+
+ anchor_amount_primary = (
+ Decimal(str(anchor.amount_primary)) if anchor.amount_primary is not None else None
+ )
+
+ def score(tx: Transaction) -> tuple[int, Decimal]:
+ date_diff = abs((tx.date - anchor.date).days)
+ if anchor_amount_primary is not None and tx.amount_primary is not None:
+ amount_diff = abs(
+ Decimal(str(tx.amount_primary)).copy_abs()
+ - anchor_amount_primary.copy_abs()
+ )
+ else:
+ amount_diff = abs(
+ Decimal(str(tx.amount)).copy_abs()
+ - Decimal(str(anchor.amount)).copy_abs()
+ )
+ return (date_diff, amount_diff)
+
+ candidates.sort(key=score)
+ candidates = candidates[:limit]
+
+ # Hydrate fields the schema needs
+ if candidates:
+ tx_ids = [tx.id for tx in candidates]
+ count_rows = await session.execute(
+ select(
+ TransactionAttachment.transaction_id,
+ func.count(TransactionAttachment.id),
+ )
+ .where(TransactionAttachment.transaction_id.in_(tx_ids))
+ .group_by(TransactionAttachment.transaction_id)
+ )
+ counts = dict(count_rows.all())
+ for tx in candidates:
+ tx.attachment_count = counts.get(tx.id, 0)
+ tx.payee_name = tx.payee_entity.name if tx.payee_entity else None
+
+ return candidates
+
+
+async def link_existing_as_transfer(
+ session: AsyncSession, user_id: uuid.UUID, transaction_ids: list[uuid.UUID]
+) -> tuple[Transaction, Transaction]:
+ """Link two existing transactions as a transfer pair.
+
+ Permissive by design: amounts don't have to match. Validation enforces
+ ownership, opposing types, different accounts, and that neither side is
+ already part of an existing transfer.
+ """
+ if len(transaction_ids) != 2:
+ raise ValueError("Exactly two transactions are required")
+ if transaction_ids[0] == transaction_ids[1]:
+ raise ValueError("Cannot link a transaction to itself")
+
+ result = await session.execute(
+ select(Transaction)
+ .outerjoin(Account)
+ .outerjoin(BankConnection)
+ .where(
+ Transaction.id.in_(transaction_ids),
+ or_(
+ Transaction.user_id == user_id,
+ BankConnection.user_id == user_id,
+ ),
+ )
+ )
+ txns = list(result.scalars().all())
+ if len(txns) != 2:
+ raise ValueError("Transaction not found")
+
+ for tx in txns:
+ if tx.transfer_pair_id is not None:
+ raise ValueError("Transaction is already part of a transfer")
+
+ if txns[0].account_id == txns[1].account_id:
+ raise ValueError("Transactions must be in different accounts")
+
+ types = {tx.type for tx in txns}
+ if types != {"debit", "credit"}:
+ raise ValueError("Transactions must be one debit and one credit")
+
+ transfer_pair_id = uuid.uuid4()
+ for tx in txns:
+ tx.transfer_pair_id = transfer_pair_id
+ tx.category_id = None # transfers are excluded from category reports
+
+ await session.commit()
+ for tx in txns:
+ await session.refresh(tx, ["category"])
+
+ debit_tx = next(tx for tx in txns if tx.type == "debit")
+ credit_tx = next(tx for tx in txns if tx.type == "credit")
+ return debit_tx, credit_tx
+
+
async def update_transaction(
session: AsyncSession, transaction_id: uuid.UUID, user_id: uuid.UUID, data: TransactionUpdate
) -> Optional[Transaction]:
diff --git a/backend/tests/test_transfer_api.py b/backend/tests/test_transfer_api.py
index 40c03c78..8fa2f175 100644
--- a/backend/tests/test_transfer_api.py
+++ b/backend/tests/test_transfer_api.py
@@ -255,6 +255,336 @@ async def test_update_cascades_to_paired_transaction(
assert credit_data["date"] == new_date
+async def _create_manual_tx(
+ client: AsyncClient,
+ auth_headers: dict,
+ account_id: uuid.UUID,
+ *,
+ type: str,
+ amount: float,
+ description: str,
+ tx_date: str | None = None,
+) -> dict:
+ response = await client.post(
+ "/api/transactions",
+ json={
+ "account_id": str(account_id),
+ "description": description,
+ "amount": amount,
+ "type": type,
+ "date": tx_date or date.today().isoformat(),
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 201
+ return response.json()
+
+
+async def test_link_existing_transactions_as_transfer(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ debit = await _create_manual_tx(
+ client, auth_headers, test_account.id, type="debit", amount=200.00, description="Sent"
+ )
+ credit = await _create_manual_tx(
+ client, auth_headers, second_account.id, type="credit", amount=200.00, description="Received"
+ )
+
+ response = await client.post(
+ "/api/transactions/link-transfer",
+ json={"transaction_ids": [debit["id"], credit["id"]]},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ data = response.json()
+
+ assert data["debit"]["id"] == debit["id"]
+ assert data["credit"]["id"] == credit["id"]
+ assert data["debit"]["transfer_pair_id"] == data["credit"]["transfer_pair_id"]
+ assert data["transfer_pair_id"] == data["debit"]["transfer_pair_id"]
+
+
+async def test_link_transfer_permissive_with_amount_mismatch(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ """Linking should succeed even if amounts differ — user is asserting intent."""
+ debit = await _create_manual_tx(
+ client, auth_headers, test_account.id, type="debit", amount=100.00, description="Sent with fee"
+ )
+ credit = await _create_manual_tx(
+ client, auth_headers, second_account.id, type="credit", amount=98.50, description="Received minus fee"
+ )
+
+ response = await client.post(
+ "/api/transactions/link-transfer",
+ json={"transaction_ids": [debit["id"], credit["id"]]},
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+
+
+async def test_link_transfer_rejects_same_account(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ debit = await _create_manual_tx(
+ client, auth_headers, test_account.id, type="debit", amount=50.00, description="A"
+ )
+ credit = await _create_manual_tx(
+ client, auth_headers, test_account.id, type="credit", amount=50.00, description="B"
+ )
+
+ response = await client.post(
+ "/api/transactions/link-transfer",
+ json={"transaction_ids": [debit["id"], credit["id"]]},
+ headers=auth_headers,
+ )
+ assert response.status_code == 400
+ assert "different accounts" in response.json()["detail"].lower()
+
+
+async def test_link_transfer_rejects_same_type(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ a = await _create_manual_tx(
+ client, auth_headers, test_account.id, type="debit", amount=50.00, description="A"
+ )
+ b = await _create_manual_tx(
+ client, auth_headers, second_account.id, type="debit", amount=50.00, description="B"
+ )
+
+ response = await client.post(
+ "/api/transactions/link-transfer",
+ json={"transaction_ids": [a["id"], b["id"]]},
+ headers=auth_headers,
+ )
+ assert response.status_code == 400
+ assert "debit and one credit" in response.json()["detail"].lower()
+
+
+async def test_link_transfer_rejects_already_linked(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ # Create an existing transfer
+ response = await client.post(
+ "/api/transactions/transfer",
+ json={
+ "from_account_id": str(test_account.id),
+ "to_account_id": str(second_account.id),
+ "amount": 75.00,
+ "date": date.today().isoformat(),
+ "description": "Already linked",
+ },
+ headers=auth_headers,
+ )
+ debit_id = response.json()["debit"]["id"]
+
+ # New unlinked transaction
+ other = await _create_manual_tx(
+ client, auth_headers, second_account.id, type="credit", amount=75.00, description="Other"
+ )
+
+ response = await client.post(
+ "/api/transactions/link-transfer",
+ json={"transaction_ids": [debit_id, other["id"]]},
+ headers=auth_headers,
+ )
+ assert response.status_code == 400
+ assert "already part of a transfer" in response.json()["detail"].lower()
+
+
+async def test_link_transfer_excludes_from_reports(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ """After linking, both transactions should be excluded when exclude_transfers=true."""
+ debit = await _create_manual_tx(
+ client, auth_headers, test_account.id, type="debit", amount=300.00, description="To exclude"
+ )
+ credit = await _create_manual_tx(
+ client, auth_headers, second_account.id, type="credit", amount=300.00, description="To exclude"
+ )
+
+ await client.post(
+ "/api/transactions/link-transfer",
+ json={"transaction_ids": [debit["id"], credit["id"]]},
+ headers=auth_headers,
+ )
+
+ list_response = await client.get(
+ "/api/transactions", params={"exclude_transfers": True}, headers=auth_headers
+ )
+ assert list_response.status_code == 200
+ items = list_response.json()["items"]
+ ids = {tx["id"] for tx in items}
+ assert debit["id"] not in ids
+ assert credit["id"] not in ids
+
+
+async def test_transfer_candidates_returns_ranked_matches(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ """Closest date and amount candidates should rank first."""
+ today = date.today()
+ anchor = await _create_manual_tx(
+ client, auth_headers, test_account.id,
+ type="debit", amount=500.00, description="Anchor",
+ tx_date=today.isoformat(),
+ )
+
+ # Best match: same date, exact amount
+ best = await _create_manual_tx(
+ client, auth_headers, second_account.id,
+ type="credit", amount=500.00, description="Best",
+ tx_date=today.isoformat(),
+ )
+ # Same amount but a few days off
+ far_date = await _create_manual_tx(
+ client, auth_headers, second_account.id,
+ type="credit", amount=500.00, description="Far date",
+ tx_date=(today - __import__("datetime").timedelta(days=5)).isoformat(),
+ )
+ # Same date but different amount
+ different_amount = await _create_manual_tx(
+ client, auth_headers, second_account.id,
+ type="credit", amount=499.00, description="Different amount",
+ tx_date=today.isoformat(),
+ )
+
+ response = await client.get(
+ f"/api/transactions/{anchor['id']}/transfer-candidates",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ candidates = response.json()
+ ids = [c["id"] for c in candidates]
+ assert best["id"] in ids
+ assert different_amount["id"] in ids
+ assert far_date["id"] in ids
+ # Best (same date + exact amount) should rank first
+ assert ids[0] == best["id"]
+ # Same date with different amount should beat different date with same amount
+ assert ids.index(different_amount["id"]) < ids.index(far_date["id"])
+
+
+async def test_transfer_candidates_excludes_same_account(
+ client: AsyncClient, auth_headers, test_account: Account
+):
+ anchor = await _create_manual_tx(
+ client, auth_headers, test_account.id,
+ type="debit", amount=100.00, description="Anchor",
+ )
+ same_account = await _create_manual_tx(
+ client, auth_headers, test_account.id,
+ type="credit", amount=100.00, description="Same account",
+ )
+
+ response = await client.get(
+ f"/api/transactions/{anchor['id']}/transfer-candidates",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ ids = [c["id"] for c in response.json()]
+ assert same_account["id"] not in ids
+
+
+async def test_transfer_candidates_excludes_same_type(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ anchor = await _create_manual_tx(
+ client, auth_headers, test_account.id,
+ type="debit", amount=100.00, description="Anchor",
+ )
+ same_type = await _create_manual_tx(
+ client, auth_headers, second_account.id,
+ type="debit", amount=100.00, description="Same type",
+ )
+
+ response = await client.get(
+ f"/api/transactions/{anchor['id']}/transfer-candidates",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ ids = [c["id"] for c in response.json()]
+ assert same_type["id"] not in ids
+
+
+async def test_transfer_candidates_excludes_already_linked(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ anchor = await _create_manual_tx(
+ client, auth_headers, test_account.id,
+ type="debit", amount=100.00, description="Anchor",
+ )
+ # Create a transfer pair that already exists in second_account
+ pair_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": "Existing transfer",
+ },
+ headers=auth_headers,
+ )
+ linked_credit_id = pair_response.json()["credit"]["id"]
+
+ response = await client.get(
+ f"/api/transactions/{anchor['id']}/transfer-candidates",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ ids = [c["id"] for c in response.json()]
+ assert linked_credit_id not in ids
+
+
+async def test_transfer_candidates_respects_date_window(
+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account
+):
+ from datetime import timedelta
+ today = date.today()
+ anchor = await _create_manual_tx(
+ client, auth_headers, test_account.id,
+ type="debit", amount=100.00, description="Anchor",
+ tx_date=today.isoformat(),
+ )
+ out_of_window = await _create_manual_tx(
+ client, auth_headers, second_account.id,
+ type="credit", amount=100.00, description="Old",
+ tx_date=(today - timedelta(days=60)).isoformat(),
+ )
+
+ response = await client.get(
+ f"/api/transactions/{anchor['id']}/transfer-candidates",
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ ids = [c["id"] for c in response.json()]
+ assert out_of_window["id"] not in ids
+
+
+async def test_transfer_candidates_returns_404_for_unknown_anchor(
+ client: AsyncClient, auth_headers
+):
+ fake_id = uuid.uuid4()
+ response = await client.get(
+ f"/api/transactions/{fake_id}/transfer-candidates",
+ headers=auth_headers,
+ )
+ assert response.status_code == 404
+
+
@pytest.mark.asyncio
async def test_transfers_appear_in_transaction_list(
client: AsyncClient, auth_headers, test_account: Account, second_account: Account
diff --git a/frontend/src/components/link-transfer-dialog.tsx b/frontend/src/components/link-transfer-dialog.tsx
new file mode 100644
index 00000000..2a8800fd
--- /dev/null
+++ b/frontend/src/components/link-transfer-dialog.tsx
@@ -0,0 +1,341 @@
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery } from '@tanstack/react-query'
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogFooter,
+} from '@/components/ui/dialog'
+import { Skeleton } from '@/components/ui/skeleton'
+import { ArrowRight, AlertTriangle, Info, ArrowLeft, Search, Sparkles } from 'lucide-react'
+import { transactions as transactionsApi } from '@/lib/api'
+import type { Account, Transaction } from '@/types'
+
+function formatCurrency(value: number, currency = 'USD', locale = 'en-US') {
+ return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(value)
+}
+
+type CounterpartCardProps = {
+ label: string
+ description: string
+ account: string
+ date: string
+ amount: number
+ currency: string
+ sign: '+' | '−'
+ locale: string
+}
+
+function CounterpartCard({ label, description, account, date, amount, currency, sign, locale }: CounterpartCardProps) {
+ const colorClass = sign === '+' ? 'text-emerald-600' : 'text-rose-500'
+ return (
+ <div className="rounded-lg border border-border bg-muted/30 p-3">
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-1">
+ {label}
+ </p>
+ <p className="text-sm font-semibold text-foreground truncate" title={description}>
+ {description}
+ </p>
+ <p className="text-xs text-muted-foreground truncate">{account}</p>
+ <p className="text-xs text-muted-foreground mt-1">
+ {new Date(date + 'T00:00:00').toLocaleDateString(locale)}
+ </p>
+ <p className={`text-sm font-bold tabular-nums ${colorClass} mt-2`}>
+ {sign}
+ {formatCurrency(amount, currency, locale)}
+ </p>
+ </div>
+ )
+}
+
+type Props = {
+ open: boolean
+ onClose: () => void
+ /** Direct mode (legacy 2-selection): both must be provided. */
+ debit?: Transaction | null
+ credit?: Transaction | null
+ /** Picker mode: pass a single anchor transaction. */
+ anchor?: Transaction | null
+ accounts: Account[]
+ onConfirm: (debitId: string, creditId: string) => void
+ loading: boolean
+}
+
+export function LinkTransferDialog({
+ open,
+ onClose,
+ debit,
+ credit,
+ anchor,
+ accounts,
+ onConfirm,
+ loading,
+}: Props) {
+ const { t, i18n } = useTranslation()
+ const locale = i18n.language === 'en' ? 'en-US' : i18n.language
+
+ const isDirectMode = !!(debit && credit)
+ const isPickerMode = !!anchor && !isDirectMode
+
+ // In picker mode, the user clicks a candidate to "select" it; that promotes
+ // us into a small confirm step which reuses the same FROM/TO card layout.
+ const [pickedCandidate, setPickedCandidate] = useState<Transaction | null>(null)
+ const [searchTerm, setSearchTerm] = useState('')
+
+ // Reset internal picker state when the dialog opens with a new anchor or
+ // when it transitions from open → closed. Done during render via the
+ // "adjusting state on prop change" pattern to avoid effect cascades.
+ const sessionKey = `${open ? '1' : '0'}-${anchor?.id ?? ''}`
+ const [prevSessionKey, setPrevSessionKey] = useState(sessionKey)
+ if (sessionKey !== prevSessionKey) {
+ setPrevSessionKey(sessionKey)
+ setPickedCandidate(null)
+ setSearchTerm('')
+ }
+
+ const { data: candidates, isLoading: candidatesLoading } = useQuery({
+ queryKey: ['transfer-candidates', anchor?.id],
+ queryFn: () => transactionsApi.transferCandidates(anchor!.id),
+ enabled: open && isPickerMode,
+ })
+
+ const filteredCandidates = useMemo(() => {
+ if (!candidates) return []
+ const term = searchTerm.trim().toLowerCase()
+ if (!term) return candidates
+ return candidates.filter((c) => c.description.toLowerCase().includes(term))
+ }, [candidates, searchTerm])
+
+ // The "Best match" badge should only appear when the top-ranked candidate
+ // is genuinely close to the anchor — same date neighborhood AND amount
+ // close enough to suggest they're the same transfer (allowing for FX/fees).
+ const bestMatchId = useMemo(() => {
+ if (!candidates || candidates.length === 0 || !anchor) return null
+ const top = candidates[0]
+ const anchorDate = new Date(anchor.date + 'T00:00:00').getTime()
+ const candidateDate = new Date(top.date + 'T00:00:00').getTime()
+ const dayDiff = Math.abs(candidateDate - anchorDate) / (1000 * 60 * 60 * 24)
+ if (dayDiff > 3) return null
+ const anchorAmount = Math.abs(Number(anchor.amount_primary ?? anchor.amount))
+ const topAmount = Math.abs(Number(top.amount_primary ?? top.amount))
+ if (anchorAmount === 0) return null
+ const pctDiff = Math.abs(anchorAmount - topAmount) / anchorAmount
+ if (pctDiff > 0.02) return null
+ return top.id
+ }, [candidates, anchor])
+
+ // Resolve which transactions are currently shown as the FROM/TO pair.
+ const effectiveDebit: Transaction | null = useMemo(() => {
+ if (isDirectMode) return debit ?? null
+ if (!anchor || !pickedCandidate) return null
+ return anchor.type === 'debit' ? anchor : pickedCandidate
+ }, [isDirectMode, debit, anchor, pickedCandidate])
+
+ const effectiveCredit: Transaction | null = useMemo(() => {
+ if (isDirectMode) return credit ?? null
+ if (!anchor || !pickedCandidate) return null
+ return anchor.type === 'credit' ? anchor : pickedCandidate
+ }, [isDirectMode, credit, anchor, pickedCandidate])
+
+ if (!open) return null
+ if (!isDirectMode && !isPickerMode) return null
+
+ // Picker view (no candidate selected yet)
+ if (isPickerMode && !pickedCandidate) {
+ const anchorAccount = accounts.find((a) => a.id === anchor!.account_id)
+ const anchorAmount = Math.abs(Number(anchor!.amount))
+
+ return (
+ <Dialog open={open} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-xl overflow-hidden">
+ <DialogHeader>
+ <DialogTitle>{t('transactions.linkTransferPickerTitle')}</DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-4 min-w-0">
+ <p className="text-sm text-muted-foreground">
+ {t('transactions.linkTransferPickerDescription')}
+ </p>
+
+ <CounterpartCard
+ label={t('transactions.linkTransferAnchor')}
+ description={anchor!.description}
+ account={anchorAccount?.name ?? '—'}
+ date={anchor!.date}
+ amount={anchorAmount}
+ currency={anchor!.currency}
+ sign={anchor!.type === 'debit' ? '−' : '+'}
+ locale={locale}
+ />
+
+ <div className="relative">
+ <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="text"
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ placeholder={t('transactions.linkTransferSearchPlaceholder')}
+ className="w-full pl-9 pr-3 py-2 text-sm rounded-md border border-border bg-card text-foreground focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
+ />
+ </div>
+
+ <div>
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-2">
+ {t('transactions.linkTransferCandidatesHeader')}
+ </p>
+ {candidatesLoading ? (
+ <div className="space-y-2">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <Skeleton key={i} className="h-14 w-full" />
+ ))}
+ </div>
+ ) : filteredCandidates.length === 0 ? (
+ <p className="text-xs text-muted-foreground italic py-4 text-center">
+ {t('transactions.linkTransferNoCandidates')}
+ </p>
+ ) : (
+ <ul className="max-h-72 overflow-y-auto space-y-1.5 -mx-1 px-1">
+ {filteredCandidates.map((c) => {
+ const account = accounts.find((a) => a.id === c.account_id)
+ const amount = Math.abs(Number(c.amount))
+ const sign = c.type === 'debit' ? '−' : '+'
+ const colorClass = c.type === 'debit' ? 'text-rose-500' : 'text-emerald-600'
+ const isBest = !searchTerm && c.id === bestMatchId
+ return (
+ <li key={c.id}>
+ <button
+ type="button"
+ onClick={() => setPickedCandidate(c)}
+ className="w-full text-left rounded-lg border border-border bg-card hover:bg-muted/50 hover:border-primary/40 transition-colors p-3 flex items-center gap-3 min-w-0"
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2 min-w-0">
+ <p className="text-sm font-semibold text-foreground truncate min-w-0 flex-1">
+ {c.description}
+ </p>
+ {isBest && (
+ <span className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/15 px-1.5 py-0.5 rounded-full shrink-0">
+ <Sparkles size={10} />
+ {t('transactions.linkTransferBestMatch', 'Best match')}
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground truncate">
+ {account?.name ?? '—'} · {new Date(c.date + 'T00:00:00').toLocaleDateString(locale)}
+ </p>
+ </div>
+ <p className={`text-sm font-bold tabular-nums ${colorClass} shrink-0`}>
+ {sign}
+ {formatCurrency(amount, c.currency, locale)}
+ </p>
+ </button>
+ </li>
+ )
+ })}
+ </ul>
+ )}
+ </div>
+ </div>
+
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
+ {t('common.cancel')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+ }
+
+ // Confirm view — used in direct mode and after picking a candidate.
+ if (!effectiveDebit || !effectiveCredit) return null
+
+ const fromAccount = accounts.find((a) => a.id === effectiveDebit.account_id)
+ const toAccount = accounts.find((a) => a.id === effectiveCredit.account_id)
+ const sameCurrency = effectiveDebit.currency === effectiveCredit.currency
+ const debitAmount = Math.abs(Number(effectiveDebit.amount))
+ const creditAmount = Math.abs(Number(effectiveCredit.amount))
+ const amountMismatch = sameCurrency && debitAmount !== creditAmount
+
+ return (
+ <Dialog open={open} onOpenChange={onClose}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t('transactions.linkTransferTitle')}</DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ <p className="text-sm text-muted-foreground">
+ {t('transactions.linkTransferDescription')}
+ </p>
+
+ <div className="grid grid-cols-[1fr_auto_1fr] items-stretch gap-3">
+ <CounterpartCard
+ label={t('transactions.linkTransferFrom')}
+ description={effectiveDebit.description}
+ account={fromAccount?.name ?? '—'}
+ date={effectiveDebit.date}
+ amount={debitAmount}
+ currency={effectiveDebit.currency}
+ sign="−"
+ locale={locale}
+ />
+ <div className="flex items-center">
+ <ArrowRight size={18} className="text-muted-foreground" />
+ </div>
+ <CounterpartCard
+ label={t('transactions.linkTransferTo')}
+ description={effectiveCredit.description}
+ account={toAccount?.name ?? '—'}
+ date={effectiveCredit.date}
+ amount={creditAmount}
+ currency={effectiveCredit.currency}
+ sign="+"
+ locale={locale}
+ />
+ </div>
+
+ {amountMismatch && (
+ <div className="flex items-start gap-2 p-3 text-xs bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-900 rounded-md text-amber-800 dark:text-amber-300">
+ <AlertTriangle size={14} className="shrink-0 mt-0.5" />
+ <span>{t('transactions.linkTransferAmountMismatch')}</span>
+ </div>
+ )}
+
+ <div className="flex items-start gap-2 p-3 text-xs bg-muted/50 border border-border rounded-md text-muted-foreground">
+ <Info size={14} className="shrink-0 mt-0.5" />
+ <span>{t('transactions.linkTransferCascadeWarning')}</span>
+ </div>
+ </div>
+
+ <DialogFooter className="gap-2 sm:gap-2">
+ {isPickerMode && (
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => setPickedCandidate(null)}
+ disabled={loading}
+ className="mr-auto"
+ >
+ <ArrowLeft size={14} className="mr-1" />
+ {t('transactions.linkTransferBack')}
+ </Button>
+ )}
+ <Button type="button" variant="outline" onClick={onClose} disabled={loading}>
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ onClick={() => onConfirm(effectiveDebit.id, effectiveCredit.id)}
+ disabled={loading}
+ >
+ {loading ? t('common.loading') : t('transactions.linkTransferConfirm')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 4c5bf676..4e918dad 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -15,7 +15,7 @@ import {
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
-import { AlertTriangle, ChevronLeft, Download, Paperclip, Upload, X, FileText, Plus } from 'lucide-react'
+import { AlertTriangle, ChevronLeft, Download, Paperclip, Upload, X, FileText, Plus, Unlink } from 'lucide-react'
import { TransactionAttachments } from '@/components/transaction-attachments'
import type { AttachmentPreview } from '@/components/transaction-attachments'
import type { Transaction, RecurringTransaction } from '@/types'
@@ -58,6 +58,7 @@ export function TransactionDialog({
recurringMatch,
onSave,
onDelete,
+ onUnlinkTransfer,
loading,
error,
isSynced = false,
@@ -70,6 +71,7 @@ export function TransactionDialog({
recurringMatch?: RecurringTransaction
onSave: (data: Partial<Transaction>, recurringData?: { frequency: string; end_date?: string }, pendingFiles?: File[]) => void
onDelete?: () => void
+ onUnlinkTransfer?: (pairId: string) => void
loading: boolean
error: string | null
isSynced?: boolean
@@ -135,6 +137,7 @@ export function TransactionDialog({
recurringMatch={recurringMatch}
onSave={onSave}
onDelete={onDelete}
+ onUnlinkTransfer={onUnlinkTransfer}
onCancel={onClose}
loading={loading}
error={error}
@@ -248,6 +251,7 @@ function TransactionForm({
recurringMatch,
onSave,
onDelete,
+ onUnlinkTransfer,
onCancel,
loading,
error,
@@ -262,6 +266,7 @@ function TransactionForm({
recurringMatch?: RecurringTransaction
onSave: (data: Partial<Transaction>, recurringData?: { frequency: string; end_date?: string }, pendingFiles?: File[]) => void
onDelete?: () => void
+ onUnlinkTransfer?: (pairId: string) => void
onCancel: () => void
loading: boolean
error: string | null
@@ -438,11 +443,29 @@ function TransactionForm({
</div>
)}
{!!transaction?.transfer_pair_id && (
- <div className="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 space-y-1">
- <div className="flex items-center gap-2">
- {t('transactions.transferInfo')}
+ <div className="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 space-y-2">
+ <div className="flex items-start justify-between gap-3">
+ <div className="space-y-1 min-w-0">
+ <p>{t('transactions.transferInfo')}</p>
+ <p className="text-xs text-blue-500 dark:text-blue-400">{t('transactions.transferTooltip')}</p>
+ </div>
+ {onUnlinkTransfer && transaction?.transfer_pair_id && (
+ <button
+ type="button"
+ disabled={loading}
+ onClick={() => {
+ if (transaction?.transfer_pair_id) {
+ onUnlinkTransfer(transaction.transfer_pair_id)
+ }
+ }}
+ className="shrink-0 inline-flex items-center gap-1.5 rounded-md border border-blue-200 dark:border-blue-800 bg-white/60 dark:bg-blue-900/40 px-2.5 py-1.5 text-xs font-medium text-blue-700 dark:text-blue-200 hover:bg-white dark:hover:bg-blue-900/70 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
+ title={t('transactions.unlinkTransferConfirm')}
+ >
+ <Unlink size={12} />
+ {t('transactions.unlinkTransfer')}
+ </button>
+ )}
</div>
- <p className="text-xs text-blue-500 dark:text-blue-400">{t('transactions.transferTooltip')}</p>
</div>
)}
{recurringMatch && (
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 5ea84970..008fe2f4 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -286,6 +286,19 @@ export const transactions = {
})
return data
},
+ linkTransfer: async (transactionIds: string[]): Promise<{ debit: Transaction; credit: Transaction; transfer_pair_id: string }> => {
+ const { data } = await api.post('/transactions/link-transfer', {
+ transaction_ids: transactionIds,
+ })
+ return data
+ },
+ transferCandidates: async (transactionId: string, params?: { limit?: number; window_days?: number }): Promise<Transaction[]> => {
+ const { data } = await api.get(`/transactions/${transactionId}/transfer-candidates`, { params })
+ return data
+ },
+ unlinkTransfer: async (pairId: string): Promise<void> => {
+ await api.delete(`/connections/transfers/${pairId}`)
+ },
previewImport: async (file: File, options?: {
date_format?: string
flip_amount?: boolean
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 9705ac8e..8c837e75 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -215,6 +215,29 @@
"transferNotes": "Notes",
"transferInfo": "This is a transfer — changes to description, date, and notes will apply to both sides",
"transferTooltip": "Transfers are excluded from report and dashboard totals",
+ "linkAsTransfer": "Link as transfer",
+ "linkTransferTitle": "Link as transfer",
+ "linkTransferDescription": "Mark these two transactions as a single inter-account transfer. They will be excluded from spending and income reports.",
+ "linkTransferSelectTwo": "Select exactly 2 transactions to link them",
+ "linkTransferFrom": "From",
+ "linkTransferTo": "To",
+ "linkTransferAmountMismatch": "Amounts don't match. This is fine for cross-currency transfers or when fees apply, but double-check before linking.",
+ "linkTransferCascadeWarning": "Once linked, editing or deleting one side will affect the other.",
+ "linkTransferConfirm": "Link transactions",
+ "linkTransferSuccess": "Transactions linked as transfer",
+ "linkTransferInvalidPair": "To link as a transfer, pick one debit and one credit from different accounts.",
+ "linkTransferPickerTitle": "Find the matching transaction",
+ "linkTransferPickerDescription": "Pick the counterpart from another account. Best matches by date and amount appear first.",
+ "linkTransferSearchPlaceholder": "Search by description…",
+ "linkTransferNoCandidates": "No matching transactions found within 30 days.",
+ "linkTransferLoadingCandidates": "Loading candidates…",
+ "linkTransferAnchor": "Selected",
+ "linkTransferBack": "Back",
+ "linkTransferCandidatesHeader": "Suggested matches",
+ "linkTransferBestMatch": "Best match",
+ "unlinkTransfer": "Unlink transfer",
+ "unlinkTransferConfirm": "Unlink this transfer? Both transactions will be treated as regular transactions again.",
+ "unlinkTransferSuccess": "Transfer unlinked",
"filtersBar": {
"filters": "Filters",
"filterBy": "Filter by",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index a827ab18..1b4081bc 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -215,6 +215,29 @@
"transferNotes": "Notas",
"transferInfo": "Esta é uma transferência — alterações na descrição, data e notas serão aplicadas em ambos os lados",
"transferTooltip": "Transferências são excluídas dos totais de relatórios e dashboard",
+ "linkAsTransfer": "Vincular como transferência",
+ "linkTransferTitle": "Vincular como transferência",
+ "linkTransferDescription": "Marcar estas duas transações como uma única transferência entre contas. Elas serão excluídas dos relatórios de gastos e receitas.",
+ "linkTransferSelectTwo": "Selecione exatamente 2 transações para vincular",
+ "linkTransferFrom": "De",
+ "linkTransferTo": "Para",
+ "linkTransferAmountMismatch": "Os valores não coincidem. Isso é normal em transferências entre moedas ou quando há tarifas, mas confira antes de vincular.",
+ "linkTransferCascadeWarning": "Após vincular, editar ou excluir um lado afetará o outro.",
+ "linkTransferConfirm": "Vincular transações",
+ "linkTransferSuccess": "Transações vinculadas como transferência",
+ "linkTransferInvalidPair": "Para vincular como transferência, escolha um débito e um crédito de contas diferentes.",
+ "linkTransferPickerTitle": "Encontre a transação correspondente",
+ "linkTransferPickerDescription": "Escolha a contraparte em outra conta. As melhores correspondências por data e valor aparecem primeiro.",
+ "linkTransferSearchPlaceholder": "Buscar pela descrição…",
+ "linkTransferNoCandidates": "Nenhuma transação correspondente encontrada nos últimos 30 dias.",
+ "linkTransferLoadingCandidates": "Carregando candidatas…",
+ "linkTransferAnchor": "Selecionada",
+ "linkTransferBack": "Voltar",
+ "linkTransferCandidatesHeader": "Sugestões de correspondência",
+ "linkTransferBestMatch": "Melhor correspondência",
+ "unlinkTransfer": "Desvincular transferência",
+ "unlinkTransferConfirm": "Desvincular esta transferência? Ambas as transações voltarão a ser tratadas como transações normais.",
+ "unlinkTransferSuccess": "Transferência desvinculada",
"filtersBar": {
"filters": "Filtros",
"filterBy": "Filtrar por",
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index a75e5abd..9265f8d3 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -129,6 +129,22 @@ export default function AccountDetailPage() {
},
})
+ const unlinkTransferMutation = useMutation({
+ mutationFn: (pairId: string) => transactions.unlinkTransfer(pairId),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ queryClient.invalidateQueries({ queryKey: ['accounts', id, 'summary'] })
+ queryClient.invalidateQueries({ queryKey: ['accounts', id, 'balance-history'] })
+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })
+ setDialogOpen(false)
+ setEditingTx(null)
+ toast.success(t('transactions.unlinkTransferSuccess'))
+ },
+ onError: (error) => {
+ toast.error(extractApiError(error))
+ },
+ })
+
const reopenMutation = useMutation({
mutationFn: () => accounts.reopen(id!),
onSuccess: () => {
@@ -534,7 +550,8 @@ export default function AccountDetailPage() {
}
}}
onDelete={editingTx ? () => deleteMutation.mutate(editingTx.id) : undefined}
- loading={updateMutation.isPending || deleteMutation.isPending}
+ onUnlinkTransfer={(pairId) => unlinkTransferMutation.mutate(pairId)}
+ loading={updateMutation.isPending || deleteMutation.isPending || unlinkTransferMutation.isPending}
error={updateMutation.error ? extractApiError(updateMutation.error) : null}
isSynced={editingTx?.source === 'sync'}
/>
diff --git a/frontend/src/pages/dashboard.tsx b/frontend/src/pages/dashboard.tsx
index 7da4adcb..6f9ac74d 100644
--- a/frontend/src/pages/dashboard.tsx
+++ b/frontend/src/pages/dashboard.tsx
@@ -174,6 +174,18 @@ export default function DashboardPage() {
},
})
+ const unlinkTransferMutation = useMutation({
+ mutationFn: (pairId: string) => transactions.unlinkTransfer(pairId),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })
+ queryClient.invalidateQueries({ queryKey: ['budgets'] })
+ queryClient.invalidateQueries({ queryKey: ['drill-down'] })
+ setDialogOpen(false)
+ setEditingTx(null)
+ },
+ })
+
const cumulativeData = useMemo(() => {
if (!balanceHistory) return []
@@ -922,7 +934,8 @@ export default function DashboardPage() {
onDelete={() => {
if (editingTx) deleteMutation.mutate(editingTx.id)
}}
- loading={updateMutation.isPending || deleteMutation.isPending}
+ onUnlinkTransfer={(pairId) => unlinkTransferMutation.mutate(pairId)}
+ loading={updateMutation.isPending || deleteMutation.isPending || unlinkTransferMutation.isPending}
error={updateMutation.error ? extractApiError(updateMutation.error) : deleteMutation.error ? extractApiError(deleteMutation.error) : null}
isSynced={!!editingTx?.external_id}
/>
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index 735947ab..dfe30434 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -20,6 +20,7 @@ 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 { LinkTransferDialog } from '@/components/link-transfer-dialog'
import { TransactionsFilterBar } from '@/components/transactions-filter-bar'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useAuth } from '@/contexts/auth-context'
@@ -59,6 +60,7 @@ export default function TransactionsPage() {
const [tagFilter, setTagFilter] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
const [transferDialogOpen, setTransferDialogOpen] = useState(false)
+ const [linkTransferDialogOpen, setLinkTransferDialogOpen] = useState(false)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [bulkCategory, setBulkCategory] = useState<string>('')
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)
@@ -229,6 +231,35 @@ export default function TransactionsPage() {
},
})
+ const linkTransferMutation = useMutation({
+ mutationFn: (ids: [string, string]) => transactions.linkTransfer(ids),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })
+ queryClient.invalidateQueries({ queryKey: ['transfer-candidates'] })
+ setLinkTransferDialogOpen(false)
+ setSelectedIds(new Set())
+ toast.success(t('transactions.linkTransferSuccess'))
+ },
+ onError: (error) => {
+ toast.error(extractApiError(error))
+ },
+ })
+
+ const unlinkTransferMutation = useMutation({
+ mutationFn: (pairId: string) => transactions.unlinkTransfer(pairId),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['transactions'] })
+ queryClient.invalidateQueries({ queryKey: ['dashboard'] })
+ setDialogOpen(false)
+ setEditingTx(null)
+ toast.success(t('transactions.unlinkTransferSuccess'))
+ },
+ onError: (error) => {
+ toast.error(extractApiError(error))
+ },
+ })
+
const transferMutation = useMutation({
mutationFn: (data: {
from_account_id: string
@@ -280,6 +311,37 @@ export default function TransactionsPage() {
const allSelected = filteredItems.length > 0 && filteredItems.every(tx => selectedIds.has(tx.id))
const someSelected = filteredItems.some(tx => selectedIds.has(tx.id)) && !allSelected
+ // Resolve the currently-selected transactions into a valid debit/credit pair
+ // for the "Link as transfer" action. Returns null if the pair is invalid
+ // (wrong count, same account, same type, or already linked).
+ const linkablePair = useMemo(() => {
+ if (selectedIds.size !== 2) return null
+ const selected = (data?.items ?? []).filter(tx => selectedIds.has(tx.id))
+ if (selected.length !== 2) return null
+ if (selected.some(tx => tx.transfer_pair_id)) return null
+ if (selected[0].account_id === selected[1].account_id) return null
+ const debit = selected.find(tx => tx.type === 'debit')
+ const credit = selected.find(tx => tx.type === 'credit')
+ if (!debit || !credit) return null
+ return { debit, credit }
+ }, [selectedIds, data?.items])
+
+ // Single-selection picker mode: when exactly one unlinked transaction is
+ // selected, the user can search for its counterpart across all accounts.
+ const linkAnchor = useMemo(() => {
+ if (selectedIds.size !== 1) return null
+ const selected = (data?.items ?? []).find(tx => selectedIds.has(tx.id))
+ if (!selected) return null
+ if (selected.transfer_pair_id) return null
+ return selected
+ }, [selectedIds, data?.items])
+
+ const canOpenLinkDialog = !!linkablePair || !!linkAnchor
+ const linkDisabledTooltip =
+ !canOpenLinkDialog && selectedIds.size >= 2
+ ? t('transactions.linkTransferInvalidPair')
+ : undefined
+
const totalPages = data ? Math.ceil(data.total / 20) : 0
return (
@@ -530,7 +592,7 @@ export default function TransactionsPage() {
className={`fixed bottom-0 left-0 right-0 z-50 transition-transform duration-200 ease-out ${selectedIds.size > 0 ? 'translate-y-0' : 'translate-y-full'}`}
>
<div className="mx-auto max-w-2xl px-3 md:px-4 pb-4 md:pb-6">
- <div className="flex items-center gap-2 md:gap-3 bg-card border border-border shadow-lg rounded-xl px-3 md:px-5 py-2.5 md:py-3">
+ <div className="flex flex-wrap items-center gap-2 md:gap-3 bg-card border border-border shadow-lg rounded-xl px-3 md:px-5 py-2.5 md:py-3">
<span className="text-xs md:text-sm font-medium text-foreground whitespace-nowrap">
{t('transactions.selected', { count: selectedIds.size })}
</span>
@@ -558,6 +620,17 @@ export default function TransactionsPage() {
<Check size={14} className="mr-1" />
{t('transactions.bulkCategorize')}
</Button>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={!canOpenLinkDialog}
+ title={linkDisabledTooltip}
+ onClick={() => setLinkTransferDialogOpen(true)}
+ className="shrink-0"
+ >
+ <ArrowLeftRight size={14} className="mr-1" />
+ {t('transactions.linkAsTransfer')}
+ </Button>
<button
onClick={() => { setSelectedIds(new Set()); setBulkCategory('') }}
className="text-muted-foreground hover:text-foreground p-1 shrink-0"
@@ -568,6 +641,20 @@ export default function TransactionsPage() {
</div>
</div>
+ {/* Link Transfer Dialog */}
+ <LinkTransferDialog
+ open={linkTransferDialogOpen}
+ onClose={() => setLinkTransferDialogOpen(false)}
+ debit={linkablePair?.debit ?? null}
+ credit={linkablePair?.credit ?? null}
+ anchor={linkAnchor}
+ accounts={accountsList ?? []}
+ onConfirm={(debitId, creditId) => {
+ linkTransferMutation.mutate([debitId, creditId])
+ }}
+ loading={linkTransferMutation.isPending}
+ />
+
{/* Transfer Dialog */}
<TransferDialog
open={transferDialogOpen}
@@ -593,7 +680,8 @@ export default function TransactionsPage() {
}
}}
onDelete={editingTx ? () => deleteMutation.mutate(editingTx.id) : undefined}
- loading={createMutation.isPending || updateMutation.isPending || deleteMutation.isPending}
+ onUnlinkTransfer={(pairId) => unlinkTransferMutation.mutate(pairId)}
+ loading={createMutation.isPending || updateMutation.isPending || deleteMutation.isPending || unlinkTransferMutation.isPending}
error={createMutation.error || updateMutation.error ? extractApiError(createMutation.error || updateMutation.error) : null}
isSynced={editingTx?.source === 'sync'}
/>