Skip to content

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

fix: keep connection link on close so sync doesn't recreate the account (#90) (#107)

Tássio Noronha7153b11c0719
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index 01b5c0cc..c9379d57 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -428,9 +428,12 @@ async def close_account(
account.is_closed = True
account.closed_at = datetime.now(timezone.utc)
- # Unlink from bank connection so sync skips it
- if account.connection_id is not None:
- account.connection_id = None
+ # Keep `connection_id` intact for connected accounts so the sync loop in
+ # connection_service can find the account by (connection_id, external_id)
+ # and honor the `is_closed` skip. Unlinking caused the next sync to treat
+ # the provider account as new and create a duplicate active row, while
+ # leaving the original entry stranded in "Closed Accounts" with no link
+ # back to its connection (issue #90).
await session.commit()
await session.refresh(account)
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index e953aa32..cdf2e71e 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -626,6 +626,14 @@ async def sync_connection(
)
account = result.scalar_one_or_none()
+ # Honor user intent: a closed connected account stays closed and is
+ # not touched by sync. The row is left alone (no balance/name
+ # rewrite, no new transactions) but the connection link is kept so
+ # the next sync still finds it here instead of creating a duplicate
+ # active account (issue #90).
+ if account and account.is_closed:
+ continue
+
if account:
account.balance = acc_data.balance
account.name = acc_data.name
@@ -669,9 +677,6 @@ async def sync_connection(
session.add(account)
await session.flush()
- if account and account.is_closed:
- continue
-
# Fetch and sync transactions. The 14-day rewind is on Pluggy's
# `createdAt` (when their row was inserted), so it covers two
# cases: (1) PENDING transactions that POSTED since last sync,
diff --git a/backend/tests/test_account_closure_api.py b/backend/tests/test_account_closure_api.py
index d1ebaeba..758231e1 100644
--- a/backend/tests/test_account_closure_api.py
+++ b/backend/tests/test_account_closure_api.py
@@ -26,11 +26,18 @@ async def test_close_manual_account(client: AsyncClient, auth_headers):
@pytest.mark.asyncio
-async def test_close_bank_connected_account_unlinks(
+async def test_close_bank_connected_account_keeps_connection_link(
client: AsyncClient, auth_headers, test_account: Account
):
- """Closing a bank-connected account unlinks it from the connection."""
+ """Closing a bank-connected account preserves its connection link.
+
+ The next sync looks up accounts by (connection_id, external_id); unlinking
+ on close caused sync to treat the provider account as new and create a
+ duplicate active row (issue #90). The closed flag alone is enough to keep
+ sync from touching the account.
+ """
assert test_account.connection_id is not None
+ original_connection_id = str(test_account.connection_id)
close_resp = await client.post(
f"/api/accounts/{test_account.id}/close", headers=auth_headers
@@ -38,7 +45,7 @@ async def test_close_bank_connected_account_unlinks(
assert close_resp.status_code == 200
data = close_resp.json()
assert data["is_closed"] is True
- assert data["connection_id"] is None
+ assert data["connection_id"] == original_connection_id
@pytest.mark.asyncio
diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.py
index e4172235..12f4f551 100644
--- a/backend/tests/test_account_service.py
+++ b/backend/tests/test_account_service.py
@@ -335,14 +335,19 @@ async def test_close_account(session: AsyncSession, test_user):
@pytest.mark.asyncio
-async def test_close_bank_connected_unlinks(session: AsyncSession, test_user, test_connection):
- """Closing bank-connected account sets connection_id to None."""
+async def test_close_bank_connected_keeps_link(session: AsyncSession, test_user, test_connection):
+ """Closing a bank-connected account keeps its connection link.
+
+ Sync uses (connection_id, external_id) to find the row; unlinking on close
+ caused sync to create a duplicate active account (issue #90). The is_closed
+ flag alone is enough to keep sync from touching it.
+ """
account = await _make_account(
session, test_user.id, "Connected Close",
connection_id=test_connection.id, external_id="ext-close",
)
closed = await close_account(session, account.id, test_user.id)
- assert closed.connection_id is None
+ assert closed.connection_id == test_connection.id
assert closed.is_closed is True
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
index 1d8cebe7..aad386b8 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -620,3 +620,63 @@ async def test_sync_connection_preserves_display_name(session: AsyncSession, tes
await session.refresh(account)
assert account.name == "BANCO ATUALIZADO"
assert account.display_name == "Meu Apelido"
+
+
+async def test_sync_connection_does_not_recreate_closed_accounts(
+ session: AsyncSession, test_user,
+):
+ """Closing a connected account then resyncing must NOT create a duplicate
+ active row for the same provider account, and the original closed row must
+ keep its connection link so we can find it on subsequent syncs (issue #90).
+ """
+ from app.models.account import Account
+ from app.services.account_service import close_account
+
+ conn = await _make_connection(session, test_user.id, "Closed Bank")
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="closed-acc-1", name="Checking",
+ type="checking", balance=Decimal("500"), currency="BRL",
+ ),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \
+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \
+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):
+ await sync_connection(session, conn.id, test_user.id)
+
+ account = (await session.execute(
+ select(Account).where(Account.external_id == "closed-acc-1")
+ )).scalar_one()
+ assert account.connection_id == conn.id
+
+ await close_account(session, account.id, test_user.id)
+ await session.refresh(account)
+ assert account.is_closed is True
+ assert account.connection_id == conn.id # link preserved
+
+ # Provider still returns the same account on the next sync
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="closed-acc-1", name="Checking",
+ type="checking", balance=Decimal("999"), currency="BRL",
+ ),
+ ])
+
+ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \
+ patch("app.services.connection_service.detect_transfer_pairs", new_callable=AsyncMock), \
+ patch("app.services.connection_service.stamp_primary_amount", new_callable=AsyncMock), \
+ patch("app.services.connection_service.apply_rules_to_transaction", new_callable=AsyncMock):
+ await sync_connection(session, conn.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Account).where(Account.external_id == "closed-acc-1")
+ )).scalars().all()
+ assert len(rows) == 1, "sync must not create a duplicate active row"
+ assert rows[0].is_closed is True
+ assert rows[0].balance == Decimal("500"), "closed accounts must not be touched by sync"