Skip to content

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

feat(rules): mix AND and OR with nested condition groups (#645)

Tássio Noronha6d782a7d52ba
diff --git a/backend/app/api/rules.py b/backend/app/api/rules.py
index 1cb58d65..e186c3ad 100644
--- a/backend/app/api/rules.py
+++ b/backend/app/api/rules.py
@@ -25,15 +25,28 @@ from app.services.rule_service import DuplicateRuleError
router = APIRouter(prefix="/api/rules", tags=["rules"])
-def _normalize_conditions(conditions: list[dict]) -> list[dict]:
- return [
- {
- "field": condition.get("field"),
+def _normalize_condition(condition: dict) -> dict:
+ """Reduce one condition list entry to the keys that decide what it matches.
+
+ A group entry carries its own operator and leaves instead of a field, so it
+ has to be normalized recursively — flattening it to `field: None` would make
+ every group compare equal and hide real edits from the change check below.
+ """
+ nested = condition.get("conditions")
+ if isinstance(nested, list):
+ return {
"op": condition.get("op"),
- "value": condition.get("value"),
+ "conditions": [_normalize_condition(c) for c in nested],
}
- for condition in conditions
- ]
+ return {
+ "field": condition.get("field"),
+ "op": condition.get("op"),
+ "value": condition.get("value"),
+ }
+
+
+def _normalize_conditions(conditions: list[dict]) -> list[dict]:
+ return [_normalize_condition(condition) for condition in conditions]
def _rule_match_definition_changed(rule: RuleRead, data: RuleUpdate) -> bool:
diff --git a/backend/app/schemas/rule.py b/backend/app/schemas/rule.py
index 93ed93e9..0be0abd9 100644
--- a/backend/app/schemas/rule.py
+++ b/backend/app/schemas/rule.py
@@ -1,6 +1,6 @@
# backend/app/schemas/rule.py
import uuid
-from typing import Any, Optional
+from typing import Any, Optional, Union
from pydantic import BaseModel, ConfigDict, field_validator
@@ -24,6 +24,40 @@ class RuleCondition(BaseModel):
return v
+class RuleConditionGroup(BaseModel):
+ """A nested group of conditions joined by its own operator.
+
+ Groups let a rule mix AND and OR — `type is debit AND (contains UBER OR
+ contains 99POP)`. They hold leaf conditions only: `conditions` is typed as
+ `list[RuleCondition]`, so a nested group fails validation and rule depth
+ stays capped at two levels, which is what the engine and editor support.
+ """
+
+ op: str = "or" # and, or
+ conditions: list[RuleCondition]
+
+ @field_validator("op")
+ @classmethod
+ def op_must_be_and_or(cls, v: str) -> str:
+ if v not in ("and", "or"):
+ raise ValueError("Condition group operator must be 'and' or 'or'")
+ return v
+
+ @field_validator("conditions")
+ @classmethod
+ def group_must_not_be_empty(cls, v: list[RuleCondition]) -> list[RuleCondition]:
+ """An empty group never matches, so it can only make a rule confusing."""
+ if not v:
+ raise ValueError("Condition group cannot be empty")
+ return v
+
+
+# A rule's condition list mixes leaves and one level of groups. The two shapes
+# are disjoint — a leaf has no `conditions`, a group has no `field`/`value` — so
+# Pydantic's smart union resolves them without a discriminator.
+RuleConditionNode = Union[RuleConditionGroup, RuleCondition]
+
+
class RuleAction(BaseModel):
op: str # set_category, set_payee, set_description, append_notes, ignore
value: Any # entity UUID or text depending on action
@@ -32,7 +66,7 @@ class RuleAction(BaseModel):
class RuleCreate(BaseModel):
name: str
conditions_op: str = "and"
- conditions: list[RuleCondition]
+ conditions: list[RuleConditionNode]
actions: list[RuleAction]
priority: int = 0
is_active: bool = True
@@ -43,7 +77,7 @@ class RuleCreate(BaseModel):
class RuleUpdate(BaseModel):
name: Optional[str] = None
conditions_op: Optional[str] = None
- conditions: Optional[list[RuleCondition]] = None
+ conditions: Optional[list[RuleConditionNode]] = None
actions: Optional[list[RuleAction]] = None
priority: Optional[int] = None
is_active: Optional[bool] = None
@@ -77,7 +111,7 @@ class RuleCreateResponse(RuleMutationResponse):
class RuleExportItem(BaseModel):
name: str
conditions_op: str = "and"
- conditions: list[RuleCondition]
+ conditions: list[RuleConditionNode]
actions: list[RuleAction]
priority: int = 0
is_active: bool = True
diff --git a/backend/app/services/rule_engine.py b/backend/app/services/rule_engine.py
index aebaac91..14674ce1 100644
--- a/backend/app/services/rule_engine.py
+++ b/backend/app/services/rule_engine.py
@@ -115,11 +115,40 @@ def _match_condition(condition: dict, tx: "Transaction") -> bool:
return False
-def evaluate_conditions(conditions_op: str, conditions: list[dict], tx: "Transaction") -> bool:
- """Return True if the transaction matches the rule's conditions."""
+def _is_group(node: dict) -> bool:
+ """A condition list entry is a group when it carries its own condition list."""
+ return isinstance(node, dict) and isinstance(node.get("conditions"), list)
+
+
+def _match_group(group: dict, tx: "Transaction") -> bool:
+ """Evaluate one nested group: its leaves joined by the group's own operator.
+
+ Groups hold leaves only, which caps a rule at two levels. A nested group
+ would reach `_match_condition` with no `field`/`op` and evaluate to False;
+ creation rejects them, so this only guards hand-edited data.
+ """
+ conditions = group.get("conditions") or []
if not conditions:
return False
results = [_match_condition(c, tx) for c in conditions]
+ if group.get("op") == "or":
+ return any(results)
+ return all(results) # "and" is default
+
+
+def evaluate_conditions(conditions_op: str, conditions: list[dict], tx: "Transaction") -> bool:
+ """Return True if the transaction matches the rule's conditions.
+
+ Each entry is either a leaf condition (`field`/`op`/`value`) or a group that
+ joins its own leaves with its own operator, letting a rule mix AND and OR —
+ e.g. `type is debit AND (description contains UBER OR contains 99POP)`.
+ """
+ if not conditions:
+ return False
+ results = [
+ _match_group(node, tx) if _is_group(node) else _match_condition(node, tx)
+ for node in conditions
+ ]
if conditions_op == "or":
return any(results)
return all(results) # "and" is default
diff --git a/backend/app/services/rule_service.py b/backend/app/services/rule_service.py
index a0642f2e..52812323 100644
--- a/backend/app/services/rule_service.py
+++ b/backend/app/services/rule_service.py
@@ -35,13 +35,30 @@ def _rule_item_value(item, key: str):
return item.get(key) if isinstance(item, dict) else getattr(item, key, None)
+def _flatten_conditions(conditions: list) -> list:
+ """Return every leaf condition, unwrapping one level of AND/OR groups.
+
+ A rule's condition list mixes leaves with groups that hold their own leaves
+ (see `rule_engine.evaluate_conditions`). Field/operator checks apply to the
+ leaves either way, and the schema caps nesting at one level.
+ """
+ leaves = []
+ for node in conditions or []:
+ nested = _rule_item_value(node, "conditions")
+ if isinstance(nested, list):
+ leaves.extend(nested)
+ else:
+ leaves.append(node)
+ return leaves
+
+
async def _validate_rule_definition(
session: AsyncSession,
workspace_id: uuid.UUID,
conditions: list,
actions: list,
) -> None:
- for condition in conditions or []:
+ for condition in _flatten_conditions(conditions):
field = _rule_item_value(condition, "field")
op = _rule_item_value(condition, "op")
if field not in _ALLOWED_CONDITION_FIELDS or op not in _ALLOWED_CONDITION_OPS:
diff --git a/backend/tests/test_new_rules_api.py b/backend/tests/test_new_rules_api.py
index 5da02c5e..d8517395 100644
--- a/backend/tests/test_new_rules_api.py
+++ b/backend/tests/test_new_rules_api.py
@@ -819,3 +819,152 @@ async def test_create_rule_allows_zero_value(
}
response = await client.post("/api/rules", json=payload, headers=auth_headers)
assert response.status_code == 201
+
+
+# ─── nested condition groups (mixing AND and OR) ───
+
+
+async def test_create_rule_with_condition_group(
+ client: AsyncClient, auth_headers, test_categories
+):
+ """`type is debit AND (description contains UBER OR contains 99POP)`."""
+ payload = {
+ "name": "Rides",
+ "conditions_op": "and",
+ "conditions": [
+ {"field": "type", "op": "equals", "value": "debit"},
+ {"op": "or", "conditions": [
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "description", "op": "contains", "value": "99POP"},
+ ]},
+ ],
+ "actions": [{"op": "set_category", "value": str(test_categories[1].id)}],
+ }
+ response = await client.post("/api/rules", json=payload, headers=auth_headers)
+ assert response.status_code == 201
+ stored = response.json()["conditions"]
+ assert stored[0]["field"] == "type"
+ assert stored[1]["op"] == "or"
+ assert [c["value"] for c in stored[1]["conditions"]] == ["UBER", "99POP"]
+
+
+async def test_grouped_rule_applies_to_existing_transactions(
+ client: AsyncClient, auth_headers, test_transactions, test_categories
+):
+ """The group's OR branch decides which transactions the AND rule reaches."""
+ cat_transport = str(test_categories[1].id)
+ payload = {
+ "name": "Rides",
+ "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": cat_transport}],
+ "apply_to_existing": True,
+ "overwrite_existing_categories": True,
+ }
+ response = await client.post("/api/rules", json=payload, headers=auth_headers)
+ assert response.status_code == 201
+
+ items = (await client.get("/api/transactions", headers=auth_headers)).json()["items"]
+ by_desc = {t["description"]: t for t in items}
+ assert by_desc["UBER TRIP"]["category_id"] == cat_transport
+ assert by_desc["NETFLIX"]["category_id"] == cat_transport
+ # Credit transactions fail the outer AND, so the group never applies.
+ assert by_desc["PIX RECEBIDO"]["category_id"] is None
+
+
+async def test_create_rule_rejects_nested_group(
+ client: AsyncClient, auth_headers, test_categories
+):
+ """Groups hold leaves only — rule depth is capped at two levels."""
+ payload = {
+ "name": "Too deep",
+ "conditions_op": "and",
+ "conditions": [
+ {"op": "or", "conditions": [
+ {"op": "and", "conditions": [
+ {"field": "description", "op": "contains", "value": "UBER"},
+ ]},
+ ]},
+ ],
+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],
+ }
+ response = await client.post("/api/rules", json=payload, headers=auth_headers)
+ assert response.status_code == 422
+
+
+async def test_create_rule_rejects_empty_group(
+ client: AsyncClient, auth_headers, test_categories
+):
+ payload = {
+ "name": "Empty group",
+ "conditions_op": "and",
+ "conditions": [{"op": "or", "conditions": []}],
+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],
+ }
+ response = await client.post("/api/rules", json=payload, headers=auth_headers)
+ assert response.status_code == 422
+
+
+async def test_create_rule_rejects_blank_value_inside_group(
+ client: AsyncClient, auth_headers, test_categories
+):
+ """A blank value matches everything wherever it sits, group included."""
+ payload = {
+ "name": "Blank inside group",
+ "conditions_op": "and",
+ "conditions": [
+ {"op": "or", "conditions": [
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "description", "op": "contains", "value": " "},
+ ]},
+ ],
+ "actions": [{"op": "set_category", "value": str(test_categories[0].id)}],
+ }
+ response = await client.post("/api/rules", json=payload, headers=auth_headers)
+ assert response.status_code == 422
+
+
+async def test_grouped_rules_survive_export_import(
+ client: AsyncClient, auth_headers, test_categories
+):
+ payload = {
+ "name": "Rides",
+ "conditions_op": "and",
+ "conditions": [
+ {"field": "type", "op": "equals", "value": "debit"},
+ {"op": "or", "conditions": [
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "description", "op": "contains", "value": "99POP"},
+ ]},
+ ],
+ "actions": [{"op": "set_category", "value": str(test_categories[1].id)}],
+ }
+ assert (await client.post("/api/rules", json=payload, headers=auth_headers)).status_code == 201
+
+ exported = await client.get("/api/rules/export", headers=auth_headers)
+ assert exported.status_code == 200
+
+ imported = await client.post(
+ "/api/rules/import",
+ json={"payload": exported.json(), "overwrite": True},
+ headers=auth_headers,
+ )
+ assert imported.status_code == 200
+ assert imported.json()["imported"] == 1
+
+ listed = (await client.get("/api/rules", headers=auth_headers)).json()
+ 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"]
diff --git a/backend/tests/test_rule_engine.py b/backend/tests/test_rule_engine.py
index 70404289..8c27bca6 100644
--- a/backend/tests/test_rule_engine.py
+++ b/backend/tests/test_rule_engine.py
@@ -538,3 +538,108 @@ def test_zero_value_still_matches():
tx = make_tx(amount=Decimal("25.50"))
conditions = [{"field": "amount", "op": "gt", "value": 0}]
assert evaluate_conditions("and", conditions, tx) is True
+
+
+# --- nested condition groups (mixing AND and OR) ---
+
+def _group(op, *conditions):
+ return {"op": op, "conditions": list(conditions)}
+
+
+def test_and_of_or_group_matches():
+ """`type is debit AND (description contains UBER OR contains 99POP)`."""
+ conditions = [
+ {"field": "type", "op": "equals", "value": "debit"},
+ _group(
+ "or",
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "description", "op": "contains", "value": "99POP"},
+ ),
+ ]
+ assert evaluate_conditions("and", conditions, make_tx(description="99POP VIAGEM")) is True
+ assert evaluate_conditions("and", conditions, make_tx(description="UBER TRIP")) is True
+
+
+def test_and_of_or_group_outer_condition_fails():
+ conditions = [
+ {"field": "type", "op": "equals", "value": "debit"},
+ _group(
+ "or",
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "description", "op": "contains", "value": "99POP"},
+ ),
+ ]
+ tx = make_tx(description="UBER TRIP", type="credit")
+ assert evaluate_conditions("and", conditions, tx) is False
+
+
+def test_and_of_or_group_no_leaf_matches():
+ conditions = [
+ {"field": "type", "op": "equals", "value": "debit"},
+ _group(
+ "or",
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "description", "op": "contains", "value": "99POP"},
+ ),
+ ]
+ assert evaluate_conditions("and", conditions, make_tx(description="IFOOD")) is False
+
+
+def test_or_of_and_group():
+ """`description contains IFOOD OR (contains MERCADO AND amount > 100)`."""
+ conditions = [
+ {"field": "description", "op": "contains", "value": "IFOOD"},
+ _group(
+ "and",
+ {"field": "description", "op": "contains", "value": "MERCADO"},
+ {"field": "amount", "op": "gt", "value": 100},
+ ),
+ ]
+ assert evaluate_conditions("or", conditions, make_tx(description="IFOOD PEDIDO")) is True
+ assert evaluate_conditions(
+ "or", conditions, make_tx(description="MERCADO X", amount=Decimal("250.00"))
+ ) is True
+ assert evaluate_conditions(
+ "or", conditions, make_tx(description="MERCADO X", amount=Decimal("30.00"))
+ ) is False
+
+
+def test_group_defaults_to_and_without_op():
+ conditions = [
+ _group(
+ None,
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "type", "op": "equals", "value": "debit"},
+ ),
+ ]
+ assert evaluate_conditions("and", conditions, make_tx(description="UBER TRIP")) is True
+ conditions[0]["conditions"][1]["value"] = "credit"
+ assert evaluate_conditions("and", conditions, make_tx(description="UBER TRIP")) is False
+
+
+def test_empty_group_never_matches():
+ """An empty group has nothing to match, like an empty condition list."""
+ conditions = [_group("or")]
+ assert evaluate_conditions("and", conditions, make_tx()) is False
+ assert evaluate_conditions("or", conditions, make_tx()) is False
+
+
+def test_blank_value_inside_group_never_matches():
+ conditions = [
+ _group(
+ "or",
+ {"field": "description", "op": "contains", "value": ""},
+ {"field": "description", "op": "contains", "value": "IFOOD"},
+ ),
+ ]
+ assert evaluate_conditions("and", conditions, make_tx(description="UBER TRIP")) is False
+
+
+def test_flat_conditions_still_evaluate_unchanged():
+ """Rules saved before groups existed keep their exact meaning."""
+ conditions = [
+ {"field": "description", "op": "contains", "value": "UBER"},
+ {"field": "type", "op": "equals", "value": "debit"},
+ ]
+ assert evaluate_conditions("and", conditions, make_tx(description="UBER TRIP")) is True
+ assert evaluate_conditions("or", conditions, make_tx(description="IFOOD")) is True
diff --git a/backend/tests/test_rule_service.py b/backend/tests/test_rule_service.py
index 680c7f2c..853691e3 100644
--- a/backend/tests/test_rule_service.py
+++ b/backend/tests/test_rule_service.py
@@ -345,7 +345,10 @@ async def test_set_description_validation_and_export_compatibility(
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"
+ # The list can hold groups now, so narrow before reading a leaf's field.
+ exported_condition = exported.conditions[0]
+ assert isinstance(exported_condition, RuleCondition)
+ assert exported_condition.field == "payee"
assert exported.actions[0].op == "set_description"
# ---------------------------------------------------------------------------
# apply_rules_to_transaction
diff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsx
index d89a083a..adbac542 100644
--- a/frontend/src/components/rule-dialog.tsx
+++ b/frontend/src/components/rule-dialog.tsx
@@ -15,7 +15,16 @@ import {
import { X, Plus } from 'lucide-react'
import { cn } from '@/lib/utils'
import { CategorySelect } from '@/components/category-select'
-import type { Category, CategoryGroup, Payee, Rule, RuleCondition, RuleAction } from '@/types'
+import { flattenConditions, isConditionGroup } from '@/lib/rule-conditions'
+import type {
+ Category,
+ CategoryGroup,
+ Payee,
+ Rule,
+ RuleCondition,
+ RuleConditionNode,
+ RuleAction,
+} from '@/types'
const CONDITION_FIELDS = [
{ value: 'description', label: 'rules.fieldDescription' },
@@ -60,9 +69,133 @@ function defaultValueForField(field: string) {
return field === 'type' ? 'debit' : ''
}
+function newCondition(): RuleCondition {
+ return { field: 'description', op: 'contains', value: '' }
+}
+
+/** Apply one edit to a leaf, resetting op/value when the field changes. */
+function applyLeafChange(
+ condition: RuleCondition,
+ key: keyof RuleCondition,
+ val: string | number,
+): RuleCondition {
+ if (key !== 'field') return { ...condition, [key]: val }
+ return {
+ ...condition,
+ field: String(val),
+ op: getOpsForField(String(val))[0].value,
+ value: defaultValueForField(String(val)),
+ }
+}
+
+const SELECT_CLASS = 'border border-border rounded-lg px-2 py-1.5 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'
+
+/** AND/OR switch, used for the rule itself and for each nested group. */
+function OpToggle({ value, onChange }: { value: 'and' | 'or'; onChange: (op: 'and' | 'or') => void }) {
+ const { t } = useTranslation()
+ return (
+ <div className="flex items-center gap-1 bg-muted rounded-lg p-0.5">
+ {(['and', 'or'] as const).map(op => (
+ <button
+ key={op}
+ type="button"
+ className={cn(
+ 'px-3 py-1 text-xs font-semibold rounded-md transition-all',
+ value === op ? 'bg-card shadow-sm text-foreground' : 'text-muted-foreground hover:text-foreground'
+ )}
+ onClick={() => onChange(op)}
+ >
+ {op === 'and' ? t('rules.andOp') : t('rules.orOp')}
+ </button>
+ ))}
+ </div>
+ )
+}
+
+function ConditionRow({
+ condition, accounts, payees, onChange, onRemove,
+}: {
+ condition: RuleCondition
+ accounts: { id: string; name: string; display_name?: string | null }[]
+ payees: Payee[]
+ onChange: (key: keyof RuleCondition, val: string | number) => void
+ onRemove: () => void
+}) {
+ const { t } = useTranslation()
+ return (
+ <div className="relative grid min-w-0 grid-cols-2 gap-2 pr-7 sm:flex sm:items-center sm:pr-0">
+ <select
+ className={`${SELECT_CLASS} w-full sm:w-32 sm:shrink-0`}
+ value={condition.field}
+ onChange={(e) => onChange('field', e.target.value)}
+ >
+ {CONDITION_FIELDS.map(f => (
+ <option key={f.value} value={f.value}>{t(f.label)}</option>
+ ))}
+ </select>
+ <select
+ className={`${SELECT_CLASS} w-full sm:w-32 sm:shrink-0`}
+ value={condition.op}
+ onChange={(e) => onChange('op', e.target.value)}
+ >
+ {getOpsForField(condition.field).map(o => (
+ <option key={o.value} value={o.value}>{t(o.label)}</option>
+ ))}
+ </select>
+ {condition.field === 'type' ? (
+ <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="debit">{t('rules.typeExpense')}</option>
+ <option value="credit">{t('rules.typeIncome')}</option>
+ </select>
+ ) : condition.field === 'account_id' ? (
+ <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="">{t('rules.selectAccount')}</option>
+ {accounts.map(acc => (
+ <option key={acc.id} value={acc.id}>{getAccountName(acc)}</option>
+ ))}
+ </select>
+ ) : condition.field === 'payee_id' ? (
+ <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="">{t('rules.selectPayee')}</option>
+ {payees.map(p => (
+ <option key={p.id} value={p.id}>{p.name}</option>
+ ))}
+ </select>
+ ) : (
+ <Input
+ className="col-span-2 h-8 w-full min-w-0 text-sm sm:w-0 sm:flex-1"
+ value={String(condition.value)}
+ onChange={(e) => onChange('value', e.target.value)}
+ placeholder={condition.field === 'amount' ? '0.00' : condition.field === 'date' ? 'YYYY-MM-DD' : t('rules.valuePlaceholder')}
+ type={condition.field === 'amount' ? 'number' : condition.field === 'date' ? 'date' : 'text'}
+ />
+ )}
+ <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={onRemove}
+ >
+ <X size={13} />
+ </button>
+ </div>
+ )
+}
+
export interface RuleDialogInitialData {
name?: string
- conditions?: RuleCondition[]
+ conditions?: RuleConditionNode[]
actions?: RuleAction[]
}
@@ -83,13 +216,13 @@ export function RuleDialog({
const { t } = useTranslation()
const sortedAccounts = useMemo(() => sortAccountsByDisplayName(accounts), [accounts])
- const defaultConditions: RuleCondition[] = initialData?.conditions ?? rule?.conditions as RuleCondition[] ?? [{ field: 'description', op: 'contains', value: '' }]
+ const defaultConditions: RuleConditionNode[] = initialData?.conditions ?? rule?.conditions ?? [newCondition()]
const defaultActions: RuleAction[] = initialData?.actions ?? rule?.actions as RuleAction[] ?? [{ op: 'set_category', value: '' }]
const [name, setName] = useState(initialData?.name ?? rule?.name ?? '')
const [conditionsOp, setConditionsOp] = useState<'and' | 'or'>(rule?.conditions_op ?? 'and')
- const [conditions, setConditions] = useState<RuleCondition[]>(
- defaultConditions.length ? defaultConditions : [{ field: 'description', op: 'contains', value: '' }]
+ const [conditions, setConditions] = useState<RuleConditionNode[]>(
+ defaultConditions.length ? defaultConditions : [newCondition()]
)
const [actions, setActions] = useState<RuleAction[]>(
defaultActions.length ? defaultActions : [{ op: 'set_category', value: '' }]
@@ -99,19 +232,10 @@ export function RuleDialog({
const [applyToExisting, setApplyToExisting] = useState(!rule)
const [overwriteExistingCategories, setOverwriteExistingCategories] = useState(false)
- const selectClass = 'border border-border rounded-lg px-2 py-1.5 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'
-
function updateCondition(i: number, field: keyof RuleCondition, val: string | number) {
- setConditions(prev => prev.map((c, idx) => {
- if (idx !== i) return c
- if (field !== 'field') return { ...c, [field]: val }
- return {
- ...c,
- field: String(val),
- op: getOpsForField(String(val))[0].value,
- value: defaultValueForField(String(val)),
- }
- }))
+ setConditions(prev => prev.map((node, idx) => (
+ idx === i && !isConditionGroup(node) ? applyLeafChange(node, field, val) : node
+ )))
}
function removeCondition(i: number) {
@@ -119,7 +243,46 @@ export function RuleDialog({
}
function addCondition() {
- setConditions(prev => [...prev, { field: 'description', op: 'contains', value: '' }])
+ setConditions(prev => [...prev, newCondition()])
+ }
+
+ // A group starts with two conditions: one alone would carry no AND/OR meaning.
+ function addGroup() {
+ setConditions(prev => [...prev, { op: 'or', conditions: [newCondition(), newCondition()] }])
+ }
+
+ function setGroupOp(i: number, op: 'and' | 'or') {
+ setConditions(prev => prev.map((node, idx) => (
+ idx === i && isConditionGroup(node) ? { ...node, op } : node
+ )))
+ }
+
+ function addGroupCondition(i: number) {
+ setConditions(prev => prev.map((node, idx) => (
+ idx === i && isConditionGroup(node)
+ ? { ...node, conditions: [...node.conditions, newCondition()] }
+ : node
+ )))
+ }
+
+ function updateGroupCondition(i: number, j: number, field: keyof RuleCondition, val: string | number) {
+ setConditions(prev => prev.map((node, idx) => {
+ if (idx !== i || !isConditionGroup(node)) return node
+ return {
+ ...node,
+ conditions: node.conditions.map((c, cIdx) => (cIdx === j ? applyLeafChange(c, field, val) : c)),
+ }
+ }))
+ }
+
+ // Removing a group's last condition removes the group — an empty one never
+ // matches anything and the API rejects it.
+ function removeGroupCondition(i: number, j: number) {
+ setConditions(prev => prev.flatMap((node, idx) => {
+ if (idx !== i || !isConditionGroup(node)) return [node]
+ const remaining = node.conditions.filter((_, cIdx) => cIdx !== j)
+ return remaining.length ? [{ ...node, conditions: remaining }] : []
+ }))
}
function updateAction(i: number, field: keyof RuleAction, val: string) {
@@ -141,7 +304,7 @@ 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 hasBlankCondition = flattenConditions(conditions).some(c => String(c.value ?? '').trim() === '')
const hasInvalidDescriptionAction = actions.some(isInvalidDescriptionAction)
function handleSubmit(e: React.FormEvent) {
@@ -195,102 +358,75 @@ export function RuleDialog({
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label>{t('rules.conditions')}</Label>
- <div className="flex items-center gap-1 bg-muted rounded-lg p-0.5">
- {(['and', 'or'] as const).map(op => (
- <button
- key={op}
- type="button"
- className={cn(
- 'px-3 py-1 text-xs font-semibold rounded-md transition-all',
- conditionsOp === op ? 'bg-card shadow-sm text-foreground' : 'text-muted-foreground hover:text-foreground'
- )}
- onClick={() => setConditionsOp(op)}
- >
- {op === 'and' ? t('rules.andOp') : t('rules.orOp')}
- </button>
- ))}
- </div>
+ <OpToggle value={conditionsOp} onChange={setConditionsOp} />
</div>
<div className="space-y-2">
- {conditions.map((cond, i) => (
- <div key={i} className="relative grid min-w-0 grid-cols-2 gap-2 pr-7 sm:flex sm:items-center sm:pr-0">
- <select
- className={`${selectClass} w-full sm:w-32 sm:shrink-0`}
- value={cond.field}
- onChange={(e) => updateCondition(i, 'field', e.target.value)}
- >
- {CONDITION_FIELDS.map(f => (
- <option key={f.value} value={f.value}>{t(f.label)}</option>
- ))}
- </select>
- <select
- className={`${selectClass} w-full sm:w-32 sm:shrink-0`}
- value={cond.op}
- onChange={(e) => updateCondition(i, 'op', e.target.value)}
- >
- {getOpsForField(cond.field).map(o => (
- <option key={o.value} value={o.value}>{t(o.label)}</option>
+ {conditions.map((node, i) => (
+ isConditionGroup(node) ? (
+ <div key={i} className="rounded-lg border border-border bg-muted/40 p-2 space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium text-muted-foreground">{t('rules.group')}</span>
+ <div className="flex items-center gap-1">
+ <OpToggle value={node.op} onChange={(op) => setGroupOp(i, op)} />
+ <button
+ type="button"
+ className="shrink-0 p-1 text-muted-foreground transition-colors hover:text-rose-500"
+ title={t('rules.removeGroup')}
+ onClick={() => removeCondition(i)}
+ >
+ <X size={13} />
+ </button>
+ </div>
+ </div>
+ {node.conditions.map((cond, j) => (
+ <ConditionRow
+ key={j}
+ condition={cond}
+ accounts={sortedAccounts}
+ payees={payees}
+ onChange={(field, val) => updateGroupCondition(i, j, field, val)}
+ onRemove={() => removeGroupCondition(i, j)}
+ />
))}
- </select>
- {cond.field === 'type' ? (
- <select
- className={`${selectClass} col-span-2 w-full min-w-0 sm:w-0 sm:flex-1`}
- value={String(cond.value)}
- onChange={(e) => updateCondition(i, 'value', e.target.value)}
+ <button
+ type="button"
+ className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"
+ onClick={() => addGroupCondition(i)}
>
- <option value="debit">{t('rules.typeExpense')}</option>
- <option value="credit">{t('rules.typeIncome')}</option>
- </select>
- ) : cond.field === 'account_id' ? (
- <select
- className={`${selectClass} col-span-2 w-full min-w-0 sm:w-0 sm:flex-1`}
- value={String(cond.value)}
- onChange={(e) => updateCondition(i, 'value', e.target.value)}
- >
- <option value="">{t('rules.selectAccount')}</option>
- {sortedAccounts.map(acc => (
- <option key={acc.id} value={acc.id}>{getAccountName(acc)}</option>
- ))}
- </select>
- ) : cond.field === 'payee_id' ? (
- <select
- className={`${selectClass} col-span-2 w-full min-w-0 sm:w-0 sm:flex-1`}
- value={String(cond.value)}
- onChange={(e) => updateCondition(i, 'value', e.target.value)}
- >
- <option value="">{t('rules.selectPayee')}</option>
- {payees.map(p => (
- <option key={p.id} value={p.id}>{p.name}</option>
- ))}
- </select>
- ) : (
- <Input
- className="col-span-2 h-8 w-full min-w-0 text-sm sm:w-0 sm:flex-1"
- value={String(cond.value)}
- onChange={(e) => updateCondition(i, 'value', e.target.value)}
- placeholder={cond.field === 'amount' ? '0.00' : cond.field === 'date' ? 'YYYY-MM-DD' : t('rules.valuePlaceholder')}
- type={cond.field === 'amount' ? 'number' : cond.field === 'date' ? 'date' : 'text'}
- />
- )}
- <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={() => removeCondition(i)}
- >
- <X size={13} />
- </button>
- </div>
+ <Plus size={12} /> {t('rules.addCondition')}
+ </button>
+ </div>
+ ) : (
+ <ConditionRow
+ key={i}
+ condition={node}
+ accounts={sortedAccounts}
+ payees={payees}
+ onChange={(field, val) => updateCondition(i, field, val)}
+ onRemove={() => removeCondition(i)}
+ />
+ )
))}
{hasBlankCondition && (
<p className="text-xs text-rose-500">{t('rules.blankConditionValue')}</p>
)}
- <button
- type="button"
- className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"
- onClick={addCondition}
- >
- <Plus size={12} /> {t('rules.addCondition')}
- </button>
+ <div className="flex flex-wrap items-center gap-4">
+ <button
+ type="button"
+ className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"
+ onClick={addCondition}
+ >
+ <Plus size={12} /> {t('rules.addCondition')}
+ </button>
+ <button
+ type="button"
+ className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"
+ title={t('rules.addGroupHint')}
+ onClick={addGroup}
+ >
+ <Plus size={12} /> {t('rules.addGroup')}
+ </button>
+ </div>
</div>
</div>
@@ -304,7 +440,7 @@ export function RuleDialog({
<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`}
+ className={`${SELECT_CLASS} w-full sm:w-40 sm:shrink-0`}
value={action.op}
onChange={(e) => updateAction(i, 'op', e.target.value)}
>
@@ -326,12 +462,12 @@ export function RuleDialog({
categories={categories}
groups={categoryGroups}
placeholder={t('rules.selectCategory')}
- className={`${selectClass} w-full`}
+ className={`${SELECT_CLASS} w-full`}
/>
</div>
) : action.op === 'set_payee' ? (
<select
- className={`${selectClass} w-full min-w-0 sm:w-0 sm:flex-1`}
+ className={`${SELECT_CLASS} w-full min-w-0 sm:w-0 sm:flex-1`}
value={action.value}
onChange={(e) => updateAction(i, 'value', e.target.value)}
required
diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsx
index 459abb99..2e3a2c17 100644
--- a/frontend/src/components/transaction-dialog.tsx
+++ b/frontend/src/components/transaction-dialog.tsx
@@ -9,6 +9,7 @@ import { currencies as currenciesApi, transactions as transactionsApi, settings
import { localDateString } from '@/lib/date-utils'
import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
import { normalizeRuleMatchValue } from '@/lib/rule-match-utils'
+import { flattenConditions, hasConditionGroups } from '@/lib/rule-conditions'
import { cn, normalizeText } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -94,6 +95,10 @@ function getRuleCategoryId(rule: Rule): string | null {
}
function canExtendRuleFromTransaction(rule: Rule): boolean {
+ // Rules that mix AND and OR are left out: appending a top-level condition —
+ // and possibly flipping the rule to OR — would silently change what the
+ // grouped rule matches. Those are edited from the rules page instead.
+ if (hasConditionGroups(rule.conditions)) return false
return rule.is_active && !!getRuleCategoryId(rule) && (rule.conditions_op === 'or' || rule.conditions.length <= 1)
}
@@ -560,7 +565,7 @@ function TransactionForm({
rule: Rule
condition: RuleCondition
}) => {
- const duplicate = rule.conditions.some(existing =>
+ const duplicate = flattenConditions(rule.conditions).some(existing =>
existing.field === condition.field &&
existing.op === condition.op &&
normalizeRuleMatchValue(existing.value) === normalizeRuleMatchValue(condition.value)
diff --git a/frontend/src/lib/rule-conditions.test.ts b/frontend/src/lib/rule-conditions.test.ts
new file mode 100644
index 00000000..558b0efe
--- /dev/null
+++ b/frontend/src/lib/rule-conditions.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest'
+
+import { flattenConditions, hasConditionGroups, isConditionGroup } from './rule-conditions'
+import type { RuleConditionNode } from '../types'
+
+const leaf = { field: 'description', op: 'contains', value: 'UBER' }
+const group = {
+ op: 'or' as const,
+ conditions: [
+ { field: 'description', op: 'contains', value: 'IFOOD' },
+ { field: 'description', op: 'contains', value: 'RAPPI' },
+ ],
+}
+
+describe('rule condition helpers', () => {
+ it('tells leaves and groups apart', () => {
+ expect(isConditionGroup(leaf)).toBe(false)
+ expect(isConditionGroup(group)).toBe(true)
+ })
+
+ it('flattens one level of groups into their leaves', () => {
+ const nodes: RuleConditionNode[] = [leaf, group]
+ expect(flattenConditions(nodes).map(c => c.value)).toEqual(['UBER', 'IFOOD', 'RAPPI'])
+ })
+
+ it('leaves flat rules untouched when flattening', () => {
+ expect(flattenConditions([leaf])).toEqual([leaf])
+ })
+
+ it('detects rules that mix AND and OR', () => {
+ expect(hasConditionGroups([leaf])).toBe(false)
+ expect(hasConditionGroups([leaf, group])).toBe(true)
+ })
+})
diff --git a/frontend/src/lib/rule-conditions.ts b/frontend/src/lib/rule-conditions.ts
new file mode 100644
index 00000000..a7755678
--- /dev/null
+++ b/frontend/src/lib/rule-conditions.ts
@@ -0,0 +1,16 @@
+import type { RuleCondition, RuleConditionGroup, RuleConditionNode } from '../types'
+
+/** A condition list entry is a group when it carries its own condition list. */
+export function isConditionGroup(node: RuleConditionNode): node is RuleConditionGroup {
+ return Array.isArray((node as RuleConditionGroup).conditions)
+}
+
+/** Every leaf condition of a rule, unwrapping one level of AND/OR groups. */
+export function flattenConditions(nodes: RuleConditionNode[]): RuleCondition[] {
+ return nodes.flatMap(node => (isConditionGroup(node) ? node.conditions : [node]))
+}
+
+/** True when a rule mixes AND and OR, i.e. it holds at least one group. */
+export function hasConditionGroups(nodes: RuleConditionNode[]): boolean {
+ return nodes.some(isConditionGroup)
+}
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index e4f265ca..c8d22836 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -874,6 +874,10 @@
"andOp": "UND",
"orOp": "ODER",
"addCondition": "Bedingung hinzufügen",
+ "addGroup": "Gruppe hinzufügen",
+ "addGroupHint": "Eine Gruppe verknüpft ihre eigenen Bedingungen mit UND oder ODER",
+ "group": "Gruppe",
+ "removeGroup": "Gruppe entfernen",
"blankConditionValue": "Jede Bedingung benötigt einen Wert. Eine leere Bedingung würde auf alle Transaktionen zutreffen.",
"addAction": "Aktion hinzufügen",
"setCategory": "Kategorie festlegen",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 28e3ecfa..c04509da 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -874,6 +874,10 @@
"andOp": "AND",
"orOp": "OR",
"addCondition": "Add condition",
+ "addGroup": "Add group",
+ "addGroupHint": "A group joins its own conditions with AND or OR",
+ "group": "Group",
+ "removeGroup": "Remove group",
"blankConditionValue": "Every condition needs a value. A blank one would match every transaction.",
"addAction": "Add action",
"setCategory": "Set category",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 6ff2cd66..bcee3bbf 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -874,6 +874,10 @@
"andOp": "Y",
"orOp": "O",
"addCondition": "Agregar condición",
+ "addGroup": "Agregar grupo",
+ "addGroupHint": "Un grupo une sus propias condiciones con Y u O",
+ "group": "Grupo",
+ "removeGroup": "Eliminar grupo",
"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",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index abd313c6..ce117dff 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -874,6 +874,10 @@
"andOp": "ET",
"orOp": "OU",
"addCondition": "Ajouter une condition",
+ "addGroup": "Ajouter un groupe",
+ "addGroupHint": "Un groupe combine ses propres conditions avec ET ou OU",
+ "group": "Groupe",
+ "removeGroup": "Supprimer le groupe",
"blankConditionValue": "Chaque condition nécessite une valeur. Une condition vide correspondrait à toutes les transactions.",
"addAction": "Ajouter une action",
"setCategory": "Définir la catégorie",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index eb700111..65fea3a9 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -874,6 +874,10 @@
"andOp": "E",
"orOp": "O",
"addCondition": "Aggiungi condizione",
+ "addGroup": "Aggiungi gruppo",
+ "addGroupHint": "Un gruppo unisce le proprie condizioni con E oppure O",
+ "group": "Gruppo",
+ "removeGroup": "Rimuovi gruppo",
"blankConditionValue": "Ogni condizione richiede un valore. Una condizione vuota corrisponderebbe a tutte le transazioni.",
"addAction": "Aggiungi azione",
"setCategory": "Imposta categoria",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 4b2350c7..cc7822f7 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -934,6 +934,10 @@
"andOp": "ORAZ",
"orOp": "LUB",
"addCondition": "Dodaj warunek",
+ "addGroup": "Dodaj grupę",
+ "addGroupHint": "Grupa łączy własne warunki operatorem I lub LUB",
+ "group": "Grupa",
+ "removeGroup": "Usuń grupę",
"blankConditionValue": "Każdy warunek wymaga wartości. Pusty warunek pasowałby do wszystkich transakcji.",
"addAction": "Dodaj akcję",
"setCategory": "Ustaw kategorię",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 72f62039..079aad6c 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -874,6 +874,10 @@
"andOp": "E (AND)",
"orOp": "OU (OR)",
"addCondition": "Adicionar condição",
+ "addGroup": "Adicionar grupo",
+ "addGroupHint": "Um grupo junta suas próprias condições com E ou OU",
+ "group": "Grupo",
+ "removeGroup": "Remover grupo",
"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",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 36df1e2c..0ec9254c 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -874,6 +874,10 @@
"andOp": "E (AND)",
"orOp": "OU (OR)",
"addCondition": "Adicionar condição",
+ "addGroup": "Adicionar grupo",
+ "addGroupHint": "Um grupo junta as suas próprias condições com E ou OU",
+ "group": "Grupo",
+ "removeGroup": "Remover grupo",
"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",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 4d30efe6..72a7f78f 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -880,6 +880,10 @@
"andOp": "И",
"orOp": "ИЛИ",
"addCondition": "Добавить условие",
+ "addGroup": "Добавить группу",
+ "addGroupHint": "Группа объединяет свои условия оператором И или ИЛИ",
+ "group": "Группа",
+ "removeGroup": "Удалить группу",
"blankConditionValue": "Каждому условию нужно значение. Пустое условие совпадёт со всеми транзакциями.",
"addAction": "Добавить действие",
"setCategory": "Установить категорию",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 065a6063..8535b782 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -880,6 +880,10 @@
"andOp": "І",
"orOp": "АБО",
"addCondition": "Додати умову",
+ "addGroup": "Додати групу",
+ "addGroupHint": "Група об'єднує власні умови оператором І або АБО",
+ "group": "Група",
+ "removeGroup": "Видалити групу",
"blankConditionValue": "Кожна умова потребує значення. Порожня умова збігатиметься з усіма транзакціями.",
"addAction": "Додати дію",
"setCategory": "Установити категорію",
diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsx
index 267eb852..9d7f07e0 100644
--- a/frontend/src/pages/rules.tsx
+++ b/frontend/src/pages/rules.tsx
@@ -12,7 +12,8 @@ import {
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
-import type { Category, Payee, Rule, RuleAction, RuleCondition, RuleExportPayload } from '@/types'
+import type { Category, Payee, Rule, RuleAction, RuleCondition, RuleConditionNode, RuleExportPayload } from '@/types'
+import { isConditionGroup } from '@/lib/rule-conditions'
import { Trash2, Plus, RefreshCw, Package, Check, ArrowUpDown, ArrowUp, ArrowDown, Download, Upload } from 'lucide-react'
import { cn } from '@/lib/utils'
import { PageHeader } from '@/components/page-header'
@@ -75,7 +76,7 @@ function getOpsForField(field: string) {
return STRING_OPS
}
-function conditionSummary(conditions: RuleCondition[], conditionsOp: string, t: (key: string) => string, payeesList: Payee[]): string {
+function conditionSummary(conditions: RuleConditionNode[], conditionsOp: string, t: (key: string) => string, payeesList: Payee[]): string {
const fieldLabel = (f: string) => {
const key = CONDITION_FIELDS.find(x => x.value === f)?.label
return key ? t(key) : f
@@ -91,8 +92,15 @@ function conditionSummary(conditions: RuleCondition[], conditionsOp: string, t:
}
return String(c.value)
}
- const parts = conditions.map(c => `${fieldLabel(c.field)} ${opLabel(c.field, c.op)} "${valueLabel(c)}"`)
- return parts.join(` ${conditionsOp === 'or' ? t('rules.orOp') : t('rules.andOp')} `) || t('rules.noConditions')
+ const leafSummary = (c: RuleCondition) => `${fieldLabel(c.field)} ${opLabel(c.field, c.op)} "${valueLabel(c)}"`
+ const joiner = (op: string) => ` ${op === 'or' ? t('rules.orOp') : t('rules.andOp')} `
+ // Groups get parentheses so a mixed AND/OR rule reads unambiguously.
+ const parts = conditions.map(node => (
+ isConditionGroup(node)
+ ? `(${node.conditions.map(leafSummary).join(joiner(node.op))})`
+ : leafSummary(node)
+ ))
+ return parts.join(joiner(conditionsOp)) || t('rules.noConditions')
}
function actionSummary(actions: RuleAction[], categories: Category[], payeesList: Payee[], t: (key: string) => string): string {
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 3d54b03d..a7a90622 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -428,6 +428,20 @@ export interface RuleCondition {
value: string | number
}
+/** A nested group of conditions joined by its own operator.
+ *
+ * Groups let a rule mix AND and OR — `type is debit AND (contains UBER OR
+ * contains 99POP)`. They hold leaf conditions only, capping rule depth at the
+ * two levels the engine evaluates and the editor exposes.
+ */
+export interface RuleConditionGroup {
+ op: 'and' | 'or'
+ conditions: RuleCondition[]
+}
+
+/** An entry of a rule's condition list: a leaf condition or one group. */
+export type RuleConditionNode = RuleCondition | RuleConditionGroup
+
export interface RuleAction {
op: string
value: string
@@ -438,7 +452,7 @@ export interface Rule {
user_id: string
name: string
conditions_op: 'and' | 'or'
- conditions: RuleCondition[]
+ conditions: RuleConditionNode[]
actions: RuleAction[]
priority: number
is_active: boolean
@@ -449,7 +463,7 @@ export interface Rule {
export interface RuleExportItem {
name: string
conditions_op: 'and' | 'or'
- conditions: RuleCondition[]
+ conditions: RuleConditionNode[]
actions: RuleAction[]
priority: number
is_active: boolean