Warn on the rule form when a similar rule already exists
Closes #5176
Fork pre-flight: jaysbeekay/sure#797 (same branch, same commit).
Stack: #5525 Claims extraction → #5526 Rule health page → #5527 overlaps section → #5528 save-time warning on the rule form (stack #5529). This PR is the top: its save-time check reuses the Rule::Health comparison from #5526 and #5527.
Summary
Saving a rule never compared it with the family's other rules, so a duplicate, or a rule that a rule above already beats on every match, saved with a success message. The web form now checks before saving. If another rule is a duplicate, has the same conditions with different actions, or names the same or contained text and sets a field this one sets, the form re-renders (422) with a warning listing each similar rule: its run position and name (an edit link), its first condition and action, how many transactions both match, and, when it runs first, that it wins on those. "Save anyway" resubmits with confirm_similar and saves as today.
What changed
Rule::Health#similar_to(rule)(app/models/rule/health.rb): compares one rule, saved, new or carrying the form's unsaved changes, with the family's other rules, active and inactive.- Returns
Similar(rule, position, wins, shared_count). When either rule is switched off,winsandshared_countare nil: it doesn't run on sync, so there's no winner and no count. A new rule counts as on, since it is saved inactive and switched on at the confirm step. winsneeds the similar rule to run first where the saved rule will land, and to compete with it: set a field it sets, or stop the rules below. A new rule runs last (Rule#assign_next_position); a rule joining or leaving a group lands right after that group's other rules (Rule::Layout#place_after_group!), so that place is used; otherwise the stored order.shared_countis the number of distinct transaction ids both match, or nil (no line) when either match query fails. The form's rule is matched through an unsaved copy without the conditions marked for destruction, which#matching_scopewould otherwise still apply.- A rule is never similar to itself (
other.id == rule.id). - Only similar rules' matches are queried:
matches_ofis now lazy per rule (the health page still reads every rule). The text and field caches are keyed by object identity, since the form's copy of an edited rule shares the stored rule's id. Signatures skip conditions and actions marked for destruction. A merchant the family's rules don't name is looked up on its own.
- Returns
RulesController#create/#update: beforesave_rule, unlessconfirm_similaris present, run the check on a valid rule and render:new/:editwith 422 when it finds anything. An invalid rule shows its errors as before.rules/_similar_rules.html.erb(aDS::Alertwith Cancel and aSave anywaysubmit namedconfirm_similar), rendered at the top ofrules/_form;RulesHelper#rule_summary, whose action label (#rule_action_label) the rules list now uses too;rule_health_referencenow takes the position; locale strings.- The form's re-render keeps what was submitted:
rule/conditions/_condition_groupreads a group's sub-conditions before its template builds a blank one onto it, so a new AND/OR group keeps its conditions (it rendered only persisted ones);rule/conditions/_conditionandrule/actions/_actionwrite_destroyfrommarked_for_destruction?and hide that row, so a removed condition or action stays removed;Rule::Health#moving_groupalso takes a group typed into the form, which is built unsaved and leavesrule_group_idunchanged.render_invalid_rulerenders the same partials, so an invalid rule keeps a new group's conditions too.
Deliberately left out
- Blocking, merging, reordering; warnings in the assistant, the importers or Quick Categorize;
Transaction::Ruleable#eligible_for_category_rule?.
Blast radius: who else creates or updates rules, and what do they pass?
| Writer | Path | Effect |
|---|---|---|
Rules form (incl. the transaction page's prompt, which only pre-fills new) | RulesController#create / #update | new check |
Rule.create_from_grouping (Quick Categorize) | model | unchanged; test: still creates an identical duplicate |
Assistant::Function::CreateRule / UpdateRule | model | unchanged; test: CreateRule still creates an identical duplicate |
RuleImport and the rule CSV/JSON importers, Rule.replace_merchant_references! | model | unchanged (no validation added) |
Active toggle on the rules list (PATCH with active only), and a request with only apply_immediately | #update | not checked: a request with only these keys skips the check (tests: switching a duplicate off saves it; turning on apply immediately alone saves a duplicate, while a form edit that also sends it is still checked) |
Edit flow: the form resubmits the rule's own conditions; the rule is skipped by id, and a test edits a rule without changes and saves with no notice.
Tests
test/controllers/rules_controller_test.rb (15 new), test/models/rule/health_test.rb (2 new), test/models/rule_test.rb (1), test/models/assistant/function/create_rule_test.rb (1). Before = parent commit (#5527): the 7 positive controller tests fail (Rule.count changed by 1 / no [data-similar-rule]), the 2 Health tests error (undefined method 'similar_to'); the negatives and the unchanged-writer tests pass before and after.
| Test | Kind | Before | After |
|---|---|---|---|
| create identical to existing → 422, names it (with its condition and action), count unchanged | positive | fails | passes |
same with confirm_similar=1 → saved, +1, redirects to confirm | positive | passes | passes |
| unrelated rule → saved, no notice | negative | passes | passes |
| same conditions, Groceries vs Dining out → 422; same conditions, tags only (no shared field) → 422 with no "wins" | positive | fails | passes |
update until it repeats another → 422 naming it, value unchanged; with confirm_similar → saved | positive (update path) | fails | passes |
| inactive duplicate → "(inactive)", no wins, no count; same rule active → wins + "1 transaction" | boundary | fails | passes |
| edit: similar rule directly above → wins; moved directly below → listed, no wins | boundary | fails | passes |
| new rule placed in a group above the similar rule → listed, no wins (without the group → wins) | boundary | fails | passes |
| shared count: existing matches 3, new (OR group) matches 3, shared "2 transactions" | count | fails | passes |
| edit without changes → saves, no notice | negative (self) | passes | passes |
| "woolworths metro" → Dining under "woolworths" → Groceries → "1 transaction" | positive | fails | passes |
| narrower text, no shared transactions, sets tags → saved | negative | passes | passes |
| switching a duplicate rule off from the list saves it | toggle | fails (422) | passes |
| an inactive rule edited to repeat another: no wins, no count | boundary | fails (wins shown) | passes |
| a similar stop rule above that shares no field wins | stop half | passes; dropping other.stop_processing? fails it | passes |
| the rules list labels a rule's action as the notice does | list label | passes | passes |
Rule::Health: unsaved rule with an AND group vs active + inactive rules | model | errors | passes |
Rule::Health: a condition marked for destruction is left out | model | errors | passes |
Rule::Health: a rule whose match query fails gets no shared count, not 0 | model | errors | passes |
| the warning keeps a new group's conditions in the form, and renders no extra blank one | re-render | fails (no sub-condition inputs) | passes |
| an invalid rule keeps a new group's conditions in the form | re-render, render_invalid_rule | fails | passes |
| the warning keeps a removed condition and action removed | re-render | fails (0 hidden rows with _destroy=true) | passes |
| a similar rule wins over a rule moved into a new group typed into the form; not moved: no wins | boundary | fails (no wins) | passes |
| turning on apply immediately alone saves a duplicate; an edit that also sends it is still checked | apply_immediately | fails (422) | passes |
create_from_grouping still creates an identical duplicate | unchanged writer | passes | passes |
assistant CreateRule still creates an identical duplicate | unchanged writer | passes | passes |
Mutations (applied to the container copy only)
| Mutation | Caught by |
|---|---|
check only in #create | update test, position test |
| a rule similar to itself | edit-without-changes |
| inactive treated as active | inactive test |
| inactive skipped | inactive test |
| always "wins" | position test |
| group placement ignored | group test |
| "wins" without a shared field or stop | same-conditions tags half |
| failed match read as an empty set | failed-query model test |
| shared = the other rule's total | both shared-count tests |
| same conditions must also have the same actions | same-conditions, tags-only half |
| text overlap ignores the field | narrower-no-share negative |
confirm_similar ignored | save-anyway and update tests |
| unsaved copy keeps destroyed conditions | marked-for-destruction model test |
| group renders only persisted sub-conditions (as before) | both new-group re-render tests |
| group reads its sub-conditions after the template is built | both new-group re-render tests |
condition or action _destroy written as false, or its row not hidden (4 mutations) | removed condition and action |
moving_group ignores an unsaved group | new-group test |
apply_immediately dropped from the unchecked keys | both apply_immediately tests |
any request with apply_immediately skips the check | the edit half of the new test |
Screenshots
Before (up/rule-health): the prompt-prefilled rule "Woolworths Metro → Dining out" saves and goes straight to the Apply confirmation. After: the form shows the warning naming "#2 Woolworths", light, dark and mobile.
| Before | After | |
|---|---|---|
| Light | ![]() | ![]() |
| Dark | ![]() | ![]() |
| Mobile | ![]() | ![]() |
Validation
- Full
bin/rails testat b040cebb6: 18213 runs, 112530 assertions, 0 failures, 8 errors, 9 skips. All 8 errors are environmental:ReleaseNotesWorkflowTest,Errno::ENOENT: node. - Without the
apply_immediatelyguard,main's ownRulesControllerTest#test_update_saves_apply_immediatelyfails (422 on a rule resembling a fixture rule). test/system/rules_test.rb: 13 runs, 1 failure (keeps a rule with long text inside a phone-width screen), which fails the same way onmain(9e419e7be) in the same container.bin/rubocopanderb_linton the changed files: no offenses.bin/brakeman: 0 warnings.- Checked against upstream
AGENTS.md(blob 1a5dbebd): no deviations. - No API or migration changes.
Summary by cubic
Saving a rule never compared it with the family's other rules, so a duplicate, or a rule that a rule above already beats on every match, saved with a success message. The web form now checks before saving and re-renders (422) when another rule repeats it, shares its conditions, or names the same or contained text and sets a field it sets, listing each similar rule with its run position and name, first condition and action, the transactions both match, and whether it wins them. "Save anyway" resubmits with confirm_similar and saves as before.
Scope
- The check lives in the controller, so Quick Categorize, the assistant's rule functions, and the importers still save identical duplicates.
- Requests that change only
activeorapply_immediatelyskip the check, so the rules list's switch and the apply-immediately setting still save. - Submissions that remove an unsupported action skip the check too, since that form can't re-render the removed action.
- Inactive rules are listed without a shared count or a winner, since they don't run on sync.
- The re-rendered form keeps a new group's conditions and keeps removed conditions and actions removed.
- The comparison leaves out conditions marked for destruction, so a removed condition no longer cancels the warning for a kept one.
- The list and notice share an action-label helper, which shows a fallback instead of raising when a rule's first action type is no longer offered.
Summary by CodeRabbit
- New Features
- When creating or updating a rule that resembles an existing rule, you’ll see a warning with matching-rule details and transaction overlap information where available, including which rule takes precedence.
- You can cancel and revise the rule or choose to save it anyway.
- Bug Fixes
- Removing conditions or actions while editing a rule now correctly reflects those changes when the rule is saved.
- Newly added, unsaved sub-conditions are now included when editing a rule.





