Open-source personal finance manager. Self-hosted, privacy-first.
feat(rules): add transaction status as a rule condition (#1004)
Tássio Noronhaae1e051bef48
diff --git a/backend/app/schemas/rule.py b/backend/app/schemas/rule.pyindex e1cfcc23..bf42e406 100644--- a/backend/app/schemas/rule.py+++ b/backend/app/schemas/rule.py@@ -7,7 +7,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validatorclass RuleCondition(BaseModel):- field: str # description, payee, notes, amount, type, account_id, payee_id, date+ field: str # description, payee, notes, amount, type, account_id, payee_id, date, statusop: str # contains, not_contains, equals, not_equals, starts_with, ends_with, regex, gt, gte, lt, ltevalue: Any # str or number depending on fielddiff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.pyindex c6ea782e..fdda1d47 100644--- a/backend/app/services/rule_service.py+++ b/backend/app/services/rule_service.py@@ -38,7 +38,12 @@ class DuplicateRuleError(Exception):_ALLOWED_CONDITION_FIELDS = {"description", "payee", "notes", "amount", "type", "account_id", "payee_id", "date",+ "status",}+# Status is a closed set, so only equality makes sense and the value must be one+# of the statuses a transaction can carry.+_STATUS_CONDITION_OPS = {"equals", "not_equals"}+_STATUS_CONDITION_VALUES = {"pending", "posted"}_ALLOWED_CONDITION_OPS = {"contains", "not_contains", "equals", "not_equals", "starts_with","ends_with", "regex", "gt", "gte", "lt", "lte",@@ -80,6 +85,12 @@ async def _validate_rule_definition(op = _rule_item_value(condition, "op")if field not in _ALLOWED_CONDITION_FIELDS or op not in _ALLOWED_CONDITION_OPS:raise ValueError("Invalid rule condition")+ if field == "status" and (+ op not in _STATUS_CONDITION_OPS+ or str(_rule_item_value(condition, "value") or "").strip().lower()+ not in _STATUS_CONDITION_VALUES+ ):+ raise ValueError("Invalid rule condition")if op == "regex":compile_rule_regex(str(_rule_item_value(condition, "value") or ""))diff --git a/backend/mcp_server/tools/rules.py b/backend/mcp_server/tools/rules.pyindex 261cde66..2b281c67 100644--- a/backend/mcp_server/tools/rules.py+++ b/backend/mcp_server/tools/rules.py@@ -19,8 +19,9 @@ from mcp_server.tools.proposals import _APPLY_FIELD, _PROPOSAL_PREFACE, _can_app_RULE_CAPABILITIES = (" Conditions combine with AND/OR and filter description, payee, notes, "- "amount, type, account_id, payee_id, or date. Actions can set category, "- "payee, or description, append notes, or ignore the transaction."+ "amount, type, account_id, payee_id, date, or status (pending/posted). "+ "Actions can set category, payee, or description, append notes, or ignore "+ "the transaction.")diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.pyindex 473609b1..8f370bc9 100644--- a/backend/tests/test_new_rules_api.py+++ b/backend/tests/test_new_rules_api.py@@ -1363,3 +1363,44 @@ async def test_preview_rule_reports_no_change_when_the_draft_would_not_be_applieassert applied["will_apply"] is Trueassert applied["will_change"] == 1assert applied["sample"][0]["new_category_name"] == target.name+++async def test_preview_rule_filters_by_status(+ client: AsyncClient, auth_headers, session: AsyncSession, test_categories, test_transactions+):+ """A status condition previews only the transactions in that status."""+ netflix = next(t for t in test_transactions if t.description == "NETFLIX")+ netflix.status = "pending"+ await session.commit()++ response = await client.post(+ "/api/rules/preview",+ json={+ "conditions_op": "and",+ "conditions": [{"field": "status", "op": "equals", "value": "pending"}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ },+ headers=auth_headers,+ )+ assert response.status_code == 200+ data = response.json()+ assert data["matched"] == 1+ assert data["sample"][0]["description"] == "NETFLIX"+++async def test_create_rule_rejects_unknown_status_value(+ client: AsyncClient, auth_headers, test_categories+):+ response = await client.post(+ "/api/rules",+ json={+ "name": "Bad status",+ "conditions_op": "and",+ "conditions": [{"field": "status", "op": "equals", "value": "reserved"}],+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],+ },+ headers=auth_headers,+ )+ assert response.status_code in (400, 422)diff --git a/backend/tests/test_rule_engine.py b/backend/tests/test_rule_engine.pyindex 46a08871..6ac6696c 100644--- a/backend/tests/test_rule_engine.py+++ b/backend/tests/test_rule_engine.py@@ -678,3 +678,18 @@ def test_flat_conditions_still_evaluate_unchanged():]assert evaluate_conditions("and", conditions, make_tx(description="UBER TRIP")) is Trueassert evaluate_conditions("or", conditions, make_tx(description="IFOOD")) is True+++# --- status condition ---+++def test_status_equals_pending_matches_only_pending():+ conditions = [{"field": "status", "op": "equals", "value": "pending"}]+ assert evaluate_conditions("and", conditions, make_tx(status="pending")) is True+ assert evaluate_conditions("and", conditions, make_tx(status="posted")) is False+++def test_status_not_equals_posted_matches_pending():+ conditions = [{"field": "status", "op": "not_equals", "value": "posted"}]+ assert evaluate_conditions("and", conditions, make_tx(status="pending")) is True+ assert evaluate_conditions("and", conditions, make_tx(status="posted")) is Falsediff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.pyindex 62379209..2d76ad57 100644--- a/backend/tests/test_rule_service.py+++ b/backend/tests/test_rule_service.py@@ -1264,3 +1264,98 @@ async def test_get_installed_packs(session: AsyncSession, test_user, test_worksppacks_after = await get_installed_packs(session, test_user.id)assert packs_after["BR"] is True+++# ---------------------------------------------------------------------------+# Status condition+# ---------------------------------------------------------------------------++[email protected]("op", ["equals", "not_equals"])[email protected]("value", ["pending", "posted"])+async def test_create_rule_accepts_status_condition(+ session: AsyncSession, test_user, test_workspace, op, value+):+ rule = await create_rule(+ session,+ test_workspace.id,+ test_user.id,+ RuleCreate(+ name=f"Status {op} {value}",+ conditions=[RuleCondition(field="status", op=op, value=value)],+ actions=[RuleAction(op="ignore", value=True)],+ ),+ )+ assert rule.conditions == [{"field": "status", "op": op, "value": value}]+++ ("op", "value"),+ [("contains", "pending"), ("regex", "pend"), ("gt", "pending"), ("equals", "reserved")],+)+async def test_create_rule_rejects_invalid_status_condition(+ session: AsyncSession, test_user, test_workspace, op, value+):+ with pytest.raises(ValueError, match="Invalid rule condition"):+ await create_rule(+ session,+ test_workspace.id,+ test_user.id,+ RuleCreate(+ name="Bad status",+ conditions=[RuleCondition(field="status", op=op, value=value)],+ actions=[RuleAction(op="ignore", value=True)],+ ),+ )+++async def test_status_rule_applies_to_pending_transaction_only(+ session: AsyncSession, test_user, test_workspace, test_categories+):+ await create_rule(+ session,+ test_workspace.id,+ test_user.id,+ RuleCreate(+ name="Pending card holds",+ conditions=[RuleCondition(field="status", op="equals", value="pending")],+ actions=[RuleAction(op="set_category", value=str(test_categories[1].id))],+ ),+ )++ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ name="StatusAcc",+ type="checking",+ balance=Decimal("1000"),+ currency="BRL",+ )+ session.add(account)+ await session.commit()++ pending, posted = (+ Transaction(+ id=uuid.uuid4(),+ user_id=test_user.id,+ account_id=account.id,+ description="CARD PURCHASE",+ amount=Decimal("12.00"),+ date=date(2025, 3, 1),+ type="debit",+ source="manual",+ status=status,+ created_at=datetime.now(timezone.utc),+ )+ for status in ("pending", "posted")+ )+ session.add_all([pending, posted])+ await session.commit()++ await apply_rules_to_transaction(session, test_user.id, pending)+ await apply_rules_to_transaction(session, test_user.id, posted)++ assert (pending.category_id, posted.category_id) == (test_categories[1].id, None)diff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsxindex e9ac4b83..3af577cd 100644--- a/frontend/src/components/rule-dialog.tsx+++ b/frontend/src/components/rule-dialog.tsx@@ -40,6 +40,7 @@ const CONDITION_FIELDS = [{ value: 'account_id', label: 'rules.fieldAccount' },{ value: 'payee_id', label: 'rules.fieldPayee' },{ value: 'date', label: 'rules.fieldDate' },+ { value: 'status', label: 'rules.fieldStatus' },] as constconst STRING_OPS = [@@ -63,7 +64,7 @@ const NUMERIC_OPS = [function getOpsForField(field: string) {if (field === 'amount' || field === 'date') return NUMERIC_OPSif (field === 'type') return [{ value: 'equals', label: 'rules.opIs' }]- if (field === 'payee_id' || field === 'account_id') return [+ if (field === 'payee_id' || field === 'account_id' || field === 'status') return [{ value: 'equals', label: 'rules.opIs' },{ value: 'not_equals', label: 'rules.opIsNot' },]@@ -71,7 +72,9 @@ function getOpsForField(field: string) {}function defaultValueForField(field: string) {- return field === 'type' ? 'debit' : ''+ if (field === 'type') return 'debit'+ if (field === 'status') return 'pending'+ return ''}function newCondition(): RuleCondition {@@ -156,6 +159,15 @@ function ConditionRow({<option value="debit">{t('rules.typeExpense')}</option><option value="credit">{t('rules.typeIncome')}</option></select>+ ) : condition.field === 'status' ? (+ <select+ className={`${SELECT_CLASS} col-span-2 w-full min-w-0 sm:w-0 sm:flex-1`}+ value={String(condition.value)}+ onChange={(e) => onChange('value', e.target.value)}+ >+ <option value="pending">{t('rules.statusPending')}</option>+ <option value="posted">{t('rules.statusPosted')}</option>+ </select>) : condition.field === 'account_id' ? (<selectclassName={`${SELECT_CLASS} col-span-2 w-full min-w-0 sm:w-0 sm:flex-1`}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 48b98635..c901e201 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -1393,6 +1393,7 @@"fieldAccount": "Konto","fieldPayee": "Zahlungsempfänger","fieldDate": "Datum",+ "fieldStatus": "Status","opContains": "enthält","opNotContains": "enthält nicht","opEquals": "ist gleich",@@ -1404,6 +1405,8 @@"opIsNot": "ist nicht","typeExpense": "Ausgabe (Soll)","typeIncome": "Einnahme (Haben)",+ "statusPending": "Ausstehend",+ "statusPosted": "Gebucht","valuePlaceholder": "Wert...","sortLabel": "Sortieren nach","sortBy_priority": "Priorität",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex 25fa7552..ba785d04 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -1387,6 +1387,7 @@"fieldAccount": "Λογαριασμός","fieldPayee": "Δικαιούχος","fieldDate": "Ημερομηνία",+ "fieldStatus": "Κατάσταση","opContains": "περιέχει","opNotContains": "δεν περιέχει","opEquals": "ισούται με",@@ -1398,6 +1399,8 @@"opIsNot": "δεν είναι","typeExpense": "Έξοδο (χρέωση)","typeIncome": "Έσοδο (πίστωση)",+ "statusPending": "Εκκρεμεί",+ "statusPosted": "Καταχωρήθηκε","valuePlaceholder": "Τιμή...","sortLabel": "Ταξινόμηση κατά","sortBy_priority": "Προτεραιότητα",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 92633be8..dadb7112 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1392,6 +1392,7 @@"fieldAccount": "Account","fieldPayee": "Payee","fieldDate": "Date",+ "fieldStatus": "Status","opContains": "contains","opNotContains": "does not contain","opEquals": "equals",@@ -1403,6 +1404,8 @@"opIsNot": "is not","typeExpense": "Expense (debit)","typeIncome": "Income (credit)",+ "statusPending": "Pending",+ "statusPosted": "Posted","valuePlaceholder": "Value...","sortLabel": "Sort by","sortBy_priority": "Priority",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex ad870a04..a8095867 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1393,6 +1393,7 @@"fieldAccount": "Cuenta","fieldPayee": "Beneficiario","fieldDate": "Fecha",+ "fieldStatus": "Estado","opContains": "contiene","opNotContains": "no contiene","opEquals": "es igual a",@@ -1404,6 +1405,8 @@"opIsNot": "no es","typeExpense": "Gasto (débito)","typeIncome": "Ingreso (crédito)",+ "statusPending": "Pendiente",+ "statusPosted": "Registrada","valuePlaceholder": "Valor...","sortLabel": "Ordenar por","sortBy_priority": "Prioridad",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 6cae5b04..fb6e53d6 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -1393,6 +1393,7 @@"fieldAccount": "Compte","fieldPayee": "Bénéficiaire","fieldDate": "Date",+ "fieldStatus": "Statut","opContains": "contient","opNotContains": "ne contient pas","opEquals": "est égal à",@@ -1404,6 +1405,8 @@"opIsNot": "n'est pas","typeExpense": "Dépense (débit)","typeIncome": "Revenu (crédit)",+ "statusPending": "En attente",+ "statusPosted": "Comptabilisée","valuePlaceholder": "Valeur...","sortLabel": "Trier par","sortBy_priority": "Priorité",diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex d11bb8db..452aa4e3 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -1387,6 +1387,7 @@"fieldAccount": "खाता","fieldPayee": "प्राप्तकर्ता","fieldDate": "तिथि",+ "fieldStatus": "स्थिति","opContains": "शामिल है","opNotContains": "शामिल नहीं है","opEquals": "बराबर है",@@ -1398,6 +1399,8 @@"opIsNot": "नहीं है","typeExpense": "खर्च (डेबिट)","typeIncome": "आय (क्रेडिट)",+ "statusPending": "लंबित",+ "statusPosted": "पोस्ट किया गया","valuePlaceholder": "मान...","sortLabel": "इससे लगाएँ","sortBy_priority": "प्राथमिकता",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 70cc22cc..9bc93c19 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1393,6 +1393,7 @@"fieldAccount": "Conto","fieldPayee": "Beneficiario","fieldDate": "Data",+ "fieldStatus": "Stato","opContains": "contiene","opNotContains": "non contiene","opEquals": "uguale a",@@ -1404,6 +1405,8 @@"opIsNot": "non è","typeExpense": "Spesa (addebito)","typeIncome": "Entrata (accredito)",+ "statusPending": "In sospeso",+ "statusPosted": "Registrata","valuePlaceholder": "Valore...","sortLabel": "Ordina per","sortBy_priority": "Priorità",diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex a168aa9c..0e1ddf86 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -1387,6 +1387,7 @@"fieldAccount": "口座","fieldPayee": "取引相手","fieldDate": "日付",+ "fieldStatus": "ステータス","opContains": "次を含む","opNotContains": "次を含まない","opEquals": "次に等しい",@@ -1398,6 +1399,8 @@"opIsNot": "ではない","typeExpense": "支出(借方)","typeIncome": "収入(貸方)",+ "statusPending": "保留中",+ "statusPosted": "確定","valuePlaceholder": "値...","sortLabel": "並べ替え","sortBy_priority": "優先度",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 58dabebe..2ffb2248 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -1392,6 +1392,7 @@"fieldAccount": "Rekening","fieldPayee": "Begunstigde","fieldDate": "Datum",+ "fieldStatus": "Status","opContains": "bevat","opNotContains": "bevat niet","opEquals": "gelijk aan",@@ -1403,6 +1404,8 @@"opIsNot": "niet","typeExpense": "Kosten (debet)","typeIncome": "Inkomen (krediet)",+ "statusPending": "In behandeling",+ "statusPosted": "Geplaatst","valuePlaceholder": "Waarde...","sortLabel": "Sorteer op","sortBy_priority": "Prioriteit",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 712eff9a..0836e828 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1459,6 +1459,7 @@"fieldAccount": "Konto","fieldPayee": "Odbiorca","fieldDate": "Data",+ "fieldStatus": "Status","opContains": "zawiera","opNotContains": "nie zawiera","opEquals": "równa się",@@ -1470,6 +1471,8 @@"opIsNot": "nie jest","typeExpense": "Wydatek (obciążenie)","typeIncome": "Przychód (uznanie)",+ "statusPending": "Oczekująca",+ "statusPosted": "Zaksięgowana","valuePlaceholder": "Wartość...","sortLabel": "Sortuj wg","sortBy_priority": "Priorytet",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex fc5d61f0..40dd3f48 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1393,6 +1393,7 @@"fieldAccount": "Conta","fieldPayee": "Pessoa","fieldDate": "Data",+ "fieldStatus": "Status","opContains": "contém","opNotContains": "não contém","opEquals": "é igual a",@@ -1404,6 +1405,8 @@"opIsNot": "não é","typeExpense": "Despesa (debit)","typeIncome": "Receita (credit)",+ "statusPending": "Pendente",+ "statusPosted": "Lançada","valuePlaceholder": "Valor...","sortLabel": "Ordenar por","sortBy_priority": "Prioridade",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex b75272c8..69a3d870 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -1393,6 +1393,7 @@"fieldAccount": "Conta","fieldPayee": "Entidade","fieldDate": "Data",+ "fieldStatus": "Estado","opContains": "contém","opNotContains": "não contém","opEquals": "é igual a",@@ -1404,6 +1405,8 @@"opIsNot": "não é","typeExpense": "Despesa (debit)","typeIncome": "Receita (credit)",+ "statusPending": "Pendente",+ "statusPosted": "Lançada","valuePlaceholder": "Valor...","sortLabel": "Ordenar por","sortBy_priority": "Prioridade",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 3694f01a..9709f1c7 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -1405,6 +1405,7 @@"fieldAccount": "Счёт","fieldPayee": "Получатель","fieldDate": "Дата",+ "fieldStatus": "Статус","opContains": "содержит","opNotContains": "не содержит","opEquals": "равно",@@ -1416,6 +1417,8 @@"opIsNot": "не является","typeExpense": "Расход (дебет)","typeIncome": "Доход (кредит)",+ "statusPending": "Ожидается",+ "statusPosted": "Проведена","valuePlaceholder": "Значение...","sortLabel": "Сортировка","sortBy_priority": "Приоритет",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 601f0d58..7315155f 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -1480,6 +1480,7 @@"fieldAccount": "Účet","fieldPayee": "Príjemca","fieldDate": "Dátum",+ "fieldStatus": "Stav","opContains": "obsahuje","opNotContains": "neobsahuje","opEquals": "rovná sa",@@ -1491,6 +1492,8 @@"opIsNot": "nie je","typeExpense": "Výdavok (debet)","typeIncome": "Príjem (kredit)",+ "statusPending": "Čakajúca",+ "statusPosted": "Zaúčtovaná","valuePlaceholder": "Hodnota...","sortLabel": "Zoradiť podľa","sortBy_priority": "Priorita",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex b792fa23..8f625caf 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -1405,6 +1405,7 @@"fieldAccount": "Рахунок","fieldPayee": "Отримувач","fieldDate": "Дата",+ "fieldStatus": "Статус","opContains": "містить","opNotContains": "не містить","opEquals": "дорівнює",@@ -1416,6 +1417,8 @@"opIsNot": "не є","typeExpense": "Витрата (дебет)","typeIncome": "Дохід (кредит)",+ "statusPending": "Очікується",+ "statusPosted": "Проведена","valuePlaceholder": "Значення...","sortLabel": "Сортування","sortBy_priority": "Пріоритет",diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsxindex 084ef12e..8b2816db 100644--- a/frontend/src/pages/rules.tsx+++ b/frontend/src/pages/rules.tsx@@ -71,6 +71,7 @@ const CONDITION_FIELDS = [{ value: 'account_id', label: 'rules.fieldAccount' },{ value: 'payee_id', label: 'rules.fieldPayee' },{ value: 'date', label: 'rules.fieldDate' },+ { value: 'status', label: 'rules.fieldStatus' },] as constconst STRING_OPS = [@@ -94,7 +95,7 @@ const NUMERIC_OPS = [function getOpsForField(field: string) {if (field === 'amount' || field === 'date') return NUMERIC_OPSif (field === 'type') return [{ value: 'equals', label: 'rules.opIs' }]- if (field === 'payee_id' || field === 'account_id') return [+ if (field === 'payee_id' || field === 'account_id' || field === 'status') return [{ value: 'equals', label: 'rules.opIs' },{ value: 'not_equals', label: 'rules.opIsNot' },]@@ -115,6 +116,10 @@ function conditionSummary(conditions: RuleConditionNode[], conditionsOp: string,const p = payeesList.find(p => p.id === c.value)return p ? p.name : String(c.value)}+ if (c.field === 'status') {+ if (c.value === 'pending') return t('rules.statusPending')+ if (c.value === 'posted') return t('rules.statusPosted')+ }return String(c.value)}const leafSummary = (c: RuleCondition) => `${fieldLabel(c.field)} ${opLabel(c.field, c.op)} "${valueLabel(c)}"`