Open-source personal finance manager. Self-hosted, privacy-first.
fix(sync): inherit installment categories (#894)
Leonardo Zanivan04a1dcea59ca
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex d17485cc..41ff26bc 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -842,6 +842,48 @@ async def _match_pluggy_category(return result.scalars().first()+async def _find_installment_category(+ session: AsyncSession,+ account_id: uuid.UUID,+ txn_data,+) -> Optional[uuid.UUID]:+ """Reuse the latest user-selected category from an earlier installment.++ Pluggy gives every parcel the original purchase date, installment count,+ and total purchase amount. Together with the card account and transaction+ type, those fields identify the purchase series without relying on the+ description (whose ``03/12`` suffix changes every month).++ Only earlier synced parcels qualify. This keeps manual installment series+ separate and lets a user's most recent category correction become the+ source of truth for the next imported parcel.+ """+ if (+ txn_data.installment_number is None+ or txn_data.total_installments is None+ or txn_data.installment_total_amount is None+ or txn_data.installment_purchase_date is None+ ):+ return None++ result = await session.execute(+ select(Transaction.category_id)+ .where(+ Transaction.account_id == account_id,+ Transaction.source == "sync",+ Transaction.category_id.is_not(None),+ Transaction.installment_purchase_date == txn_data.installment_purchase_date,+ Transaction.total_installments == txn_data.total_installments,+ Transaction.installment_total_amount == txn_data.installment_total_amount,+ Transaction.type == txn_data.type,+ Transaction.installment_number < txn_data.installment_number,+ )+ .order_by(Transaction.installment_number.desc(), Transaction.date.desc())+ .limit(1)+ )+ return result.scalars().first()++async def get_connections(session: AsyncSession, workspace_id: uuid.UUID) -> list[BankConnection]:result = await session.execute(select(BankConnection)@@ -1121,9 +1163,16 @@ async def handle_oauth_callback()continue- category_id = await _match_pluggy_category(- session, workspace_id, txn_data.pluggy_category, enabled=use_provider_cats+ category_id = await _find_installment_category(+ session, account.id, txn_data)+ if category_id is None:+ category_id = await _match_pluggy_category(+ session,+ workspace_id,+ txn_data.pluggy_category,+ enabled=use_provider_cats,+ )# Resolve payee entity from raw payee textpayee_id = Noneif txn_data.payee:@@ -1940,12 +1989,16 @@ async def sync_connection(incoming_currency = (txn_data.currency or acc_data.currency or user_currency)- category_id = await _match_pluggy_category(- session,- workspace_id,- txn_data.pluggy_category,- enabled=use_provider_cats,+ category_id = await _find_installment_category(+ session, account.id, txn_data)+ if category_id is None:+ category_id = await _match_pluggy_category(+ session,+ workspace_id,+ txn_data.pluggy_category,+ enabled=use_provider_cats,+ )sync_payee_id = Noneif txn_data.payee:diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.pyindex b6610148..c3bcc097 100644--- a/backend/tests/test_connection_service.py+++ b/backend/tests/test_connection_service.py@@ -1065,6 +1065,131 @@ async def test_incremental_sync_rule_category_wins_over_provider_category(assert transaction.category_id == consorcio_category.id+async def test_incremental_sync_reuses_latest_installment_category_when_provider_categories_disabled(+ session: AsyncSession, test_user, test_workspace+):+ """A category corrected on a prior parcel follows the purchase series.++ This inheritance is independent of the provider-category setting. A+ regular charge in the same sync remains uncategorized when that setting is+ disabled, while the next installment takes the most recently selected+ category from its own series.+ """+ conn = await _make_connection(session, test_user.id, "Installment Category Bank")+ older_category = await _make_category(session, test_user.id, "Compras antigas")+ latest_category = await _make_category(session, test_user.id, "Casa")+ await _make_category(session, test_user.id, "Alimentação")++ mock_provider = AsyncMock()+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})+ mock_provider.get_accounts = AsyncMock(return_value=[+ AccountData(+ external_id="installment-category-acc-1",+ name="Credit Card",+ type="credit_card",+ balance=Decimal("0"),+ 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_workspace.id, test_user.id)++ account = (await session.execute(+ select(Account).where(Account.external_id == "installment-category-acc-1")+ )).scalar_one()+ purchase_date = date(2026, 1, 15)+ for number, tx_date, category in (+ (1, date(2026, 1, 15), older_category),+ (2, date(2026, 2, 15), latest_category),+ ):+ session.add(Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ external_id=f"existing-installment-{number}",+ description=f"LOJA EXEMPLO {number}/06",+ original_description=f"LOJA EXEMPLO {number}/06",+ amount=Decimal("100.00"),+ currency="BRL",+ date=tx_date,+ effective_date=tx_date,+ type="debit",+ source="sync",+ status="posted",+ category_id=category.id,+ installment_number=number,+ total_installments=6,+ installment_total_amount=Decimal("600.00"),+ installment_purchase_date=purchase_date,+ ))+ await session.commit()++ mock_provider.get_transactions = AsyncMock(return_value=[+ TransactionData(+ external_id="new-installment-3",+ description="LOJA EXEMPLO 3/06",+ amount=Decimal("100.00"),+ date=date(2026, 3, 15),+ type="debit",+ currency="BRL",+ pluggy_category="Eating out",+ installment_number=3,+ total_installments=6,+ installment_total_amount=Decimal("600.00"),+ installment_purchase_date=purchase_date,+ ),+ TransactionData(+ external_id="new-regular-charge",+ description="RESTAURANTE AVULSO",+ amount=Decimal("25.00"),+ date=date(2026, 3, 16),+ type="debit",+ currency="BRL",+ pluggy_category="Eating out",+ ),+ TransactionData(+ external_id="new-other-installment",+ description="OUTRA LOJA 3/06",+ amount=Decimal("100.00"),+ date=date(2026, 3, 17),+ type="debit",+ currency="BRL",+ pluggy_category="Eating out",+ installment_number=3,+ total_installments=6,+ installment_total_amount=Decimal("600.00"),+ installment_purchase_date=date(2026, 1, 16),+ ),+ ])++ with patch("app.services.connection_service.get_provider", return_value=mock_provider), \+ patch("app.services.connection_service.admin_service.use_provider_categories", new_callable=AsyncMock, return_value=False), \+ 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)++ imported = (await session.execute(+ select(Transaction).where(+ Transaction.external_id.in_([+ "new-installment-3",+ "new-regular-charge",+ "new-other-installment",+ ])+ )+ )).scalars().all()+ by_external_id = {tx.external_id: tx for tx in imported}+ assert by_external_id["new-installment-3"].category_id == latest_category.id+ assert by_external_id["new-regular-charge"].category_id is None+ assert by_external_id["new-other-installment"].category_id is None++@pytest.mark.asyncioasync def test_oauth_callback_rule_category_wins_over_provider_category(session: AsyncSession, test_user, test_workspace