Skip to content

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

fix(sync): reconcile the opening balance after phantom cleanup (#1029)

Rhuan Barretobc230ad42c24
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index c63b4367..823a4d41 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -1578,7 +1578,7 @@ async def _find_synced_duplicate(
async def _cleanup_phantom_duplicates(
session: AsyncSession,
connection_id: uuid.UUID,
-) -> int:
+) -> set[uuid.UUID]:
"""Delete synced transactions that are phantom duplicates.
Some providers (or sandbox data) report the same payment twice with
@@ -1591,13 +1591,16 @@ async def _cleanup_phantom_duplicates(
within ±1 day. The pairing of the sibling is the safety signal that lets
us distinguish the duplicate from a legitimate same-day repeat (e.g. two
real Uber rides for the same fare).
+
+ Returns the ids of the accounts that lost a row, so the caller can
+ reconcile their opening balances against what is left.
"""
accounts_result = await session.execute(
select(Account.id).where(Account.connection_id == connection_id)
)
account_ids = [row[0] for row in accounts_result.all()]
if not account_ids:
- return 0
+ return set()
unmatched_result = await session.execute(
select(Transaction).where(
@@ -1608,7 +1611,7 @@ async def _cleanup_phantom_duplicates(
)
unmatched = list(unmatched_result.scalars().all())
- deleted = 0
+ touched: set[uuid.UUID] = set()
for tx in unmatched:
date_lo = tx.date - timedelta(days=1)
date_hi = tx.date + timedelta(days=1)
@@ -1630,10 +1633,10 @@ async def _cleanup_phantom_duplicates(
tx.original_description or tx.description,
) >= 0.9:
await session.delete(tx)
- deleted += 1
+ touched.add(tx.account_id)
break
- return deleted
+ return touched
# Finance-charge `additionalInfo` strings that Pluggy emits but which would
@@ -2373,7 +2376,22 @@ async def sync_connection(
# Clean up phantom duplicates: providers occasionally double-report the
# same payment with different ids. Once transfer detection has paired
# the real one, the orphan twin gets removed here.
- await _cleanup_phantom_duplicates(session, connection.id)
+ touched_account_ids = await _cleanup_phantom_duplicates(session, connection.id)
+
+ # The opening balances above were reconciled with the phantoms still
+ # counted. Reconcile the open accounts that lost one again, so the
+ # removed amount does not stay behind in their synthetic opening
+ # transaction. Closed accounts stay out, as in the account loop.
+ if touched_account_ids:
+ await session.flush()
+ touched_accounts = await session.execute(
+ select(Account).where(
+ Account.id.in_(touched_account_ids),
+ Account.is_closed == False,
+ )
+ )
+ for touched_account in touched_accounts.scalars():
+ await sync_opening_balance_for_connected_account(session, touched_account)
# Refresh investment holdings (brokerage, fixed income, funds,
# etc.) when enabled for this connection. Errors here are logged but
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
index 5cc5a5a5..9939495a 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -1385,6 +1385,115 @@ async def test_sync_upserts_matching_csv_import_without_overwriting_user_fields(
}
+async def test_sync_connection_opening_balance_ignores_removed_phantom(
+ session: AsyncSession, test_user, test_workspace
+):
+ """A re-keyed twin of a transfer-paired row is inserted and then removed as a
+ phantom in the same sync. The opening balance must not keep its amount.
+ """
+ conn = await _make_connection(session, test_user.id, "Rekey Bank")
+
+ account = Account(
+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ connection_id=conn.id, external_id="rekey-acc-1", name="Checking",
+ type="checking", balance=Decimal("1000"), currency="NOK",
+ )
+ session.add(account)
+ await session.flush()
+ account_id = account.id
+
+ payment_day = date.today()
+ session.add(Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ account_id=account_id, external_id="card-payment-old-key",
+ description="Card payment", amount=Decimal("700.00"),
+ date=payment_day, type="debit", status="posted", source="sync",
+ currency="NOK", transfer_pair_id=uuid.uuid4(),
+ created_at=datetime.now(timezone.utc),
+ ))
+ await session.commit()
+
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(return_value=[
+ AccountData(
+ external_id="rekey-acc-1", name="Checking", type="checking",
+ balance=Decimal("1000"), currency="NOK",
+ ),
+ ])
+ mock_provider.get_transactions = AsyncMock(return_value=[
+ TransactionData(
+ external_id="card-payment-new-key", description="Card payment",
+ amount=Decimal("700.00"), date=payment_day, type="debit",
+ currency="NOK", status="posted",
+ ),
+ ])
+
+ 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_workspace.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Transaction).where(Transaction.account_id == account_id)
+ )).scalars().all()
+ synced = [row for row in rows if row.source != "opening_balance"]
+ assert [row.external_id for row in synced] == ["card-payment-old-key"]
+
+ signed_total = sum(
+ row.amount if row.type == "credit" else -row.amount for row in rows
+ )
+ assert signed_total == Decimal("1000")
+
+
+async def test_phantom_cleanup_leaves_a_closed_accounts_opening_balance_alone(
+ session: AsyncSession, test_user, test_workspace
+):
+ """The sync skips balance reconciliation for a closed account, so removing a
+ phantom from one must not write an opening balance to it either.
+ """
+ conn = await _make_connection(session, test_user.id, "Closed Bank")
+
+ account = Account(
+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ connection_id=conn.id, external_id="closed-acc-1", name="Old checking",
+ type="checking", balance=Decimal("1000"), currency="NOK", is_closed=True,
+ )
+ session.add(account)
+ await session.flush()
+ account_id = account.id
+
+ payment_day = date.today()
+ for external_id, pair in (("paired", uuid.uuid4()), ("phantom", None)):
+ session.add(Transaction(
+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=test_workspace.id,
+ account_id=account_id, external_id=external_id,
+ description="Card payment", amount=Decimal("700.00"),
+ date=payment_day, type="debit", status="posted", source="sync",
+ currency="NOK", transfer_pair_id=pair,
+ created_at=datetime.now(timezone.utc),
+ ))
+ await session.commit()
+
+ 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="Old checking", type="checking",
+ balance=Decimal("1000"), currency="NOK",
+ ),
+ ])
+ 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_workspace.id, test_user.id)
+
+ rows = (await session.execute(
+ select(Transaction).where(Transaction.account_id == account_id)
+ )).scalars().all()
+ assert [row.external_id for row in rows] == ["paired"]
+
+
@pytest.mark.asyncio
async def test_sync_connection_tolerates_duplicate_transaction_rows(
session: AsyncSession, test_user, test_workspace