Open-source personal finance manager. Self-hosted, privacy-first.
fix: delete account with import history (#114)
Leonardo Dias268c5450bb16
diff --git a/backend/alembic/versions/032_cascade_account_dependent_tables.py b/backend/alembic/versions/032_cascade_account_dependent_tables.pynew file mode 100644index 00000000..f17d4fdf--- /dev/null+++ b/backend/alembic/versions/032_cascade_account_dependent_tables.py@@ -0,0 +1,98 @@+"""cascade account-dependent tables on delete++Makes account deletion safe against the FK class of bugs (issue #110):+- import_logs.account_id -> ON DELETE CASCADE+- recurring_transactions.account_id -> ON DELETE CASCADE+- goals.account_id -> ON DELETE SET NULL++Revision ID: 032+Revises: 031+Create Date: 2026-04-23+"""++from alembic import op++revision = "032"+down_revision = "031"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ # import_logs: cascade — logs belong to the account's lifetime+ op.drop_constraint(+ "import_logs_account_id_fkey", "import_logs", type_="foreignkey"+ )+ op.create_foreign_key(+ "import_logs_account_id_fkey",+ "import_logs",+ "accounts",+ ["account_id"],+ ["id"],+ ondelete="CASCADE",+ )++ # recurring_transactions: cascade — a schedule without an account can't post+ op.drop_constraint(+ "recurring_transactions_account_id_fkey",+ "recurring_transactions",+ type_="foreignkey",+ )+ op.create_foreign_key(+ "recurring_transactions_account_id_fkey",+ "recurring_transactions",+ "accounts",+ ["account_id"],+ ["id"],+ ondelete="CASCADE",+ )++ # goals: set null — goals outlive any single tracked account; keep progress+ op.drop_constraint(+ "goals_account_id_fkey", "goals", type_="foreignkey"+ )+ op.create_foreign_key(+ "goals_account_id_fkey",+ "goals",+ "accounts",+ ["account_id"],+ ["id"],+ ondelete="SET NULL",+ )+++def downgrade() -> None:+ op.drop_constraint(+ "goals_account_id_fkey", "goals", type_="foreignkey"+ )+ op.create_foreign_key(+ "goals_account_id_fkey",+ "goals",+ "accounts",+ ["account_id"],+ ["id"],+ )++ op.drop_constraint(+ "recurring_transactions_account_id_fkey",+ "recurring_transactions",+ type_="foreignkey",+ )+ op.create_foreign_key(+ "recurring_transactions_account_id_fkey",+ "recurring_transactions",+ "accounts",+ ["account_id"],+ ["id"],+ )++ op.drop_constraint(+ "import_logs_account_id_fkey", "import_logs", type_="foreignkey"+ )+ op.create_foreign_key(+ "import_logs_account_id_fkey",+ "import_logs",+ "accounts",+ ["account_id"],+ ["id"],+ )diff --git a/backend/app/models/goal.py b/backend/app/models/goal.pyindex 8b9107e8..69931b0d 100644--- a/backend/app/models/goal.py+++ b/backend/app/models/goal.py@@ -31,7 +31,7 @@ class Goal(Base):current_amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)target_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)tracking_type: Mapped[str] = mapped_column(String(20), default="manual") # manual, account, asset, net_worth- account_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=True)+ account_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True)asset_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("assets.id"), nullable=True)status: Mapped[str] = mapped_column(String(20), default="active") # active, completed, paused, archivedicon: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)diff --git a/backend/app/models/import_log.py b/backend/app/models/import_log.pyindex c14689e9..a95fe05b 100644--- a/backend/app/models/import_log.py+++ b/backend/app/models/import_log.py@@ -19,7 +19,7 @@ class ImportLog(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))- account_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id"))+ account_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))filename: Mapped[str] = mapped_column(String(255))format: Mapped[str] = mapped_column(String(10))transaction_count: Mapped[int] = mapped_column(Integer)diff --git a/backend/app/models/recurring_transaction.py b/backend/app/models/recurring_transaction.pyindex 2d6609bb..5e5bce35 100644--- a/backend/app/models/recurring_transaction.py+++ b/backend/app/models/recurring_transaction.py@@ -24,7 +24,7 @@ class RecurringTransaction(Base):id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("users.id"))- account_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=True)+ account_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=True)category_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("categories.id"), nullable=True)description: Mapped[str] = mapped_column(String(500))amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex c9379d57..d96eb05b 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -405,12 +405,33 @@ async def delete_account(session: AsyncSession, account_id: uuid.UUID, user_id:# Clean up attachment files for all transactions in this accountfrom app.services.attachment_service import cleanup_attachment_files+ from app.models.import_log import ImportLog+ from app.models.recurring_transaction import RecurringTransaction+ from app.models.goal import Goaltx_result = await session.execute(select(Transaction.id).where(Transaction.account_id == account_id))tx_ids = [row[0] for row in tx_result.all()]await cleanup_attachment_files(session, tx_ids)+ # Break FK references before deleting the account. In production these are+ # also enforced at the DB level (see migration 032) — this code path makes+ # the behavior explicit and keeps the FK bug from #110 from regressing for+ # any of the three dependent tables.+ await session.execute(+ ImportLog.__table__.delete().where(ImportLog.account_id == account_id)+ )+ await session.execute(+ RecurringTransaction.__table__.delete().where(+ RecurringTransaction.account_id == account_id+ )+ )+ await session.execute(+ Goal.__table__.update()+ .where(Goal.account_id == account_id)+ .values(account_id=None)+ )+await session.delete(account)await session.commit()return Truediff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.pyindex 12f4f551..6035b344 100644--- a/backend/tests/test_account_service.py+++ b/backend/tests/test_account_service.py@@ -17,6 +17,9 @@ import pytestfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Account+from app.models.goal import Goal+from app.models.import_log import ImportLog+from app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction import Transactionfrom app.schemas.account import AccountCreate, AccountUpdatefrom app.services.account_service import (@@ -318,6 +321,86 @@ async def test_delete_account_not_found(session: AsyncSession, test_user):assert result is False+async def test_delete_account_with_import_logs(session: AsyncSession, test_user):+ """Regression (#110): deleting an account with import_logs must succeed and+ cascade-delete the orphaned log rows instead of tripping the FK constraint."""+ from sqlalchemy import select++ account = await _make_account(session, test_user.id, "With Imports")+ log = ImportLog(+ id=uuid.uuid4(), user_id=test_user.id, account_id=account.id,+ filename="stmt.ofx", format="ofx", transaction_count=3,+ )+ session.add(log)+ await session.commit()+ log_id = log.id++ result = await delete_account(session, account.id, test_user.id)+ assert result is True++ assert await get_account(session, account.id, test_user.id) is None+ orphan = await session.execute(+ select(ImportLog).where(ImportLog.id == log_id)+ )+ assert orphan.scalar_one_or_none() is None+++async def test_delete_account_with_recurring_transactions(session: AsyncSession, test_user):+ """Regression (#110, @stanleyndachi): deleting an account with a recurring+ transaction must succeed; the recurring rows cascade away since a schedule+ without an account can't post."""+ from sqlalchemy import select++ account = await _make_account(session, test_user.id, "With Recurring")+ rec = RecurringTransaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=account.id,+ description="Rent", amount=Decimal("1000.00"), currency="BRL",+ type="debit", frequency="monthly",+ start_date=date.today(), next_occurrence=date.today(),+ )+ session.add(rec)+ await session.commit()+ rec_id = rec.id++ result = await delete_account(session, account.id, test_user.id)+ assert result is True++ orphan = await session.execute(+ select(RecurringTransaction).where(RecurringTransaction.id == rec_id)+ )+ assert orphan.scalar_one_or_none() is None+++async def test_delete_account_with_linked_goal(session: AsyncSession, test_user):+ """Regression (#110): deleting an account tracked by a goal must succeed;+ the goal survives with account_id nulled out (progress history is kept)."""+ from sqlalchemy import select++ account = await _make_account(session, test_user.id, "Goal Tracked")+ goal = Goal(+ id=uuid.uuid4(), user_id=test_user.id, name="Emergency fund",+ target_amount=Decimal("10000.00"), current_amount=Decimal("2500.00"),+ currency="BRL", tracking_type="account", account_id=account.id,+ )+ session.add(goal)+ await session.commit()+ goal_id = goal.id++ result = await delete_account(session, account.id, test_user.id)+ assert result is True++ session.expire_all()+ surviving = await session.execute(+ select(Goal).where(Goal.id == goal_id)+ )+ kept = surviving.scalar_one()+ assert kept.account_id is None+ assert kept.current_amount == Decimal("2500.00")++# ---------------------------------------------------------------------------# close_account / reopen_account# ---------------------------------------------------------------------------diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 0b904f35..ad6ae726 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -279,7 +279,7 @@"title": "Accounts","connectBank": "Connect Bank","confirmDeleteTitle": "Delete account?",- "confirmDeleteDesc": "This action is irreversible and will remove all transactions associated with this account.",+ "confirmDeleteDesc": "This action is irreversible. It will also delete every transaction, import record and recurring transaction attached to this account, and unlink any goals that were tracking it.","openingBalance": "opening balance","notFound": "Account not found.","balance": "Balance",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex d1f31723..a362f316 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -279,7 +279,7 @@"title": "Contas","connectBank": "Conectar Banco","confirmDeleteTitle": "Excluir conta?",- "confirmDeleteDesc": "Esta ação é irreversível e removerá todas as transações associadas a esta conta.",+ "confirmDeleteDesc": "Esta ação é irreversível. Também excluirá todas as transações, registros de importação e transações recorrentes vinculadas a esta conta, e desvinculará qualquer meta que estivesse acompanhando-a.","openingBalance": "saldo inicial","notFound": "Conta não encontrada.","balance": "Saldo",diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex 09b481cc..8d988e86 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -148,6 +148,7 @@ export default function AccountsPage() {mutationFn: (id: string) => accounts.delete(id),onSuccess: () => {invalidateFinancialQueries(queryClient)+ queryClient.invalidateQueries({ queryKey: ['import-logs'] })setDeletingId(null)toast.success(t('accounts.deleted'))},