diff --git a/app/models/rule/condition_filter/transaction_account.rb b/app/models/rule/condition_filter/transaction_account.rb new file mode 100644 index 000000000..dcdabdf65 --- /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 +end diff --git a/app/models/rule/registry/transaction_resource.rb b/app/models/rule/registry/transaction_resource.rb index a9497d9c0..fb4847728 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::Registry Rule::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) ] end diff --git a/test/models/rule_test.rb b/test/models/rule_test.rb index 6f50221be..cc4256436 100644 --- a/test/models/rule_test.rb +++ b/test/models/rule_test.rb @@ -294,4 +294,58 @@ class RuleTest < ActiveSupport::TestCase test "total_affected_resource_count returns zero for empty rules" do assert_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" + end end