Skip to content

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

fix: allow editing transaction account (#63)

Tássio Noronha20a96cb8fe09
diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.py
index 0356a9eb..eeb82617 100644
--- a/backend/app/api/transactions.py
+++ b/backend/app/api/transactions.py
@@ -242,7 +242,10 @@ async def update_transaction(
session: AsyncSession = Depends(get_async_session),
user: User = Depends(current_active_user),
):
- transaction = await transaction_service.update_transaction(session, transaction_id, user.id, data)
+ try:
+ transaction = await transaction_service.update_transaction(session, transaction_id, user.id, data)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
if not transaction:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Transaction not found")
primary_currency = user.primary_currency
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index c4e55a4e..8d66027b 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -35,6 +35,7 @@ class TransactionUpdate(BaseModel):
date: Optional[_Date] = None
type: Optional[str] = None
currency: Optional[str] = None
+ account_id: Optional[uuid.UUID] = None
category_id: Optional[uuid.UUID] = None
payee_id: Optional[uuid.UUID] = None
notes: Optional[str] = None
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index 8c64c61d..1f0e882d 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -478,6 +478,37 @@ async def update_transaction(
update_data = data.model_dump(exclude_unset=True)
+ # Verify the new account belongs to the user before touching the row.
+ # When changing the account on one side of a transfer pair, refuse to
+ # collide with the paired transaction's account (a transfer must have two
+ # distinct accounts).
+ new_account_id = update_data.get("account_id")
+ if new_account_id is not None and new_account_id != transaction.account_id:
+ account_result = await session.execute(
+ select(Account)
+ .outerjoin(BankConnection)
+ .where(
+ Account.id == new_account_id,
+ or_(
+ Account.user_id == user_id,
+ BankConnection.user_id == user_id,
+ ),
+ )
+ )
+ if account_result.scalar_one_or_none() is None:
+ raise ValueError("Account not found")
+
+ 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 and paired_tx.account_id == new_account_id:
+ raise ValueError("Cannot move transfer to the same account as its paired transaction")
+
# Pop FX override fields before generic setattr loop
override_amount_primary = update_data.pop("amount_primary", None)
override_fx_rate = update_data.pop("fx_rate_used", None)
diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.py
index fcb8e2d0..41396f17 100644
--- a/backend/tests/test_transaction_service.py
+++ b/backend/tests/test_transaction_service.py
@@ -799,3 +799,94 @@ async def test_delete_transfer_cascades(session: AsyncSession, test_user, txn_ac
))
assert await delete_transaction(session, debit_tx.id, test_user.id) is True
assert await get_transaction(session, credit_tx.id, test_user.id) is None
+
+
+# ---------------------------------------------------------------------------
+# update_transaction — changing account_id (regression for #63)
+# ---------------------------------------------------------------------------
+
+
+async def test_update_transaction_changes_account(
+ session: AsyncSession, test_user, txn_account
+):
+ other_account = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="OtherAcc",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(other_account)
+ await session.commit()
+
+ txn = await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Move me",
+ amount=Decimal("42"), date=date.today(), type="debit",
+ ))
+
+ updated = await update_transaction(
+ session, txn.id, test_user.id,
+ TransactionUpdate(account_id=other_account.id),
+ )
+ assert updated is not None
+ assert updated.account_id == other_account.id
+
+ # Re-fetch to make sure the change was committed, not just set in memory.
+ reloaded = await get_transaction(session, txn.id, test_user.id)
+ assert reloaded.account_id == other_account.id
+
+
+async def test_update_transaction_rejects_foreign_account(
+ session: AsyncSession, test_user, txn_account
+):
+ from app.models.user import User
+ import bcrypt as _bcrypt
+
+ other_user = User(
+ id=uuid.uuid4(),
+ hashed_password=_bcrypt.hashpw(b"x", _bcrypt.gensalt()).decode(),
+ is_active=True, is_superuser=False, is_verified=True,
+ )
+ session.add(other_user)
+ foreign_account = Account(
+ id=uuid.uuid4(), user_id=other_user.id, name="ForeignAcc",
+ type="checking", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(foreign_account)
+ await session.commit()
+
+ txn = await create_transaction(session, test_user.id, TransactionCreate(
+ account_id=txn_account.id, description="Stay put",
+ amount=Decimal("10"), date=date.today(), type="debit",
+ ))
+
+ with pytest.raises(ValueError, match="Account not found"):
+ await update_transaction(
+ session, txn.id, test_user.id,
+ TransactionUpdate(account_id=foreign_account.id),
+ )
+
+
+async def test_update_transfer_rejects_collapsing_accounts(
+ session: AsyncSession, test_user, txn_account
+):
+ acct2 = Account(
+ id=uuid.uuid4(), user_id=test_user.id, name="XferSav",
+ type="savings", balance=Decimal("0"), currency="BRL",
+ )
+ session.add(acct2)
+ await session.commit()
+
+ debit_tx, credit_tx = await create_transfer(session, test_user.id, TransferCreate(
+ from_account_id=txn_account.id, to_account_id=acct2.id,
+ description="Xfer", amount=Decimal("100"), date=date.today(),
+ ))
+
+ # Moving the debit side to acct2 would put both legs of the transfer
+ # in the same account, which is invalid.
+ with pytest.raises(ValueError, match="same account"):
+ await update_transaction(
+ session, debit_tx.id, test_user.id,
+ TransactionUpdate(account_id=acct2.id),
+ )