Skip to content

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

feat: normalize imported transaction descriptions with rules (#586)

seraphblade2010d754f00b57fa
diff --git a/backend/alembic/versions/071_transaction_original_description.py b/backend/alembic/versions/071_transaction_original_description.py
new file mode 100644
index 00000000..437588e0
--- /dev/null
+++ b/backend/alembic/versions/071_transaction_original_description.py
@@ -0,0 +1,37 @@
+"""add original transaction description
+
+Revision ID: 071
+Revises: 070
+Create Date: 2026-08-13
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "071"
+down_revision: Union[str, None] = "070"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "transactions",
+ sa.Column("original_description", sa.String(length=500), nullable=True),
+ )
+ op.add_column(
+ "transactions",
+ sa.Column(
+ "description_is_rule_managed",
+ sa.Boolean(),
+ nullable=False,
+ server_default=sa.text("false"),
+ ),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("transactions", "description_is_rule_managed")
+ op.drop_column("transactions", "original_description")
diff --git a/backend/app/models/transaction.py b/backend/app/models/transaction.py
index 3a85e553..d66a85aa 100644
--- a/backend/app/models/transaction.py
+++ b/backend/app/models/transaction.py
@@ -32,6 +32,10 @@ class Transaction(Base):
category_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), ForeignKey("categories.id"), nullable=True)
external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True) # Provider's transaction ID
description: Mapped[str] = mapped_column(String(500))
+ original_description: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
+ description_is_rule_managed: Mapped[bool] = mapped_column(
+ Boolean, default=False, server_default="false"
+ )
amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))
currency: Mapped[str] = mapped_column(String(3), default="USD")
date: Mapped[_date] = mapped_column(Date)
diff --git a/backend/app/schemas/rule.py b/backend/app/schemas/rule.py
index 6714aa49..93ed93e9 100644
--- a/backend/app/schemas/rule.py
+++ b/backend/app/schemas/rule.py
@@ -6,7 +6,7 @@ from pydantic import BaseModel, ConfigDict, field_validator
class RuleCondition(BaseModel):
- field: str # description, notes, amount, type, account_id, payee_id, date
+ field: str # description, payee, notes, amount, type, account_id, payee_id, date
op: str # contains, not_contains, equals, not_equals, starts_with, ends_with, regex, gt, gte, lt, lte
value: Any # str or number depending on field
@@ -25,8 +25,8 @@ class RuleCondition(BaseModel):
class RuleAction(BaseModel):
- op: str # set_category, set_payee, append_notes, ignore
- value: Any # category UUID str or notes string
+ op: str # set_category, set_payee, set_description, append_notes, ignore
+ value: Any # entity UUID or text depending on action
class RuleCreate(BaseModel):
diff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.py
index fc76f640..2a60c9c5 100644
--- a/backend/app/schemas/transaction.py
+++ b/backend/app/schemas/transaction.py
@@ -148,6 +148,7 @@ class TransactionRead(TransactionBase):
source: str
status: str = "posted"
payee: Optional[str] = None
+ original_description: Optional[str] = None
payee_id: Optional[uuid.UUID] = None
payee_name: Optional[str] = None
notes: Optional[str] = None
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index 6304250d..64613fa2 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -36,7 +36,8 @@ from app.services.account_service import (
)
from app.services.asset_group_service import ensure_group_for_connection
from app.services.credit_card_service import apply_effective_date
-from app.services.rule_service import apply_rules_to_transaction
+from app.services.rule_engine import merge_notes
+from app.services.rule_service import apply_rules_to_transaction, preview_rules_for_transaction
from app.services.transfer_detection_service import detect_transfer_pairs
from app.services.fx_rate_service import stamp_primary_amount
from app.services.payee_service import get_or_create_payee
@@ -617,6 +618,8 @@ async def handle_oauth_callback(
# second copy from landing.
synced_dup = await _find_synced_duplicate(session, account.id, txn_data)
if synced_dup:
+ if synced_dup.original_description is None:
+ synced_dup.original_description = txn_data.description
if synced_dup.status == "pending" and txn_data.status == "posted":
synced_dup.status = "posted"
synced_dup.external_id = txn_data.external_id
@@ -655,6 +658,7 @@ async def handle_oauth_callback(
account_id=account.id,
external_id=txn_data.external_id,
description=txn_data.description,
+ original_description=txn_data.description,
amount=txn_data.amount,
currency=txn_data.currency or acc_data.currency or user_currency,
date=txn_data.date,
@@ -677,8 +681,7 @@ async def handle_oauth_callback(
session.add(transaction)
await session.flush()
new_tx_ids.append(transaction.id)
- if not category_id:
- await apply_rules_to_transaction(session, user_id, transaction)
+ await apply_rules_to_transaction(session, user_id, transaction)
# Prefer bank-provided conversion for international transactions
acct_currency = acc_data.currency or user_currency
@@ -753,7 +756,10 @@ async def _fuzzy_match_manual(
best_match = None
best_score = 0.0
for candidate in candidates:
- score = _description_similarity(candidate.description, txn_data.description)
+ score = _description_similarity(
+ candidate.original_description or candidate.description,
+ txn_data.description,
+ )
if score > best_score:
best_score = score
best_match = candidate
@@ -832,7 +838,10 @@ async def _find_synced_duplicate(
for candidate in result.scalars():
if candidate.external_id and candidate.external_id.startswith("bill_charge:"):
continue
- if _description_similarity(candidate.description, txn_data.description) >= 0.7:
+ if _description_similarity(
+ candidate.original_description or candidate.description,
+ txn_data.description,
+ ) >= 0.7:
return candidate
return None
@@ -888,7 +897,10 @@ async def _cleanup_phantom_duplicates(
)
)
for sibling in sibling_result.scalars():
- if _description_similarity(sibling.description, tx.description) >= 0.9:
+ if _description_similarity(
+ sibling.original_description or sibling.description,
+ tx.original_description or tx.description,
+ ) >= 0.9:
await session.delete(tx)
deleted += 1
break
@@ -1322,6 +1334,8 @@ async def sync_connection(
# a re-sync can't revive a transaction the user hid.
if existing_tx.is_ignored:
continue
+ if existing_tx.original_description is None:
+ existing_tx.original_description = txn_data.description
if existing_tx.status == "pending" and txn_data.status == "posted":
existing_tx.status = "posted"
# Self-heal bill linkage: a tx that pre-dates the bills
@@ -1354,6 +1368,8 @@ async def sync_connection(
fuzzy_match.external_id = txn_data.external_id
fuzzy_match.source = "sync"
fuzzy_match.raw_data = txn_data.raw_data
+ if fuzzy_match.original_description is None:
+ fuzzy_match.original_description = txn_data.description
if not fuzzy_match.payee and txn_data.payee:
fuzzy_match.payee = txn_data.payee
merged_count += 1
@@ -1368,6 +1384,8 @@ async def sync_connection(
session, account.id, txn_data
)
if synced_dup:
+ if synced_dup.original_description is None:
+ synced_dup.original_description = txn_data.description
if synced_dup.status == "pending" and txn_data.status == "posted":
# Posted truth wins: swap in the new id so subsequent
# syncs match by external_id and update raw_data.
@@ -1386,51 +1404,26 @@ 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,
+ incoming_currency = (
+ txn_data.currency or acc_data.currency or user_currency
)
- 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
+ session,
+ workspace_id,
+ txn_data.pluggy_category,
+ enabled=use_provider_cats,
)
- # Resolve payee entity from raw payee text
sync_payee_id = None
if txn_data.payee:
sync_payee_entity = await get_or_create_payee(
- session, user_id, txn_data.payee, workspace_id=workspace_id
+ session,
+ user_id,
+ txn_data.payee,
+ workspace_id=workspace_id,
)
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
@@ -1438,11 +1431,13 @@ async def sync_connection(
)
transaction = Transaction(
user_id=user_id,
+ workspace_id=workspace_id,
account_id=account.id,
external_id=txn_data.external_id,
description=txn_data.description,
+ original_description=txn_data.description,
amount=txn_data.amount,
- currency=txn_data.currency or acc_data.currency or user_currency,
+ currency=incoming_currency,
date=txn_data.date,
type=txn_data.type,
source="sync",
@@ -1456,18 +1451,82 @@ 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
+ transaction,
+ account,
+ bill_due_date=bill.due_date if bill else None,
+ )
+ preview = await preview_rules_for_transaction(
+ session, user_id, transaction
+ )
+
+ # Normalize before recurring reconciliation. A generated
+ # placeholder is upgraded in place; otherwise the normalized
+ # candidate may fulfill an active definition, which advances so
+ # later generation cannot duplicate the occurrence.
+ placeholder = (
+ await recurring_match_service.find_placeholder_for_incoming(
+ session,
+ account.id,
+ txn_data.amount,
+ incoming_currency,
+ txn_data.type,
+ txn_data.date,
+ preview.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
+ # Same shape as the import path: fold in the `preview` the
+ # rules already produced from the incoming charge instead of
+ # re-running them against the placeholder, whose description
+ # is the recurring definition's own wording. Existing values
+ # win, the charge fills the empty ones, and only its
+ # provenance is recorded outright.
+ placeholder.original_description = txn_data.description
+ if placeholder.category_id is None:
+ placeholder.category_id = preview.category_id
+ if txn_data.payee and not placeholder.payee:
+ placeholder.payee = txn_data.payee
+ if placeholder.payee_id is None:
+ placeholder.payee_id = preview.payee_id
+ placeholder.notes = merge_notes(
+ placeholder.notes, preview.notes
+ )
+ if preview.is_ignored:
+ placeholder.is_ignored = True
+ merged_count += 1
+ continue
+
+ 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,
+ preview.description,
+ )
+ )
+ transaction.recurring_transaction_id = (
+ recurring_link.id if recurring_link else None
)
session.add(transaction)
await session.flush()
if recurring_link is not None:
- recurring_match_service.advance_past(recurring_link, txn_data.date)
+ 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)
+ await apply_rules_to_transaction(session, user_id, transaction)
# Prefer bank-provided conversion for international transactions
acct_currency = acc_data.currency or user_currency
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index 2e128f66..5416cc58 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -8,7 +8,7 @@ from datetime import datetime
from decimal import Decimal
from ofxparse import OfxParser
-from sqlalchemy import select
+from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import get_settings
@@ -19,8 +19,8 @@ from app.models.transaction import Transaction
from app.schemas.transaction import TransactionImport
from app.services import recurring_match_service
from app.services.credit_card_service import apply_effective_date
-from app.services.rule_engine import apply_rule_actions, evaluate_conditions
-from app.services.rule_service import apply_rules_to_transaction
+from app.services.rule_engine import apply_rule_actions, evaluate_conditions, merge_notes
+from app.services.rule_service import apply_rules_to_transaction, preview_rules_for_transaction
from app.services.fx_rate_service import stamp_primary_amount
from app.services.payee_service import get_or_create_payee
@@ -711,12 +711,10 @@ async def import_transactions(
txn_currency = txn_data.currency or account_currency
if should_detect_duplicates:
- # Duplicate detection: use external_id when available (OFX FITID),
- # fall back to field-based matching for formats without unique IDs.
- # When matching by external_id, also require the same `date` so that
- # Brazilian credit-card installments — where some banks reuse one
- # purchase FITID across every monthly statement — don't get skipped
- # as duplicates from later monthly imports (issue #98).
+ # Prefer an external ID (OFX FITID), with date retained because some
+ # Brazilian cards reuse one purchase FITID across monthly installments.
+ # Formats without unique IDs fall back to transaction fields; compare
+ # both descriptions because rules may have changed the displayed one.
if txn_data.external_id:
existing = await session.execute(
select(Transaction).where(
@@ -732,19 +730,19 @@ async def import_transactions(
Transaction.date == txn_data.date,
Transaction.amount == txn_data.amount,
Transaction.type == txn_data.type,
- Transaction.description == txn_data.description,
+ or_(
+ Transaction.description == txn_data.description,
+ Transaction.original_description == txn_data.description,
+ ),
)
)
- # `.first()` rather than `.scalar_one_or_none()`: the dedup key can
- # legitimately match more than one row (e.g. a prior sync/import race
- # left a duplicate, or a bank reuses one FITID across statements),
- # and we only need to know whether *any* match exists. Requiring
- # exactly one would raise MultipleResultsFound and abort the import.
+ # `.first()` is intentional: duplicate keys can legitimately match
+ # multiple rows after an import/sync race or reused bank identifier,
+ # and duplicate detection only needs to establish that any row exists.
if existing.scalars().first() is not None:
skipped += 1
continue
- # Resolve payee entity from raw payee text (OFX/QIF)
import_payee_id = None
import_payee_raw = getattr(txn_data, "payee_raw", None)
if import_payee_raw:
@@ -754,42 +752,25 @@ async def import_transactions(
)
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_id
suggested_cat_id = txn_data.suggested_category_id
- csv_category_id = category_map.get(txn_data.category_name) if txn_data.category_name else None
- if txn_data.force_uncategorized:
- category_id = None
- else:
- category_id = user_category_id or suggested_cat_id or csv_category_id
+ csv_category_id = (
+ category_map.get(txn_data.category_name)
+ if txn_data.category_name
+ else None
+ )
+ category_id = (
+ None
+ if txn_data.force_uncategorized
+ else user_category_id or suggested_cat_id or csv_category_id
+ )
- transaction = Transaction(
+ incoming = Transaction(
user_id=user_id,
workspace_id=workspace_id,
account_id=account_id,
description=txn_data.description,
+ original_description=txn_data.description,
amount=txn_data.amount,
date=txn_data.date,
type=txn_data.type,
@@ -801,24 +782,83 @@ async def import_transactions(
payee_id=import_payee_id,
category_id=category_id,
notes=getattr(txn_data, "notes", None),
- recurring_transaction_id=recurring_link.id if recurring_link else None,
)
- apply_effective_date(transaction, account)
+ apply_effective_date(incoming, account)
+ preview = await preview_rules_for_transaction(
+ session,
+ user_id,
+ incoming,
+ skip_category_rules=txn_data.force_uncategorized,
+ )
+
+ # Normalize a detached candidate before either recurring match. If a
+ # generated placeholder already represents this occurrence, upgrade it
+ # in place; otherwise link the new row to an active recurring definition.
+ placeholder = await recurring_match_service.find_placeholder_for_incoming(
+ session,
+ account_id,
+ txn_data.amount,
+ txn_currency,
+ txn_data.type,
+ txn_data.date,
+ preview.description,
+ )
+ if placeholder and not placeholder.is_ignored:
+ placeholder.source = source
+ placeholder.external_id = txn_data.external_id
+ placeholder.import_id = import_log.id
+ placeholder.status = "posted"
+ # The rules already ran, against the incoming charge, to build
+ # `preview`. Fold that result in rather than re-running them
+ # against the placeholder: its description is the recurring
+ # definition's own wording, so conditions written for the bank's
+ # text would no longer match. Everything the user can already see
+ # wins, the charge only fills what is still empty, and only its
+ # provenance is recorded outright.
+ placeholder.original_description = txn_data.description
+ if placeholder.category_id is None:
+ placeholder.category_id = preview.category_id
+ if import_payee_raw and not placeholder.payee:
+ placeholder.payee = import_payee_raw
+ if placeholder.payee_id is None:
+ placeholder.payee_id = preview.payee_id
+ placeholder.notes = merge_notes(placeholder.notes, preview.notes)
+ if preview.is_ignored:
+ placeholder.is_ignored = True
+ imported += 1
+ continue
+ 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,
+ preview.description,
+ )
+ incoming.recurring_transaction_id = (
+ recurring_link.id if recurring_link else None
+ )
if txn_data.fx_rate:
- transaction.fx_rate_used = txn_data.fx_rate
- transaction.amount_primary = txn_data.amount * txn_data.fx_rate
+ incoming.fx_rate_used = txn_data.fx_rate
+ incoming.amount_primary = txn_data.amount * txn_data.fx_rate
- session.add(transaction)
+ session.add(incoming)
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)
+ await apply_rules_to_transaction(
+ session,
+ user_id,
+ incoming,
+ skip_category_rules=txn_data.force_uncategorized,
+ )
- # Only auto-convert if no fx_rate was provided by the CSV
if not txn_data.fx_rate:
- await stamp_primary_amount(session, user_id, transaction)
+ await stamp_primary_amount(session, user_id, incoming)
imported += 1
diff --git a/backend/app/services/rule_engine.py b/backend/app/services/rule_engine.py
index 8062a748..aebaac91 100644
--- a/backend/app/services/rule_engine.py
+++ b/backend/app/services/rule_engine.py
@@ -125,12 +125,32 @@ def evaluate_conditions(conditions_op: str, conditions: list[dict], tx: "Transac
return all(results) # "and" is default
+def merge_notes(existing: str | None, incoming: str | None) -> str | None:
+ """Combine two note strings the way `append_notes` combines tags.
+
+ Used when an incoming charge is folded into a row that already has notes:
+ the existing text is never dropped, the incoming one is only appended when
+ it is not already in there.
+ """
+ incoming = (incoming or "").strip()
+ if not incoming:
+ return existing
+ existing = (existing or "").strip()
+ if not existing:
+ return incoming
+ if incoming in existing:
+ return existing
+ return f"{existing} {incoming}"
+
+
def apply_rule_actions(
actions: list[dict],
tx: "Transaction",
category_already_set: bool,
+ *,
+ skip_description: bool = False,
) -> bool:
- """Apply actions to transaction in-place. Returns updated category_already_set flag."""
+ """Apply actions in-place and return the updated category-set flag."""
for action in actions:
op = action.get("op")
value = action.get("value")
@@ -142,6 +162,17 @@ def apply_rule_actions(
except (ValueError, AttributeError):
pass
+ elif op == "set_description":
+ if skip_description:
+ continue
+ description = str(value or "").strip()
+ if not description or description == tx.description:
+ continue
+ if getattr(tx, "original_description", None) is None:
+ tx.original_description = tx.description
+ tx.description = description
+ tx.description_is_rule_managed = True
+
elif op == "set_payee":
try:
tx.payee_id = uuid.UUID(str(value))
diff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.py
index f9839a8b..a0642f2e 100644
--- a/backend/app/services/rule_service.py
+++ b/backend/app/services/rule_service.py
@@ -20,13 +20,15 @@ class DuplicateRuleError(Exception):
_ALLOWED_CONDITION_FIELDS = {
- "description", "notes", "amount", "type", "account_id", "payee_id", "date",
+ "description", "payee", "notes", "amount", "type", "account_id", "payee_id", "date",
}
_ALLOWED_CONDITION_OPS = {
"contains", "not_contains", "equals", "not_equals", "starts_with",
"ends_with", "regex", "gt", "gte", "lt", "lte",
}
-_ALLOWED_ACTION_OPS = {"set_category", "set_payee", "append_notes", "ignore"}
+_ALLOWED_ACTION_OPS = {
+ "set_category", "set_payee", "set_description", "append_notes", "ignore",
+}
def _rule_item_value(item, key: str):
@@ -76,6 +78,11 @@ async def _validate_rule_definition(
)
if exists_result.scalar_one_or_none() is None:
raise ValueError("Payee not found")
+ elif op == "set_description":
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError("Description cannot be blank")
+ if len(value.strip()) > 500:
+ raise ValueError("Description cannot exceed 500 characters")
# ─── Universal rules (work for any language/country) ───
@@ -1064,6 +1071,60 @@ async def _get_existing_rule_names_for_workspace(
return {row[0] for row in result.all()}
+def _rule_preview(transaction: Transaction) -> Transaction:
+ """Build a detached transaction-shaped object for side-effect-free rule evaluation."""
+ return Transaction(
+ user_id=transaction.user_id,
+ workspace_id=transaction.workspace_id,
+ account_id=transaction.account_id,
+ category_id=transaction.category_id,
+ description=transaction.description,
+ original_description=transaction.original_description,
+ description_is_rule_managed=bool(transaction.description_is_rule_managed),
+ amount=transaction.amount,
+ currency=transaction.currency,
+ date=transaction.date,
+ type=transaction.type,
+ source=transaction.source,
+ status=transaction.status,
+ payee=transaction.payee,
+ payee_id=transaction.payee_id,
+ notes=transaction.notes,
+ is_ignored=transaction.is_ignored,
+ )
+
+
+def _has_manual_description(transaction: Transaction) -> bool:
+ """True when the displayed description is the user's own text.
+
+ An imported row whose description drifted from its raw provenance without a
+ rule having done it was edited by hand. Rules may still run every other
+ matching action on it, but they must not replace that text.
+ """
+ return (
+ not transaction.description_is_rule_managed
+ and transaction.original_description is not None
+ and transaction.description != transaction.original_description
+ )
+
+
+async def preview_rules_for_transaction(
+ session: AsyncSession,
+ user_id: uuid.UUID,
+ transaction: Transaction,
+ skip_category_rules: bool = False,
+) -> Transaction:
+ """Apply active rules to a detached preview and return it without persistence."""
+ preview = _rule_preview(transaction)
+ await apply_rules_to_transaction(
+ session,
+ user_id,
+ preview,
+ skip_category_rules=skip_category_rules,
+ )
+ return preview
+
+
async def apply_rules_to_transaction(
session: AsyncSession, user_id: uuid.UUID, transaction: Transaction,
skip_category_rules: bool = False,
@@ -1100,15 +1161,16 @@ async def apply_single_rule(
rule: Rule,
overwrite_existing_categories: bool = False,
) -> int:
- """Apply one rule to all existing workspace transactions. Returns the number
- of transactions actually modified.
-
- Used right after a rule is created so it takes effect on history without the
- user having to hit "Reapply all". Unlike `apply_all_rules` this is
- non-destructive by default: a transaction that already has a category keeps
- it unless the caller explicitly opts into replacing existing categories.
- Payee/notes/ignore actions still apply on a match. Only transactions whose
- fields actually change are counted.
+ """Apply one rule to existing workspace transactions and count modifications.
+
+ Used after rule creation or editing so it can affect history without the
+ destructive reset performed by `apply_all_rules`. Existing categories are
+ protected unless the caller opts into replacement; other actions still
+ apply. Conditions first inspect the current transaction state so rules can
+ depend on earlier normalization. If that does not match, the preserved
+ imported description is tried as a fallback so edited normalization rules
+ can still find transactions they previously changed. A description the user
+ typed themselves is left alone, exactly as `apply_all_rules` leaves it.
"""
if not rule.is_active:
return 0
@@ -1120,22 +1182,47 @@ async def apply_single_rule(
)
)
transactions = result.scalars().all()
-
conditions = rule.conditions or []
actions = rule.actions or []
count = 0
for tx in transactions:
- if not evaluate_conditions(rule.conditions_op, conditions, tx):
+ matches = evaluate_conditions(rule.conditions_op, conditions, tx)
+ if not matches and tx.original_description is not None:
+ original_target = _rule_preview(tx)
+ original_target.description = tx.original_description
+ matches = evaluate_conditions(
+ rule.conditions_op, conditions, original_target
+ )
+ if not matches:
continue
- before = (tx.category_id, tx.payee_id, tx.notes, tx.is_ignored)
+
+ before = (
+ tx.category_id,
+ tx.payee_id,
+ tx.description,
+ tx.original_description,
+ tx.description_is_rule_managed,
+ tx.notes,
+ tx.is_ignored,
+ )
apply_rule_actions(
actions,
tx,
category_already_set=tx.category_id is not None
and not overwrite_existing_categories,
+ skip_description=_has_manual_description(tx),
+ )
+ after = (
+ tx.category_id,
+ tx.payee_id,
+ tx.description,
+ tx.original_description,
+ tx.description_is_rule_managed,
+ tx.notes,
+ tx.is_ignored,
)
- if before != (tx.category_id, tx.payee_id, tx.notes, tx.is_ignored):
+ if before != after:
count += 1
await session.commit()
@@ -1143,15 +1230,9 @@ async def apply_single_rule(
async def apply_all_rules(session: AsyncSession, workspace_id: uuid.UUID) -> int:
- """Re-apply all active rules to all workspace transactions. Returns count of affected transactions."""
- from app.models.account import Account
- from app.models.bank_connection import BankConnection
-
+ """Reset rule-managed fields and reapply active rules in priority order."""
result = await session.execute(
- select(Transaction)
- .outerjoin(Account)
- .outerjoin(BankConnection)
- .where(
+ select(Transaction).where(
Transaction.workspace_id == workspace_id,
Transaction.source != "opening_balance",
)
@@ -1167,21 +1248,47 @@ async def apply_all_rules(session: AsyncSession, workspace_id: uuid.UUID) -> int
count = 0
for tx in transactions:
+ preserve_manual_description = _has_manual_description(tx)
+ before = (
+ tx.category_id,
+ tx.payee_id,
+ tx.description,
+ tx.original_description,
+ tx.description_is_rule_managed,
+ tx.notes,
+ tx.is_ignored,
+ )
+ if tx.description_is_rule_managed:
+ if tx.original_description is not None:
+ tx.description = tx.original_description
+ tx.description_is_rule_managed = False
matched = False
category_set = False
-
for rule in rules:
conditions = rule.conditions or []
actions = rule.actions or []
if evaluate_conditions(rule.conditions_op, conditions, tx):
if not matched:
- # First match: reset so rules are applied from scratch
tx.category_id = None
tx.notes = None
matched = True
- category_set = apply_rule_actions(actions, tx, category_set)
+ category_set = apply_rule_actions(
+ actions,
+ tx,
+ category_set,
+ skip_description=preserve_manual_description,
+ )
- if matched:
+ after = (
+ tx.category_id,
+ tx.payee_id,
+ tx.description,
+ tx.original_description,
+ tx.description_is_rule_managed,
+ tx.notes,
+ tx.is_ignored,
+ )
+ if matched or before != after:
count += 1
await session.commit()
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index d4de6248..0019442f 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -1380,6 +1380,13 @@ async def _apply_update_to_row(
)
)
+ description_changed = (
+ "description" in update_data
+ and update_data["description"] != tx.description
+ )
+ if description_changed:
+ tx.description_is_rule_managed = False
+
fx_keys = {"amount_primary", "fx_rate_used"}
for key, value in update_data.items():
if key in fx_keys:
@@ -1433,6 +1440,8 @@ async def _apply_update_to_row(
# away the number the user entered (issue #529).
keeps_own_amount = tx.transfer_amount_explicit or paired_tx.transfer_amount_explicit
for key in cascade_fields & update_data.keys():
+ if key == "description" and not description_changed:
+ continue
if key == "amount" and paired_tx.currency != tx.currency:
if keeps_own_amount:
continue
@@ -1442,6 +1451,11 @@ async def _apply_update_to_row(
)
paired_tx.amount = converted
elif key != "amount":
+ if (
+ key == "description"
+ and update_data[key] != paired_tx.description
+ ):
+ paired_tx.description_is_rule_managed = False
setattr(paired_tx, key, update_data[key])
else:
paired_tx.amount = update_data[key]
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
index 834aecfe..db3687d5 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -12,6 +12,7 @@ from app.models.asset import Asset
from app.models.bank_connection import BankConnection
from app.models.category import Category
from app.models.transaction import Transaction
+from app.schemas.rule import RuleAction, RuleCondition, RuleCreate
from app.providers.base import (
AccountData,
BillData,
@@ -32,6 +33,7 @@ from app.services.connection_service import (
sync_connection,
update_connection_settings,
)
+from app.services.rule_service import create_rule
# ---------------------------------------------------------------------------
@@ -648,6 +650,14 @@ async def test_handle_oauth_callback_creates_connection(session: AsyncSession, t
assert conn.institution_name == "Test Bank"
assert conn.external_id == "ext-oauth-1"
assert conn.status == "active"
+ transaction = (
+ await session.execute(
+ select(Transaction).where(Transaction.external_id == "tx-1")
+ )
+ ).scalar_one()
+ assert transaction.description == "UBER"
+ assert transaction.original_description == "UBER"
+ assert transaction.description_is_rule_managed is False
@pytest.mark.asyncio
@@ -712,6 +722,11 @@ async def test_sync_connection_new_transactions(session: AsyncSession, test_user
assert result_conn.status == "active"
assert merged == 0
+ transaction = await session.scalar(
+ select(Transaction).where(Transaction.external_id == "sync-tx-1")
+ )
+ assert transaction is not None
+ assert transaction.original_description == "GROCERY"
@pytest.mark.asyncio
@@ -815,6 +830,87 @@ async def test_sync_connection_with_category_mapping(session: AsyncSession, test
assert result_conn.status == "active"
+async def test_sync_keeps_provider_category_while_normalizing_description(
+ session: AsyncSession, test_user, test_workspace
+):
+ conn = await _make_connection(session, test_user.id, "Normalized Cat Bank")
+ category = await _make_category(session, test_user.id, "Alimentação")
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Normalize iFood sync",
+ conditions=[
+ RuleCondition(field="payee", op="contains", value="IFOOD.COM")
+ ],
+ actions=[
+ RuleAction(op="set_description", value="iFood"),
+ RuleAction(op="append_notes", value="#delivery"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ mock_provider = AsyncMock()
+ mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})
+ mock_provider.get_accounts = AsyncMock(
+ return_value=[
+ AccountData(
+ external_id="norm-acc-1",
+ name="Checking",
+ type="checking",
+ balance=Decimal("100"),
+ currency="BRL",
+ )
+ ]
+ )
+ mock_provider.get_transactions = AsyncMock(
+ return_value=[
+ TransactionData(
+ external_id="norm-tx-1",
+ description="|fd*f|ood Club",
+ payee="IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A.",
+ amount=Decimal("50"),
+ date=date.today(),
+ type="debit",
+ currency="BRL",
+ pluggy_category="Eating out",
+ raw_data={"merchant": {"name": "IFOOD.COM"}},
+ )
+ ]
+ )
+
+ 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,
+ ):
+ await sync_connection(
+ session, conn.id, test_workspace.id, test_user.id
+ )
+
+ transaction = (
+ await session.execute(
+ select(Transaction).where(
+ Transaction.external_id == "norm-tx-1"
+ )
+ )
+ ).scalar_one()
+ assert transaction.category_id == category.id
+ assert transaction.description == "iFood"
+ assert transaction.original_description == "|fd*f|ood Club"
+ assert transaction.description_is_rule_managed is True
+ assert transaction.payee == "IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A."
+ assert transaction.payee_id is not None
+ assert transaction.raw_data == {"merchant": {"name": "IFOOD.COM"}}
+ assert transaction.notes == "#delivery"
+
@pytest.mark.asyncio
async def test_sync_connection_error_raises(session: AsyncSession, test_user, test_workspace):
conn = await _make_connection(session, test_user.id, "Error Bank")
diff --git a/backend/tests/test_import_service.py b/backend/tests/test_import_service.py
index 09907985..8d7525a0 100644
--- a/backend/tests/test_import_service.py
+++ b/backend/tests/test_import_service.py
@@ -1379,6 +1379,8 @@ class TestImportTransactionsFx:
assert imported == 1
tx = (await session.execute(select(Transaction).where(Transaction.external_id == "ext_456"))).scalar_one()
assert tx.notes == "Tools for repair"
+ assert tx.original_description == "Hardware Store"
+ assert tx.description_is_rule_managed is False
@pytest.mark.asyncio
@patch("app.services.fx_rate_service._provider")
diff --git a/backend/tests/test_recurring_match_import.py b/backend/tests/test_recurring_match_import.py
index ce0365f2..40c8251a 100644
--- a/backend/tests/test_recurring_match_import.py
+++ b/backend/tests/test_recurring_match_import.py
@@ -8,12 +8,15 @@ from unittest.mock import AsyncMock, patch
import pytest
from sqlalchemy import select
+from app.models.payee import Payee
from app.models.recurring_transaction import RecurringTransaction
from app.models.transaction import Transaction
from app.schemas.recurring_transaction import RecurringTransactionCreate
+from app.schemas.rule import RuleAction, RuleCondition, RuleCreate
from app.schemas.transaction import TransactionImport
from app.services.import_service import import_transactions
from app.services.recurring_transaction_service import create_recurring_transaction
+from app.services.rule_service import create_rule
async def _make_bill(session, test_workspace, test_user, account, **ov):
@@ -96,6 +99,412 @@ async def test_import_merges_into_placeholder(session, test_user, test_workspace
assert txs[0].id == placeholder_id
assert txs[0].source == "csv"
assert txs[0].recurring_transaction_id == bill_id
+ assert txs[0].original_description == "NETFLIX SUBSCRIPTION"
+
+
+async def test_import_preserves_original_description_without_normalization(
+ session, test_user, test_workspace, test_account
+):
+ incoming = TransactionImport(
+ description="BANK RAW DESCRIPTION",
+ amount=Decimal("12.34"),
+ date=date(2026, 1, 11),
+ type="debit",
+ currency="BRL",
+ )
+
+ imported, skipped, _, _ = await _run_import(
+ session,
+ test_workspace,
+ test_user,
+ test_account.id,
+ [incoming],
+ )
+
+ assert (imported, skipped) == (1, 0)
+ txs = await _real_txs(session, test_account.id)
+ assert len(txs) == 1
+ assert txs[0].description == incoming.description
+ assert txs[0].original_description == incoming.description
+ assert txs[0].description_is_rule_managed is False
+
+async def test_import_normalizes_before_recurring_match_and_deduplicates_raw_reimport(
+ session, test_user, test_workspace, test_account
+):
+ account_id = test_account.id
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ test_account,
+ description="Amazon Prime",
+ amount=Decimal("19.90"),
+ start_date=date(2026, 1, 10),
+ )
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Normalize Amazon",
+ conditions=[
+ RuleCondition(
+ field="description", op="contains", value="AMZNPrime DE"
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="Amazon Prime"),
+ RuleAction(op="append_notes", value="#subscription"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ noisy = TransactionImport(
+ description="D01-123 AMZNPrime DE changing-token",
+ amount=Decimal("19.90"),
+ date=date(2026, 1, 11),
+ type="debit",
+ currency="BRL",
+ )
+
+ with patch(
+ "app.services.import_service.stamp_primary_amount",
+ new_callable=AsyncMock,
+ ):
+ imported, skipped, _, _ = await import_transactions(
+ session,
+ test_workspace.id,
+ test_user.id,
+ account_id,
+ [noisy],
+ "csv",
+ )
+ imported_again, skipped_again, _, _ = await import_transactions(
+ session,
+ test_workspace.id,
+ test_user.id,
+ account_id,
+ [noisy],
+ "csv",
+ )
+
+ assert (imported, skipped) == (1, 0)
+ assert (imported_again, skipped_again) == (0, 1)
+ txs = await _real_txs(session, account_id)
+ assert len(txs) == 1
+ assert txs[0].recurring_transaction_id == bill.id
+ assert txs[0].description == "Amazon Prime"
+ assert txs[0].original_description == noisy.description
+ assert txs[0].description_is_rule_managed is True
+ assert txs[0].notes == "#subscription"
+
+
+async def test_import_normalizes_before_placeholder_upgrade(
+ session, test_user, test_workspace, test_account, test_categories
+):
+ account_id = test_account.id
+ rule_payee = Payee(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="iFood Rule Target",
+ )
+ session.add(rule_payee)
+ await session.flush()
+ rule_payee_id = rule_payee.id
+
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ test_account,
+ description="iFood",
+ amount=Decimal("49.90"),
+ start_date=date(2026, 1, 10),
+ )
+ bill.next_occurrence = date(2026, 2, 10)
+ placeholder = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account_id,
+ description="iFood",
+ amount=Decimal("49.90"),
+ currency="BRL",
+ date=date(2026, 1, 10),
+ type="debit",
+ source="recurring",
+ status="pending",
+ recurring_transaction_id=bill.id,
+ category_id=test_categories[0].id,
+ )
+ session.add(placeholder)
+ await session.commit()
+ placeholder_id = placeholder.id
+
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Normalize raw iFood transaction",
+ conditions=[
+ RuleCondition(
+ field="description", op="contains", value="f|ood Club"
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="iFood"),
+ RuleAction(op="set_payee", value=str(rule_payee_id)),
+ RuleAction(op="ignore", value=True),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ incoming = TransactionImport(
+ description="|fd*f|ood Club",
+ payee_raw="IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A.",
+ amount=Decimal("49.90"),
+ date=date(2026, 1, 11),
+ type="debit",
+ currency="BRL",
+ category_id=test_categories[1].id,
+ notes="#statement",
+ )
+
+ with patch(
+ "app.services.import_service.stamp_primary_amount",
+ new_callable=AsyncMock,
+ ):
+ await import_transactions(
+ session,
+ test_workspace.id,
+ test_user.id,
+ account_id,
+ [incoming],
+ "ofx",
+ )
+
+ txs = await _real_txs(session, account_id)
+ assert len(txs) == 1
+ assert txs[0].id == placeholder_id
+ assert txs[0].recurring_transaction_id == bill.id
+ # The placeholder keeps the recurring definition's own wording, so the
+ # description was never rule-managed even though the rule matched and
+ # applied its other actions.
+ assert txs[0].description == "iFood"
+ assert txs[0].original_description == "|fd*f|ood Club"
+ assert txs[0].description_is_rule_managed is False
+ assert txs[0].source == "ofx"
+ assert txs[0].status == "posted"
+ assert txs[0].import_id is not None
+ # Keep the provider's raw counterparty as provenance, while preserving the
+ # canonical Payee chosen by the rule.
+ assert txs[0].payee == "IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A."
+ assert txs[0].payee_id == rule_payee_id
+ assert txs[0].is_ignored is True
+ assert txs[0].notes == "#statement"
+ assert txs[0].category_id == test_categories[0].id
+
+
+async def test_import_placeholder_rule_payee_without_raw_payee(
+ session, test_user, test_workspace, test_account
+):
+ account_id = test_account.id
+ rule_payee = Payee(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="PR586 Rule Target",
+ )
+ session.add(rule_payee)
+ await session.flush()
+ rule_payee_id = rule_payee.id
+
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ test_account,
+ description="PR586 NoPayee",
+ amount=Decimal("29.90"),
+ start_date=date(2026, 1, 10),
+ )
+ bill.next_occurrence = date(2026, 2, 10)
+ placeholder = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account_id,
+ description="PR586 NoPayee",
+ amount=Decimal("29.90"),
+ currency="BRL",
+ date=date(2026, 1, 10),
+ type="debit",
+ source="recurring",
+ status="pending",
+ recurring_transaction_id=bill.id,
+ )
+ session.add(placeholder)
+ await session.commit()
+ placeholder_id = placeholder.id
+
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Set placeholder payee without raw import payee",
+ conditions=[
+ RuleCondition(
+ field="description",
+ op="contains",
+ value="PR586 NoPayee bank",
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="PR586 NoPayee"),
+ RuleAction(op="set_payee", value=str(rule_payee_id)),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ incoming = TransactionImport(
+ description="PR586 NoPayee bank",
+ amount=Decimal("29.90"),
+ date=date(2026, 1, 11),
+ type="debit",
+ currency="BRL",
+ )
+
+ with patch(
+ "app.services.import_service.stamp_primary_amount",
+ new_callable=AsyncMock,
+ ):
+ await import_transactions(
+ session,
+ test_workspace.id,
+ test_user.id,
+ account_id,
+ [incoming],
+ "csv",
+ )
+
+ txs = await _real_txs(session, account_id)
+ assert len(txs) == 1
+ assert txs[0].id == placeholder_id
+ assert txs[0].recurring_transaction_id == bill.id
+ assert txs[0].payee is None
+ assert txs[0].payee_id == rule_payee_id
+
+
+ ("incoming_category", "force_uncategorized", "expected_category"),
+ [
+ (True, False, "incoming"),
+ (False, False, "rule"),
+ (False, True, None),
+ ],
+)
+async def test_import_placeholder_category_precedence(
+ session,
+ test_user,
+ test_workspace,
+ test_account,
+ test_categories,
+ incoming_category,
+ force_uncategorized,
+ expected_category,
+):
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ test_account,
+ description="iFood",
+ amount=Decimal("59.90"),
+ start_date=date(2026, 2, 10),
+ )
+ bill.next_occurrence = date(2026, 3, 10)
+ placeholder = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=test_account.id,
+ description="iFood",
+ amount=Decimal("59.90"),
+ currency="BRL",
+ date=date(2026, 2, 10),
+ type="debit",
+ source="recurring",
+ status="posted",
+ recurring_transaction_id=bill.id,
+ )
+ session.add(placeholder)
+ await session.commit()
+ placeholder_id = placeholder.id
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name=(
+ "Import placeholder precedence "
+ f"{incoming_category}-{force_uncategorized}"
+ ),
+ conditions=[
+ RuleCondition(
+ field="description", op="contains", value="noisy iFood"
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="iFood"),
+ RuleAction(
+ op="set_category", value=str(test_categories[0].id)
+ ),
+ RuleAction(op="append_notes", value="#delivery"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ incoming = TransactionImport(
+ description="changing noisy iFood token",
+ amount=Decimal("59.90"),
+ date=date(2026, 2, 11),
+ type="debit",
+ currency="BRL",
+ category_id=(
+ test_categories[1].id if incoming_category else None
+ ),
+ force_uncategorized=force_uncategorized,
+ )
+
+ with patch(
+ "app.services.import_service.stamp_primary_amount",
+ new_callable=AsyncMock,
+ ):
+ await import_transactions(
+ session,
+ test_workspace.id,
+ test_user.id,
+ test_account.id,
+ [incoming],
+ "csv",
+ )
+
+ txs = await _real_txs(session, test_account.id)
+ assert len(txs) == 1
+ assert txs[0].id == placeholder_id
+ assert txs[0].recurring_transaction_id == bill.id
+ if expected_category == "incoming":
+ assert txs[0].category_id == test_categories[1].id
+ elif expected_category == "rule":
+ assert txs[0].category_id == test_categories[0].id
+ else:
+ assert txs[0].category_id is None
+ assert txs[0].description == "iFood"
+ assert txs[0].original_description == incoming.description
+ assert txs[0].notes == "#delivery"
@pytest.mark.asyncio
diff --git a/backend/tests/test_recurring_match_sync.py b/backend/tests/test_recurring_match_sync.py
index 81120e05..b0a31cda 100644
--- a/backend/tests/test_recurring_match_sync.py
+++ b/backend/tests/test_recurring_match_sync.py
@@ -23,14 +23,17 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.account import Account
from app.models.bank_connection import BankConnection
+from app.models.payee import Payee
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.schemas.rule import RuleAction, RuleCondition, RuleCreate
+from app.services.connection_service import _description_similarity, sync_connection
from app.services.recurring_transaction_service import (
create_recurring_transaction,
generate_pending,
)
+from app.services.rule_service import create_rule
@pytest_asyncio.fixture
@@ -75,12 +78,42 @@ def _tx(**kw):
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 _run_sync(
+ session,
+ conn_id,
+ test_workspace,
+ test_user,
+ provider,
+ *,
+ mock_rules=True,
+):
+ patches = [
+ 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,
+ ),
+ ]
+ if mock_rules:
+ patches.append(
+ patch(
+ "app.services.connection_service.apply_rules_to_transaction",
+ new_callable=AsyncMock,
+ )
+ )
+ with patches[0], patches[1], patches[2]:
+ if mock_rules:
+ with patches[3]:
+ return await sync_connection(
+ session, conn_id, test_workspace.id, test_user.id
+ )
+ return await sync_connection(
+ session, conn_id, test_workspace.id, test_user.id
+ )
async def _make_bill(session, test_workspace, test_user, account, **ov):
@@ -133,6 +166,397 @@ async def test_sync_links_and_advances_bill(session, test_user, test_workspace,
assert refreshed.next_occurrence == date(2025, 2, 10) # advanced past fulfilled occ
+async def test_sync_normalizes_before_active_recurring_match(
+ session,
+ test_user,
+ test_workspace,
+ conn_account,
+ test_categories,
+):
+ conn, account = conn_account
+ conn_id, account_id = conn.id, account.id
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ account,
+ description="Amazon Prime",
+ amount=Decimal("19.90"),
+ start_date=date(2025, 1, 10),
+ category_id=test_categories[1].id,
+ )
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Normalize synced Amazon",
+ conditions=[
+ RuleCondition(
+ field="description", op="contains", value="AMZNPrime DE"
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="Amazon Prime"),
+ RuleAction(op="append_notes", value="#subscription"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ raw_description = "D01-1234567 AMZNPrime DE changing-token"
+ assert _description_similarity(raw_description, "Amazon Prime") < 0.6
+ provider = _provider(
+ [
+ _tx(
+ external_id="amazon-sync-1",
+ description=raw_description,
+ amount=Decimal("19.90"),
+ date=date(2025, 1, 11),
+ pluggy_category="Eating out",
+ )
+ ]
+ )
+
+ await _run_sync(
+ session,
+ conn_id,
+ test_workspace,
+ test_user,
+ provider,
+ mock_rules=False,
+ )
+ await _run_sync(
+ session,
+ conn_id,
+ test_workspace,
+ test_user,
+ provider,
+ mock_rules=False,
+ )
+
+ txs = await _all_txs(session, account_id)
+ assert len(txs) == 1
+ assert txs[0].recurring_transaction_id == bill.id
+ assert txs[0].description == "Amazon Prime"
+ assert txs[0].original_description == raw_description
+ assert txs[0].description_is_rule_managed is True
+ assert txs[0].category_id == test_categories[0].id
+ assert txs[0].notes == "#subscription"
+ refreshed = await session.get(RecurringTransaction, bill.id)
+ assert refreshed.next_occurrence == date(2025, 2, 10)
+
+
[email protected]("placeholder_has_category", [False, True])
+async def test_sync_placeholder_provider_category_precedence(
+ session,
+ test_user,
+ test_workspace,
+ conn_account,
+ test_categories,
+ placeholder_has_category,
+):
+ conn, account = conn_account
+ conn_id, account_id = conn.id, account.id
+ rule_payee = Payee(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name=f"iFood Rule Target {placeholder_has_category}",
+ )
+ session.add(rule_payee)
+ await session.flush()
+ rule_payee_id = rule_payee.id
+
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ account,
+ description="iFood",
+ amount=Decimal("49.90"),
+ start_date=date(2025, 1, 10),
+ category_id=test_categories[1].id,
+ )
+ bill.next_occurrence = date(2025, 2, 10)
+ placeholder = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account_id,
+ description="iFood",
+ amount=Decimal("49.90"),
+ currency="BRL",
+ date=date(2025, 1, 10),
+ type="debit",
+ source="recurring",
+ status="pending",
+ recurring_transaction_id=bill.id,
+ category_id=(
+ test_categories[1].id if placeholder_has_category else None
+ ),
+ notes="#planned",
+ )
+ session.add(placeholder)
+ await session.commit()
+ placeholder_id = placeholder.id
+
+ raw_description = "|fd*f|ood Club"
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name=f"Normalize sync placeholder {placeholder_has_category}",
+ conditions=[
+ RuleCondition(
+ field="description", op="contains", value="f|ood Club"
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="iFood"),
+ RuleAction(op="set_payee", value=str(rule_payee_id)),
+ RuleAction(op="append_notes", value="#delivery"),
+ RuleAction(op="ignore", value=True),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ provider = _provider(
+ [
+ _tx(
+ external_id=f"ifood-sync-{placeholder_has_category}",
+ description=raw_description,
+ payee="IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A.",
+ amount=Decimal("49.90"),
+ date=date(2025, 1, 11),
+ pluggy_category="Eating out",
+ raw_data={"merchant": {"name": "IFOOD.COM"}},
+ )
+ ]
+ )
+
+ await _run_sync(
+ session,
+ conn_id,
+ test_workspace,
+ test_user,
+ provider,
+ mock_rules=False,
+ )
+
+ txs = await _all_txs(session, account_id)
+ assert len(txs) == 1
+ assert txs[0].id == placeholder_id
+ assert txs[0].recurring_transaction_id == bill.id
+ assert txs[0].category_id == (
+ test_categories[1].id
+ if placeholder_has_category
+ else test_categories[0].id
+ )
+ # The placeholder keeps the recurring definition's own wording, so the
+ # description was never rule-managed even though the rule matched and
+ # applied its other actions.
+ assert txs[0].description == "iFood"
+ assert txs[0].original_description == raw_description
+ assert txs[0].description_is_rule_managed is False
+ assert txs[0].source == "sync"
+ assert txs[0].status == "posted"
+ assert txs[0].external_id == f"ifood-sync-{placeholder_has_category}"
+ # Keep the provider's raw counterparty as provenance, while preserving the
+ # canonical Payee chosen by the rule.
+ assert txs[0].payee == "IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A."
+ assert txs[0].payee_id == rule_payee_id
+ assert txs[0].is_ignored is True
+ assert txs[0].raw_data == {"merchant": {"name": "IFOOD.COM"}}
+ assert txs[0].notes == "#planned #delivery"
+
+
+async def test_sync_placeholder_rule_payee_without_raw_payee(
+ session, test_user, test_workspace, conn_account
+):
+ conn, account = conn_account
+ conn_id, account_id = conn.id, account.id
+ rule_payee = Payee(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="PR586 Sync Rule Target",
+ )
+ session.add(rule_payee)
+ await session.flush()
+ rule_payee_id = rule_payee.id
+
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ account,
+ description="PR586 NoPayee",
+ amount=Decimal("29.90"),
+ start_date=date(2025, 1, 10),
+ )
+ bill.next_occurrence = date(2025, 2, 10)
+ placeholder = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account_id,
+ description="PR586 NoPayee",
+ amount=Decimal("29.90"),
+ currency="BRL",
+ date=date(2025, 1, 10),
+ type="debit",
+ source="recurring",
+ status="pending",
+ recurring_transaction_id=bill.id,
+ )
+ session.add(placeholder)
+ await session.commit()
+ placeholder_id = placeholder.id
+
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Set sync placeholder payee without raw provider payee",
+ conditions=[
+ RuleCondition(
+ field="description",
+ op="contains",
+ value="PR586 NoPayee bank",
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="PR586 NoPayee"),
+ RuleAction(op="set_payee", value=str(rule_payee_id)),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ provider = _provider(
+ [
+ _tx(
+ external_id="pr586-no-payee-sync",
+ description="PR586 NoPayee bank",
+ amount=Decimal("29.90"),
+ date=date(2025, 1, 11),
+ )
+ ]
+ )
+
+ await _run_sync(
+ session,
+ conn_id,
+ test_workspace,
+ test_user,
+ provider,
+ mock_rules=False,
+ )
+
+ txs = await _all_txs(session, account_id)
+ assert len(txs) == 1
+ assert txs[0].id == placeholder_id
+ assert txs[0].recurring_transaction_id == bill.id
+ assert txs[0].payee is None
+ assert txs[0].payee_id == rule_payee_id
+
+
+async def test_sync_placeholder_keeps_the_payee_the_user_already_chose(
+ session, test_user, test_workspace, conn_account, test_categories
+):
+ """A merge fills the placeholder's gaps, it does not restate it.
+
+ The recurring definition's payee is the user's own choice; the bank's raw
+ counterparty string must not replace it. Only what is still empty is
+ filled, and the raw text is kept as provenance.
+ """
+ conn, account = conn_account
+ conn_id, account_id = conn.id, account.id
+ chosen_payee = Payee(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="iFood Brasil",
+ )
+ session.add(chosen_payee)
+ await session.flush()
+ chosen_payee_id = chosen_payee.id
+
+ bill = await _make_bill(
+ session,
+ test_workspace,
+ test_user,
+ account,
+ description="iFood",
+ amount=Decimal("49.90"),
+ start_date=date(2025, 1, 10),
+ )
+ bill.next_occurrence = date(2025, 2, 10)
+ placeholder = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account_id,
+ description="iFood",
+ amount=Decimal("49.90"),
+ currency="BRL",
+ date=date(2025, 1, 10),
+ type="debit",
+ source="recurring",
+ status="pending",
+ recurring_transaction_id=bill.id,
+ payee="iFood Brasil",
+ payee_id=chosen_payee_id,
+ notes="#planned",
+ )
+ session.add(placeholder)
+ await session.commit()
+ placeholder_id = placeholder.id
+
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Normalize iFood from the raw counterparty",
+ conditions=[
+ RuleCondition(field="payee", op="contains", value="IFOOD.COM")
+ ],
+ actions=[
+ RuleAction(op="set_description", value="iFood"),
+ RuleAction(op="append_notes", value="#delivery"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+ raw_description = "|fd*f|ood Club"
+ provider = _provider(
+ [
+ _tx(
+ external_id="ifood-keeps-payee",
+ description=raw_description,
+ payee="IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A.",
+ amount=Decimal("49.90"),
+ date=date(2025, 1, 11),
+ )
+ ]
+ )
+
+ await _run_sync(
+ session, conn_id, test_workspace, test_user, provider, mock_rules=False
+ )
+
+ txs = await _all_txs(session, account_id)
+ assert len(txs) == 1
+ assert txs[0].id == placeholder_id
+ assert txs[0].payee == "iFood Brasil"
+ assert txs[0].payee_id == chosen_payee_id
+ assert txs[0].description == "iFood"
+ assert txs[0].original_description == raw_description
+ # The gaps still get filled and the rule's own action still lands.
+ assert txs[0].notes == "#planned #delivery"
+ assert txs[0].external_id == "ifood-keeps-payee"
+
+
# ---------------------------------------------------------------------------
# Placeholder-first: incoming charge merges into the generated row
# ---------------------------------------------------------------------------
@@ -168,6 +592,7 @@ async def test_sync_promotes_pending_placeholder_to_posted(
assert merged.source == "sync"
assert merged.status == "posted"
assert merged.recurring_transaction_id == bill_id
+ assert merged.original_description == "NETFLIX SUBSCRIPTION"
refreshed = await session.get(RecurringTransaction, bill_id)
assert refreshed.next_occurrence == date(2025, 2, 10) # NOT advanced again
diff --git a/backend/tests/test_rule_engine.py b/backend/tests/test_rule_engine.py
index 5bacbef6..70404289 100644
--- a/backend/tests/test_rule_engine.py
+++ b/backend/tests/test_rule_engine.py
@@ -226,6 +226,46 @@ def test_ignore_action_sets_flag():
apply_rule_actions(actions, tx, category_already_set=False)
assert tx.is_ignored is True
+def test_set_description_preserves_first_original_and_is_idempotent():
+ tx = make_tx(description="|fd*f|ood Club", original_description=None)
+
+ apply_rule_actions(
+ [{"op": "set_description", "value": "iFood"}],
+ tx,
+ category_already_set=False,
+ )
+ assert tx.description == "iFood"
+ assert tx.original_description == "|fd*f|ood Club"
+ assert tx.description_is_rule_managed is True
+
+ apply_rule_actions(
+ [{"op": "set_description", "value": "iFood Delivery"}],
+ tx,
+ category_already_set=False,
+ )
+ assert tx.description == "iFood Delivery"
+ assert tx.original_description == "|fd*f|ood Club"
+ assert tx.description_is_rule_managed is True
+
+
+def test_raw_payee_condition_is_case_and_accent_insensitive():
+ tx = make_tx(payee="IFOOD.COM AGÊNCIA DE RESTAURANTES ONLINE S.A.")
+ conditions = [
+ {"field": "payee", "op": "contains", "value": "ifood.com agencia"}
+ ]
+
+ assert evaluate_conditions("and", conditions, tx) is True
+
+
+def test_payee_id_condition_remains_compatible():
+ payee_id = uuid.uuid4()
+ tx = make_tx(payee_id=payee_id)
+ conditions = [
+ {"field": "payee_id", "op": "equals", "value": str(payee_id)}
+ ]
+
+ assert evaluate_conditions("and", conditions, tx) is True
+
# --- Edge-case: evaluate_conditions ---
diff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.py
index 8a548139..680c7f2c 100644
--- a/backend/tests/test_rule_service.py
+++ b/backend/tests/test_rule_service.py
@@ -10,14 +10,17 @@ from app.models.category import Category
from app.models.payee import Payee
from app.models.transaction import Transaction
from app.schemas.rule import RuleAction, RuleCondition, RuleCreate, RuleExportItem, RuleExportPayload, RuleUpdate
+from app.schemas.transaction import TransactionUpdate
from app.services.rule_service import (
DuplicateRuleError,
RULE_PACKS,
apply_all_rules,
apply_rules_to_transaction,
+ apply_single_rule,
create_default_rules,
create_rule,
delete_rule,
+ export_rules,
get_installed_packs,
get_rule,
get_rules,
@@ -25,6 +28,7 @@ from app.services.rule_service import (
install_rule_pack,
update_rule,
)
+from app.services.transaction_service import update_transaction
from app.services.category_service import create_default_categories
@@ -298,6 +302,51 @@ async def test_import_rules_skips_invalid_rules(
assert result.skipped == 2
+async def test_set_description_validation_and_export_compatibility(
+ session: AsyncSession, test_user, test_workspace
+):
+ condition = RuleCondition(field="payee", op="contains", value="IFOOD.COM")
+
+ with pytest.raises(ValueError, match="blank"):
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Blank description",
+ conditions=[condition],
+ actions=[RuleAction(op="set_description", value=" ")],
+ ),
+ )
+
+ with pytest.raises(ValueError, match="500"):
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Long description",
+ conditions=[condition],
+ actions=[RuleAction(op="set_description", value="x" * 501)],
+ ),
+ )
+
+ rule = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Normalize iFood",
+ conditions=[condition],
+ actions=[RuleAction(op="set_description", value="iFood")],
+ ),
+ )
+ payload = await export_rules(session, test_workspace.id)
+ assert payload.version == 1
+ exported = next(item for item in payload.rules if item.name == rule.name)
+ assert exported.conditions[0].field == "payee"
+ assert exported.actions[0].op == "set_description"
# ---------------------------------------------------------------------------
# apply_rules_to_transaction
# ---------------------------------------------------------------------------
@@ -467,6 +516,371 @@ async def test_apply_all_rules(session: AsyncSession, test_user, test_workspace,
assert txn2.category_id == test_categories[0].id # food
+async def test_apply_all_rules_replaces_edited_normalization_idempotently(
+ session: AsyncSession, test_user, test_workspace
+):
+ account = Account(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Normalization",
+ type="checking",
+ balance=Decimal("1000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.commit()
+ transaction = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account.id,
+ description="D01-123 AMZNPrime DE changing-token",
+ amount=Decimal("19.90"),
+ date=date(2026, 1, 10),
+ type="debit",
+ source="sync",
+ )
+ session.add(transaction)
+ await session.commit()
+ rule = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Editable normalization",
+ conditions=[
+ RuleCondition(
+ field="description", op="contains", value="AMZNPrime DE"
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="Amazon Prime"),
+ RuleAction(op="append_notes", value="#subscription"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+
+ assert await apply_all_rules(session, test_workspace.id) == 1
+ await session.refresh(transaction)
+ assert transaction.description == "Amazon Prime"
+ assert transaction.original_description == "D01-123 AMZNPrime DE changing-token"
+ assert transaction.description_is_rule_managed is True
+ assert transaction.notes == "#subscription"
+
+ await update_rule(
+ session,
+ rule.id,
+ test_workspace.id,
+ RuleUpdate(
+ actions=[
+ RuleAction(op="set_description", value="Prime"),
+ RuleAction(op="append_notes", value="#subscription"),
+ ]
+ ),
+ )
+ assert await apply_all_rules(session, test_workspace.id) == 1
+ await session.refresh(transaction)
+ assert transaction.description == "Prime"
+ assert transaction.original_description == "D01-123 AMZNPrime DE changing-token"
+ assert transaction.description_is_rule_managed is True
+ assert transaction.notes == "#subscription"
+ await apply_all_rules(session, test_workspace.id)
+ await session.refresh(transaction)
+ assert transaction.description == "Prime"
+ assert transaction.original_description == "D01-123 AMZNPrime DE changing-token"
+ assert transaction.description_is_rule_managed is True
+ assert transaction.notes == "#subscription"
+
+ assert await delete_rule(
+ session, rule.id, test_workspace.id
+ ) is True
+ assert await apply_all_rules(session, test_workspace.id) == 1
+ await session.refresh(transaction)
+ assert transaction.description == "D01-123 AMZNPrime DE changing-token"
+ assert transaction.original_description == "D01-123 AMZNPrime DE changing-token"
+ assert transaction.description_is_rule_managed is False
+
+
+async def test_apply_all_rules_preserves_manually_edited_import_description(
+ session: AsyncSession, test_user, test_workspace
+):
+ account = Account(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Imported",
+ type="checking",
+ balance=Decimal("1000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.flush()
+ transaction = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account.id,
+ description="BANK RAW DESCRIPTION",
+ original_description="BANK RAW DESCRIPTION",
+ amount=Decimal("12.34"),
+ date=date(2026, 1, 11),
+ type="debit",
+ source="csv",
+ payee="IFOOD.COM RESTAURANTES",
+ )
+ session.add(transaction)
+ await session.commit()
+
+ updated = await update_transaction(
+ session,
+ transaction.id,
+ test_workspace.id,
+ test_user.id,
+ TransactionUpdate(description="Manually edited merchant"),
+ )
+ assert updated is not None
+ assert updated.description_is_rule_managed is False
+
+ await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Stable payee normalization",
+ conditions=[
+ RuleCondition(field="payee", op="contains", value="IFOOD.COM")
+ ],
+ actions=[
+ RuleAction(op="set_description", value="iFood"),
+ RuleAction(op="append_notes", value="#delivery"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+
+ assert await apply_all_rules(session, test_workspace.id) == 1
+ await session.refresh(transaction)
+ assert transaction.description == "Manually edited merchant"
+ assert transaction.original_description == "BANK RAW DESCRIPTION"
+ assert transaction.description_is_rule_managed is False
+ assert transaction.notes == "#delivery"
+
+
+async def test_apply_single_rule_preserves_manually_edited_import_description(
+ session: AsyncSession, test_user, test_workspace
+):
+ """Re-saving a normalization rule must not undo the user's own wording.
+
+ `apply_all_rules` already protects a hand-edited description; the same must
+ hold for the far more common path of editing one rule and re-applying it.
+ """
+ account = Account(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Imported",
+ type="checking",
+ balance=Decimal("1000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.flush()
+ transaction = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account.id,
+ description="D01-123 AMZNPrime DE changing-token",
+ original_description="D01-123 AMZNPrime DE changing-token",
+ amount=Decimal("19.90"),
+ date=date(2026, 1, 10),
+ type="debit",
+ source="csv",
+ )
+ session.add(transaction)
+ await session.commit()
+
+ rule = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Amazon Prime normalization",
+ conditions=[
+ RuleCondition(field="description", op="contains", value="AMZNPrime")
+ ],
+ actions=[
+ RuleAction(op="set_description", value="Amazon Prime"),
+ RuleAction(op="append_notes", value="#subscription"),
+ ],
+ apply_to_existing=False,
+ ),
+ )
+
+ assert await apply_single_rule(session, test_workspace.id, rule) == 1
+ await session.refresh(transaction)
+ assert transaction.description == "Amazon Prime"
+ assert transaction.description_is_rule_managed is True
+
+ updated = await update_transaction(
+ session,
+ transaction.id,
+ test_workspace.id,
+ test_user.id,
+ TransactionUpdate(description="Amazon Prime (family)"),
+ )
+ assert updated is not None
+ assert updated.description_is_rule_managed is False
+
+ # Clear the notes so the re-application has something left to do: the rule
+ # must still match and still run its other actions, and only the typed
+ # description is off limits.
+ transaction.notes = None
+ await session.commit()
+
+ assert await apply_single_rule(session, test_workspace.id, rule) == 1
+ await session.refresh(transaction)
+ assert transaction.description == "Amazon Prime (family)"
+ assert transaction.original_description == "D01-123 AMZNPrime DE changing-token"
+ assert transaction.description_is_rule_managed is False
+ assert transaction.notes == "#subscription"
+
+
+async def test_apply_single_rule_prefers_current_description_then_falls_back_to_original(
+ session: AsyncSession, test_user, test_workspace, test_categories
+):
+ account = Account(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ name="Rule chain",
+ type="checking",
+ balance=Decimal("1000"),
+ currency="BRL",
+ )
+ session.add(account)
+ await session.flush()
+ transaction = Transaction(
+ user_id=test_user.id,
+ workspace_id=test_workspace.id,
+ account_id=account.id,
+ description="D01-123 AMZNPrime DE changing-token",
+ amount=Decimal("19.90"),
+ date=date(2026, 1, 10),
+ type="debit",
+ source="sync",
+ )
+ session.add(transaction)
+ await session.commit()
+
+ normalizer = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Normalize Amazon",
+ conditions=[
+ RuleCondition(
+ field="description", op="contains", value="AMZNPrime DE"
+ )
+ ],
+ actions=[
+ RuleAction(op="set_description", value="Amazon Prime")
+ ],
+ apply_to_existing=False,
+ priority=10,
+ ),
+ )
+ assert await apply_single_rule(
+ session, test_workspace.id, normalizer
+ ) == 1
+ assert transaction.description == "Amazon Prime"
+ assert (
+ transaction.original_description
+ == "D01-123 AMZNPrime DE changing-token"
+ )
+
+ dependent = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Categorize normalized Amazon",
+ conditions=[
+ RuleCondition(
+ field="description", op="equals", value="Amazon Prime"
+ )
+ ],
+ actions=[
+ RuleAction(
+ op="set_category", value=str(test_categories[0].id)
+ )
+ ],
+ apply_to_existing=False,
+ priority=20,
+ ),
+ )
+ assert await apply_single_rule(
+ session, test_workspace.id, dependent
+ ) == 1
+ assert transaction.category_id == test_categories[0].id
+ assert await apply_single_rule(
+ session, test_workspace.id, dependent
+ ) == 0
+ negative = await create_rule(
+ session,
+ test_workspace.id,
+ test_user.id,
+ RuleCreate(
+ name="Current-state negative match",
+ conditions=[
+ RuleCondition(
+ field="description",
+ op="not_contains",
+ value="AMZNPrime DE",
+ )
+ ],
+ actions=[RuleAction(op="append_notes", value="#normalized")],
+ apply_to_existing=False,
+ priority=30,
+ ),
+ )
+ assert await apply_single_rule(
+ session, test_workspace.id, negative
+ ) == 1
+ assert transaction.notes == "#normalized"
+ assert await apply_single_rule(
+ session, test_workspace.id, negative
+ ) == 0
+
+ normalizer = await update_rule(
+ session,
+ normalizer.id,
+ test_workspace.id,
+ RuleUpdate(
+ actions=[
+ RuleAction(op="set_description", value="Prime"),
+ RuleAction(
+ op="set_category", value=str(test_categories[1].id)
+ ),
+ ]
+ ),
+ )
+ assert normalizer is not None
+ assert await apply_single_rule(
+ session, test_workspace.id, normalizer
+ ) == 1
+ assert transaction.description == "Prime"
+ assert (
+ transaction.original_description
+ == "D01-123 AMZNPrime DE changing-token"
+ )
+ assert transaction.category_id == test_categories[0].id
+ assert await apply_single_rule(
+ session, test_workspace.id, normalizer
+ ) == 0
+ assert transaction.category_id == test_categories[0].id
+
+
@pytest.mark.asyncio
async def test_apply_all_rules_preserves_manual_categories(
session: AsyncSession, test_user, test_workspace, test_categories
diff --git a/backend/tests/test_transaction_schemas.py b/backend/tests/test_transaction_schemas.py
index a5915e53..d40a5896 100644
--- a/backend/tests/test_transaction_schemas.py
+++ b/backend/tests/test_transaction_schemas.py
@@ -129,6 +129,21 @@ class TestTransactionReadInstallmentFields:
assert dumped["installment_total_amount"] == 300.00
assert dumped["installment_purchase_date"] == "2026-03-25"
+ def test_exposes_original_description_without_raw_provider_data(self):
+ data = TransactionRead.model_validate(
+ self._base(
+ description="iFood",
+ original_description="|fd*f|ood Club",
+ raw_data={"provider_secret": "not-safe"},
+ description_is_rule_managed=True,
+ )
+ )
+ dumped = data.model_dump(mode="json")
+
+ assert dumped["original_description"] == "|fd*f|ood Club"
+ assert "raw_data" not in dumped
+ assert "description_is_rule_managed" not in dumped
+
class TestTransactionCreateDateField:
"""Ensure TransactionCreate also handles the date field correctly."""
diff --git a/backend/tests/test_transaction_service.py b/backend/tests/test_transaction_service.py
index 75b8bf5e..8b3f00c4 100644
--- a/backend/tests/test_transaction_service.py
+++ b/backend/tests/test_transaction_service.py
@@ -596,15 +596,27 @@ async def test_update_transaction(session: AsyncSession, test_user, test_workspa
user_id=test_user.id,
account_id=txn_account.id,
description="Old",
+ original_description="Bank Raw",
+ description_is_rule_managed=True,
amount=Decimal("10"),
date=date(2025, 3, 1),
type="debit",
- source="manual",
+ source="sync",
created_at=datetime.now(timezone.utc),
)
session.add(txn)
await session.commit()
+ unchanged = await update_transaction(
+ session,
+ txn.id,
+ test_workspace.id,
+ test_user.id,
+ TransactionUpdate(description="Old", notes="#reviewed"),
+ )
+ assert unchanged is not None
+ assert unchanged.description_is_rule_managed is True
+
updated = await update_transaction(
session,
txn.id,
@@ -615,6 +627,8 @@ async def test_update_transaction(session: AsyncSession, test_user, test_workspa
assert updated is not None
assert updated.description == "New"
assert updated.amount == Decimal("99")
+ assert updated.original_description == "Bank Raw"
+ assert updated.description_is_rule_managed is False
@pytest.mark.asyncio
@@ -1312,6 +1326,24 @@ async def test_update_transfer_cascades(
date=date.today(),
),
)
+ credit_tx.description = "Custom paired description"
+ credit_tx.original_description = "Paired bank description"
+ credit_tx.description_is_rule_managed = True
+ await session.commit()
+
+ unchanged = await update_transaction(
+ session,
+ debit_tx.id,
+ test_workspace.id,
+ test_user.id,
+ TransactionUpdate(description="Cascade Xfer", notes="#reviewed"),
+ )
+ assert unchanged is not None
+ paired = await get_transaction(session, credit_tx.id, test_workspace.id)
+ assert paired is not None
+ assert paired.description == "Custom paired description"
+ assert paired.description_is_rule_managed is True
+
data = TransactionUpdate(description="Updated Xfer")
updated = await update_transaction(session, debit_tx.id, test_workspace.id, test_user.id, data)
@@ -1322,6 +1354,7 @@ async def test_update_transfer_cascades(
assert paired is not None
assert paired.description == "Updated Xfer"
+ assert paired.description_is_rule_managed is False
# ---------------------------------------------------------------------------
diff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsx
index 136d3dce..d89a083a 100644
--- a/frontend/src/components/rule-dialog.tsx
+++ b/frontend/src/components/rule-dialog.tsx
@@ -1,6 +1,7 @@
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { getAccountName, sortAccountsByDisplayName } from '@/lib/account-utils'
+import { isInvalidDescriptionAction, parseRulePriority } from '@/lib/rule-form-utils'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
@@ -18,6 +19,7 @@ import type { Category, CategoryGroup, Payee, Rule, RuleCondition, RuleAction }
const CONDITION_FIELDS = [
{ value: 'description', label: 'rules.fieldDescription' },
+ { value: 'payee', label: 'rules.fieldRawPayee' },
{ value: 'notes', label: 'rules.fieldNotes' },
{ value: 'amount', label: 'rules.fieldAmount' },
{ value: 'type', label: 'rules.fieldType' },
@@ -92,7 +94,7 @@ export function RuleDialog({
const [actions, setActions] = useState<RuleAction[]>(
defaultActions.length ? defaultActions : [{ op: 'set_category', value: '' }]
)
- const [priority, setPriority] = useState(rule?.priority ?? 0)
+ const [priority, setPriority] = useState(String(rule?.priority ?? 0))
const [isActive, setIsActive] = useState(rule?.is_active ?? true)
const [applyToExisting, setApplyToExisting] = useState(!rule)
const [overwriteExistingCategories, setOverwriteExistingCategories] = useState(false)
@@ -140,16 +142,17 @@ export function RuleDialog({
// A blank condition value matches every transaction, so the rule would apply
// its actions to the whole ledger. The API rejects these too.
const hasBlankCondition = conditions.some(c => String(c.value ?? '').trim() === '')
+ const hasInvalidDescriptionAction = actions.some(isInvalidDescriptionAction)
function handleSubmit(e: React.FormEvent) {
e.preventDefault()
- if (hasBlankCondition) return
+ if (hasBlankCondition || hasInvalidDescriptionAction) return
onSave({
name,
conditions_op: conditionsOp,
conditions,
actions,
- priority,
+ priority: parseRulePriority(priority),
is_active: isActive,
apply_to_existing: applyToExisting,
overwrite_existing_categories: applyToExisting && overwriteExistingCategories,
@@ -174,7 +177,17 @@ export function RuleDialog({
</div>
<div className="space-y-1.5">
<Label>{t('rules.priority')}</Label>
- <Input type="number" value={priority} onChange={(e) => setPriority(Number(e.target.value))} />
+ <Input
+ type="number"
+ step="1"
+ value={priority}
+ onChange={(e) => setPriority(e.target.value)}
+ onBlur={() => {
+ if (priority.trim() === '' || !Number.isFinite(Number(priority))) {
+ setPriority('0')
+ }
+ }}
+ />
</div>
</div>
@@ -285,62 +298,81 @@ export function RuleDialog({
<div className="space-y-2">
<Label>{t('rules.actions')}</Label>
<div className="space-y-2">
- {actions.map((action, i) => (
- <div key={i} className="relative grid min-w-0 gap-2 pr-7 sm:flex sm:items-center sm:pr-0">
- <select
- className={`${selectClass} w-full sm:w-40 sm:shrink-0`}
- value={action.op}
- onChange={(e) => updateAction(i, 'op', e.target.value)}
- >
- <option value="set_category">{t('rules.setCategory')}</option>
- <option value="set_payee">{t('rules.setPayee')}</option>
- <option value="append_notes">{t('rules.appendNotes')}</option>
- <option value="ignore">{t('rules.ignoreAction')}</option>
- </select>
- {action.op === 'ignore' ? (
- <span className="min-w-0 text-sm italic text-muted-foreground sm:w-0 sm:flex-1">
- {t('rules.ignoreActionHint')}
- </span>
- ) : action.op === 'set_category' ? (
- <div className="w-full min-w-0 sm:w-0 sm:flex-1">
- <CategorySelect
- value={action.value}
- onChange={(val) => updateAction(i, 'value', val)}
- categories={categories}
- groups={categoryGroups}
- placeholder={t('rules.selectCategory')}
- className={`${selectClass} w-full`}
- />
+ {actions.map((action, i) => {
+ const invalidDescription = isInvalidDescriptionAction(action)
+ return (
+ <div key={i} className="space-y-1">
+ <div className="relative grid min-w-0 gap-2 pr-7 sm:flex sm:items-center sm:pr-0">
+ <select
+ className={`${selectClass} w-full sm:w-40 sm:shrink-0`}
+ value={action.op}
+ onChange={(e) => updateAction(i, 'op', e.target.value)}
+ >
+ <option value="set_category">{t('rules.setCategory')}</option>
+ <option value="set_description">{t('rules.setDescription')}</option>
+ <option value="set_payee">{t('rules.setPayee')}</option>
+ <option value="append_notes">{t('rules.appendNotes')}</option>
+ <option value="ignore">{t('rules.ignoreAction')}</option>
+ </select>
+ {action.op === 'ignore' ? (
+ <span className="min-w-0 text-sm italic text-muted-foreground sm:w-0 sm:flex-1">
+ {t('rules.ignoreActionHint')}
+ </span>
+ ) : action.op === 'set_category' ? (
+ <div className="w-full min-w-0 sm:w-0 sm:flex-1">
+ <CategorySelect
+ value={action.value}
+ onChange={(val) => updateAction(i, 'value', val)}
+ categories={categories}
+ groups={categoryGroups}
+ placeholder={t('rules.selectCategory')}
+ className={`${selectClass} w-full`}
+ />
+ </div>
+ ) : action.op === 'set_payee' ? (
+ <select
+ className={`${selectClass} w-full min-w-0 sm:w-0 sm:flex-1`}
+ value={action.value}
+ onChange={(e) => updateAction(i, 'value', e.target.value)}
+ required
+ >
+ <option value="">{t('rules.selectPayee')}</option>
+ {payees.map(p => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ ) : (
+ <Input
+ className="h-8 w-full min-w-0 text-sm aria-invalid:border-input aria-invalid:ring-0 dark:aria-invalid:ring-0 sm:w-0 sm:flex-1"
+ value={action.value}
+ onChange={(e) => updateAction(i, 'value', e.target.value)}
+ placeholder={
+ action.op === 'set_description'
+ ? t('rules.descriptionValuePlaceholder')
+ : t('rules.notesValuePlaceholder')
+ }
+ maxLength={action.op === 'set_description' ? 500 : undefined}
+ required={action.op === 'set_description'}
+ aria-invalid={invalidDescription || undefined}
+ aria-describedby={invalidDescription ? `action-${i}-description-error` : undefined}
+ />
+ )}
+ <button
+ type="button"
+ className="absolute right-0 top-1 shrink-0 p-1 text-muted-foreground transition-colors hover:text-rose-500 sm:static"
+ onClick={() => removeAction(i)}
+ >
+ <X size={13} />
+ </button>
</div>
- ) : action.op === 'set_payee' ? (
- <select
- className={`${selectClass} w-full min-w-0 sm:w-0 sm:flex-1`}
- value={action.value}
- onChange={(e) => updateAction(i, 'value', e.target.value)}
- required
- >
- <option value="">{t('rules.selectPayee')}</option>
- {payees.map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
- </select>
- ) : (
- <Input
- className="h-8 w-full min-w-0 text-sm sm:w-0 sm:flex-1"
- value={action.value}
- onChange={(e) => updateAction(i, 'value', e.target.value)}
- placeholder="Ex: #work #reimbursable"
- />
- )}
- <button
- type="button"
- className="absolute right-0 top-1 shrink-0 p-1 text-muted-foreground transition-colors hover:text-rose-500 sm:static"
- onClick={() => removeAction(i)}
- >
- <X size={13} />
- </button>
- </div>
- ))}
+ {invalidDescription && (
+ <p id={`action-${i}-description-error`} className="text-xs text-rose-500">
+ {t('rules.invalidDescriptionValue')}
+ </p>
+ )}
+ </div>
+ )
+ })}
<button
type="button"
className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index b167b452..459abb99 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -906,6 +906,15 @@ function TransactionForm({
className="bg-card"
/>
)}
+ {transaction?.original_description &&
+ transaction.original_description !== transaction.description && (
+ <p className="text-xs text-muted-foreground">
+ {t('transactions.originalDescription')}: {transaction.original_description}
+ </p>
+ )}
+ {/* Rows that pre-date the original_description column have no
+ provenance to show, so the raw payee stays the only hint at what
+ the bank actually sent. */}
{isSynced && transaction?.payee && transaction.payee !== transaction.description && (
<p className="text-xs text-muted-foreground">{transaction.payee}</p>
)}
diff --git a/frontend/src/lib/rule-form-utils.test.ts b/frontend/src/lib/rule-form-utils.test.ts
new file mode 100644
index 00000000..1f912027
--- /dev/null
+++ b/frontend/src/lib/rule-form-utils.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+
+import { isInvalidDescriptionAction, parseRulePriority } from './rule-form-utils'
+
+describe('isInvalidDescriptionAction', () => {
+ it('validates each description action independently', () => {
+ expect(isInvalidDescriptionAction({ op: 'set_description', value: '' })).toBe(true)
+ expect(isInvalidDescriptionAction({ op: 'set_description', value: ' ' })).toBe(true)
+ expect(isInvalidDescriptionAction({ op: 'set_description', value: 'iFood' })).toBe(false)
+ expect(isInvalidDescriptionAction({ op: 'set_description', value: 'x'.repeat(501) })).toBe(true)
+ expect(isInvalidDescriptionAction({ op: 'append_notes', value: '' })).toBe(false)
+ })
+})
+
+describe('parseRulePriority', () => {
+ it('uses zero for a temporarily blank priority', () => {
+ expect(parseRulePriority('')).toBe(0)
+ expect(parseRulePriority(' ')).toBe(0)
+ })
+
+ it('returns finite numeric priority values', () => {
+ expect(parseRulePriority('0')).toBe(0)
+ expect(parseRulePriority('1')).toBe(1)
+ expect(parseRulePriority('-2')).toBe(-2)
+ expect(parseRulePriority('not-a-number')).toBe(0)
+ })
+})
diff --git a/frontend/src/lib/rule-form-utils.ts b/frontend/src/lib/rule-form-utils.ts
new file mode 100644
index 00000000..8637907f
--- /dev/null
+++ b/frontend/src/lib/rule-form-utils.ts
@@ -0,0 +1,13 @@
+import type { RuleAction } from '../types'
+
+export function isInvalidDescriptionAction(action: RuleAction): boolean {
+ if (action.op !== 'set_description') return false
+ const value = String(action.value ?? '').trim()
+ return value === '' || value.length > 500
+}
+
+export function parseRulePriority(value: string): number {
+ if (value.trim() === '') return 0
+ const priority = Number(value)
+ return Number.isFinite(priority) ? priority : 0
+}
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index ed7eecd6..31dd8098 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -297,6 +297,7 @@
"monthPrevious": "Vorheriger Monat",
"monthNext": "Nächster Monat",
"description": "Beschreibung",
+ "originalDescription": "Ursprüngliche Beschreibung",
"amount": "Betrag",
"status": "Status",
"date": "Datum",
@@ -847,7 +848,7 @@
"duplicateName": "Eine Regel mit diesem Namen existiert bereits",
"sectionTitle": "Kategorisierungsregeln",
"resetAndReapplyAll": "Zurücksetzen und erneut anwenden",
- "confirmResetAndReapplyAll": "Kategorien und Notizen übereinstimmender Transaktionen zurücksetzen und anschließend alle aktiven Regeln erneut anwenden?",
+ "confirmResetAndReapplyAll": "Kategorien, Notizen und durch Regeln geänderte Beschreibungen übereinstimmender Transaktionen zurücksetzen und anschließend alle aktiven Regeln erneut anwenden?",
"add": "Hinzufügen",
"created": "Regel erstellt",
"createdAndApplied": "Regel erstellt und auf {{count}} Transaktionen angewendet",
@@ -871,6 +872,10 @@
"blankConditionValue": "Jede Bedingung benötigt einen Wert. Eine leere Bedingung würde auf alle Transaktionen zutreffen.",
"addAction": "Aktion hinzufügen",
"setCategory": "Kategorie festlegen",
+ "setDescription": "Beschreibung festlegen",
+ "descriptionValuePlaceholder": "Normalisierte Beschreibung eingeben",
+ "notesValuePlaceholder": "z. B. #arbeit #erstattbar",
+ "invalidDescriptionValue": "Die Beschreibung ist erforderlich und darf höchstens 500 Zeichen lang sein.",
"setPayee": "Zahlungsempfänger festlegen",
"selectPayee": "Zahlungsempfänger auswählen...",
"appendNotes": "Tags/Notizen anhängen",
@@ -882,6 +887,7 @@
"noConditions": "(keine Bedingungen)",
"noActions": "(keine Aktionen)",
"fieldDescription": "Beschreibung",
+ "fieldRawPayee": "Importierter Zahlungsempfänger",
"fieldNotes": "Notizen",
"fieldAmount": "Betrag",
"fieldType": "Typ",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index d12d72bb..0cc9c9e1 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -297,6 +297,7 @@
"monthPrevious": "Previous month",
"monthNext": "Next month",
"description": "Description",
+ "originalDescription": "Original description",
"amount": "Amount",
"status": "Status",
"date": "Date",
@@ -847,7 +848,7 @@
"duplicateName": "A rule with this name already exists",
"sectionTitle": "Categorization Rules",
"resetAndReapplyAll": "Reset and reapply",
- "confirmResetAndReapplyAll": "Reset matching transaction categories and notes, then reapply all active rules?",
+ "confirmResetAndReapplyAll": "Reset matching transaction categories, notes, and rule-managed descriptions, then reapply all active rules?",
"add": "Add",
"created": "Rule created",
"createdAndApplied": "Rule created and applied to {{count}} transactions",
@@ -871,6 +872,10 @@
"blankConditionValue": "Every condition needs a value. A blank one would match every transaction.",
"addAction": "Add action",
"setCategory": "Set category",
+ "setDescription": "Set description",
+ "descriptionValuePlaceholder": "Enter the normalized description",
+ "notesValuePlaceholder": "e.g. #work #reimbursable",
+ "invalidDescriptionValue": "Description is required and must be 500 characters or fewer.",
"setPayee": "Set payee",
"selectPayee": "Select payee...",
"appendNotes": "Append tags/notes",
@@ -882,6 +887,7 @@
"noConditions": "(no conditions)",
"noActions": "(no actions)",
"fieldDescription": "Description",
+ "fieldRawPayee": "Imported payee",
"fieldNotes": "Notes",
"fieldAmount": "Amount",
"fieldType": "Type",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 99cf5736..cf56ed5c 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -297,6 +297,7 @@
"monthPrevious": "Mes anterior",
"monthNext": "Mes siguiente",
"description": "Descripción",
+ "originalDescription": "Descripción original",
"amount": "Importe",
"status": "Estado",
"date": "Fecha",
@@ -847,7 +848,7 @@
"duplicateName": "Ya existe una regla con este nombre",
"sectionTitle": "Reglas de categorización",
"resetAndReapplyAll": "Restablecer y reaplicar",
- "confirmResetAndReapplyAll": "¿Restablecer categorías y notas de las transacciones coincidentes y reaplicar todas las reglas activas?",
+ "confirmResetAndReapplyAll": "¿Restablecer las categorías, las notas y las descripciones gestionadas por reglas de las transacciones coincidentes y volver a aplicar todas las reglas activas?",
"add": "Agregar",
"created": "Regla creada",
"createdAndApplied": "Regla creada y aplicada a {{count}} transacciones",
@@ -871,6 +872,10 @@
"blankConditionValue": "Cada condición necesita un valor. Una condición en blanco coincidiría con todas las transacciones.",
"addAction": "Agregar acción",
"setCategory": "Establecer categoría",
+ "setDescription": "Establecer descripción",
+ "descriptionValuePlaceholder": "Introduce la descripción normalizada",
+ "notesValuePlaceholder": "p. ej. #trabajo #reembolsable",
+ "invalidDescriptionValue": "La descripción es obligatoria y debe tener 500 caracteres o menos.",
"setPayee": "Establecer beneficiario",
"selectPayee": "Seleccionar beneficiario...",
"appendNotes": "Añadir etiquetas/notas",
@@ -882,6 +887,7 @@
"noConditions": "(sin condiciones)",
"noActions": "(sin acciones)",
"fieldDescription": "Descripción",
+ "fieldRawPayee": "Beneficiario importado",
"fieldNotes": "Notas",
"fieldAmount": "Importe",
"fieldType": "Tipo",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 0d14a98d..53464b4b 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -297,6 +297,7 @@
"monthPrevious": "Mois précédent",
"monthNext": "Mois suivant",
"description": "Description",
+ "originalDescription": "Description d'origine",
"amount": "Montant",
"status": "Statut",
"date": "Date",
@@ -847,7 +848,7 @@
"duplicateName": "Une règle portant ce nom existe déjà",
"sectionTitle": "Règles de catégorisation",
"resetAndReapplyAll": "Réinitialiser et réappliquer",
- "confirmResetAndReapplyAll": "Réinitialiser les catégories et les notes des transactions correspondantes, puis réappliquer toutes les règles actives ?",
+ "confirmResetAndReapplyAll": "Réinitialiser les catégories, les notes et les descriptions gérées par des règles des transactions correspondantes, puis réappliquer toutes les règles actives ?",
"add": "Ajouter",
"created": "Règle créée",
"createdAndApplied": "Règle créée et appliquée à {{count}} transactions",
@@ -871,6 +872,10 @@
"blankConditionValue": "Chaque condition nécessite une valeur. Une condition vide correspondrait à toutes les transactions.",
"addAction": "Ajouter une action",
"setCategory": "Définir la catégorie",
+ "setDescription": "Définir la description",
+ "descriptionValuePlaceholder": "Saisissez la description normalisée",
+ "notesValuePlaceholder": "ex. #travail #remboursable",
+ "invalidDescriptionValue": "La description est obligatoire et doit contenir au maximum 500 caractères.",
"setPayee": "Définir le bénéficiaire",
"selectPayee": "Sélectionner un bénéficiaire...",
"appendNotes": "Ajouter des étiquettes/notes",
@@ -882,6 +887,7 @@
"noConditions": "(aucune condition)",
"noActions": "(aucune action)",
"fieldDescription": "Description",
+ "fieldRawPayee": "Bénéficiaire importé",
"fieldNotes": "Notes",
"fieldAmount": "Montant",
"fieldType": "Type",
diff --git a/frontend/src/locales/i18n.test.ts b/frontend/src/locales/i18n.test.ts
index 1528f75e..94e78c98 100644
--- a/frontend/src/locales/i18n.test.ts
+++ b/frontend/src/locales/i18n.test.ts
@@ -191,4 +191,22 @@ describe('i18n locale files', () => {
})
}
})
+
+ it('contains imported-description normalization labels in every locale', () => {
+ const required = [
+ 'transactions.originalDescription',
+ 'rules.setDescription',
+ 'rules.descriptionValuePlaceholder',
+ 'rules.invalidDescriptionValue',
+ 'rules.fieldRawPayee',
+ ]
+
+ for (const locale of LOCALES) {
+ const keys = new Set(flattenKeys(JSON.parse(readRaw(locale))))
+ expect(
+ required.filter((key) => !keys.has(key)),
+ `Normalization labels missing in ${locale}:`,
+ ).toEqual([])
+ }
+ })
})
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index f7349d2e..a8fb12d8 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -297,6 +297,7 @@
"monthPrevious": "Mese precedente",
"monthNext": "Mese successivo",
"description": "Descrizione",
+ "originalDescription": "Descrizione originale",
"amount": "Importo",
"status": "Stato",
"date": "Data",
@@ -847,7 +848,7 @@
"duplicateName": "Esiste già una regola con questo nome",
"sectionTitle": "Regole di categorizzazione",
"resetAndReapplyAll": "Reimposta e riapplica",
- "confirmResetAndReapplyAll": "Reimpostare categorie e note delle transazioni corrispondenti e riapplicare tutte le regole attive?",
+ "confirmResetAndReapplyAll": "Reimpostare categorie, note e descrizioni gestite dalle regole delle transazioni corrispondenti e riapplicare tutte le regole attive?",
"add": "Aggiungi",
"created": "Regola creata",
"createdAndApplied": "Regola creata e applicata a {{count}} transazioni",
@@ -871,6 +872,10 @@
"blankConditionValue": "Ogni condizione richiede un valore. Una condizione vuota corrisponderebbe a tutte le transazioni.",
"addAction": "Aggiungi azione",
"setCategory": "Imposta categoria",
+ "setDescription": "Imposta descrizione",
+ "descriptionValuePlaceholder": "Inserisci la descrizione normalizzata",
+ "notesValuePlaceholder": "es. #lavoro #rimborsabile",
+ "invalidDescriptionValue": "La descrizione è obbligatoria e deve contenere al massimo 500 caratteri.",
"setPayee": "Imposta beneficiario",
"selectPayee": "Seleziona beneficiario...",
"appendNotes": "Aggiungi tag/note",
@@ -882,6 +887,7 @@
"noConditions": "(nessuna condizione)",
"noActions": "(nessuna azione)",
"fieldDescription": "Descrizione",
+ "fieldRawPayee": "Beneficiario importato",
"fieldNotes": "Note",
"fieldAmount": "Importo",
"fieldType": "Tipo",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 3f939e48..188df6af 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -303,6 +303,7 @@
"monthPrevious": "Poprzedni miesiąc",
"monthNext": "Następny miesiąc",
"description": "Opis",
+ "originalDescription": "Oryginalny opis",
"amount": "Kwota",
"status": "Status",
"date": "Data",
@@ -904,7 +905,7 @@
"duplicateName": "Reguła o tej nazwie już istnieje",
"sectionTitle": "Reguły kategoryzacji",
"resetAndReapplyAll": "Zresetuj i zastosuj ponownie",
- "confirmResetAndReapplyAll": "Zresetować kategorie i notatki pasujących transakcji, a następnie zastosować ponownie wszystkie aktywne reguły?",
+ "confirmResetAndReapplyAll": "Zresetować kategorie, notatki i opisy zarządzane przez reguły pasujących transakcji, a następnie zastosować ponownie wszystkie aktywne reguły?",
"add": "Dodaj",
"created": "Utworzono regułę",
"createdAndApplied": "Utworzono regułę i zastosowano do {{count}} transakcji",
@@ -931,6 +932,10 @@
"blankConditionValue": "Każdy warunek wymaga wartości. Pusty warunek pasowałby do wszystkich transakcji.",
"addAction": "Dodaj akcję",
"setCategory": "Ustaw kategorię",
+ "setDescription": "Ustaw opis",
+ "descriptionValuePlaceholder": "Wpisz znormalizowany opis",
+ "notesValuePlaceholder": "np. #praca #zwrot",
+ "invalidDescriptionValue": "Opis jest wymagany i może mieć maksymalnie 500 znaków.",
"setPayee": "Ustaw odbiorcę",
"selectPayee": "Wybierz odbiorcę...",
"appendNotes": "Dołącz tagi/notatki",
@@ -942,6 +947,7 @@
"noConditions": "(brak warunków)",
"noActions": "(brak akcji)",
"fieldDescription": "Opis",
+ "fieldRawPayee": "Importowany odbiorca",
"fieldNotes": "Notatki",
"fieldAmount": "Kwota",
"fieldType": "Typ",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index e75de2fc..925a554c 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -297,6 +297,7 @@
"monthPrevious": "Mês anterior",
"monthNext": "Próximo mês",
"description": "Descrição",
+ "originalDescription": "Descrição original",
"amount": "Valor",
"status": "Status",
"date": "Data",
@@ -847,7 +848,7 @@
"duplicateName": "Já existe uma regra com este nome",
"sectionTitle": "Regras de Categorização",
"resetAndReapplyAll": "Redefinir e reaplicar",
- "confirmResetAndReapplyAll": "Redefinir categorias e notas das transações correspondentes e reaplicar todas as regras ativas?",
+ "confirmResetAndReapplyAll": "Redefinir categorias, notas e descrições gerenciadas por regras das transações correspondentes e reaplicar todas as regras ativas?",
"add": "Adicionar",
"created": "Regra criada",
"createdAndApplied": "Regra criada e aplicada a {{count}} transações",
@@ -871,6 +872,10 @@
"blankConditionValue": "Toda condição precisa de um valor. Uma condição em branco corresponderia a todas as transações.",
"addAction": "Adicionar ação",
"setCategory": "Definir categoria",
+ "setDescription": "Definir descrição",
+ "descriptionValuePlaceholder": "Digite a descrição normalizada",
+ "notesValuePlaceholder": "ex.: #trabalho #reembolsável",
+ "invalidDescriptionValue": "A descrição é obrigatória e deve ter no máximo 500 caracteres.",
"setPayee": "Atribuir pessoa",
"selectPayee": "Selecionar pessoa...",
"appendNotes": "Adicionar tags/notas",
@@ -882,6 +887,7 @@
"noConditions": "(sem condições)",
"noActions": "(sem ações)",
"fieldDescription": "Descrição",
+ "fieldRawPayee": "Pessoa importada",
"fieldNotes": "Notas",
"fieldAmount": "Valor",
"fieldType": "Tipo",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index afe6938e..6b884c51 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -297,6 +297,7 @@
"monthPrevious": "Mês anterior",
"monthNext": "Próximo mês",
"description": "Descrição",
+ "originalDescription": "Descrição original",
"amount": "Valor",
"status": "Estado",
"date": "Data",
@@ -847,7 +848,7 @@
"duplicateName": "Já existe uma regra com este nome",
"sectionTitle": "Regras de Categorização",
"resetAndReapplyAll": "Redefinir e reaplicar",
- "confirmResetAndReapplyAll": "Redefinir categorias e notas das transações correspondentes e reaplicar todas as regras ativas?",
+ "confirmResetAndReapplyAll": "Redefinir categorias, notas e descrições geridas por regras das transações correspondentes e reaplicar todas as regras ativas?",
"add": "Adicionar",
"created": "Regra criada",
"createdAndApplied": "Regra criada e aplicada a {{count}} transações",
@@ -871,6 +872,10 @@
"blankConditionValue": "Todas as condições precisam de um valor. Uma condição em branco corresponderia a todas as transações.",
"addAction": "Adicionar ação",
"setCategory": "Definir categoria",
+ "setDescription": "Definir descrição",
+ "descriptionValuePlaceholder": "Introduz a descrição normalizada",
+ "notesValuePlaceholder": "ex.: #trabalho #reembolsável",
+ "invalidDescriptionValue": "A descrição é obrigatória e deve ter no máximo 500 caracteres.",
"setPayee": "Atribuir entidade",
"selectPayee": "Selecionar entidade...",
"appendNotes": "Adicionar tags/notas",
@@ -882,6 +887,7 @@
"noConditions": "(sem condições)",
"noActions": "(sem ações)",
"fieldDescription": "Descrição",
+ "fieldRawPayee": "Entidade importada",
"fieldNotes": "Notas",
"fieldAmount": "Valor",
"fieldType": "Tipo",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 4ac4cf5f..5bc1f3a0 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -297,6 +297,7 @@
"monthPrevious": "Предыдущий месяц",
"monthNext": "Следующий месяц",
"description": "Описание",
+ "originalDescription": "Исходное описание",
"amount": "Сумма",
"status": "Статус",
"date": "Дата",
@@ -853,7 +854,7 @@
"duplicateName": "Правило с таким именем уже существует",
"sectionTitle": "Правила категоризации",
"resetAndReapplyAll": "Сбросить и применить заново",
- "confirmResetAndReapplyAll": "Сбросить категории и примечания у совпадающих транзакций, затем заново применить все активные правила?",
+ "confirmResetAndReapplyAll": "Сбросить категории, примечания и описания, изменённые правилами, у совпадающих транзакций, затем заново применить все активные правила?",
"add": "Добавить",
"created": "Правило создано",
"createdAndApplied": "Правило создано и применено к {{count}} транзакциям",
@@ -877,6 +878,10 @@
"blankConditionValue": "Каждому условию нужно значение. Пустое условие совпадёт со всеми транзакциями.",
"addAction": "Добавить действие",
"setCategory": "Установить категорию",
+ "setDescription": "Установить описание",
+ "descriptionValuePlaceholder": "Введите нормализованное описание",
+ "notesValuePlaceholder": "например, #работа #возмещение",
+ "invalidDescriptionValue": "Описание обязательно и должно содержать не более 500 символов.",
"setPayee": "Установить получателя",
"selectPayee": "Выберите получателя...",
"appendNotes": "Добавить теги/примечания",
@@ -888,6 +893,7 @@
"noConditions": "(нет условий)",
"noActions": "(нет действий)",
"fieldDescription": "Описание",
+ "fieldRawPayee": "Импортированный получатель",
"fieldNotes": "Примечания",
"fieldAmount": "Сумма",
"fieldType": "Тип",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 3ec2c516..7fe46bb1 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -297,6 +297,7 @@
"monthPrevious": "Попередній місяць",
"monthNext": "Наступний місяць",
"description": "Опис",
+ "originalDescription": "Початковий опис",
"amount": "Сума",
"status": "Статус",
"date": "Дата",
@@ -853,7 +854,7 @@
"duplicateName": "Правило з такою назвою вже існує",
"sectionTitle": "Правила категоризації",
"resetAndReapplyAll": "Скинути й застосувати заново",
- "confirmResetAndReapplyAll": "Скинути категорії та примітки у відповідних транзакцій, а потім заново застосувати всі активні правила?",
+ "confirmResetAndReapplyAll": "Скинути категорії, примітки й описи, змінені правилами, у відповідних транзакцій, а потім заново застосувати всі активні правила?",
"add": "Додати",
"created": "Правило створено",
"createdAndApplied": "Правило створено й застосовано до {{count}} транзакцій",
@@ -877,6 +878,10 @@
"blankConditionValue": "Кожна умова потребує значення. Порожня умова збігатиметься з усіма транзакціями.",
"addAction": "Додати дію",
"setCategory": "Установити категорію",
+ "setDescription": "Установити опис",
+ "descriptionValuePlaceholder": "Введіть нормалізований опис",
+ "notesValuePlaceholder": "наприклад, #робота #відшкодування",
+ "invalidDescriptionValue": "Опис є обов’язковим і має містити не більше 500 символів.",
"setPayee": "Установити отримувача",
"selectPayee": "Оберіть отримувача...",
"appendNotes": "Додати теги/примітки",
@@ -888,6 +893,7 @@
"noConditions": "(немає умов)",
"noActions": "(немає дій)",
"fieldDescription": "Опис",
+ "fieldRawPayee": "Імпортований отримувач",
"fieldNotes": "Примітки",
"fieldAmount": "Сума",
"fieldType": "Тип",
diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsx
index e22e582c..92273025 100644
--- a/frontend/src/pages/account-detail.tsx
+++ b/frontend/src/pages/account-detail.tsx
@@ -658,6 +658,7 @@ export default function AccountDetailPage() {
: null,
external_id: null,
description: p.description,
+ original_description: null,
amount: p.amount,
currency: p.currency,
date: p.date,
diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsx
index 7c95bac2..267eb852 100644
--- a/frontend/src/pages/rules.tsx
+++ b/frontend/src/pages/rules.tsx
@@ -38,6 +38,7 @@ function SectionHeader({ title, action }: { title: string; action?: React.ReactN
const CONDITION_FIELDS = [
{ value: 'description', label: 'rules.fieldDescription' },
+ { value: 'payee', label: 'rules.fieldRawPayee' },
{ value: 'notes', label: 'rules.fieldNotes' },
{ value: 'amount', label: 'rules.fieldAmount' },
{ value: 'type', label: 'rules.fieldType' },
@@ -104,6 +105,9 @@ function actionSummary(actions: RuleAction[], categories: Category[], payeesList
const p = payeesList.find(p => p.id === a.value)
return p ? `→ ${t('payees.payee')}: ${p.name}` : `→ ${t('payees.payee')}`
}
+ if (a.op === 'set_description') {
+ return `→ ${t('rules.fieldDescription')}: ${a.value}`
+ }
if (a.op === 'append_notes') return `→ ${t('rules.fieldNotes')}: ${a.value}`
if (a.op === 'ignore') return `→ ${t('rules.ignoreAction')}`
return a.op
@@ -348,7 +352,7 @@ export default function RulesPage() {
size="sm"
className="gap-1.5 h-8"
onClick={() => {
- if (window.confirm(t('rules.confirmResetAndReapplyAll', 'Reset matching transaction categories and notes, then reapply all active rules?'))) {
+ if (window.confirm(t('rules.confirmResetAndReapplyAll', 'Reset matching transaction categories, notes, and rule-managed descriptions, then reapply all active rules?'))) {
applyAllMutation.mutate()
}
}}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 9ab444e3..3d54b03d 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -210,6 +210,7 @@ export interface Transaction {
category: Category | null
external_id: string | null
description: string
+ original_description: string | null
amount: number
currency: string
date: string