Open-source personal finance manager. Self-hosted, privacy-first.
feat(rules): preview what a rule would match before saving it (#669)
Paulo Henriquee1b62f03ff8e
diff --git a/backend/app/api/rules.py b/backend/app/api/rules.pyindex e186c3ad..48b835c7 100644--- a/backend/app/api/rules.py+++ b/backend/app/api/rules.py@@ -16,6 +16,8 @@ from app.schemas.rule import (RuleImportRequest,RuleImportResponse,RuleMutationResponse,+ RulePreviewRequest,+ RulePreviewResponse,RuleRead,RuleUpdate,)@@ -108,6 +110,31 @@ async def create_rule(return response[email protected]("/preview", response_model=RulePreviewResponse)+async def preview_rule(+ data: RulePreviewRequest,+ ctx: WorkspaceContext = Depends(current_workspace),+ session: AsyncSession = Depends(get_async_session),+):+ """Show which existing transactions a draft rule would match, and how it+ would change them, without saving anything."""+ try:+ return await rule_service.preview_rule(+ session,+ ctx.workspace.id,+ data.conditions_op,+ [c.model_dump() for c in data.conditions],+ [a.model_dump() for a in data.actions],+ is_active=data.is_active,+ apply_to_existing=data.apply_to_existing,+ overwrite_existing_categories=data.overwrite_existing_categories,+ limit=data.limit,+ offset=data.offset,+ )+ except ValueError as e:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))++@router.get("/export")async def export_rules(ctx: WorkspaceContext = Depends(current_workspace),diff --git a/backend/app/schemas/rule.py b/backend/app/schemas/rule.pyindex 0be0abd9..e1cfcc23 100644--- a/backend/app/schemas/rule.py+++ b/backend/app/schemas/rule.py@@ -1,8 +1,9 @@# backend/app/schemas/rule.py+import datetimeimport uuidfrom typing import Any, Optional, Union-from pydantic import BaseModel, ConfigDict, field_validator+from pydantic import BaseModel, ConfigDict, Field, field_validatorclass RuleCondition(BaseModel):@@ -132,3 +133,59 @@ class RuleImportResponse(BaseModel):imported: intskipped: intoverwritten: int+++class RulePreviewRequest(BaseModel):+ """A draft rule sent from the editor, before it is saved.++ Carries the same save-time flags as `RuleCreate` — the preview answers+ "what happens when I save this?", and saving an inactive rule, or one not+ being applied to existing transactions, changes nothing right now.+ Name and priority play no part: neither decides what a rule matches.+ """++ conditions_op: str = "and"+ conditions: list[RuleConditionNode]+ actions: list[RuleAction] = []+ is_active: bool = True+ apply_to_existing: bool = True+ overwrite_existing_categories: bool = False+ limit: int = Field(default=20, ge=1, le=100)+ # The sample is a window over the matches, newest first. Counts are exact+ # whatever the window is, so the editor pages through a broad rule's+ # matches instead of judging it by the first screenful.+ offset: int = Field(default=0, ge=0)+++class RulePreviewItem(BaseModel):+ """One matched transaction plus the category the draft rule would leave it in."""++ id: uuid.UUID+ date: datetime.date+ description: str+ # float, not Decimal: this is display data for the editor's preview table,+ # and Decimal would serialize as a JSON string the UI has to coerce back.+ amount: float+ currency: str+ type: str+ current_category_id: Optional[uuid.UUID] = None+ current_category_name: Optional[str] = None+ new_category_id: Optional[uuid.UUID] = None+ new_category_name: Optional[str] = None+ # False when the rule matches but leaves the transaction as it is — most+ # often because it already has a category and the draft does not overwrite.+ will_change: bool+++class RulePreviewResponse(BaseModel):+ matched: int+ will_change: int+ # False when the draft's own flags mean saving it touches nothing now: an+ # inactive rule, or one not being applied to existing transactions. The+ # matches are still reported, so the conditions can be checked either way.+ will_apply: bool+ # The requested window of the matches — `offset` through `offset + limit`,+ # newest first. Compare `offset + len(sample)` with `matched` to know+ # whether more can be fetched.+ sample: list[RulePreviewItem]+ offset: int = 0diff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.pyindex 18377cdc..c6ea782e 100644--- a/backend/app/services/rule_service.py+++ b/backend/app/services/rule_service.py@@ -4,18 +4,30 @@ from typing import Any, Optional, castfrom sqlalchemy import delete, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import load_onlyfrom app.models.rule import Rulefrom app.models.category import Categoryfrom app.models.payee import Payeefrom app.models.transaction import Transaction-from app.schemas.rule import RuleCreate, RuleExportPayload, RuleImportResponse, RuleUpdate++from app.schemas.rule import (+ RuleCreate,+ RuleExportPayload,+ RuleImportResponse,+ RulePreviewItem,+ RulePreviewResponse,+ RuleUpdate,+)+from app.services.category_service import get_hidden_category_ids+from app.services.rule_engine import (apply_rule_actions,compile_rule_regex,evaluate_conditions,)+from app.services.category_service import DEFAULT_CATEGORIES_I18N@@ -1095,6 +1107,31 @@ async def _get_existing_rule_names_for_workspace(return {row[0] for row in result.all()}+# Exactly the columns `_rule_preview` copies. Anything reading a column that is+# not here off a transaction loaded with `load_only(*_PREVIEW_COLUMNS)` would+# trigger a lazy refresh — which raises under async — so the two lists move+# together.+_PREVIEW_COLUMNS = (+ Transaction.user_id,+ Transaction.workspace_id,+ Transaction.account_id,+ Transaction.category_id,+ Transaction.description,+ Transaction.original_description,+ Transaction.description_is_rule_managed,+ Transaction.amount,+ Transaction.currency,+ Transaction.date,+ Transaction.type,+ Transaction.source,+ Transaction.status,+ Transaction.payee,+ Transaction.payee_id,+ Transaction.notes,+ Transaction.is_ignored,+)++def _rule_preview(transaction: Transaction) -> Transaction:"""Build a detached transaction-shaped object for side-effect-free rule evaluation."""return Transaction(@@ -1189,6 +1226,141 @@ async def apply_rules_to_transaction()+def _rule_effect_state(tx: Transaction) -> tuple:+ """Everything rule actions can write, for a before/after comparison.++ Mirrors the tuple `apply_single_rule` compares, so a preview counts a+ transaction as changed exactly when saving the rule would change it.+ """+ return (+ tx.category_id,+ tx.payee_id,+ tx.description,+ tx.original_description,+ tx.description_is_rule_managed,+ tx.notes,+ tx.is_ignored,+ )+++async def preview_rule(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ conditions_op: str,+ conditions: list,+ actions: list,+ is_active: bool = True,+ apply_to_existing: bool = True,+ overwrite_existing_categories: bool = False,+ limit: int = 20,+ offset: int = 0,+) -> RulePreviewResponse:+ """Report which existing transactions an unsaved rule would match.++ Read-only counterpart of `apply_single_rule`: same transaction scope, same+ engine, same overwrite semantics — so the table the editor shows is exactly+ what saving the rule would produce. Returns the full match/change counts+ plus one window of the matches — `limit` of them from `offset`, newest+ first — so a rule matching thousands of rows can be paged through rather+ than judged by its first screenful. Every match is evaluated whatever the+ window is, which is what keeps the counts exact.++ That means honouring the two gates the save path applies before any rule+ touches history: `apply_single_rule` does nothing for an inactive rule, and+ the create/update endpoints only call it when `apply_to_existing` is set.+ With either off, the matches are still listed — they are what the+ conditions select, which is worth seeing — but nothing is reported as+ changing, because saving would change nothing.+ """+ will_apply = is_active and apply_to_existing+ await _validate_rule_definition(session, workspace_id, conditions, actions or [])++ # Every transaction is evaluated in Python, so only the columns the engine+ # reads and `_rule_preview` copies are worth fetching — notably not+ # `raw_data`, whose provider payloads dwarf the rest of the row and which+ # no condition or action can see.+ result = await session.execute(+ select(Transaction)+ .options(load_only(*_PREVIEW_COLUMNS))+ .where(+ Transaction.workspace_id == workspace_id,+ Transaction.source != "opening_balance",+ )+ # `id` breaks date ties, so the match list is in the same order for+ # every window: without a total order two rows sharing a date could+ # swap between requests and be shown twice, or skipped, while paging.+ .order_by(Transaction.date.desc(), Transaction.id.desc())+ )+ transactions = result.scalars().all()++ category_rows = await session.execute(+ select(Category.id, Category.name).where(Category.workspace_id == workspace_id)+ )+ category_names = {row.id: row.name for row in category_rows}++ action_dicts = [+ action if isinstance(action, dict) else action.model_dump() for action in actions or []+ ]++ matched = 0+ changed = 0+ sample: list[RulePreviewItem] = []++ for tx in transactions:+ matches = evaluate_conditions(conditions_op, conditions or [], tx)+ # A rule that renamed this row before should still recognise it, so a+ # miss is retried against the original text — same as apply_single_rule.+ if not matches and tx.original_description is not None:+ original_target = _rule_preview(tx)+ original_target.description = tx.original_description+ matches = evaluate_conditions(conditions_op, conditions or [], original_target)+ if not matches:+ continue+ matched += 1+ # An untouched copy when nothing is applied, so `new_category_*` below+ # simply mirrors what the transaction already has.+ draft = _rule_preview(tx)+ will_change = False+ if will_apply:+ before = _rule_effect_state(draft)+ apply_rule_actions(+ action_dicts,+ draft,+ category_already_set=tx.category_id is not None+ and not overwrite_existing_categories,+ skip_description=_has_manual_description(tx),+ )+ will_change = _rule_effect_state(draft) != before+ if will_change:+ changed += 1+ # `matched` has just counted this row, so `matched - 1` is its index+ # in the match list the window is cut from.+ if offset <= matched - 1 < offset + limit:+ sample.append(+ RulePreviewItem(+ id=tx.id,+ date=tx.date,+ description=tx.description,+ amount=tx.amount,+ currency=tx.currency,+ type=tx.type,+ current_category_id=tx.category_id,+ current_category_name=category_names.get(tx.category_id),+ new_category_id=draft.category_id,+ new_category_name=category_names.get(draft.category_id),+ will_change=will_change,+ )+ )++ return RulePreviewResponse(+ matched=matched,+ will_change=changed,+ will_apply=will_apply,+ sample=sample,+ offset=offset,+ )++async def apply_single_rule(session: AsyncSession,workspace_id: uuid.UUID,diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.pyindex 19199c7c..473609b1 100644--- a/backend/tests/test_new_rules_api.py+++ b/backend/tests/test_new_rules_api.py@@ -1134,3 +1134,232 @@ async def test_grouped_rules_survive_export_import(conditions = next(r["conditions"] for r in listed if r["name"] == "Rides")assert conditions[1]["op"] == "or"assert [c["value"] for c in conditions[1]["conditions"]] == ["UBER", "99POP"]+++async def test_preview_rule_reports_matches_without_saving(+ client: AsyncClient, auth_headers, test_categories, test_transactions+):+ """Preview an unsaved rule: it reports matches but changes nothing."""+ target = test_categories[0]+ response = await client.post(+ "/api/rules/preview",+ json={+ "conditions_op": "and",+ "conditions": [{"field": "description", "op": "contains", "value": "NETFLIX"}],+ "actions": [{"op": "set_category", "value": str(target.id)}],+ },+ headers=auth_headers,+ )+ assert response.status_code == 200+ data = response.json()+ assert data["matched"] == 1+ assert data["will_change"] == 1++ item = data["sample"][0]+ assert item["description"] == "NETFLIX"+ assert item["amount"] == 39.90+ assert item["current_category_id"] is None+ assert item["new_category_name"] == target.name+ assert item["will_change"] is True++ # Nothing was persisted and no rule was created.+ assert (await client.get("/api/rules", headers=auth_headers)).json() == []+ txn = (await client.get(f"/api/transactions/{item['id']}", headers=auth_headers)).json()+ assert txn["category_id"] is None+++async def test_preview_rule_flags_already_categorized_as_unchanged(+ client: AsyncClient, auth_headers, test_categories, test_transactions+):+ """A match that keeps its category is reported as matched but unchanged."""+ body = {+ "conditions_op": "and",+ "conditions": [{"field": "description", "op": "contains", "value": "UBER"}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ }++ data = (await client.post("/api/rules/preview", json=body, headers=auth_headers)).json()+ assert data["matched"] == 1+ assert data["will_change"] == 0+ item = data["sample"][0]+ assert item["will_change"] is False+ # Without overwrite the transaction keeps the category it already has.+ assert item["new_category_name"] == item["current_category_name"] == test_categories[1].name++ overwritten = (+ await client.post(+ "/api/rules/preview",+ json={**body, "overwrite_existing_categories": True},+ headers=auth_headers,+ )+ ).json()+ assert overwritten["matched"] == 1+ assert overwritten["will_change"] == 1+ assert overwritten["sample"][0]["new_category_name"] == test_categories[0].name+++async def test_preview_rule_honors_condition_groups_and_sample_limit(+ client: AsyncClient, auth_headers, test_categories, test_transactions+):+ response = await client.post(+ "/api/rules/preview",+ json={+ "conditions_op": "and",+ "conditions": [+ {"field": "type", "op": "equals", "value": "debit"},+ {"op": "or", "conditions": [+ {"field": "description", "op": "contains", "value": "UBER"},+ {"field": "description", "op": "contains", "value": "NETFLIX"},+ ]},+ ],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ "limit": 1,+ },+ headers=auth_headers,+ )+ assert response.status_code == 200+ data = response.json()+ assert data["matched"] == 2+ # The sample is capped by `limit`, the counts still cover every match.+ assert len(data["sample"]) == 1+++async def test_preview_rule_pages_through_the_matches(+ client: AsyncClient, auth_headers, test_categories, test_transactions+):+ """Every match is reachable, one window at a time.++ A rule matching four figures of transactions is exactly the one worth+ inspecting, so the sample has to be pageable rather than a fixed first+ screenful. The windows tile the match list without gaps or repeats, and+ the counts stay exact whichever window is asked for.+ """+ body = {+ "conditions_op": "and",+ "conditions": [{"field": "amount", "op": "gt", "value": "0"}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ "limit": 2,+ }++ seen: list[str] = []+ for offset in (0, 2, 4):+ data = (+ await client.post(+ "/api/rules/preview",+ json={**body, "offset": offset},+ headers=auth_headers,+ )+ ).json()+ assert data["matched"] == len(test_transactions)+ assert data["offset"] == offset+ seen.extend(item["id"] for item in data["sample"])++ # Three windows of two over five matches: 2 + 2 + 1, every row once.+ assert len(seen) == len(set(seen)) == len(test_transactions)+ assert set(seen) == {str(tx.id) for tx in test_transactions}++ # Past the end is empty, not an error — the counts still come back.+ past_end = (+ await client.post(+ "/api/rules/preview",+ json={**body, "offset": len(test_transactions)},+ headers=auth_headers,+ )+ ).json()+ assert past_end["matched"] == len(test_transactions)+ assert past_end["sample"] == []+++ "action, detail",+ [+ ({"op": "set_category", "value": "not-a-uuid"}, "Category not found"),+ ({"op": "set_payee", "value": str(uuid.uuid4())}, "Payee not found"),+ ({"op": "set_description", "value": " "}, "Description cannot be blank"),+ ],+)+async def test_preview_rule_validates_actions_like_the_save_path(+ client: AsyncClient, auth_headers, test_transactions, action, detail+):+ """The preview runs the draft's actions, so it has to vet them first.++ Otherwise a malformed action reaches `apply_rule_actions` unvalidated and+ the preview quietly reports the no-op it degrades into, rather than the+ error the same draft would raise on save.+ """+ response = await client.post(+ "/api/rules/preview",+ json={+ "conditions_op": "and",+ "conditions": [{"field": "description", "op": "contains", "value": "UBER"}],+ "actions": [action],+ },+ headers=auth_headers,+ )+ assert response.status_code == 400+ assert response.json()["detail"] == detail+++async def test_preview_rule_rejects_blank_condition_value(+ client: AsyncClient, auth_headers, test_categories+):+ response = await client.post(+ "/api/rules/preview",+ json={+ "conditions_op": "and",+ "conditions": [{"field": "description", "op": "contains", "value": " "}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ },+ headers=auth_headers,+ )+ assert response.status_code == 422+++ "flags, reason",+ [+ ({"is_active": False}, "an inactive rule is never applied"),+ ({"apply_to_existing": False}, "existing transactions are left alone"),+ ],+)+async def test_preview_rule_reports_no_change_when_the_draft_would_not_be_applied(+ client: AsyncClient, auth_headers, test_categories, test_transactions, flags, reason+):+ """The preview forecasts saving, and these flags mean saving changes nothing.++ The matches still come back — they are what the conditions select, and that+ is worth seeing while writing the rule — but nothing is reported as+ changing, because `apply_single_rule` would not run at all.+ """+ target = test_categories[0]+ body = {+ "conditions_op": "and",+ "conditions": [{"field": "description", "op": "contains", "value": "NETFLIX"}],+ "actions": [{"op": "set_category", "value": str(target.id)}],+ }++ data = (+ await client.post("/api/rules/preview", json={**body, **flags}, headers=auth_headers)+ ).json()+ assert data["matched"] == 1, reason+ assert data["will_change"] == 0+ assert data["will_apply"] is False+ item = data["sample"][0]+ assert item["will_change"] is False+ # Nothing is applied, so the row keeps the category it already has.+ assert item["new_category_id"] == item["current_category_id"] is None++ # Same draft with the flag on: the match is now a change.+ applied = (+ await client.post("/api/rules/preview", json=body, headers=auth_headers)+ ).json()+ assert applied["will_apply"] is True+ assert applied["will_change"] == 1+ assert applied["sample"][0]["new_category_name"] == target.namediff --git a/backend/tests/test_write_permission_coverage.py b/backend/tests/test_write_permission_coverage.pyindex 114a7143..51305892 100644--- a/backend/tests/test_write_permission_coverage.py+++ b/backend/tests/test_write_permission_coverage.py@@ -74,6 +74,9 @@ ALLOWLIST: dict[tuple[str, str], str] = {# Same shape for investment orders: the upload has to be a body, and the# dry run only reports what an import would do.("POST", "/api/assets/import/preview"): "parses an upload and returns a preview; writes nothing",+ # And for a rule being written: the draft has to be a body, and the answer+ # is which existing transactions it would match. Reads rules' own scope.+ ("POST", "/api/rules/preview"): "evaluates an unsaved rule against transactions; writes nothing",# A read that has to be a POST: the backup password belongs in a body,# not in a query string. Same read permission as GET /api/export/backup.("POST", "/api/export/backup"): "exports the workspace it can already read; writes nothing",diff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsxindex 2643e09e..313e8880 100644--- a/frontend/src/components/rule-dialog.tsx+++ b/frontend/src/components/rule-dialog.tsx@@ -1,7 +1,12 @@-import { useMemo, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useInfiniteQuery } from '@tanstack/react-query'import { getAccountName, sortAccountsByDisplayName } from '@/lib/account-utils'-import { isInvalidDescriptionAction, parseRulePriority } from '@/lib/rule-form-utils'+import { isInvalidDescriptionAction, parseRulePriority, previewableActions } from '@/lib/rule-form-utils'+import { rules as rulesApi } from '@/lib/api'+import { formatCurrency } from '@/lib/format'+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'+import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'import { Button } from '@/components/ui/button'@@ -12,7 +17,7 @@ import {DialogTitle,DialogFooter,} from '@/components/ui/dialog'-import { X, Plus } from 'lucide-react'+import { X, Plus, ChevronDown, Eye, ArrowRight } from 'lucide-react'import { cn } from '@/lib/utils'import { CategorySelect } from '@/components/category-select'import { flattenConditions, isConditionGroup } from '@/lib/rule-conditions'@@ -193,6 +198,212 @@ function ConditionRow({)}+/** Rows per preview request. Each one re-evaluates the whole ledger, so the+ * page is large enough that reading through a broad rule's matches is a few+ * requests rather than dozens. The API caps it at 100. */+const PREVIEW_PAGE_SIZE = 50++/** Collapsible "what would this rule do?" panel.+ *+ * Matching runs on the backend against the same engine that applies rules, so+ * the table shows exactly what saving the draft would produce — including the+ * transactions it matches but leaves untouched because they already have a+ * category. The counts cover every match; the table is one window of them at a+ * time, so a broad rule — the kind this panel exists to catch before it is+ * saved — can be read through rather than judged by its first screenful. Any+ * edit to the draft collapses the panel rather than leaving a stale table on+ * screen.+ */+function RulePreviewPanel({+ conditionsOp, conditions, actions, isActive, applyToExisting, overwriteExistingCategories,+ disabled, open, onOpenChange,+}: {+ conditionsOp: 'and' | 'or'+ conditions: RuleConditionNode[]+ actions: RuleAction[]+ // The save-time flags go to the backend too: an inactive rule, or one not+ // being applied to existing transactions, changes nothing when saved, and+ // the preview has to say so rather than promise changes that won't happen.+ isActive: boolean+ applyToExisting: boolean+ overwriteExistingCategories: boolean+ disabled: boolean+ // Open state lives in the parent: the dialog widens while the table is+ // expanded, so both have to react to the same toggle.+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const { mask } = usePrivacyMode()++ // A half-filled action row is a draft in progress, not a rule to reject, so+ // it is left out of the request the backend validates.+ const draftActions = useMemo(() => previewableActions(actions), [actions])++ // Keyed on the whole draft, so flipping a flag refetches while the panel+ // stays open — and a slower response for a previous draft can never land on+ // top of the current one. Paged, because a rule matching four figures of+ // transactions is one worth reading past the first page of.+ const preview = useInfiniteQuery({+ queryKey: [+ 'rule-preview', conditionsOp, conditions, draftActions,+ isActive, applyToExisting, overwriteExistingCategories,+ ],+ queryFn: ({ pageParam }) => rulesApi.preview({+ conditions_op: conditionsOp,+ conditions,+ actions: draftActions,+ is_active: isActive,+ apply_to_existing: applyToExisting,+ overwrite_existing_categories: overwriteExistingCategories,+ limit: PREVIEW_PAGE_SIZE,+ offset: pageParam,+ }),+ initialPageParam: 0,+ // The counts are exact whatever window came back, so what is already on+ // screen is the offset of the next page.+ getNextPageParam: (lastPage, pages) => {+ const shown = pages.reduce((total, page) => total + page.sample.length, 0)+ return shown < lastPage.matched ? shown : undefined+ },+ enabled: open,+ staleTime: Infinity,+ gcTime: 0,+ })++ // Editing the rule itself collapses the panel rather than leaving a table+ // that describes a draft the user has moved on from. The flags don't: their+ // whole point is watching the numbers move.+ useEffect(() => {+ onOpenChange(false)+ }, [conditionsOp, conditions, actions, onOpenChange])++ // Every page carries the same counts; the rows accumulate.+ const data = preview.data?.pages[0]+ const sample = useMemo(+ () => preview.data?.pages.flatMap(page => page.sample) ?? [],+ [preview.data],+ )++ return (+ <div className="rounded-lg border border-border">+ <button+ type="button"+ disabled={disabled}+ aria-expanded={open}+ className="flex w-full items-center justify-between gap-2 px-3 py-2 text-sm text-foreground transition-colors hover:bg-muted/60 disabled:cursor-not-allowed disabled:opacity-50"+ onClick={() => onOpenChange(!open)}+ >+ <span className="flex items-center gap-1.5 font-medium">+ <Eye size={13} /> {t('rules.preview')}+ </span>+ <span className="flex items-center gap-2 text-xs text-muted-foreground">+ {data && t('rules.previewMatched', { matched: data.matched })}+ <ChevronDown size={14} className={cn('transition-transform', open && 'rotate-180')} />+ </span>+ </button>++ {open && (+ <div className="border-t border-border p-3">+ {preview.isError ? (+ <p className="text-xs text-rose-500">{t('rules.previewError')}</p>+ ) : /* also while a flag change is being recomputed: the old numbers+ no longer describe the flags now on screen. Fetching a further+ page is not that — those rows are appended to a table that is+ still current. */+ !data || (preview.isFetching && !preview.isFetchingNextPage) ? (+ <p className="text-xs text-muted-foreground">{t('common.loading')}</p>+ ) : data.matched === 0 ? (+ <p className="text-xs text-muted-foreground">{t('rules.previewEmpty')}</p>+ ) : (+ <div className="space-y-2">+ <p className="text-xs text-muted-foreground">+ {t('rules.previewSummary', { matched: data.matched, changed: data.will_change })}+ {!data.will_apply && (+ <> · <span className="font-medium text-amber-600 dark:text-amber-400">+ {isActive ? t('rules.previewNotAppliedToExisting') : t('rules.previewInactive')}+ </span></>+ )}+ {sample.length < data.matched && (+ <> · {t('rules.previewSampleNote', { shown: sample.length })}</>+ )}+ </p>+ <div className="max-h-56 overflow-y-auto overflow-x-auto">+ <table className="w-full text-xs">+ <thead className="sticky top-0 bg-card text-muted-foreground">+ <tr className="border-b border-border text-left">+ <th className="py-1.5 pr-2 font-medium">{t('transactions.date')}</th>+ <th className="py-1.5 pr-2 font-medium">{t('transactions.description')}</th>+ <th className="py-1.5 pr-2 text-right font-medium">{t('transactions.amount')}</th>+ <th className="py-1.5 font-medium">{t('transactions.category')}</th>+ </tr>+ </thead>+ <tbody className="divide-y divide-border">+ {sample.map(item => (+ <tr key={item.id} className={cn(!item.will_change && 'text-muted-foreground')}>+ <td className="whitespace-nowrap py-1.5 pr-2 tabular-nums">+ {new Date(item.date + 'T00:00:00').toLocaleDateString(dateLocale)}+ </td>+ <td className="max-w-[22rem] truncate py-1.5 pr-2" title={item.description}>+ {item.description}+ </td>+ <td className={cn(+ 'whitespace-nowrap py-1.5 pr-2 text-right tabular-nums',+ item.will_change && item.type === 'credit' && 'text-emerald-600',+ )}>+ {mask(formatCurrency(Math.abs(item.amount), item.currency, locale))}+ </td>+ <td className="py-1.5">+ {item.will_change ? (+ <span className="flex items-center gap-1">+ <span className="truncate">+ {item.current_category_name ?? t('transactions.uncategorized')}+ </span>+ <ArrowRight size={11} className="shrink-0 text-muted-foreground" />+ <span className="truncate font-medium text-emerald-600">+ {item.new_category_name ?? t('transactions.uncategorized')}+ </span>+ </span>+ ) : (+ <span className="flex items-center gap-1">+ <span className="truncate">+ {item.current_category_name ?? t('transactions.uncategorized')}+ </span>+ <span className="shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-semibold">+ {t('rules.previewNoChange')}+ </span>+ </span>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ {preview.hasNextPage && (+ <button+ type="button"+ className="w-full rounded-md border border-border py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-muted/60 disabled:cursor-not-allowed disabled:opacity-50"+ disabled={preview.isFetchingNextPage}+ onClick={() => preview.fetchNextPage()}+ >+ {preview.isFetchingNextPage+ ? t('common.loading')+ : t('rules.previewLoadMore', {+ more: Math.min(PREVIEW_PAGE_SIZE, data.matched - sample.length),+ })}+ </button>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ )+}+export interface RuleDialogInitialData {name?: stringconditions?: RuleConditionNode[]@@ -232,6 +443,7 @@ export function RuleDialog({const [isActive, setIsActive] = useState(rule?.is_active ?? true)const [applyToExisting, setApplyToExisting] = useState(!rule)const [overwriteExistingCategories, setOverwriteExistingCategories] = useState(false)+ const [previewOpen, setPreviewOpen] = useState(false)function updateCondition(i: number, field: keyof RuleCondition, val: string | number) {setConditions(prev => prev.map((node, idx) => (@@ -327,7 +539,12 @@ export function RuleDialog({<Dialog open={open} onOpenChange={onClose}><DialogContentaria-describedby={undefined}- className="max-w-2xl max-h-[90vh] overflow-y-auto overflow-x-hidden"+ className={cn(+ // The preview table needs room to breathe, so the dialog widens while+ // it is expanded — same idiom as the transaction dialog's preview pane.+ 'max-h-[90vh] overflow-y-auto overflow-x-hidden transition-[max-width] duration-300',+ previewOpen ? 'sm:max-w-5xl max-w-2xl' : 'sm:max-w-2xl max-w-2xl',+ )}><DialogHeader><DialogTitle>{rule ? t('rules.editRule') : t('rules.newRule')}</DialogTitle>@@ -560,6 +777,18 @@ export function RuleDialog({</label>)}+ <RulePreviewPanel+ conditionsOp={conditionsOp}+ conditions={conditions}+ actions={actions}+ isActive={isActive}+ applyToExisting={applyToExisting}+ overwriteExistingCategories={overwriteExistingCategories}+ disabled={hasBlankCondition || conditions.length === 0}+ open={previewOpen}+ onOpenChange={setPreviewOpen}+ />+<DialogFooter><Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}</Button><Button type="submit" disabled={loading || hasBlankCondition}>diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex fc64deb0..a8d11cd7 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -25,8 +25,11 @@ import type {Budget,BudgetVsActual,Rule,+ RuleAction,+ RuleConditionNode,RuleExportPayload,RuleImportResponse,+ RulePreviewResponse,ImportLog,ImportPreviewTransaction,PayeeTaxId,@@ -928,6 +931,21 @@ export const rules = {delete: async (id: string): Promise<void> => {await api.delete(`/rules/${id}`)},+ preview: async (draft: {+ conditions_op: 'and' | 'or'+ conditions: RuleConditionNode[]+ actions: RuleAction[]+ is_active?: boolean+ apply_to_existing?: boolean+ overwrite_existing_categories?: boolean+ /** One window of the matches: `limit` of them starting at `offset`,+ * newest first. The counts are exact whatever the window is. */+ limit?: number+ offset?: number+ }): Promise<RulePreviewResponse> => {+ const { data } = await api.post('/rules/preview', draft)+ return data+ },applyAll: async (): Promise<{ applied: number }> => {const { data } = await api.post('/rules/apply-all')return datadiff --git a/frontend/src/lib/rule-form-utils.test.ts b/frontend/src/lib/rule-form-utils.test.tsindex 1f912027..9462ecc9 100644--- a/frontend/src/lib/rule-form-utils.test.ts+++ b/frontend/src/lib/rule-form-utils.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest'-import { isInvalidDescriptionAction, parseRulePriority } from './rule-form-utils'+import type { RuleAction } from '../types'++import { isInvalidDescriptionAction, parseRulePriority, previewableActions } from './rule-form-utils'describe('isInvalidDescriptionAction', () => {it('validates each description action independently', () => {@@ -12,6 +14,25 @@ describe('isInvalidDescriptionAction', () => {})})+describe('previewableActions', () => {+ it('drops the half-filled rows a draft carries while it is being written', () => {+ expect(previewableActions([+ { op: 'set_category', value: '' },+ { op: 'set_payee', value: ' ' },+ { op: 'set_description', value: 'x'.repeat(501) },+ ])).toEqual([])+ })++ it('keeps completed actions, and `ignore`, which has no value', () => {+ const actions: RuleAction[] = [+ { op: 'set_category', value: 'cat-1' },+ { op: 'ignore', value: '' },+ { op: 'set_category', value: '' },+ ]+ expect(previewableActions(actions)).toEqual([actions[0], actions[1]])+ })+})+describe('parseRulePriority', () => {it('uses zero for a temporarily blank priority', () => {expect(parseRulePriority('')).toBe(0)diff --git a/frontend/src/lib/rule-form-utils.ts b/frontend/src/lib/rule-form-utils.tsindex 8637907f..19e1a6e4 100644--- a/frontend/src/lib/rule-form-utils.ts+++ b/frontend/src/lib/rule-form-utils.ts@@ -6,6 +6,24 @@ export function isInvalidDescriptionAction(action: RuleAction): boolean {return value === '' || value.length > 500}+/** The actions a draft is complete enough to preview.+ *+ * The editor holds an action row from the moment it is added, so a draft in+ * progress routinely carries `set_category` with nothing picked yet. That is a+ * rule still being written, not a broken one — the engine already treats it as+ * a no-op — and the preview should keep answering the question about the+ * conditions instead of failing the backend's action validation. Actions the+ * form itself flags are dropped for the same reason: the inline error already+ * says what is wrong. `ignore` carries no value at all.+ */+export function previewableActions(actions: RuleAction[]): RuleAction[] {+ return actions.filter((action) => {+ if (action.op === 'ignore') return true+ if (isInvalidDescriptionAction(action)) return false+ return String(action.value ?? '').trim() !== ''+ })+}+export function parseRulePriority(value: string): number {if (value.trim() === '') return 0const priority = Number(value)diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex cc217cce..f314afaa 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -853,6 +853,16 @@"confirmDeleteDescription": "Die wiederkehrende Transaktion \"{{description}}\" wird dauerhaft gelöscht. Vorhandene Transaktionen bleiben bestehen, verlieren jedoch ihre Verknüpfung zur wiederkehrenden Transaktion. Diese Aktion kann nicht rückgängig gemacht werden."},"rules": {+ "preview": "Vorschau",+ "previewMatched": "{{matched}} Treffer",+ "previewSummary": "{{matched}} passende Transaktionen · {{changed}} würden geändert",+ "previewSampleNote": "die {{shown}} neuesten werden angezeigt",+ "previewLoadMore": "{{more}} weitere laden",+ "previewNoChange": "keine Änderung",+ "previewEmpty": "Keine Transaktion erfüllt diese Bedingungen",+ "previewInactive": "Regel ist inaktiv, es ändert sich noch nichts",+ "previewNotAppliedToExisting": "wird nicht auf bestehende Transaktionen angewendet",+ "previewError": "Vorschau konnte nicht geladen werden","section": "Automatisierung","packs": "Regelpakete","packRuleCount": "{{count}} Regeln",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 019828bd..a5a603ec 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -852,6 +852,16 @@"confirmDeleteDescription": "The recurring definition \"{{description}}\" will be permanently deleted. Existing transactions will remain but lose their recurring link. This action cannot be undone."},"rules": {+ "preview": "Preview",+ "previewMatched": "{{matched}} matches",+ "previewSummary": "{{matched}} matching transactions · {{changed}} would change",+ "previewSampleNote": "showing the {{shown}} most recent",+ "previewLoadMore": "Load {{more}} more",+ "previewNoChange": "no change",+ "previewEmpty": "No transaction matches these conditions",+ "previewInactive": "rule is inactive, nothing changes yet",+ "previewNotAppliedToExisting": "not applied to existing transactions",+ "previewError": "Could not load the preview","section": "Automation","packs": "Rule Packs","packRuleCount": "{{count}} rules",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 9e9d2da8..4ae5926a 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -853,6 +853,16 @@"confirmDeleteDescription": "La definición recurrente \"{{description}}\" se eliminará permanentemente. Las transacciones existentes permanecerán, pero perderán su vínculo recurrente. Esta acción no se puede deshacer."},"rules": {+ "preview": "Vista previa",+ "previewMatched": "{{matched}} coincidencias",+ "previewSummary": "{{matched}} transacciones coinciden · {{changed}} cambiarían",+ "previewSampleNote": "mostrando las {{shown}} más recientes",+ "previewLoadMore": "Cargar {{more}} más",+ "previewNoChange": "sin cambios",+ "previewEmpty": "Ninguna transacción coincide con estas condiciones",+ "previewInactive": "la regla está inactiva, aún no cambia nada",+ "previewNotAppliedToExisting": "no se aplica a las transacciones existentes",+ "previewError": "No se pudo cargar la vista previa","section": "Automatización","packs": "Paquetes de reglas","packRuleCount": "{{count}} reglas",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 0e2c3581..55d30c3e 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -853,6 +853,16 @@"confirmDeleteDescription": "La définition récurrente « {{description}} » sera définitivement supprimée. Les transactions existantes resteront, mais perdront leur lien récurrent. Cette action est irréversible."},"rules": {+ "preview": "Aperçu",+ "previewMatched": "{{matched}} correspondances",+ "previewSummary": "{{matched}} transactions correspondent · {{changed}} seraient modifiées",+ "previewSampleNote": "affichage des {{shown}} plus récentes",+ "previewLoadMore": "Charger {{more}} de plus",+ "previewNoChange": "aucun changement",+ "previewEmpty": "Aucune transaction ne correspond à ces conditions",+ "previewInactive": "règle inactive, rien ne change pour l'instant",+ "previewNotAppliedToExisting": "non appliquée aux transactions existantes",+ "previewError": "Impossible de charger l'aperçu","section": "Automatisation","packs": "Packs de règles","packRuleCount": "{{count}} règles",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex c8348cd4..c0d089dd 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -853,6 +853,16 @@"confirmDeleteDescription": "La definizione ricorrente \"{{description}}\" verrà eliminata definitivamente. Le transazioni esistenti rimarranno, ma perderanno il collegamento ricorrente. Questa azione non può essere annullata."},"rules": {+ "preview": "Anteprima",+ "previewMatched": "{{matched}} corrispondenze",+ "previewSummary": "{{matched}} transazioni corrispondono · {{changed}} verrebbero modificate",+ "previewSampleNote": "mostrando le {{shown}} più recenti",+ "previewLoadMore": "Carica altri {{more}}",+ "previewNoChange": "nessuna modifica",+ "previewEmpty": "Nessuna transazione corrisponde a queste condizioni",+ "previewInactive": "regola inattiva, per ora non cambia nulla",+ "previewNotAppliedToExisting": "non applicata alle transazioni esistenti",+ "previewError": "Impossibile caricare l'anteprima","section": "Automazione","packs": "Pacchetti di regole","packRuleCount": "{{count}} regole",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex e606faed..f121cb22 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -853,6 +853,16 @@"confirmDeleteDescription": "De terugkerende definitie \"{{description}}\" wordt permanent verwijderd. Bestaande transacties blijven bestaan, maar verliezen hun koppeling met de terugkerende transactie. Deze actie kan niet ongedaan worden gemaakt."},"rules": {+ "preview": "Voorbeeld",+ "previewMatched": "{{matched}} overeenkomsten",+ "previewSummary": "{{matched}} overeenkomende transacties · {{changed}} zouden wijzigen",+ "previewSampleNote": "de {{shown}} meest recente worden getoond",+ "previewLoadMore": "{{more}} meer laden",+ "previewNoChange": "geen wijziging",+ "previewEmpty": "Geen transactie voldoet aan deze voorwaarden",+ "previewInactive": "regel is inactief, er wijzigt nog niets",+ "previewNotAppliedToExisting": "wordt niet toegepast op bestaande transacties",+ "previewError": "Voorbeeld kon niet worden geladen","section": "Automatisering","packs": "Regelpakketten","packRuleCount": "{{count}} regels",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 885bb904..5e1ef17b 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -906,6 +906,16 @@"confirmDeleteDescription": "Definicja transakcji cyklicznej „{{description}}” zostanie trwale usunięta. Istniejące transakcje pozostaną, ale utracą powiązanie z transakcją cykliczną. Tej operacji nie można cofnąć."},"rules": {+ "preview": "Podgląd",+ "previewMatched": "dopasowania: {{matched}}",+ "previewSummary": "pasujące transakcje: {{matched}} · zmieniłoby się: {{changed}}",+ "previewSampleNote": "pokazano {{shown}} najnowszych",+ "previewLoadMore": "Załaduj jeszcze {{more}}",+ "previewNoChange": "bez zmian",+ "previewEmpty": "Żadna transakcja nie spełnia tych warunków",+ "previewInactive": "reguła jest nieaktywna, nic się jeszcze nie zmieni",+ "previewNotAppliedToExisting": "nie zostanie zastosowana do istniejących transakcji",+ "previewError": "Nie udało się wczytać podglądu","section": "Automatyzacja","packs": "Pakiety reguł","packRuleCount_one": "{{count}} reguła",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex af74232d..faeffb09 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -853,6 +853,16 @@"confirmDeleteDescription": "A definição recorrente \"{{description}}\" será excluída permanentemente. As transações existentes permanecerão, mas perderão o vínculo recorrente. Esta ação não pode ser desfeita."},"rules": {+ "preview": "Pré-visualizar",+ "previewMatched": "{{matched}} correspondências",+ "previewSummary": "{{matched}} transações correspondem · {{changed}} seriam alteradas",+ "previewSampleNote": "mostrando as {{shown}} mais recentes",+ "previewLoadMore": "Carregar mais {{more}}",+ "previewNoChange": "sem alteração",+ "previewEmpty": "Nenhuma transação corresponde a estas condições",+ "previewInactive": "regra inativa, nada muda por enquanto",+ "previewNotAppliedToExisting": "não será aplicada às transações existentes",+ "previewError": "Não foi possível carregar a pré-visualização","section": "Automação","packs": "Pacotes de Regras","packRuleCount": "{{count}} regras",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex ba57a180..ff148adc 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -853,6 +853,16 @@"confirmDeleteDescription": "A definição recorrente \"{{description}}\" será eliminada permanentemente. As transações existentes manter-se-ão, mas perderão a ligação recorrente. Esta ação não pode ser desfeita."},"rules": {+ "preview": "Pré-visualizar",+ "previewMatched": "{{matched}} correspondências",+ "previewSummary": "{{matched}} transações correspondem · {{changed}} seriam alteradas",+ "previewSampleNote": "a mostrar as {{shown}} mais recentes",+ "previewLoadMore": "Carregar mais {{more}}",+ "previewNoChange": "sem alteração",+ "previewEmpty": "Nenhuma transação corresponde a estas condições",+ "previewInactive": "regra inativa, nada muda por enquanto",+ "previewNotAppliedToExisting": "não será aplicada às transações existentes",+ "previewError": "Não foi possível carregar a pré-visualização","section": "Automação","packs": "Pacotes de Regras","packRuleCount": "{{count}} regras",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 0429a870..4b47bffb 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -861,6 +861,16 @@"confirmDeleteDescription": "Определение регулярной транзакции «{{description}}» будет удалено навсегда. Существующие транзакции останутся, но потеряют связь с регулярной транзакцией. Это действие нельзя отменить."},"rules": {+ "preview": "Предпросмотр",+ "previewMatched": "совпадений: {{matched}}",+ "previewSummary": "подходящих транзакций: {{matched}} · изменится: {{changed}}",+ "previewSampleNote": "показаны {{shown}} последних",+ "previewLoadMore": "Загрузить ещё {{more}}",+ "previewNoChange": "без изменений",+ "previewEmpty": "Ни одна транзакция не подходит под эти условия",+ "previewInactive": "правило неактивно, пока ничего не изменится",+ "previewNotAppliedToExisting": "не применяется к существующим транзакциям",+ "previewError": "Не удалось загрузить предпросмотр","section": "Автоматизация","packs": "Пакеты правил","packRuleCount": "{{count}} правил",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex f1b8d1e9..bbee3127 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -861,6 +861,16 @@"confirmDeleteDescription": "Визначення регулярної транзакції «{{description}}» буде видалено назавжди. Наявні транзакції залишаться, але втратять зв’язок із регулярною транзакцією. Цю дію не можна скасувати."},"rules": {+ "preview": "Попередній перегляд",+ "previewMatched": "збігів: {{matched}}",+ "previewSummary": "відповідних транзакцій: {{matched}} · зміниться: {{changed}}",+ "previewSampleNote": "показано {{shown}} найновіших",+ "previewLoadMore": "Завантажити ще {{more}}",+ "previewNoChange": "без змін",+ "previewEmpty": "Жодна транзакція не відповідає цим умовам",+ "previewInactive": "правило неактивне, поки нічого не зміниться",+ "previewNotAppliedToExisting": "не застосовується до наявних транзакцій",+ "previewError": "Не вдалося завантажити попередній перегляд","section": "Автоматизація","packs": "Пакети правил","packRuleCount": "{{count}} правил",diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex cc819180..5b7985e0 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -496,6 +496,35 @@ export interface RuleImportResponse {overwritten: number}+/** One matched transaction in a rule preview, with the category the draft rule+ * would leave it in. `will_change` is false when the rule matches but changes+ * nothing — usually a transaction that already has a category the draft keeps. */+export interface RulePreviewItem {+ id: string+ date: string+ description: string+ amount: number+ currency: string+ type: 'debit' | 'credit'+ current_category_id: string | null+ current_category_name: string | null+ new_category_id: string | null+ new_category_name: string | null+ will_change: boolean+}++export interface RulePreviewResponse {+ matched: number+ will_change: number+ /** False when the draft's flags mean saving it changes nothing right now —+ * an inactive rule, or one not being applied to existing transactions. */+ will_apply: boolean+ /** One window of the matches, newest first: `offset` through+ * `offset + limit`. More remain while `offset + sample.length < matched`. */+ sample: RulePreviewItem[]+ offset: number+}+export interface ImportLog {id: stringuser_id: string