The personal finance app for everyone (by everyone)
Ruby
Add "Transaction account" as rule condition filter (#1186)
Alessio Cappa80026aeee44d
diff --git a/app/models/rule/condition_filter/transaction_account.rb b/app/models/rule/condition_filter/transaction_account.rbnew file mode 100644index 0000000000..dcdabdf65f--- /dev/null+++ b/app/models/rule/condition_filter/transaction_account.rb@@ -0,0 +1,14 @@+class Rule::ConditionFilter::TransactionAccount < Rule::ConditionFilter+ def type+ "select"+ end++ def options+ family.accounts.alphabetically.pluck(:name, :id)+ end++ def apply(scope, operator, value)+ expression = build_sanitized_where_condition("entries.account_id", operator, value)+ scope.where(expression)+ end+enddiff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rbindex a9497d9c03..fb48477287 100644--- a/app/models/rule/registry/transaction_resource.rb+++ b/app/models/rule/registry/transaction_resource.rb@@ -11,7 +11,8 @@ class Rule::Registry::TransactionResource < Rule::RegistryRule::ConditionFilter::TransactionMerchant.new(rule),Rule::ConditionFilter::TransactionCategory.new(rule),Rule::ConditionFilter::TransactionDetails.new(rule),- Rule::ConditionFilter::TransactionNotes.new(rule)+ Rule::ConditionFilter::TransactionNotes.new(rule),+ Rule::ConditionFilter::TransactionAccount.new(rule)]enddiff --git a/test/models/rule_test.rb b/test/models/rule_test.rbindex 6f50221be3..cc42564362 100644--- a/test/models/rule_test.rb+++ b/test/models/rule_test.rb@@ -294,4 +294,58 @@ class RuleTest < ActiveSupport::TestCasetest "total_affected_resource_count returns zero for empty rules" doassert_equal 0, Rule.total_affected_resource_count([])end++ test "rule matching on transaction account" do+ # Create a second account+ other_account = @family.accounts.create!(+ name: "Other account",+ balance: 500,+ currency: "USD",+ accountable: Depository.new+ )++ # Transaction on the target account+ transaction_entry1 = create_transaction(+ date: Date.current,+ account: @account,+ amount: 50+ )++ # Transaction on another account+ transaction_entry2 = create_transaction(+ date: Date.current,+ account: other_account,+ amount: 75+ )++ rule = Rule.create!(+ family: @family,+ resource_type: "transaction",+ effective_date: 1.day.ago.to_date,+ conditions: [+ Rule::Condition.new(+ condition_type: "transaction_account",+ operator: "=",+ value: @account.id+ )+ ],+ actions: [+ Rule::Action.new(+ action_type: "set_transaction_category",+ value: @groceries_category.id+ )+ ]+ )++ rule.apply++ transaction_entry1.reload+ transaction_entry2.reload++ assert_equal @groceries_category, transaction_entry1.transaction.category,+ "Transaction on selected account should be categorized"++ assert_nil transaction_entry2.transaction.category,+ "Transaction on other account should not be categorized"+ endend