Open-source personal finance manager. Self-hosted, privacy-first.
fix(admin): let users with reconciliation history be deleted (#1024)
Albert Dolkune86637201da4
diff --git a/backend/alembic/versions/096_reconciliation_user_fks_set_null.py b/backend/alembic/versions/096_reconciliation_user_fks_set_null.pynew file mode 100644index 00000000..148dcc5f--- /dev/null+++ b/backend/alembic/versions/096_reconciliation_user_fks_set_null.py@@ -0,0 +1,44 @@+"""let a user with reconciliation history be deleted++Three columns record who did something to matching, and 086/088 created+their foreign keys to `users` without an ON DELETE action. Deleting a+user who wrote a rule, answered a suggestion, or appears in the history+then fails on the constraint. The rows belong to the workspace, not to+the person, so they stay and only the reference is cleared:++- reconciliation_rules.user_id -> ON DELETE SET NULL+- reconciliation_suggestions.resolved_by -> ON DELETE SET NULL+- reconciliation_events.user_id -> ON DELETE SET NULL++Revision ID: 096+Revises: 095+"""+from alembic import op++revision = "096"+down_revision = "095"+branch_labels = None+depends_on = None++_COLUMNS = (+ ("reconciliation_rules", "user_id"),+ ("reconciliation_suggestions", "resolved_by"),+ ("reconciliation_events", "user_id"),+)+++def _recreate(ondelete: str | None) -> None:+ for table, column in _COLUMNS:+ name = f"{table}_{column}_fkey"+ op.drop_constraint(name, table, type_="foreignkey")+ op.create_foreign_key(+ name, table, "users", [column], ["id"], ondelete=ondelete+ )+++def upgrade() -> None:+ _recreate("SET NULL")+++def downgrade() -> None:+ _recreate(None)diff --git a/backend/app/models/reconciliation.py b/backend/app/models/reconciliation.pyindex ca8605e3..a96985a3 100644--- a/backend/app/models/reconciliation.py+++ b/backend/app/models/reconciliation.py@@ -81,7 +81,7 @@ class ReconciliationRule(Base):#: it: in a workspace with several members, "who changed this" is the#: first question asked when matching starts behaving differently.user_id: Mapped[Optional[uuid.UUID]] = mapped_column(- UUID(as_uuid=True), ForeignKey("users.id"), nullable=True+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)#: Which policy document this belongs to: invoices or recurring bills.node: Mapped[str] = mapped_column(String(64))@@ -199,7 +199,7 @@ class ReconciliationSuggestion(Base):DateTime(timezone=True), nullable=True)resolved_by: Mapped[Optional[uuid.UUID]] = mapped_column(- UUID(as_uuid=True), ForeignKey("users.id"), nullable=True+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()@@ -264,6 +264,6 @@ class ReconciliationEvent(Base):#: Null means the system did it on its own: the difference a reader#: most often wants: was this me, or was this the rules?user_id: Mapped[Optional[uuid.UUID]] = mapped_column(- UUID(as_uuid=True), ForeignKey("users.id"), nullable=True+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)detail: Mapped[dict[str, Any]] = mapped_column(_Json, default=dict)diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex a5b86e03..db34ea9c 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -45,6 +45,7 @@ setattr(_pgv, "Vector", _VectorJSON)import pytest # noqa: E402import pytest_asyncio # noqa: E402from httpx import ASGITransport, AsyncClient # noqa: E402+from sqlalchemy import text # noqa: E402from sqlalchemy.dialects.postgresql import UUID # noqa: E402from sqlalchemy.ext.compiler import compiles # noqa: E402from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker # noqa: E402@@ -123,6 +124,31 @@ async def session() -> AsyncGenerator[AsyncSession, None]:await session.rollback()+@pytest_asyncio.fixture+async def postgres_sessions():+ """Give each PostgreSQL test its own schema, including under xdist."""+ url = os.environ.get("POSTGRES_TEST_URL")+ if not url:+ if os.environ.get("CI"):+ pytest.fail("CI must supply POSTGRES_TEST_URL for PostgreSQL tests")+ pytest.skip("isolated PostgreSQL not configured")+ schema = f"postgres_test_{uuid.uuid4().hex}"+ pg_engine = create_async_engine(url)+ scoped = pg_engine.execution_options(schema_translate_map={None: schema})+ try:+ async with pg_engine.begin() as conn:+ await conn.execute(text(f'CREATE SCHEMA "{schema}"'))+ async with scoped.begin() as conn:+ await conn.run_sync(Base.metadata.create_all)+ yield async_sessionmaker(scoped, expire_on_commit=False)+ finally:+ try:+ async with pg_engine.begin() as conn:+ await conn.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))+ finally:+ await pg_engine.dispose()++@pytest_asyncio.fixtureasync def clean_db(session: AsyncSession):"""Clean all data between tests."""diff --git a/backend/tests/test_admin_service.py b/backend/tests/test_admin_service.pyindex ac8e0a1d..e0e0c27c 100644--- a/backend/tests/test_admin_service.py+++ b/backend/tests/test_admin_service.py@@ -14,6 +14,11 @@ from app.models.category import Categoryfrom app.models.category_group import CategoryGroupfrom app.models.import_log import ImportLogfrom app.models.payee import Payee, PayeeMapping+from app.models.reconciliation import (+ ReconciliationEvent,+ ReconciliationRule,+ ReconciliationSuggestion,+)from app.models.recurring_transaction import RecurringTransactionfrom app.models.rule import Rulefrom app.models.transaction import Transaction@@ -299,6 +304,55 @@ async def test_delete_user_cascade(session: AsyncSession, clean_db):assert await get_user(session, target.id) is None+async def test_delete_user_keeps_reconciliation_history(postgres_sessions):+ """SQLite runs without foreign keys, so only PostgreSQL shows the failure."""+ async with postgres_sessions() as session:+ admin = await _make_user(session, "[email protected]", is_superuser=True)+ target = await _make_user(session, "[email protected]")+ # The admin owns the transaction: were it the member's, delete_user+ # would remove it and the suggestion would cascade away with it.+ acct = Account(+ id=uuid.uuid4(), user_id=admin.id, name="Shared",+ type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add(acct)+ await session.flush()+ txn = Transaction(+ id=uuid.uuid4(), user_id=admin.id, account_id=acct.id,+ description="Invoice payment", amount=Decimal("50"), date=date.today(),+ type="credit", source="manual", currency="BRL",+ )+ session.add(txn)+ await session.flush()+ expectation_id = uuid.uuid4()+ rule = ReconciliationRule(+ workspace_id=acct.workspace_id, user_id=target.id,+ node="reconciliation.match_invoice", strategy_id="same_client_exact",+ )+ suggestion = ReconciliationSuggestion(+ workspace_id=acct.workspace_id, transaction_id=txn.id,+ expectation_kind="invoice", expectation_id=expectation_id,+ strategy_id="same_client_exact", node="reconciliation.match_invoice",+ amount=Decimal("50"), status="accepted",+ resolved_at=datetime.now(timezone.utc), resolved_by=target.id,+ )+ event = ReconciliationEvent(+ workspace_id=acct.workspace_id, action="accepted", transaction_id=txn.id,+ expectation_kind="invoice", expectation_id=expectation_id,+ amount=Decimal("50"), user_id=target.id,+ )+ session.add_all([rule, suggestion, event])+ await session.commit()++ assert await delete_user(session, target.id, admin.id) is True++ for row in (rule, suggestion, event):+ await session.refresh(row)+ assert rule.user_id is None+ assert suggestion.resolved_by is None+ assert event.user_id is None++async def test_delete_user_self_protection(session: AsyncSession, clean_db):admin = await _make_user(session, "[email protected]", is_superuser=True)with pytest.raises(ValueError, match="own account"):diff --git a/backend/tests/test_reports_postgres.py b/backend/tests/test_reports_postgres.pyindex dd7d6658..17aa385b 100644--- a/backend/tests/test_reports_postgres.py+++ b/backend/tests/test_reports_postgres.py@@ -1,5 +1,4 @@"""Real PostgreSQL report/API/MCP checks using the shared disposable schemas."""-import osimport uuidfrom datetime import date, timedeltafrom decimal import Decimal@@ -7,10 +6,9 @@ from decimal import Decimalimport pytestimport pytest_asynciofrom httpx import ASGITransport, AsyncClient-from sqlalchemy import select, text-from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine+from sqlalchemy import select-from app.core.database import Base, get_async_session+from app.core.database import get_async_sessionfrom app.main import appfrom app.models.transaction import Transactionfrom app.services import admin_service, report_service@@ -21,31 +19,6 @@ from mcp_server.registry import REGISTRYpytestmark = pytest.mark.asyncio-@pytest_asyncio.fixture-async def postgres_sessions():- """Give each PostgreSQL test its own schema, including under xdist."""- url = os.environ.get("POSTGRES_TEST_URL")- if not url:- if os.environ.get("CI"):- pytest.fail("CI must supply POSTGRES_TEST_URL for PostgreSQL tests")- pytest.skip("isolated PostgreSQL not configured")- schema = f"postgres_test_{uuid.uuid4().hex}"- pg_engine = create_async_engine(url)- scoped = pg_engine.execution_options(schema_translate_map={None: schema})- try:- async with pg_engine.begin() as conn:- await conn.execute(text(f'CREATE SCHEMA "{schema}"'))- async with scoped.begin() as conn:- await conn.run_sync(Base.metadata.create_all)- yield async_sessionmaker(scoped, expire_on_commit=False)- finally:- try:- async with pg_engine.begin() as conn:- await conn.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))- finally:- await pg_engine.dispose()--@pytest_asyncio.fixtureasync def session(postgres_sessions):async with postgres_sessions() as session: