Warn on the rule form when a similar rule already exists

JA
9d ago
+651-44

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, wins and shared_count are 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.
    • wins needs 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_count is 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_scope would otherwise still apply.
    • A rule is never similar to itself (other.id == rule.id).
    • Only similar rules' matches are queried: matches_of is 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.
  • RulesController#create / #update: before save_rule, unless confirm_similar is present, run the check on a valid rule and render :new / :edit with 422 when it finds anything. An invalid rule shows its errors as before.
  • rules/_similar_rules.html.erb (a DS::Alert with Cancel and a Save anyway submit named confirm_similar), rendered at the top of rules/_form; RulesHelper#rule_summary, whose action label (#rule_action_label) the rules list now uses too; rule_health_reference now takes the position; locale strings.
  • The form's re-render keeps what was submitted: rule/conditions/_condition_group reads 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/_condition and rule/actions/_action write _destroy from marked_for_destruction? and hide that row, so a removed condition or action stays removed; Rule::Health#moving_group also takes a group typed into the form, which is built unsaved and leaves rule_group_id unchanged. render_invalid_rule renders 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?

WriterPathEffect
Rules form (incl. the transaction page's prompt, which only pre-fills new)RulesController#create / #updatenew check
Rule.create_from_grouping (Quick Categorize)modelunchanged; test: still creates an identical duplicate
Assistant::Function::CreateRule / UpdateRulemodelunchanged; test: CreateRule still creates an identical duplicate
RuleImport and the rule CSV/JSON importers, Rule.replace_merchant_references!modelunchanged (no validation added)
Active toggle on the rules list (PATCH with active only), and a request with only apply_immediately#updatenot 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.

TestKindBeforeAfter
create identical to existing → 422, names it (with its condition and action), count unchangedpositivefailspasses
same with confirm_similar=1 → saved, +1, redirects to confirmpositivepassespasses
unrelated rule → saved, no noticenegativepassespasses
same conditions, Groceries vs Dining out → 422; same conditions, tags only (no shared field) → 422 with no "wins"positivefailspasses
update until it repeats another → 422 naming it, value unchanged; with confirm_similar → savedpositive (update path)failspasses
inactive duplicate → "(inactive)", no wins, no count; same rule active → wins + "1 transaction"boundaryfailspasses
edit: similar rule directly above → wins; moved directly below → listed, no winsboundaryfailspasses
new rule placed in a group above the similar rule → listed, no wins (without the group → wins)boundaryfailspasses
shared count: existing matches 3, new (OR group) matches 3, shared "2 transactions"countfailspasses
edit without changes → saves, no noticenegative (self)passespasses
"woolworths metro" → Dining under "woolworths" → Groceries → "1 transaction"positivefailspasses
narrower text, no shared transactions, sets tags → savednegativepassespasses
switching a duplicate rule off from the list saves ittogglefails (422)passes
an inactive rule edited to repeat another: no wins, no countboundaryfails (wins shown)passes
a similar stop rule above that shares no field winsstop halfpasses; dropping other.stop_processing? fails itpasses
the rules list labels a rule's action as the notice doeslist labelpassespasses
Rule::Health: unsaved rule with an AND group vs active + inactive rulesmodelerrorspasses
Rule::Health: a condition marked for destruction is left outmodelerrorspasses
Rule::Health: a rule whose match query fails gets no shared count, not 0modelerrorspasses
the warning keeps a new group's conditions in the form, and renders no extra blank onere-renderfails (no sub-condition inputs)passes
an invalid rule keeps a new group's conditions in the formre-render, render_invalid_rulefailspasses
the warning keeps a removed condition and action removedre-renderfails (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 winsboundaryfails (no wins)passes
turning on apply immediately alone saves a duplicate; an edit that also sends it is still checkedapply_immediatelyfails (422)passes
create_from_grouping still creates an identical duplicateunchanged writerpassespasses
assistant CreateRule still creates an identical duplicateunchanged writerpassespasses

Mutations (applied to the container copy only)

MutationCaught by
check only in #createupdate test, position test
a rule similar to itselfedit-without-changes
inactive treated as activeinactive test
inactive skippedinactive test
always "wins"position test
group placement ignoredgroup test
"wins" without a shared field or stopsame-conditions tags half
failed match read as an empty setfailed-query model test
shared = the other rule's totalboth shared-count tests
same conditions must also have the same actionssame-conditions, tags-only half
text overlap ignores the fieldnarrower-no-share negative
confirm_similar ignoredsave-anyway and update tests
unsaved copy keeps destroyed conditionsmarked-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 builtboth 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 groupnew-group test
apply_immediately dropped from the unchecked keysboth apply_immediately tests
any request with apply_immediately skips the checkthe 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.

BeforeAfter
Light703-before-light-after-submit703-after-light-after-submit
Dark703-before-dark-after-submit703-after-dark-after-submit
Mobile703-before-light-mobile-after-submit703-after-light-mobile-after-submit

Validation

  • Full bin/rails test at b040cebb6: 18213 runs, 112530 assertions, 0 failures, 8 errors, 9 skips. All 8 errors are environmental: ReleaseNotesWorkflowTest, Errno::ENOENT: node.
  • Without the apply_immediately guard, main's own RulesControllerTest#test_update_saves_apply_immediately fails (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 on main (9e419e7be) in the same container.
  • bin/rubocop and erb_lint on 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 active or apply_immediately skip 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.