The personal finance app for everyone (by everyone)
Ruby
fix(rules): validate Rule::Condition type registry + normalize legacy values (#1908)
Khaosticac3cfdf03b2e5
diff --git a/app/models/rule/condition.rb b/app/models/rule/condition.rbindex c8b804f560..1fece12df5 100644--- a/app/models/rule/condition.rb+++ b/app/models/rule/condition.rb@@ -1,10 +1,18 @@class Rule::Condition < ApplicationRecord+ SUPPORTED_CONDITION_TYPES = (Rule::Registry::TransactionResource.condition_filter_keys + [ "compound" ]).freeze++ LEGACY_CONDITION_TYPE_ALIASES = {+ "name" => "transaction_name"+ }.freeze+belongs_to :rule, touch: true, optional: -> { where.not(parent_id: nil) }belongs_to :parent, class_name: "Rule::Condition", optional: true, inverse_of: :sub_conditionshas_many :sub_conditions, -> { order(:created_at, :id) }, class_name: "Rule::Condition", foreign_key: :parent_id, dependent: :destroy, inverse_of: :parent- validates :condition_type, presence: true+ before_validation :normalize_legacy_condition_type++ validates :condition_type, presence: true, inclusion: { in: SUPPORTED_CONDITION_TYPES, allow_blank: true }validates :operator, presence: truevalidates :value, presence: true, unless: -> { compound? || operator == "is_null" }@@ -57,9 +65,18 @@ class Rule::Condition < ApplicationRecorddef filterrule.registry.get_filter!(condition_type)+ rescue Rule::Registry::UnsupportedConditionError+ Rule::ConditionFilter::Unsupported.new(rule, condition_type)endprivate+ def normalize_legacy_condition_type+ return if condition_type.blank?++ normalized = LEGACY_CONDITION_TYPE_ALIASES[condition_type]+ self.condition_type = normalized if normalized+ end+def build_compound_scope(scope)if operator == "or"combined_scope = sub_conditionsdiff --git a/app/models/rule/condition_filter.rb b/app/models/rule/condition_filter.rbindex 387fdb355d..fdabcfa34b 100644--- a/app/models/rule/condition_filter.rb+++ b/app/models/rule/condition_filter.rb@@ -13,6 +13,10 @@ class Rule::ConditionFilter@rule = ruleend+ def self.key+ name.demodulize.underscore+ end+def type"text"end@@ -23,7 +27,7 @@ class Rule::ConditionFilterenddef key- self.class.name.demodulize.underscore+ self.class.keyenddef labeldiff --git a/app/models/rule/condition_filter/unsupported.rb b/app/models/rule/condition_filter/unsupported.rbnew file mode 100644index 0000000000..c7bb4fbccf--- /dev/null+++ b/app/models/rule/condition_filter/unsupported.rb@@ -0,0 +1,22 @@+class Rule::ConditionFilter::Unsupported < Rule::ConditionFilter+ def initialize(rule, condition_type)+ super(rule)+ @condition_type = condition_type.to_s+ end++ def key+ @condition_type+ end++ def label+ I18n.t("rule.conditions.unsupported_label", type: @condition_type)+ end++ def apply(scope, _operator, _value)+ Rails.logger.warn(+ "Rule::ConditionFilter::Unsupported applied: " \+ "rule_id=#{rule&.id.inspect} condition_type=#{@condition_type.inspect} — matching zero records"+ )+ scope.none+ end+enddiff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rbindex 20075f79b4..f4dc219625 100644--- a/app/models/rule/registry/transaction_resource.rb+++ b/app/models/rule/registry/transaction_resource.rb@@ -1,20 +1,26 @@class Rule::Registry::TransactionResource < Rule::Registry+ CONDITION_FILTER_CLASSES = [+ Rule::ConditionFilter::TransactionName,+ Rule::ConditionFilter::TransactionAmount,+ Rule::ConditionFilter::TransactionType,+ Rule::ConditionFilter::TransactionMerchant,+ Rule::ConditionFilter::TransactionCategory,+ Rule::ConditionFilter::TransactionTag,+ Rule::ConditionFilter::TransactionDetails,+ Rule::ConditionFilter::TransactionNotes,+ Rule::ConditionFilter::TransactionAccount+ ].freeze++ def self.condition_filter_keys+ CONDITION_FILTER_CLASSES.map(&:key)+ end+def resource_scopefamily.transactions.visible.with_entry.merge(Entry.excluding_split_parents).where(entry: { date: rule.effective_date.. })enddef condition_filters- [- Rule::ConditionFilter::TransactionName.new(rule),- Rule::ConditionFilter::TransactionAmount.new(rule),- Rule::ConditionFilter::TransactionType.new(rule),- Rule::ConditionFilter::TransactionMerchant.new(rule),- Rule::ConditionFilter::TransactionCategory.new(rule),- Rule::ConditionFilter::TransactionTag.new(rule),- Rule::ConditionFilter::TransactionDetails.new(rule),- Rule::ConditionFilter::TransactionNotes.new(rule),- Rule::ConditionFilter::TransactionAccount.new(rule)- ]+ CONDITION_FILTER_CLASSES.map { |filter_class| filter_class.new(rule) }enddef action_executorsdiff --git a/config/locales/models/rule/en.yml b/config/locales/models/rule/en.ymlindex adcc09b184..d869dc0d1e 100644--- a/config/locales/models/rule/en.yml+++ b/config/locales/models/rule/en.yml@@ -7,3 +7,6 @@ en:min_actions: "must have at least one action"duplicate_actions: "Rule cannot have duplicate actions %{types}"nested_conditions: "Compound conditions cannot be nested"+ rule:+ conditions:+ unsupported_label: "Unsupported (%{type})"diff --git a/db/migrate/20260616120000_normalize_rule_condition_types.rb b/db/migrate/20260616120000_normalize_rule_condition_types.rbnew file mode 100644index 0000000000..b0f18fce93--- /dev/null+++ b/db/migrate/20260616120000_normalize_rule_condition_types.rb@@ -0,0 +1,14 @@+class NormalizeRuleConditionTypes < ActiveRecord::Migration[7.2]+ def up+ execute <<~SQL+ UPDATE rule_conditions+ SET condition_type = 'transaction_name'+ WHERE condition_type = 'name'+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration,+ "Cannot reverse normalization of legacy 'name' condition_type values"+ end+enddiff --git a/test/models/rule/condition_test.rb b/test/models/rule/condition_test.rbindex 0af031c83f..4eb18e50b1 100644--- a/test/models/rule/condition_test.rb+++ b/test/models/rule/condition_test.rb@@ -604,6 +604,54 @@ class Rule::ConditionTest < ActiveSupport::TestCaseassert_not expense_filtered.map(&:id).include?(contribution_entry.transaction.id)end+ test "SUPPORTED_CONDITION_TYPES comes from the registry's filter keys" do+ expected = (Rule::Registry::TransactionResource.condition_filter_keys + [ "compound" ]).sort++ assert_equal expected, Rule::Condition::SUPPORTED_CONDITION_TYPES.sort+ end++ test "validates condition_type against supported registry" do+ condition = Rule::Condition.new(+ rule: @transaction_rule,+ condition_type: "definitely_not_a_real_type",+ operator: "like",+ value: "x"+ )++ assert_not condition.valid?+ assert_includes condition.errors[:condition_type], "is not included in the list"+ end++ test "normalizes legacy 'name' condition_type to 'transaction_name' on save" do+ condition = Rule::Condition.new(+ rule: @transaction_rule,+ condition_type: "name",+ operator: "like",+ value: "starbucks"+ )++ assert condition.valid?, condition.errors.full_messages.to_sentence+ assert_equal "transaction_name", condition.condition_type+ end++ test "filter falls back gracefully when persisted condition_type is unsupported" do+ # Bypass validations to simulate legacy rows that already exist in the database.+ condition = Rule::Condition.new(+ condition_type: "transaction_name",+ operator: "like",+ value: "x"+ )+ condition.rule = @transaction_rule+ condition.save!+ condition.update_columns(condition_type: "name")+ condition.reload++ assert_nothing_raised do+ assert_equal "Unsupported (name)", condition.filter.label+ assert_equal "name", condition.filter.key+ end+ end+test "transaction_type income excludes investment_contribution" doscope = @rule_scopediff --git a/test/system/rules_test.rb b/test/system/rules_test.rbindex 49f4601bcd..e0fd6fe3c3 100644--- a/test/system/rules_test.rb+++ b/test/system/rules_test.rb@@ -34,4 +34,25 @@ class RulesTest < ApplicationSystemTestCaseassert_selector "th", text: /queued\s+processed\s+modified\s+blocked/iassert_selector "td", text: "20 / 20 / 10 / 10"end++ test "rules page renders gracefully when a condition has an unsupported condition_type" do+ rule = @user.family.rules.create!(+ name: "Legacy bad rule",+ resource_type: "transaction",+ conditions: [+ Rule::Condition.new(condition_type: "transaction_name", operator: "like", value: "x")+ ],+ actions: [+ Rule::Action.new(action_type: "set_transaction_category", value: categories(:food_and_drink).id)+ ]+ )++ # Simulate a legacy row written before the inclusion validation existed.+ rule.conditions.first.update_columns(condition_type: "name")++ visit rules_path++ assert_selector "h3", text: "Legacy bad rule"+ assert_text "Unsupported (name)"+ endend