Open-source personal finance manager. Self-hosted, privacy-first.
feat: auto-create transfer counterpart for manual accounts (#191) (#210)
Tássio Noronhad72d06a5425b
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 2c76098a..c1302909 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -12,7 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import current_active_userfrom app.core.database import get_async_sessionfrom app.models.user import User-from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, BulkTagsRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferRead+from app.schemas.transaction import BulkAddToGroupRequest, BulkCategorizeRequest, BulkTagsRequest, CreateCounterpartRequest, LinkTransferRequest, TransactionCreate, TransactionRead, TransactionUpdate, TransferCreate, TransferReadfrom app.services import transaction_servicefrom app.services.admin_service import get_credit_card_accounting_mode@@ -276,6 +276,31 @@ async def link_transfer(raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))[email protected]("/{transaction_id}/create-counterpart", response_model=TransferRead, status_code=status.HTTP_201_CREATED)+async def create_counterpart(+ transaction_id: uuid.UUID,+ data: CreateCounterpartRequest,+ session: AsyncSession = Depends(get_async_session),+ user: User = Depends(current_active_user),+):+ """Mark a transaction as a transfer by auto-creating its counterpart in+ another (typically manual) account."""+ try:+ debit_tx, credit_tx = await transaction_service.create_transfer_counterpart(+ session, user.id, transaction_id, data.to_account_id+ )+ 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}/transfer-candidates", response_model=list[TransactionRead])async def get_transfer_candidates(transaction_id: uuid.UUID,diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex d556ca13..bd093122 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -128,6 +128,13 @@ class LinkTransferRequest(BaseModel):transaction_ids: list[uuid.UUID]+class CreateCounterpartRequest(BaseModel):+ """Mark a transaction as a transfer by auto-creating its counterpart in+ another account. Used when the counterpart account is manual, so no+ matching transaction exists to link against."""+ to_account_id: uuid.UUID++class BulkTagsRequest(BaseModel):transaction_ids: list[uuid.UUID]tags: list[str]diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 6fcd2331..39cb0399 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -888,6 +888,93 @@ async def link_existing_as_transfer(return debit_tx, credit_tx+async def create_transfer_counterpart(+ session: AsyncSession,+ user_id: uuid.UUID,+ transaction_id: uuid.UUID,+ to_account_id: uuid.UUID,+) -> tuple[Transaction, Transaction]:+ """Mark an existing transaction as a transfer by auto-creating its+ counterpart in another account.++ Used when the counterpart account is manual (not bank-synced), so no+ matching transaction exists to link against. The counterpart mirrors the+ anchor's date / description / notes with the opposite type, converting the+ amount when the destination account uses a different currency.+ """+ from decimal import Decimal++ anchor = await get_transaction(session, transaction_id, user_id)+ if not anchor:+ raise ValueError("Transaction not found")+ if anchor.transfer_pair_id is not None:+ raise ValueError("Transaction is already part of a transfer")+ if anchor.account_id == to_account_id:+ raise ValueError("Counterpart must be in a different account")++ to_result = await session.execute(+ select(Account)+ .outerjoin(BankConnection)+ .where(+ Account.id == 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")++ opposing_type = "credit" if anchor.type == "debit" else "debit"++ # Convert the amount when the destination account uses another currency.+ if anchor.currency != to_account.currency:+ counterpart_amount, _ = await fx_convert(+ session, Decimal(str(anchor.amount)), anchor.currency, to_account.currency, anchor.date+ )+ else:+ counterpart_amount = anchor.amount++ transfer_pair_id = uuid.uuid4()++ counterpart_tx = Transaction(+ user_id=user_id,+ account_id=to_account_id,+ description=anchor.description,+ amount=counterpart_amount,+ currency=to_account.currency,+ date=anchor.date,+ type=opposing_type,+ source="transfer",+ notes=anchor.notes,+ transfer_pair_id=transfer_pair_id,+ )+ apply_effective_date(counterpart_tx, to_account)+ session.add(counterpart_tx)++ # Link the anchor into the pair; transfers are excluded from category reports.+ anchor.transfer_pair_id = transfer_pair_id+ anchor.category_id = None++ await session.flush()+ await stamp_primary_amount(session, user_id, counterpart_tx)++ # Cross-currency: keep both sides on the same primary amount.+ if anchor.currency != to_account.currency and anchor.amount_primary is not None:+ counterpart_tx.amount_primary = anchor.amount_primary+ if counterpart_tx.amount and Decimal(str(counterpart_tx.amount)):+ counterpart_tx.fx_rate_used = Decimal(str(anchor.amount_primary)) / Decimal(+ str(counterpart_tx.amount)+ )++ await session.commit()+ await session.refresh(anchor, ["category"])+ await session.refresh(counterpart_tx, ["category"])++ debit_tx = anchor if anchor.type == "debit" else counterpart_tx+ credit_tx = counterpart_tx if anchor.type == "debit" else anchor+ return debit_tx, credit_tx++async def _resync_bill_link_from_override(session: AsyncSession, transaction: Transaction, account: Optional[Account]) -> None:diff --git a/backend/tests/test_transfer_api.py b/backend/tests/test_transfer_api.pyindex 7d3d1414..dfd302af 100644--- a/backend/tests/test_transfer_api.py+++ b/backend/tests/test_transfer_api.py@@ -715,6 +715,256 @@ async def test_transfer_candidates_returns_404_for_unknown_anchor(assert response.status_code == 404+async def test_create_counterpart_from_debit(+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account+):+ """Auto-create the credit counterpart for a debit anchor."""+ anchor = await _create_manual_tx(+ client, auth_headers, test_account.id,+ type="debit", amount=200.00, description="Sent from checking",+ )++ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(second_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 201+ data = response.json()++ # Anchor stays the debit side; counterpart is the new credit.+ assert data["debit"]["id"] == anchor["id"]+ assert data["debit"]["account_id"] == str(test_account.id)+ assert data["credit"]["id"] != anchor["id"]+ assert data["credit"]["account_id"] == str(second_account.id)+ assert data["credit"]["type"] == "credit"+ assert data["credit"]["source"] == "transfer"+ assert float(data["credit"]["amount"]) == 200.00+ assert data["credit"]["description"] == "Sent from checking"++ # Both sides share the transfer pair id.+ assert data["debit"]["transfer_pair_id"] == data["transfer_pair_id"]+ assert data["credit"]["transfer_pair_id"] == data["transfer_pair_id"]+++async def test_create_counterpart_from_credit(+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account+):+ """Auto-create the debit counterpart for a credit anchor."""+ anchor = await _create_manual_tx(+ client, auth_headers, test_account.id,+ type="credit", amount=150.00, description="Money in",+ )++ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(second_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 201+ data = response.json()++ assert data["credit"]["id"] == anchor["id"]+ assert data["debit"]["id"] != anchor["id"]+ assert data["debit"]["account_id"] == str(second_account.id)+ assert data["debit"]["type"] == "debit"+ assert data["debit"]["source"] == "transfer"+ assert float(data["debit"]["amount"]) == 150.00+++async def test_create_counterpart_cross_currency(+ client: AsyncClient, auth_headers, test_account: Account, usd_account: Account+):+ """Counterpart in another currency takes the destination account's currency."""+ anchor = await _create_manual_tx(+ client, auth_headers, test_account.id,+ type="debit", amount=1000.00, description="BRL to USD",+ )++ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(usd_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 201+ data = response.json()++ assert data["debit"]["currency"] == "BRL"+ assert data["credit"]["currency"] == "USD"+ # Amount may differ from the anchor's after FX conversion.+ assert float(data["credit"]["amount"]) > 0+++async def test_create_counterpart_rejects_same_account(+ client: AsyncClient, auth_headers, test_account: Account+):+ anchor = await _create_manual_tx(+ client, auth_headers, test_account.id,+ type="debit", amount=50.00, description="Anchor",+ )++ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(test_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 400+ assert "different account" in response.json()["detail"].lower()+++async def test_create_counterpart_rejects_unknown_account(+ client: AsyncClient, auth_headers, test_account: Account+):+ anchor = await _create_manual_tx(+ client, auth_headers, test_account.id,+ type="debit", amount=50.00, description="Anchor",+ )++ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(uuid.uuid4())},+ headers=auth_headers,+ )+ assert response.status_code == 400+ assert "not found" in response.json()["detail"].lower()+++async def test_create_counterpart_rejects_unknown_transaction(+ client: AsyncClient, auth_headers, second_account: Account+):+ response = await client.post(+ f"/api/transactions/{uuid.uuid4()}/create-counterpart",+ json={"to_account_id": str(second_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 400+ assert "not found" in response.json()["detail"].lower()+++async def test_create_counterpart_rejects_already_linked(+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account+):+ """A transaction that is already part of a transfer cannot get another counterpart."""+ pair = 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 = pair.json()["debit"]["id"]++ response = await client.post(+ f"/api/transactions/{debit_id}/create-counterpart",+ json={"to_account_id": str(test_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 400+ assert "already part of a transfer" in response.json()["detail"].lower()+++async def test_create_counterpart_clears_anchor_category(+ client: AsyncClient,+ auth_headers,+ test_account: Account,+ second_account: Account,+ test_categories,+):+ """Marking a categorized transaction as a transfer clears its category."""+ create_response = await client.post(+ "/api/transactions",+ json={+ "account_id": str(test_account.id),+ "description": "Categorized anchor",+ "amount": 120.00,+ "type": "debit",+ "date": date.today().isoformat(),+ "category_id": str(test_categories[0].id),+ },+ headers=auth_headers,+ )+ assert create_response.status_code == 201+ anchor = create_response.json()+ assert anchor["category_id"] == str(test_categories[0].id)++ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(second_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 201++ refreshed = await client.get(+ f"/api/transactions/{anchor['id']}", headers=auth_headers+ )+ assert refreshed.status_code == 200+ assert refreshed.json()["category_id"] is None+++async def test_create_counterpart_excludes_pair_from_reports(+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account+):+ """Both sides drop out of the list when exclude_transfers=true."""+ anchor = await _create_manual_tx(+ client, auth_headers, test_account.id,+ type="debit", amount=300.00, description="To exclude",+ )++ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(second_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 201+ counterpart_id = response.json()["credit"]["id"]++ list_response = await client.get(+ "/api/transactions", params={"exclude_transfers": True}, headers=auth_headers+ )+ assert list_response.status_code == 200+ ids = {tx["id"] for tx in list_response.json()["items"]}+ assert anchor["id"] not in ids+ assert counterpart_id not in ids+++async def test_create_counterpart_cascades_on_delete(+ client: AsyncClient, auth_headers, test_account: Account, second_account: Account+):+ """Deleting the anchor removes the auto-created counterpart too."""+ anchor = await _create_manual_tx(+ client, auth_headers, test_account.id,+ type="debit", amount=90.00, description="Cascade delete",+ )+ response = await client.post(+ f"/api/transactions/{anchor['id']}/create-counterpart",+ json={"to_account_id": str(second_account.id)},+ headers=auth_headers,+ )+ assert response.status_code == 201+ counterpart_id = response.json()["credit"]["id"]++ del_response = await client.delete(+ f"/api/transactions/{anchor['id']}", headers=auth_headers+ )+ assert del_response.status_code == 204+ assert (await client.get(f"/api/transactions/{anchor['id']}", headers=auth_headers)).status_code == 404+ assert (await client.get(f"/api/transactions/{counterpart_id}", headers=auth_headers)).status_code == 404++@pytest.mark.asyncioasync def test_transfers_appear_in_transaction_list(client: AsyncClient, auth_headers, test_account: Account, second_account: Accountdiff --git a/frontend/src/components/link-transfer-dialog.tsx b/frontend/src/components/link-transfer-dialog.tsxindex 7d82c290..00936664 100644--- a/frontend/src/components/link-transfer-dialog.tsx+++ b/frontend/src/components/link-transfer-dialog.tsx@@ -62,6 +62,8 @@ type Props = {anchor?: Transaction | nullaccounts: Account[]onConfirm: (debitId: string, creditId: string) => void+ /** Picker mode only: auto-create the counterpart in a manual account. */+ onCreateCounterpart?: (anchorId: string, toAccountId: string) => voidloading: boolean}@@ -73,6 +75,7 @@ export function LinkTransferDialog({anchor,accounts,onConfirm,+ onCreateCounterpart,loading,}: Props) {const { t, i18n } = useTranslation()@@ -85,6 +88,8 @@ export function LinkTransferDialog({// 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('')+ // Account chosen for auto-creating a counterpart when none exists yet.+ const [counterpartAccountId, setCounterpartAccountId] = 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@@ -95,6 +100,7 @@ export function LinkTransferDialog({setPrevSessionKey(sessionKey)setPickedCandidate(null)setSearchTerm('')+ setCounterpartAccountId('')}const { data: candidates, isLoading: candidatesLoading } = useQuery({@@ -148,6 +154,12 @@ export function LinkTransferDialog({if (isPickerMode && !pickedCandidate) {const anchorAccount = accounts.find((a) => a.id === anchor!.account_id)const anchorAmount = Math.abs(Number(anchor!.amount))+ // Manual accounts (no bank connection) where we can auto-create the+ // counterpart, since a synced account would already have a real+ // transaction showing in the candidates list above.+ const manualCounterpartAccounts = accounts.filter(+ (a) => a.connection_id == null && a.id !== anchor!.account_id,+ )return (<Dialog open={open} onOpenChange={onClose}>@@ -239,6 +251,40 @@ export function LinkTransferDialog({</ul>)}</div>++ {onCreateCounterpart && manualCounterpartAccounts.length > 0 && (+ <div className="border-t border-border pt-4">+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-1">+ {t('transactions.createCounterpartHeader')}+ </p>+ <p className="text-xs text-muted-foreground mb-2">+ {t('transactions.createCounterpartDescription')}+ </p>+ <div className="flex gap-2">+ <select+ value={counterpartAccountId}+ onChange={(e) => setCounterpartAccountId(e.target.value)}+ className="flex-1 min-w-0 px-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]"+ >+ <option value="">{t('transactions.createCounterpartSelectAccount')}</option>+ {manualCounterpartAccounts.map((a) => (+ <option key={a.id} value={a.id}>+ {getAccountName(a)}+ </option>+ ))}+ </select>+ <Button+ type="button"+ variant="outline"+ disabled={!counterpartAccountId || loading}+ onClick={() => onCreateCounterpart(anchor!.id, counterpartAccountId)}+ className="shrink-0"+ >+ {loading ? t('common.loading') : t('transactions.createCounterpartConfirm')}+ </Button>+ </div>+ </div>+ )}</div><DialogFooter>diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 94c146cc..ec56fd75 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -355,6 +355,15 @@ export const transactions = {})return data},+ createTransferCounterpart: async (+ transactionId: string,+ toAccountId: string,+ ): Promise<{ debit: Transaction; credit: Transaction; transfer_pair_id: string }> => {+ const { data } = await api.post(`/transactions/${transactionId}/create-counterpart`, {+ to_account_id: toAccountId,+ })+ 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 datadiff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex e4ee803c..0270a29b 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -293,6 +293,10 @@"linkTransferBack": "Back","linkTransferCandidatesHeader": "Suggested matches","linkTransferBestMatch": "Best match",+ "createCounterpartHeader": "Counterpart not listed?",+ "createCounterpartDescription": "If the other side is a manual account, create the matching transaction automatically.",+ "createCounterpartSelectAccount": "Select an account…",+ "createCounterpartConfirm": "Create","unlinkTransfer": "Unlink transfer","unlinkTransferConfirm": "Unlink this transfer? Both transactions will be treated as regular transactions again.","unlinkTransferSuccess": "Transfer unlinked",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex cb1921be..ccc1615b 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -293,6 +293,10 @@"linkTransferBack": "Voltar","linkTransferCandidatesHeader": "Sugestões de correspondência","linkTransferBestMatch": "Melhor correspondência",+ "createCounterpartHeader": "Contraparte não está na lista?",+ "createCounterpartDescription": "Se o outro lado for uma conta manual, crie a transação correspondente automaticamente.",+ "createCounterpartSelectAccount": "Selecione uma conta…",+ "createCounterpartConfirm": "Criar","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",diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex e798e9e7..50c79397 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -452,6 +452,21 @@ export default function TransactionsPage() {},})+ const createCounterpartMutation = useMutation({+ mutationFn: ({ anchorId, toAccountId }: { anchorId: string; toAccountId: string }) =>+ transactions.createTransferCounterpart(anchorId, toAccountId),+ onSuccess: () => {+ invalidateAfterTxMutation()+ 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: () => {@@ -1363,7 +1378,10 @@ export default function TransactionsPage() {onConfirm={(debitId, creditId) => {linkTransferMutation.mutate([debitId, creditId])}}- loading={linkTransferMutation.isPending}+ onCreateCounterpart={(anchorId, toAccountId) => {+ createCounterpartMutation.mutate({ anchorId, toAccountId })+ }}+ loading={linkTransferMutation.isPending || createCounterpartMutation.isPending}/>{/* Transfer Dialog */}