Open-source personal finance manager. Self-hosted, privacy-first.
feat: link recurring bills to actual transactions (#116) (#381)
Tássio Noronha2c9e53799bb5
diff --git a/backend/alembic/versions/064_link_recurring_transactions.py b/backend/alembic/versions/064_link_recurring_transactions.pynew file mode 100644index 00000000..f33f3903--- /dev/null+++ b/backend/alembic/versions/064_link_recurring_transactions.py@@ -0,0 +1,71 @@+"""link recurring bills to actual transactions (issue #116)++Revision ID: 064+Revises: 063+Create Date: 2026-07-02++Adds the plumbing to reconcile recurring bills with the real transactions that+pay them, so bank-synced charges stop duplicating generated recurring rows.++- transactions.recurring_transaction_id: FK to the recurring bill a transaction+ fulfills. Nullable, ON DELETE SET NULL (removing a bill just unlinks its+ transactions). Indexed for the match lookups.+- recurring_transactions.auto_generate: when True (default, preserving today's+ behavior) generate_pending materializes due occurrences into transactions;+ when False the bill stays a projection until a real charge is matched to it.++Both changes are additive and nullable/defaulted, so existing rows are+unaffected: every current recurring bill keeps auto_generate = True.+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "064"+down_revision: Union[str, None] = "063"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column(+ "recurring_transactions",+ sa.Column(+ "auto_generate",+ sa.Boolean(),+ nullable=False,+ server_default=sa.text("true"),+ ),+ )+ op.add_column(+ "transactions",+ sa.Column("recurring_transaction_id", sa.UUID(), nullable=True),+ )+ op.create_index(+ "ix_transactions_recurring_transaction_id",+ "transactions",+ ["recurring_transaction_id"],+ )+ op.create_foreign_key(+ "fk_transactions_recurring_transaction_id",+ "transactions",+ "recurring_transactions",+ ["recurring_transaction_id"],+ ["id"],+ ondelete="SET NULL",+ )+++def downgrade() -> None:+ op.drop_constraint(+ "fk_transactions_recurring_transaction_id",+ "transactions",+ type_="foreignkey",+ )+ op.drop_index(+ "ix_transactions_recurring_transaction_id",+ table_name="transactions",+ )+ op.drop_column("transactions", "recurring_transaction_id")+ op.drop_column("recurring_transactions", "auto_generate")diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 3e32ee7a..318f3e92 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -403,6 +403,24 @@ async def toggle_ignore_transaction(return _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)[email protected]("/{transaction_id}/unlink-recurring", response_model=TransactionRead)+async def unlink_recurring_transaction(+ transaction_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ transaction = await transaction_service.unlink_recurring_transaction(+ session, transaction_id, ctx.workspace.id+ )+ if not transaction:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="Transaction not found or not linked to a recurring bill",+ )+ primary_currency = ctx.user.primary_currency+ return _tag_fx_fallback(TransactionRead.model_validate(transaction, from_attributes=True), primary_currency)++@router.delete("/{transaction_id}", status_code=status.HTTP_204_NO_CONTENT)async def delete_transaction(transaction_id: uuid.UUID,diff --git a/backend/app/models/recurring_transaction.py b/backend/app/models/recurring_transaction.pyindex 90087bc6..a5ef42ac 100644--- a/backend/app/models/recurring_transaction.py+++ b/backend/app/models/recurring_transaction.py@@ -13,6 +13,7 @@ from app.core.database import Baseif TYPE_CHECKING:from app.models.account import Accountfrom app.models.category import Category+ from app.models.transaction import Transactionfrom app.models.user import User@@ -38,6 +39,12 @@ class RecurringTransaction(Base):start_date: Mapped[date] = mapped_column(Date)end_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)is_active: Mapped[bool] = mapped_column(Boolean, default=True)+ # When True (the default), generate_pending materializes this bill's due+ # occurrences into real transactions. When False, no placeholder is written+ # and the bill is only shown as a projection until the actual charge is+ # matched to it (e.g. from bank sync). Either way, incoming real+ # transactions are linked back to the bill to avoid duplicates.+ auto_generate: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")next_occurrence: Mapped[date] = mapped_column(Date)amount_primary: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=15, scale=2), nullable=True)fx_rate_used: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=20, scale=10), nullable=True)@@ -46,3 +53,6 @@ class RecurringTransaction(Base):user: Mapped["User"] = relationship()account: Mapped[Optional["Account"]] = relationship()category: Mapped[Optional["Category"]] = relationship()+ transactions: Mapped[list["Transaction"]] = relationship(+ back_populates="recurring_transaction"+ )diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.pyindex a81ea680..457e2079 100644--- a/backend/app/models/transaction.py+++ b/backend/app/models/transaction.py@@ -15,6 +15,7 @@ if TYPE_CHECKING:from app.models.credit_card_bill import CreditCardBillfrom app.models.import_log import ImportLogfrom app.models.payee import Payee+ from app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction_attachment import TransactionAttachmentfrom app.models.transaction_split import TransactionSplit@@ -79,12 +80,25 @@ class Transaction(Base):# Flag to exclude this transaction from reports and dashboard aggregations.# When set to True, the transaction is ignored for income/expense calculations.is_ignored: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")+ # Link to the recurring bill this transaction fulfills (issue #116). Set when+ # a synced/imported/manual charge is matched to a recurring bill, or stamped+ # onto the placeholder generate_pending materializes. ON DELETE SET NULL: if+ # the recurring bill is removed, the transaction stays put and just unlinks.+ recurring_transaction_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("recurring_transactions.id", ondelete="SET NULL"),+ nullable=True,+ index=True,+ )created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))account: Mapped["Account"] = relationship(back_populates="transactions")category: Mapped[Optional["Category"]] = relationship()bill: Mapped[Optional["CreditCardBill"]] = relationship()payee_entity: Mapped[Optional["Payee"]] = relationship(back_populates="transactions")+ recurring_transaction: Mapped[Optional["RecurringTransaction"]] = relationship(+ back_populates="transactions"+ )import_log: Mapped[Optional["ImportLog"]] = relationship(back_populates="transactions")attachments: Mapped[list["TransactionAttachment"]] = relationship(back_populates="transaction", cascade="all, delete-orphan"diff --git a/backend/app/schemas/recurring_transaction.py b/backend/app/schemas/recurring_transaction.pyindex c79726c8..8fccd313 100644--- a/backend/app/schemas/recurring_transaction.py+++ b/backend/app/schemas/recurring_transaction.py@@ -18,6 +18,7 @@ class RecurringTransactionCreate(BaseModel):account_id: uuid.UUIDcategory_id: Optional[uuid.UUID] = Noneskip_first: bool = False # Set true when first occurrence already created as a transaction+ auto_generate: bool = True # Materialize occurrences; when false, wait for the real chargeclass RecurringTransactionUpdate(BaseModel):@@ -32,6 +33,7 @@ class RecurringTransactionUpdate(BaseModel):account_id: Optional[uuid.UUID] = Nonecategory_id: Optional[uuid.UUID] = Noneis_active: Optional[bool] = None+ auto_generate: Optional[bool] = Noneclass RecurringTransactionRead(BaseModel):@@ -48,6 +50,7 @@ class RecurringTransactionRead(BaseModel):start_date: _Dateend_date: Optional[_Date] = Noneis_active: bool+ auto_generate: bool = Truenext_occurrence: _Dateamount_primary: Optional[float] = Nonefx_rate_used: Optional[float] = Nonediff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex a74c4feb..80bafcab 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -82,6 +82,7 @@ class TransactionRead(TransactionBase):installment_purchase_date: Optional[_Date] = Nonebill_id: Optional[uuid.UUID] = Noneeffective_bill_date: Optional[_Date] = None+ recurring_transaction_id: Optional[uuid.UUID] = Nonesplits: list[TransactionSplitRead] = []# Shared-transaction view fields. Set per-request when the viewer# is a linked member of one of this transaction's splits but notdiff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex d7a82801..cf0a8ded 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -28,6 +28,7 @@ from app.providers.base import ()from app.services import oauth_statefrom app.services import admin_service+from app.services import recurring_match_servicefrom app.services.account_service import (_simplefin_to_internal_balance,sync_opening_balance_for_connected_account,@@ -1320,6 +1321,31 @@ async def sync_connection()continue+ # Pass 4: recurring bill placeholder. If generate_pending+ # already materialized this bill's occurrence, merge the incoming+ # charge into that placeholder instead of duplicating (issue+ # #116). The recurring link is preserved by upgrading in place.+ incoming_currency = txn_data.currency or acc_data.currency or user_currency+ placeholder = await recurring_match_service.find_placeholder_for_incoming(+ session, account.id, txn_data.amount, incoming_currency,+ txn_data.type, txn_data.date, txn_data.description,+ )+ if placeholder:+ if placeholder.is_ignored:+ continue+ placeholder.external_id = txn_data.external_id+ placeholder.source = "sync"+ placeholder.status = txn_data.status+ placeholder.raw_data = txn_data.raw_data+ if txn_data.payee:+ if not placeholder.payee:+ placeholder.payee = txn_data.payee+ placeholder.payee_id = (+ await get_or_create_payee(session, user_id, txn_data.payee)+ ).id+ merged_count += 1+ continue+category_id = await _match_pluggy_category(session, workspace_id, txn_data.pluggy_category, enabled=use_provider_cats)@@ -1330,6 +1356,14 @@ async def sync_connection(sync_payee_entity = await get_or_create_payee(session, user_id, txn_data.payee)sync_payee_id = sync_payee_entity.id+ # No placeholder existed: if this charge fulfills an active bill's+ # next occurrence, link it and advance the bill so a later+ # generate_pending won't create a duplicate placeholder.+ recurring_link = await recurring_match_service.find_bill_for_incoming(+ session, user_id, account.id, txn_data.amount, incoming_currency,+ txn_data.type, txn_data.date, txn_data.description,+ )+bill = (bills_by_external_id.get(txn_data.bill_external_id)if txn_data.bill_external_id@@ -1355,12 +1389,15 @@ async def sync_connection(installment_total_amount=txn_data.installment_total_amount,installment_purchase_date=txn_data.installment_purchase_date,bill_id=bill.id if bill else None,+ recurring_transaction_id=recurring_link.id if recurring_link else None,)apply_effective_date(transaction, account, bill_due_date=bill.due_date if bill else None)session.add(transaction)await session.flush()+ if recurring_link is not None:+ recurring_match_service.advance_past(recurring_link, txn_data.date)new_tx_ids.append(transaction.id)if not category_id:await apply_rules_to_transaction(session, user_id, transaction)diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.pyindex aab8bc4d..7e8d9c77 100644--- a/backend/app/services/import_service.py+++ b/backend/app/services/import_service.py@@ -19,6 +19,7 @@ from app.models.category import Categoryfrom app.models.rule import Rulefrom app.models.transaction import Transactionfrom app.schemas.transaction import TransactionImport+from app.services import recurring_match_servicefrom app.services.credit_card_service import apply_effective_datefrom app.services.rule_engine import apply_rule_actions, evaluate_conditionsfrom app.services.rule_service import apply_rules_to_transaction@@ -623,6 +624,29 @@ async def import_transactions(import_payee_entity = await get_or_create_payee(session, user_id, import_payee_raw)import_payee_id = import_payee_entity.id+ # Recurring bill reconciliation (issue #116): if this imported charge+ # fulfills a generated placeholder, merge into it instead of creating a+ # duplicate; the recurring link is preserved.+ placeholder = await recurring_match_service.find_placeholder_for_incoming(+ session, account_id, txn_data.amount, txn_currency, txn_data.type,+ txn_data.date, txn_data.description,+ )+ if placeholder and not placeholder.is_ignored:+ placeholder.source = source+ placeholder.external_id = txn_data.external_id+ placeholder.import_id = import_log.id+ if import_payee_raw and not placeholder.payee:+ placeholder.payee = import_payee_raw+ placeholder.payee_id = import_payee_id+ imported += 1+ continue++ # Otherwise, link to an active bill's next occurrence if this fulfills it.+ recurring_link = await recurring_match_service.find_bill_for_incoming(+ session, user_id, account_id, txn_data.amount, txn_currency, txn_data.type,+ txn_data.date, txn_data.description,+ )+user_category_id = txn_data.category_idsuggested_cat_id = txn_data.suggested_category_idcsv_category_id = category_map.get(txn_data.category_name) if txn_data.category_name else None@@ -646,6 +670,7 @@ async def import_transactions(payee=import_payee_raw,payee_id=import_payee_id,category_id=category_id,+ recurring_transaction_id=recurring_link.id if recurring_link else None,)apply_effective_date(transaction, account)@@ -655,6 +680,8 @@ async def import_transactions(session.add(transaction)await session.flush()+ if recurring_link is not None:+ recurring_match_service.advance_past(recurring_link, txn_data.date)await apply_rules_to_transaction(session, user_id, transaction, skip_category_rules=txn_data.force_uncategorized)diff --git a/backend/app/services/recurring_match_service.py b/backend/app/services/recurring_match_service.pynew file mode 100644index 00000000..b60f988f--- /dev/null+++ b/backend/app/services/recurring_match_service.py@@ -0,0 +1,196 @@+"""Match recurring bills to the real transactions that pay them (issue #116).++A recurring bill (rent, a subscription) is charged to a bank account or credit+card, and bank sync then imports that charge as its own transaction. Without+linking, the user ends up with two rows: the bill's generated placeholder and+the synced charge. This service reconciles the two.++Matching signals (the intersection of what Actual and Sure use): same account,+same direction (``type``), exact amount, transaction date within a small window+of the expected occurrence, and description token-similarity above the same bar+the bank-sync fuzzy merge already uses. Matches are one-to-one and only the+high-confidence (exact-amount) tier auto-links; softer/variable-amount matching+is intentionally left for a later suggestion-based pass.+"""+import uuid+from datetime import date, timedelta+from decimal import Decimal+from typing import Optional++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction++# Description-similarity bar for accepting a link. Matches the established+# bank-sync fuzzy-merge threshold (connection_service._fuzzy_match_manual).+_SIMILARITY_THRESHOLD = 0.6++# Real-transaction sources a recurring charge can arrive under. Excludes+# "recurring" itself — that is the generated placeholder, handled separately.+_REAL_SOURCES = ("sync", "ofx", "csv", "manual")+++def _description_similarity(a: Optional[str], b: Optional[str]) -> float:+ """Token-overlap ratio between two descriptions (0..1)."""+ if not a or not b:+ return 0.0+ tokens_a = set(a.lower().split())+ tokens_b = set(b.lower().split())+ if not tokens_a or not tokens_b:+ return 0.0+ return len(tokens_a & tokens_b) / max(len(tokens_a), len(tokens_b))+++def _match_window(frequency: str) -> tuple[int, int]:+ """Days (before, after) an expected occurrence a real charge may land.++ Charges commonly post a few days after the nominal due date and sometimes+ a day or two early. Windows stay well under one period so a charge can+ never match the neighbouring occurrence.+ """+ if frequency == "weekly":+ return 2, 2+ # monthly / yearly+ return 3, 5+++def _best_by_similarity(+ candidates, description: Optional[str]+) -> Optional[Transaction]:+ best: Optional[Transaction] = None+ best_score = 0.0+ for cand in candidates:+ if cand.is_ignored:+ continue+ score = _description_similarity(cand.description, description)+ if score > best_score:+ best_score = score+ best = cand+ return best if best and best_score >= _SIMILARITY_THRESHOLD else None+++async def find_real_tx_for_occurrence(+ session: AsyncSession,+ recurring: RecurringTransaction,+ occurrence_date: date,+) -> Optional[Transaction]:+ """Find an unlinked real transaction that fulfills this bill's occurrence.++ Used by generate_pending: instead of writing a duplicate placeholder for an+ occurrence a real charge already covers, link that charge to the bill.+ """+ before, after = _match_window(recurring.frequency)+ result = await session.execute(+ select(Transaction).where(+ Transaction.account_id == recurring.account_id,+ Transaction.recurring_transaction_id.is_(None),+ Transaction.source.in_(_REAL_SOURCES),+ Transaction.amount == recurring.amount,+ Transaction.currency == recurring.currency,+ Transaction.type == recurring.type,+ Transaction.date >= occurrence_date - timedelta(days=before),+ Transaction.date <= occurrence_date + timedelta(days=after),+ )+ )+ return _best_by_similarity(result.scalars(), recurring.description)+++async def find_placeholder_for_incoming(+ session: AsyncSession,+ account_id: uuid.UUID,+ amount: Decimal,+ currency: str,+ tx_type: str,+ tx_date: date,+ description: Optional[str],+) -> Optional[Transaction]:+ """Find an unmatched generated placeholder this incoming charge fulfills.++ Placeholders carry ``source="recurring"`` and a ``recurring_transaction_id``+ but no ``external_id`` yet. The caller upgrades the matched row in place to+ the synced/imported charge, preserving the recurring link (no duplicate).+ """+ result = await session.execute(+ select(Transaction).where(+ Transaction.account_id == account_id,+ Transaction.source == "recurring",+ Transaction.recurring_transaction_id.is_not(None),+ Transaction.external_id.is_(None),+ Transaction.amount == amount,+ Transaction.currency == currency,+ Transaction.type == tx_type,+ Transaction.date >= tx_date - timedelta(days=5),+ Transaction.date <= tx_date + timedelta(days=5),+ )+ )+ return _best_by_similarity(result.scalars(), description)+++async def find_bill_for_incoming(+ session: AsyncSession,+ user_id: uuid.UUID,+ account_id: uuid.UUID,+ amount: Decimal,+ currency: str,+ tx_type: str,+ tx_date: date,+ description: Optional[str],+) -> Optional[RecurringTransaction]:+ """Find an active bill whose next expected occurrence this charge fulfills.++ Used when a real charge arrives before any placeholder was generated. The+ caller stamps the charge with the bill and advances the bill past the+ fulfilled occurrence so generate_pending won't later duplicate it.+ """+ result = await session.execute(+ select(RecurringTransaction).where(+ RecurringTransaction.user_id == user_id,+ RecurringTransaction.account_id == account_id,+ RecurringTransaction.is_active.is_(True),+ RecurringTransaction.amount == amount,+ RecurringTransaction.currency == currency,+ RecurringTransaction.type == tx_type,+ )+ )+ best: Optional[RecurringTransaction] = None+ best_score = 0.0+ for rec in result.scalars():+ before, after = _match_window(rec.frequency)+ lo = rec.next_occurrence - timedelta(days=before)+ hi = rec.next_occurrence + timedelta(days=after)+ if not (lo <= tx_date <= hi):+ continue+ score = _description_similarity(rec.description, description)+ if score > best_score:+ best_score = score+ best = rec+ return best if best and best_score >= _SIMILARITY_THRESHOLD else None+++def advance_past(recurring: RecurringTransaction, fulfilled_date: date) -> None:+ """Advance a bill's next_occurrence past the occurrence a charge fulfilled.++ The target is floored at the bill's current next_occurrence — the matched+ occurrence — so an *early-posted* charge (one that lands inside the+ before-window, i.e. before next_occurrence) still moves the pointer forward.+ Advancing only past the posting date would leave next_occurrence unchanged+ for early charges (e.g. a Jan 8 charge for a Jan 10 occurrence), and+ generate_pending would then re-create that occurrence as a duplicate.++ Deactivates the bill if it advances beyond its end_date. Lazy-imports the+ date helper to avoid a circular import with recurring_transaction_service.+ """+ from app.services.recurring_transaction_service import _advance_date++ intended_day = recurring.day_of_month or recurring.start_date.day+ target = max(fulfilled_date, recurring.next_occurrence)+ guard = 0+ while recurring.next_occurrence <= target and guard < 500:+ recurring.next_occurrence = _advance_date(+ recurring.next_occurrence, recurring.frequency, intended_day=intended_day+ )+ guard += 1+ if recurring.end_date and recurring.next_occurrence > recurring.end_date:+ recurring.is_active = Falsediff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.pyindex 2d0f0203..389e67c6 100644--- a/backend/app/services/recurring_transaction_service.py+++ b/backend/app/services/recurring_transaction_service.py@@ -11,6 +11,7 @@ from app.models.bank_connection import BankConnectionfrom app.models.recurring_transaction import RecurringTransactionfrom app.models.transaction import Transactionfrom app.schemas.recurring_transaction import RecurringTransactionCreate, RecurringTransactionUpdate+from app.services import recurring_match_servicefrom app.services.credit_card_service import apply_effective_datefrom app.services.fx_rate_service import stamp_primary_amount@@ -81,6 +82,7 @@ async def create_recurring_transaction(day_of_month=data.day_of_month,start_date=data.start_date,end_date=data.end_date,+ auto_generate=data.auto_generate,next_occurrence=next_occ,)session.add(recurring)@@ -198,6 +200,7 @@ async def generate_pending(.where(RecurringTransaction.user_id == user_id,RecurringTransaction.is_active == True,+ RecurringTransaction.auto_generate == True,RecurringTransaction.next_occurrence <= cutoff,))@@ -217,23 +220,35 @@ async def generate_pending(recurring.is_active = Falsebreak- transaction = Transaction(- user_id=user_id,- account_id=recurring.account_id,- category_id=recurring.category_id,- description=recurring.description,- amount=recurring.amount,- currency=recurring.currency,- date=recurring.next_occurrence,- type=recurring.type,- source="recurring",+ # If a real transaction (synced/imported/manual) already covers this+ # occurrence, link it to the bill instead of writing a duplicate+ # placeholder (issue #116). Otherwise materialize the placeholder,+ # stamped with the recurring link so a later synced charge merges+ # into it rather than duplicating.+ existing_real = await recurring_match_service.find_real_tx_for_occurrence(+ session, recurring, recurring.next_occurrence)- account = await session.get(Account, recurring.account_id)- apply_effective_date(transaction, account)- session.add(transaction)- await session.flush()- await stamp_primary_amount(session, user_id, transaction)- count += 1+ if existing_real is not None:+ existing_real.recurring_transaction_id = recurring.id+ else:+ transaction = Transaction(+ user_id=user_id,+ account_id=recurring.account_id,+ category_id=recurring.category_id,+ description=recurring.description,+ amount=recurring.amount,+ currency=recurring.currency,+ date=recurring.next_occurrence,+ type=recurring.type,+ source="recurring",+ recurring_transaction_id=recurring.id,+ )+ account = await session.get(Account, recurring.account_id)+ apply_effective_date(transaction, account)+ session.add(transaction)+ await session.flush()+ await stamp_primary_amount(session, user_id, transaction)+ count += 1# Advance to next occurrencerecurring.next_occurrence = _advance_date(diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.pyindex 15b81e07..23e7abb0 100644--- a/backend/app/services/transaction_service.py+++ b/backend/app/services/transaction_service.py@@ -1414,6 +1414,26 @@ async def toggle_ignore_transaction(return transaction+async def unlink_recurring_transaction(+ session: AsyncSession,+ transaction_id: uuid.UUID,+ workspace_id: uuid.UUID,+) -> Optional[Transaction]:+ """Clear a transaction's link to a recurring bill (issue #116).++ The escape hatch for a wrong auto-link: only the FK is cleared, the+ transaction row is otherwise untouched, and the bill is left as-is (its+ next_occurrence already moved on). Returns the transaction, or None if not+ found / not currently linked."""+ transaction = await get_transaction(session, transaction_id, workspace_id)+ if not transaction or transaction.recurring_transaction_id is None:+ return None+ transaction.recurring_transaction_id = None+ await session.commit()+ await session.refresh(transaction)+ return transaction++async def delete_transaction(session: AsyncSession,transaction_id: uuid.UUID,diff --git a/backend/tests/test_recurring_match.py b/backend/tests/test_recurring_match.pynew file mode 100644index 00000000..d62065fd--- /dev/null+++ b/backend/tests/test_recurring_match.py@@ -0,0 +1,357 @@+"""Tests for recurring-bill ↔ transaction matching (issue #116)."""+import uuid+from datetime import date+from decimal import Decimal++import pytest+import pytest_asyncio+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.transaction import Transaction+from app.schemas.recurring_transaction import RecurringTransactionCreate+from app.services import recurring_match_service as rms+from app.services.recurring_transaction_service import (+ create_recurring_transaction,+ generate_pending,+)+++@pytest_asyncio.fixture+async def account(session: AsyncSession, test_user, test_workspace) -> Account:+ acc = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ name="MatchAcc",+ type="checking",+ balance=Decimal("10000"),+ currency="BRL",+ )+ session.add(acc)+ await session.commit()+ await session.refresh(acc)+ return acc+++async def _make_bill(session, test_workspace, test_user, account, **overrides):+ data = RecurringTransactionCreate(+ description=overrides.pop("description", "Netflix Subscription"),+ amount=overrides.pop("amount", Decimal("39.90")),+ currency=overrides.pop("currency", "BRL"),+ type=overrides.pop("type", "debit"),+ frequency=overrides.pop("frequency", "monthly"),+ start_date=overrides.pop("start_date", date(2025, 1, 10)),+ account_id=account.id,+ **overrides,+ )+ return await create_recurring_transaction(session, test_workspace.id, test_user.id, data)+++async def _add_tx(session, test_user, test_workspace, account, **kw):+ tx = Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ description=kw.get("description", "NETFLIX SUBSCRIPTION"),+ amount=kw.get("amount", Decimal("39.90")),+ currency="BRL",+ date=kw["date"],+ type=kw.get("type", "debit"),+ source=kw.get("source", "sync"),+ status=kw.get("status", "posted"),+ external_id=kw.get("external_id", "ext-1"),+ recurring_transaction_id=kw.get("recurring_transaction_id"),+ )+ session.add(tx)+ await session.commit()+ await session.refresh(tx)+ return tx+++# ---------------------------------------------------------------------------+# Pure helpers+# ---------------------------------------------------------------------------+++def test_description_similarity():+ assert rms._description_similarity("Netflix Sub", "netflix sub") == 1.0+ assert rms._description_similarity("Netflix", "Spotify") == 0.0+ assert rms._description_similarity(None, "x") == 0.0+++def test_match_window():+ assert rms._match_window("weekly") == (2, 2)+ assert rms._match_window("monthly") == (3, 5)+ assert rms._match_window("yearly") == (3, 5)+++# ---------------------------------------------------------------------------+# find_bill_for_incoming (sync-first path)+# ---------------------------------------------------------------------------+++async def test_find_bill_matches_within_window(session, test_user, test_workspace, account):+ bill = await _make_bill(session, test_workspace, test_user, account)+ # next_occurrence = 2025-01-10; charge posts 2 days late.+ match = await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("39.90"), "BRL", "debit",+ date(2025, 1, 12), "NETFLIX SUBSCRIPTION",+ )+ assert match is not None+ assert match.id == bill.id+++async def test_find_bill_rejects_outside_window(session, test_user, test_workspace, account):+ await _make_bill(session, test_workspace, test_user, account)+ # 10 days after the due date is well outside the monthly window.+ match = await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("39.90"), "BRL", "debit",+ date(2025, 1, 20), "NETFLIX SUBSCRIPTION",+ )+ assert match is None+++async def test_find_bill_rejects_amount_and_type_mismatch(session, test_user, test_workspace, account):+ await _make_bill(session, test_workspace, test_user, account)+ assert await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("41.00"), "BRL", "debit",+ date(2025, 1, 10), "NETFLIX SUBSCRIPTION",+ ) is None+ assert await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("39.90"), "BRL", "credit",+ date(2025, 1, 10), "NETFLIX SUBSCRIPTION",+ ) is None+++async def test_find_bill_rejects_currency_mismatch(session, test_user, test_workspace, account):+ # Bill is in BRL; a same-numeric charge in another currency must not match.+ await _make_bill(session, test_workspace, test_user, account, currency="BRL")+ assert await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("39.90"), "USD", "debit",+ date(2025, 1, 10), "NETFLIX SUBSCRIPTION",+ ) is None+++async def test_find_bill_rejects_low_similarity(session, test_user, test_workspace, account):+ await _make_bill(session, test_workspace, test_user, account)+ match = await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("39.90"), "BRL", "debit",+ date(2025, 1, 10), "Amazon Prime",+ )+ assert match is None+++# ---------------------------------------------------------------------------+# find_placeholder_for_incoming (placeholder-first path)+# ---------------------------------------------------------------------------+++async def test_find_placeholder_matches_generated_row(session, test_user, test_workspace, account):+ bill = await _make_bill(session, test_workspace, test_user, account)+ placeholder = await _add_tx(+ session, test_user, test_workspace, account,+ date=date(2025, 1, 10), source="recurring", external_id=None,+ recurring_transaction_id=bill.id, description="Netflix Subscription",+ )+ found = await rms.find_placeholder_for_incoming(+ session, account.id, Decimal("39.90"), "BRL", "debit",+ date(2025, 1, 11), "NETFLIX SUBSCRIPTION",+ )+ assert found is not None and found.id == placeholder.id+++async def test_find_placeholder_ignores_already_linked_synced(session, test_user, test_workspace, account):+ bill = await _make_bill(session, test_workspace, test_user, account)+ # A real synced row (has external_id) is not a placeholder to merge into.+ await _add_tx(+ session, test_user, test_workspace, account,+ date=date(2025, 1, 10), source="sync", external_id="ext-9",+ recurring_transaction_id=bill.id,+ )+ found = await rms.find_placeholder_for_incoming(+ session, account.id, Decimal("39.90"), "BRL", "debit",+ date(2025, 1, 10), "NETFLIX SUBSCRIPTION",+ )+ assert found is None+++# ---------------------------------------------------------------------------+# advance_past+# ---------------------------------------------------------------------------+++async def test_advance_past_moves_pointer(session, test_user, test_workspace, account):+ bill = await _make_bill(session, test_workspace, test_user, account)+ assert bill.next_occurrence == date(2025, 1, 10)+ rms.advance_past(bill, date(2025, 1, 12))+ assert bill.next_occurrence == date(2025, 2, 10)+++async def test_advance_past_deactivates_past_end_date(session, test_user, test_workspace, account):+ bill = await _make_bill(+ session, test_workspace, test_user, account, end_date=date(2025, 1, 31),+ )+ rms.advance_past(bill, date(2025, 1, 10))+ assert bill.next_occurrence == date(2025, 2, 10)+ assert bill.is_active is False+++async def test_advance_past_early_charge_still_advances(session, test_user, test_workspace, account):+ """An early-posted charge (inside the before-window, before next_occurrence)+ must still advance the pointer, or generate_pending would duplicate it."""+ bill = await _make_bill(session, test_workspace, test_user, account) # next_occ 2025-01-10+ rms.advance_past(bill, date(2025, 1, 8)) # 2 days early+ assert bill.next_occurrence == date(2025, 2, 10)+++# ---------------------------------------------------------------------------+# generate_pending integration+# ---------------------------------------------------------------------------+++async def test_generate_pending_links_existing_real_tx(session, test_user, test_workspace, account):+ """A synced charge that already covers the occurrence is linked, not duplicated."""+ bill = await _make_bill(session, test_workspace, test_user, account)+ real = await _add_tx(+ session, test_user, test_workspace, account,+ date=date(2025, 1, 11), source="sync", external_id="bank-1",+ )++ count = await generate_pending(session, test_user.id, up_to=date(2025, 1, 20))++ # No placeholder was written for January; the real charge got linked.+ assert count == 0+ await session.refresh(real)+ assert real.recurring_transaction_id == bill.id++ result = await session.execute(+ select(Transaction).where(Transaction.account_id == account.id)+ )+ assert len(result.scalars().all()) == 1 # only the synced row, no duplicate+++async def test_generate_pending_stamps_placeholder_link(session, test_user, test_workspace, account):+ bill = await _make_bill(session, test_workspace, test_user, account)+ count = await generate_pending(session, test_user.id, up_to=date(2025, 1, 20))+ assert count == 1+ result = await session.execute(+ select(Transaction).where(Transaction.source == "recurring")+ )+ tx = result.scalar_one()+ assert tx.recurring_transaction_id == bill.id+++async def test_generate_pending_skips_auto_generate_off(session, test_user, test_workspace, account):+ await _make_bill(session, test_workspace, test_user, account, auto_generate=False)+ count = await generate_pending(session, test_user.id, up_to=date(2025, 6, 1))+ assert count == 0+ result = await session.execute(+ select(Transaction).where(Transaction.account_id == account.id)+ )+ assert result.scalars().all() == []+++async def test_generate_pending_description_mismatch_creates_placeholder(+ session, test_user, test_workspace, account+):+ """A real charge with the same amount/type/date but an unrelated description+ must NOT be swallowed as the bill's occurrence; a placeholder is written and+ the real charge is left untouched."""+ bill = await _make_bill(session, test_workspace, test_user, account)+ unrelated = await _add_tx(+ session, test_user, test_workspace, account,+ date=date(2025, 1, 10), source="sync", external_id="bank-x",+ description="Amazon Marketplace",+ )+ count = await generate_pending(session, test_user.id, up_to=date(2025, 1, 20))+ assert count == 1 # placeholder created, real charge not reused+ await session.refresh(unrelated)+ assert unrelated.recurring_transaction_id is None+ result = await session.execute(+ select(Transaction).where(Transaction.source == "recurring")+ )+ ph = result.scalar_one()+ assert ph.recurring_transaction_id == bill.id+++async def test_find_bill_weekly_window_boundary(session, test_user, test_workspace, account):+ await _make_bill(+ session, test_workspace, test_user, account,+ description="Weekly Gym", frequency="weekly", start_date=date(2025, 1, 6),+ )+ # weekly window is (2, 2): 2 days late matches, 3 days late does not.+ assert await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("39.90"), "BRL", "debit",+ date(2025, 1, 8), "Weekly Gym",+ ) is not None+ assert await rms.find_bill_for_incoming(+ session, test_user.id, account.id, Decimal("39.90"), "BRL", "debit",+ date(2025, 1, 9), "Weekly Gym",+ ) is None+++async def test_find_real_tx_ignores_already_linked(session, test_user, test_workspace, account):+ bill = await _make_bill(session, test_workspace, test_user, account)+ await _add_tx(+ session, test_user, test_workspace, account,+ date=date(2025, 1, 10), source="sync", external_id="bank-1",+ recurring_transaction_id=bill.id, # already linked+ )+ found = await rms.find_real_tx_for_occurrence(session, bill, date(2025, 1, 10))+ assert found is None+++# ---------------------------------------------------------------------------+# Unlink escape hatch+# ---------------------------------------------------------------------------+++async def test_unlink_recurring_clears_link(session, test_user, test_workspace, account):+ from app.services import transaction_service++ bill = await _make_bill(session, test_workspace, test_user, account)+ tx = await _add_tx(+ session, test_user, test_workspace, account,+ date=date(2025, 1, 10), source="sync", external_id="bank-1",+ recurring_transaction_id=bill.id,+ )+ result = await transaction_service.unlink_recurring_transaction(+ session, tx.id, test_workspace.id+ )+ assert result is not None+ assert result.recurring_transaction_id is None+ await session.refresh(tx)+ assert tx.recurring_transaction_id is None+++async def test_unlink_recurring_noop_when_not_linked(session, test_user, test_workspace, account):+ from app.services import transaction_service++ tx = await _add_tx(+ session, test_user, test_workspace, account,+ date=date(2025, 1, 10), source="sync", external_id="bank-2",+ )+ result = await transaction_service.unlink_recurring_transaction(+ session, tx.id, test_workspace.id+ )+ assert result is None # nothing to unlink → 404 at the API layerdiff --git a/backend/tests/test_recurring_match_import.py b/backend/tests/test_recurring_match_import.pynew file mode 100644index 00000000..ce0365f2--- /dev/null+++ b/backend/tests/test_recurring_match_import.py@@ -0,0 +1,115 @@+"""Integration tests for recurring-bill matching through the CSV/OFX import+path (issue #116)."""+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal+from unittest.mock import AsyncMock, patch++import pytest+from sqlalchemy import select++from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction+from app.schemas.recurring_transaction import RecurringTransactionCreate+from app.schemas.transaction import TransactionImport+from app.services.import_service import import_transactions+from app.services.recurring_transaction_service import create_recurring_transaction+++async def _make_bill(session, test_workspace, test_user, account, **ov):+ data = RecurringTransactionCreate(+ description=ov.pop("description", "Netflix Subscription"),+ amount=ov.pop("amount", Decimal("39.90")),+ currency=ov.pop("currency", "BRL"),+ type=ov.pop("type", "debit"),+ frequency=ov.pop("frequency", "monthly"),+ start_date=ov.pop("start_date", date(2026, 1, 10)),+ account_id=account.id, **ov,+ )+ return await create_recurring_transaction(session, test_workspace.id, test_user.id, data)+++async def _run_import(session, test_workspace, test_user, account_id, txns, source="csv"):+ with patch("app.services.import_service.stamp_primary_amount", new_callable=AsyncMock), \+ patch("app.services.import_service.apply_rules_to_transaction", new_callable=AsyncMock):+ return await import_transactions(+ session, test_workspace.id, test_user.id, account_id, txns, source,+ )+++async def _real_txs(session, account_id):+ r = await session.execute(+ select(Transaction).where(+ Transaction.account_id == account_id,+ Transaction.source != "opening_balance",+ )+ )+ return list(r.scalars().all())+++async def test_import_links_and_advances_bill(session, test_user, test_workspace, test_account):+ account_id = test_account.id+ bill = await _make_bill(session, test_workspace, test_user, test_account,+ amount=Decimal("39.90"), start_date=date(2026, 1, 10))+ bill_id = bill.id+ txns = [TransactionImport(description="NETFLIX SUBSCRIPTION", amount=Decimal("39.90"),+ date=date(2026, 1, 12), type="debit", currency="BRL")]++ imported, skipped, _, _ = await _run_import(session, test_workspace, test_user, account_id, txns)++ assert imported == 1 and skipped == 0+ txs = await _real_txs(session, account_id)+ assert len(txs) == 1+ assert txs[0].recurring_transaction_id == bill_id+ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2026, 2, 10)+++async def test_import_merges_into_placeholder(session, test_user, test_workspace, test_account):+ account_id = test_account.id+ bill = await _make_bill(session, test_workspace, test_user, test_account,+ amount=Decimal("39.90"), start_date=date(2026, 1, 10))+ bill_id = bill.id+ bill.next_occurrence = date(2026, 2, 10)+ placeholder = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=account_id,+ workspace_id=test_workspace.id, description="Netflix Subscription",+ amount=Decimal("39.90"), currency="BRL", date=date(2026, 1, 10),+ type="debit", source="recurring", status="posted",+ recurring_transaction_id=bill_id, created_at=datetime.now(timezone.utc),+ )+ session.add(placeholder)+ await session.commit()+ placeholder_id = placeholder.id++ # Different case bypasses the exact-match field dedup, so the recurring+ # merge (case-insensitive similarity) is what catches it.+ txns = [TransactionImport(description="NETFLIX SUBSCRIPTION", amount=Decimal("39.90"),+ date=date(2026, 1, 11), type="debit", currency="BRL")]+ imported, skipped, _, _ = await _run_import(session, test_workspace, test_user, account_id, txns)++ assert imported == 1+ txs = await _real_txs(session, account_id)+ assert len(txs) == 1 # merged into placeholder, no duplicate+ assert txs[0].id == placeholder_id+ assert txs[0].source == "csv"+ assert txs[0].recurring_transaction_id == bill_id+++async def test_import_amount_mismatch_not_linked(session, test_user, test_workspace, test_account):+ account_id = test_account.id+ bill = await _make_bill(session, test_workspace, test_user, test_account,+ amount=Decimal("39.90"), start_date=date(2026, 1, 10))+ bill_id = bill.id+ txns = [TransactionImport(description="NETFLIX SUBSCRIPTION", amount=Decimal("99.00"),+ date=date(2026, 1, 10), type="debit", currency="BRL")]+ await _run_import(session, test_workspace, test_user, account_id, txns)++ txs = await _real_txs(session, account_id)+ assert len(txs) == 1+ assert txs[0].recurring_transaction_id is None+ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2026, 1, 10)diff --git a/backend/tests/test_recurring_match_sync.py b/backend/tests/test_recurring_match_sync.pynew file mode 100644index 00000000..5b93698f--- /dev/null+++ b/backend/tests/test_recurring_match_sync.py@@ -0,0 +1,279 @@+"""Deep integration tests for recurring-bill matching through the real+bank-sync ingestion path (issue #116).++These drive `sync_connection` end-to-end with a mocked provider, so they+exercise the actual incremental-loop wiring (placeholder merge, bill+stamp+advance, no-match passthrough, and the greedy one-per-occurrence+behaviour within a single sync batch), not just the matcher helpers.++Note: `sync_connection` commits (expire_on_commit), so ORM objects created+before the sync are expired afterwards. We capture primitive ids up front and+re-fetch rows after the sync rather than touching expired attributes (which+would trigger a synchronous lazy-load).+"""+import uuid+from datetime import date, datetime, timezone+from decimal import Decimal+from unittest.mock import AsyncMock, patch++import pytest+import pytest_asyncio+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.bank_connection import BankConnection+from app.models.recurring_transaction import RecurringTransaction+from app.models.transaction import Transaction+from app.schemas.recurring_transaction import RecurringTransactionCreate+from app.services.connection_service import sync_connection+from app.services.recurring_transaction_service import create_recurring_transaction+++@pytest_asyncio.fixture+async def conn_account(session: AsyncSession, test_user, test_workspace):+ conn = BankConnection(+ id=uuid.uuid4(), user_id=test_user.id, provider="test",+ external_id=f"ext-{uuid.uuid4().hex[:8]}",+ institution_name="Sync Bank", credentials={"token": "fake"},+ status="active", last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(conn)+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,+ workspace_id=test_workspace.id, name="Checking", type="checking",+ external_id="acc-ext-1", balance=Decimal("0"), currency="BRL",+ )+ session.add(account)+ await session.commit()+ await session.refresh(conn)+ await session.refresh(account)+ return conn, account+++def _provider(transactions, account_ext="acc-ext-1"):+ from app.providers.base import AccountData+ p = AsyncMock()+ p.refresh_credentials = AsyncMock(return_value={"token": "t"})+ p.get_accounts = AsyncMock(return_value=[+ AccountData(external_id=account_ext, name="Checking",+ type="checking", balance=Decimal("0"), currency="BRL"),+ ])+ p.get_transactions = AsyncMock(return_value=transactions)+ return p+++def _tx(**kw):+ from app.providers.base import TransactionData+ kw.setdefault("currency", "BRL")+ kw.setdefault("type", "debit")+ kw.setdefault("status", "posted")+ return TransactionData(**kw)+++async def _run_sync(session, conn_id, test_workspace, test_user, provider):+ with patch("app.services.connection_service.get_provider", return_value=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):+ return await sync_connection(session, conn_id, test_workspace.id, test_user.id)+++async def _make_bill(session, test_workspace, test_user, account, **ov):+ data = RecurringTransactionCreate(+ description=ov.pop("description", "Netflix Subscription"),+ amount=ov.pop("amount", Decimal("39.90")),+ currency=ov.pop("currency", "BRL"),+ type=ov.pop("type", "debit"),+ frequency=ov.pop("frequency", "monthly"),+ start_date=ov.pop("start_date", date(2025, 1, 10)),+ account_id=account.id, **ov,+ )+ return await create_recurring_transaction(session, test_workspace.id, test_user.id, data)+++async def _all_txs(session, account_id):+ # Exclude the synthetic opening-balance row the sync writes to reconcile+ # the provider-reported balance; we only care about real/recurring rows.+ r = await session.execute(+ select(Transaction).where(+ Transaction.account_id == account_id,+ Transaction.source != "opening_balance",+ )+ )+ return list(r.scalars().all())+++# ---------------------------------------------------------------------------+# Sync-first: incoming charge stamps the bill and advances it+# ---------------------------------------------------------------------------+++async def test_sync_links_and_advances_bill(session, test_user, test_workspace, conn_account):+ conn, account = conn_account+ conn_id, account_id = conn.id, account.id+ bill = await _make_bill(session, test_workspace, test_user, account,+ start_date=date(2025, 1, 10))+ bill_id = bill.id+ provider = _provider([_tx(external_id="s1", description="NETFLIX SUBSCRIPTION",+ amount=Decimal("39.90"), date=date(2025, 1, 12))])++ await _run_sync(session, conn_id, test_workspace, test_user, provider)++ txs = await _all_txs(session, account_id)+ assert len(txs) == 1+ assert txs[0].recurring_transaction_id == bill_id+ assert txs[0].source == "sync"+ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2025, 2, 10) # advanced past fulfilled occ+++# ---------------------------------------------------------------------------+# Placeholder-first: incoming charge merges into the generated row+# ---------------------------------------------------------------------------+++async def test_sync_merges_into_placeholder(session, test_user, test_workspace, conn_account):+ conn, account = conn_account+ conn_id, account_id = conn.id, account.id+ bill = await _make_bill(session, test_workspace, test_user, account,+ start_date=date(2025, 1, 10))+ bill_id = bill.id+ # Placeholder as generate_pending would have written it (occurrence already+ # advanced next_occurrence to Feb).+ bill.next_occurrence = date(2025, 2, 10)+ placeholder = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=account_id,+ workspace_id=test_workspace.id, description="Netflix Subscription",+ amount=Decimal("39.90"), currency="BRL", date=date(2025, 1, 10),+ type="debit", source="recurring", status="posted",+ recurring_transaction_id=bill_id, created_at=datetime.now(timezone.utc),+ )+ session.add(placeholder)+ await session.commit()+ placeholder_id = placeholder.id++ provider = _provider([_tx(external_id="s1", description="NETFLIX SUBSCRIPTION",+ amount=Decimal("39.90"), date=date(2025, 1, 11))])+ await _run_sync(session, conn_id, test_workspace, test_user, provider)++ txs = await _all_txs(session, account_id)+ assert len(txs) == 1 # merged, not duplicated+ merged = txs[0]+ assert merged.id == placeholder_id+ assert merged.external_id == "s1"+ assert merged.source == "sync"+ assert merged.recurring_transaction_id == bill_id+ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2025, 2, 10) # NOT advanced again+++# ---------------------------------------------------------------------------+# Non-matching charge is left independent+# ---------------------------------------------------------------------------+++async def test_sync_early_charge_advances_and_no_duplicate(+ session, test_user, test_workspace, conn_account+):+ """A charge that posts before the expected occurrence links, advances the+ bill, and does NOT leave an opening for generate_pending to duplicate it."""+ from app.services.recurring_transaction_service import generate_pending++ conn, account = conn_account+ conn_id, account_id = conn.id, account.id+ bill = await _make_bill(session, test_workspace, test_user, account,+ start_date=date(2025, 1, 10))+ bill_id = bill.id+ # Posts 2 days early, inside the before-window of the Jan 10 occurrence.+ provider = _provider([_tx(external_id="s1", description="NETFLIX SUBSCRIPTION",+ amount=Decimal("39.90"), date=date(2025, 1, 8))])+ await _run_sync(session, conn_id, test_workspace, test_user, provider)++ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2025, 2, 10) # advanced despite early posting++ # generate_pending past the Jan 10 occurrence must not re-create it.+ await generate_pending(session, test_user.id, up_to=date(2025, 1, 20))+ txs = await _all_txs(session, account_id)+ assert len(txs) == 1+ assert txs[0].recurring_transaction_id == bill_id+++async def test_sync_amount_mismatch_not_linked(session, test_user, test_workspace, conn_account):+ conn, account = conn_account+ conn_id, account_id = conn.id, account.id+ bill = await _make_bill(session, test_workspace, test_user, account,+ amount=Decimal("39.90"), start_date=date(2025, 1, 10))+ bill_id = bill.id+ provider = _provider([_tx(external_id="s1", description="NETFLIX SUBSCRIPTION",+ amount=Decimal("50.00"), date=date(2025, 1, 10))])+ await _run_sync(session, conn_id, test_workspace, test_user, provider)++ txs = await _all_txs(session, account_id)+ assert len(txs) == 1+ assert txs[0].recurring_transaction_id is None+ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2025, 1, 10) # untouched+++# ---------------------------------------------------------------------------+# Greedy one-per-occurrence: two matching charges in one batch link only once+# ---------------------------------------------------------------------------+++async def test_sync_two_charges_same_occurrence_links_one(+ session, test_user, test_workspace, conn_account+):+ conn, account = conn_account+ conn_id, account_id = conn.id, account.id+ bill = await _make_bill(session, test_workspace, test_user, account,+ amount=Decimal("39.90"), start_date=date(2025, 1, 10))+ bill_id = bill.id+ provider = _provider([+ _tx(external_id="s1", description="NETFLIX SUBSCRIPTION",+ amount=Decimal("39.90"), date=date(2025, 1, 10)),+ _tx(external_id="s2", description="NETFLIX SUBSCRIPTION",+ amount=Decimal("39.90"), date=date(2025, 1, 11)),+ ])+ await _run_sync(session, conn_id, test_workspace, test_user, provider)++ txs = await _all_txs(session, account_id)+ assert len(txs) == 2 # both land, no collapse+ linked = [t for t in txs if t.recurring_transaction_id == bill_id]+ assert len(linked) == 1 # exactly one occurrence fulfilled+ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2025, 2, 10) # advanced exactly once+++# ---------------------------------------------------------------------------+# Re-sync of an already-linked charge is idempotent (external_id pass 1)+# ---------------------------------------------------------------------------+++async def test_resync_is_idempotent(session, test_user, test_workspace, conn_account):+ conn, account = conn_account+ conn_id, account_id = conn.id, account.id+ bill = await _make_bill(session, test_workspace, test_user, account,+ amount=Decimal("39.90"), start_date=date(2025, 1, 10))+ bill_id = bill.id++ def txns():+ return [_tx(external_id="s1", description="NETFLIX SUBSCRIPTION",+ amount=Decimal("39.90"), date=date(2025, 1, 10))]++ await _run_sync(session, conn_id, test_workspace, test_user, _provider(txns()))+ await _run_sync(session, conn_id, test_workspace, test_user, _provider(txns()))++ txs = await _all_txs(session, account_id)+ assert len(txs) == 1+ assert txs[0].recurring_transaction_id == bill_id+ refreshed = await session.get(RecurringTransaction, bill_id)+ assert refreshed.next_occurrence == date(2025, 2, 10) # advanced once, not twicediff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex 933ddb84..28d2ea08 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -427,6 +427,8 @@ function TransactionForm({}, [description, isSynced])const [isIgnored, setIsIgnored] = useState(seed?.is_ignored ?? false)const [togglingIgnore, setTogglingIgnore] = useState(false)+ const [recurringLinked, setRecurringLinked] = useState(seed?.recurring_transaction_id != null)+ const [unlinkingRecurring, setUnlinkingRecurring] = useState(false)const [addToRuleOpen, setAddToRuleOpen] = useState(false)const { data: rulesList, isLoading: rulesLoading } = useQuery({@@ -502,6 +504,21 @@ function TransactionForm({}}+ const handleUnlinkRecurring = async () => {+ if (!seed?.id || unlinkingRecurring) return+ setUnlinkingRecurring(true)+ try {+ await transactionsApi.unlinkRecurring(seed.id)+ setRecurringLinked(false)+ toast.success(t('transactions.recurringUnlinkSuccess'))+ onIgnoreChanged?.()+ } catch {+ toast.error(t('common.error'))+ } finally {+ setUnlinkingRecurring(false)+ }+ }+const triggerSubmit = (action: SaveAction) => {pendingActionRef.current = actionformRef.current?.requestSubmit()@@ -704,6 +721,22 @@ function TransactionForm({})}</span></div>)}+ {recurringLinked && !isCreating && (+ <div className="flex items-center justify-between gap-2 p-3 text-sm bg-muted/50 border border-border rounded-md">+ <span className="text-muted-foreground">{t('transactions.recurringLinkedInfo')}</span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="gap-1.5 shrink-0"+ onClick={handleUnlinkRecurring}+ disabled={unlinkingRecurring}+ >+ <Unlink size={14} />+ {t('transactions.recurringUnlinkAction')}+ </Button>+ </div>+ )}<div className="space-y-2"><Label>{t('transactions.description')}</Label>{isSynced ? (diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex d2870df4..76897470 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -461,6 +461,10 @@ export const transactions = {const { data } = await api.patch(`/transactions/${id}/ignore`)return data},+ unlinkRecurring: async (id: string): Promise<Transaction> => {+ const { data } = await api.patch(`/transactions/${id}/unlink-recurring`)+ return data+ },createTransfer: async (transfer: {from_account_id: stringto_account_id: stringdiff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex a6441aca..d439246d 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -313,6 +313,10 @@"confirmDelete": "Möchtest du diese Transaktion wirklich löschen?","makeRecurring": "Als wiederkehrend einrichten","recurringBadge": "Wiederkehrend",+ "recurringLinkedTooltip": "Mit einer wiederkehrenden Rechnung verknüpft",+ "recurringLinkedInfo": "Diese Transaktion ist mit einer wiederkehrenden Rechnung verknüpft.",+ "recurringUnlinkAction": "Verknüpfung aufheben",+ "recurringUnlinkSuccess": "Transaktion von der wiederkehrenden Rechnung getrennt","transfer": "Umbuchung","pending": "Ausstehend","recurringInfo": "Wiederkehrende Transaktion ({{frequency}}). Nächste: {{next}}",@@ -742,6 +746,8 @@"deleted": "Wiederkehrende Transaktion gelöscht","generated": "{{count}} Transaktionen erstellt","generatePending": "Ausstehende erstellen",+ "autoGenerate": "Transaktionen automatisch erstellen",+ "autoGenerateHelp": "Erstellt bei jeder Fälligkeit dieser Rechnung eine Transaktion. Deaktivieren, um auf die tatsächliche Belastung (z. B. aus der Banksynchronisierung) zu warten und sie bis dahin nur als anstehend anzuzeigen.","fxEstimate": "Schätzung basierend auf dem aktuellsten Wechselkurs ({{rate}}). Der endgültige Betrag kann abweichen."},"rules": {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 20562442..1cfe4d49 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -313,6 +313,10 @@"confirmDelete": "Are you sure you want to delete this transaction?","makeRecurring": "Make recurring","recurringBadge": "Recurring",+ "recurringLinkedTooltip": "Linked to a recurring bill",+ "recurringLinkedInfo": "This transaction is linked to a recurring bill.",+ "recurringUnlinkAction": "Unlink",+ "recurringUnlinkSuccess": "Transaction unlinked from the recurring bill","transfer": "Transfer","pending": "Pending","recurringInfo": "Recurring transaction ({{frequency}}). Next: {{next}}",@@ -742,6 +746,8 @@"deleted": "Recurring transaction deleted","generated": "{{count}} transactions generated","generatePending": "Generate Pending",+ "autoGenerate": "Generate transactions automatically",+ "autoGenerateHelp": "Create a transaction each time this bill is due. Turn off to wait for the real charge (e.g. from bank sync) and only show it as upcoming until then.","fxEstimate": "Estimate based on latest exchange rate ({{rate}}). Final amount may change."},"rules": {diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 7fd04f28..33af15fe 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -313,6 +313,10 @@"confirmDelete": "¿Estás seguro de que quieres eliminar esta transacción?","makeRecurring": "Hacer recurrente","recurringBadge": "Recurrente",+ "recurringLinkedTooltip": "Vinculada a una factura recurrente",+ "recurringLinkedInfo": "Esta transacción está vinculada a una factura recurrente.",+ "recurringUnlinkAction": "Desvincular",+ "recurringUnlinkSuccess": "Transacción desvinculada de la factura recurrente","transfer": "Transferencia","pending": "Pendiente","recurringInfo": "Transacción recurrente ({{frequency}}). Próxima: {{next}}",@@ -742,6 +746,8 @@"deleted": "Transacción recurrente eliminada","generated": "{{count}} transacciones generadas","generatePending": "Generar pendientes",+ "autoGenerate": "Generar transacciones automáticamente",+ "autoGenerateHelp": "Crea una transacción cada vez que vence esta factura. Desactívalo para esperar el cargo real (por ejemplo, de la sincronización bancaria) y mostrarla solo como próxima hasta entonces.","fxEstimate": "Estimación basada en el último tipo de cambio ({{rate}}). El importe final puede cambiar."},"rules": {diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 0565d2c2..db25b218 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -313,6 +313,10 @@"confirmDelete": "Sei sicuro di voler eliminare questa transazione?","makeRecurring": "Rendi ricorrente","recurringBadge": "Ricorrente",+ "recurringLinkedTooltip": "Collegata a una spesa ricorrente",+ "recurringLinkedInfo": "Questa transazione è collegata a una spesa ricorrente.",+ "recurringUnlinkAction": "Scollega",+ "recurringUnlinkSuccess": "Transazione scollegata dalla spesa ricorrente","transfer": "Trasferimento","pending": "In sospeso","recurringInfo": "Transazione ricorrente ({{frequency}}). Prossima: {{next}}",@@ -742,6 +746,8 @@"deleted": "Transazione ricorrente eliminata","generated": "{{count}} transazioni generate","generatePending": "Genera in sospeso",+ "autoGenerate": "Genera transazioni automaticamente",+ "autoGenerateHelp": "Crea una transazione ogni volta che questa spesa è in scadenza. Disattiva per attendere l'addebito reale (ad es. dalla sincronizzazione bancaria) e mostrarla solo come in arrivo fino ad allora.","fxEstimate": "Stima basata sull'ultimo tasso di cambio ({{rate}}). L'importo finale può variare."},"rules": {diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 9a36a304..23cfc756 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -319,6 +319,10 @@"confirmDelete": "Czy na pewno usunąć tę transakcję?","makeRecurring": "Ustaw jako cykliczną","recurringBadge": "Cykliczna",+ "recurringLinkedTooltip": "Powiązana z cyklicznym rachunkiem",+ "recurringLinkedInfo": "Ta transakcja jest powiązana z cyklicznym rachunkiem.",+ "recurringUnlinkAction": "Odłącz",+ "recurringUnlinkSuccess": "Transakcja odłączona od cyklicznego rachunku","transfer": "Transfer","pending": "Oczekująca","recurringInfo": "Transakcja cykliczna ({{frequency}}). Następna: {{next}}",@@ -787,6 +791,8 @@"generated_many": "Wygenerowano {{count}} transakcji","generated_other": "Wygenerowano {{count}} transakcji","generatePending": "Generuj oczekujące",+ "autoGenerate": "Automatycznie generuj transakcje",+ "autoGenerateHelp": "Tworzy transakcję za każdym razem, gdy ten rachunek jest wymagalny. Wyłącz, aby poczekać na rzeczywiste obciążenie (np. z synchronizacji bankowej) i do tego czasu pokazywać je tylko jako nadchodzące.","fxEstimate": "Szacunek na podstawie najnowszego kursu wymiany ({{rate}}). Ostateczna kwota może się zmienić."},"rules": {diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 7ee1e174..97a6a0de 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -313,6 +313,10 @@"confirmDelete": "Tem certeza que deseja excluir esta transação?","makeRecurring": "Tornar recorrente","recurringBadge": "Recorrente",+ "recurringLinkedTooltip": "Vinculada a uma conta recorrente",+ "recurringLinkedInfo": "Esta transação está vinculada a uma conta recorrente.",+ "recurringUnlinkAction": "Desvincular",+ "recurringUnlinkSuccess": "Transação desvinculada da conta recorrente","transfer": "Transferência","pending": "Pendente","recurringInfo": "Transação recorrente ({{frequency}}). Próxima: {{next}}",@@ -742,6 +746,8 @@"deleted": "Transação recorrente excluída","generated": "{{count}} transações geradas","generatePending": "Gerar Pendentes",+ "autoGenerate": "Gerar transações automaticamente",+ "autoGenerateHelp": "Cria uma transação sempre que esta conta vence. Desative para aguardar o lançamento real (por exemplo, da sincronização bancária) e mostrá-la apenas como prevista até lá.","fxEstimate": "Estimativa baseada na última taxa de câmbio ({{rate}}). O valor final pode mudar."},"rules": {diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 8f5d5066..63d1e06f 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -313,6 +313,10 @@"confirmDelete": "Вы уверены, что хотите удалить эту транзакцию?","makeRecurring": "Сделать регулярной","recurringBadge": "Регулярная",+ "recurringLinkedTooltip": "Связана с регулярным платежом",+ "recurringLinkedInfo": "Эта транзакция связана с регулярным платежом.",+ "recurringUnlinkAction": "Отвязать",+ "recurringUnlinkSuccess": "Транзакция отвязана от регулярного платежа","transfer": "Перевод","pending": "Ожидание","recurringInfo": "Регулярная транзакция ({{frequency}}). Следующая: {{next}}",@@ -742,6 +746,8 @@"deleted": "Регулярная транзакция удалена","generated": "Создано {{count}} транзакций","generatePending": "Создать ожидающие",+ "autoGenerate": "Создавать транзакции автоматически",+ "autoGenerateHelp": "Создаёт транзакцию при каждом наступлении срока оплаты. Отключите, чтобы дождаться реального списания (например, из банковской синхронизации) и до тех пор показывать её только как предстоящую.","fxEstimate": "Оценка на основе последнего курса ({{rate}}). Итоговая сумма может измениться."},"rules": {diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex e3e3480f..93d6b79c 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -313,6 +313,10 @@"confirmDelete": "Ви впевнені, що хочете видалити цю транзакцію?","makeRecurring": "Зробити регулярною","recurringBadge": "Регулярна",+ "recurringLinkedTooltip": "Пов'язана з регулярним платежем",+ "recurringLinkedInfo": "Ця транзакція пов'язана з регулярним платежем.",+ "recurringUnlinkAction": "Відв'язати",+ "recurringUnlinkSuccess": "Транзакцію відв'язано від регулярного платежу","transfer": "Переказ","pending": "Очікування","recurringInfo": "Регулярна транзакція ({{frequency}}). Наступна: {{next}}",@@ -742,6 +746,8 @@"deleted": "Регулярну транзакцію видалено","generated": "Створено {{count}} транзакцій","generatePending": "Створити очікувані",+ "autoGenerate": "Створювати транзакції автоматично",+ "autoGenerateHelp": "Створює транзакцію щоразу, коли настає термін оплати. Вимкніть, щоб дочекатися реального списання (наприклад, із банківської синхронізації) і до того часу показувати її лише як майбутню.","fxEstimate": "Оцінка на основі останнього курсу ({{rate}}). Підсумкова сума може змінитися."},"rules": {diff --git a/frontend/src/pages/recurring.tsx b/frontend/src/pages/recurring.tsxindex 56213a59..5ab251ac 100644--- a/frontend/src/pages/recurring.tsx+++ b/frontend/src/pages/recurring.tsx@@ -301,6 +301,7 @@ function RecurringForm({const [categoryId, setCategoryId] = useState(recurring?.category_id ?? '')const [accountId, setAccountId] = useState(recurring?.account_id ?? accounts[0]?.id ?? '')const [isActive, setIsActive] = useState(recurring?.is_active ?? true)+ const [autoGenerate, setAutoGenerate] = useState(recurring?.auto_generate ?? true)const selectClass = 'w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'@@ -320,6 +321,7 @@ function RecurringForm({category_id: categoryId || null,account_id: accountId || null,is_active: isActive,+ auto_generate: autoGenerate,} as Partial<RecurringTransaction>)}}className="space-y-4"@@ -402,6 +404,18 @@ function RecurringForm({</select></div></div>+ <label className="flex items-start gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={autoGenerate}+ onChange={(e) => setAutoGenerate(e.target.checked)}+ className="h-4 w-4 mt-0.5 rounded border-border"+ />+ <span className="text-sm text-foreground">+ {t('recurring.autoGenerate')}+ <span className="block text-xs text-muted-foreground">{t('recurring.autoGenerateHelp')}</span>+ </span>+ </label>{recurring && (<label className="flex items-center gap-2 cursor-pointer"><inputdiff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex f6f17f95..dba0ad81 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -933,8 +933,12 @@ export default function TransactionsPage() {</span>)}- {recurringList?.some(r => r.description === tx.description && r.type === tx.type) && (- <span className="text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1.5 py-0.5 rounded-full">+ {(tx.recurring_transaction_id != null ||+ recurringList?.some(r => r.description === tx.description && r.type === tx.type)) && (+ <span+ className="text-[10px] font-semibold uppercase tracking-wide text-primary bg-primary/5 border border-primary/10 px-1.5 py-0.5 rounded-full"+ title={tx.recurring_transaction_id != null ? t('transactions.recurringLinkedTooltip') : undefined}+ >{t('transactions.recurringBadge')}</span>)}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex e8b9f3ee..2db5d25b 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -216,6 +216,8 @@ export interface Transaction {// available, cycle math otherwise). Setting it forces the tx into the// bill whose due_date matches.effective_bill_date: string | null+ // The recurring bill this transaction fulfills, if any (issue #116).+ recurring_transaction_id?: string | nullsplits: TransactionSplit[]// Shared-transaction view fields. Set per-request when the viewer// is a linked split member but not the owner. Render `viewer_share`@@ -427,6 +429,7 @@ export interface RecurringTransaction {start_date: stringend_date: string | nullis_active: boolean+ auto_generate: booleannext_occurrence: stringamount_primary: number | nullfx_rate_used: number | null