The personal finance app for everyone (by everyone)
Ruby
Let the set-merchant rule action use provider merchants (#4759)
GFR2bf00a4aac10
diff --git a/app/models/assistant/function/rule_support.rb b/app/models/assistant/function/rule_support.rbindex 664de32008..db04e85a9e 100644--- a/app/models/assistant/function/rule_support.rb+++ b/app/models/assistant/function/rule_support.rb@@ -225,6 +225,7 @@ module Assistant::Function::RuleSupportreturn [ "#{path}: value is required for #{type}." ] if value.blank?allowed = allowed_values(type)+ allowed += saved_merchant_values(rule) if type == "set_transaction_merchant"return [ "#{path}: '#{value}' is not a valid value for #{type}. #{value_hint(type)}" ] if allowed && !allowed.include?(value)end@@ -245,6 +246,14 @@ module Assistant::Function::RuleSupport[ e.message ]end+ # A merchant another member saved on the rule may be on accounts this user+ # can't see. Re-submitting the rule keeps it, as the rule form does (see+ # Rule::Action#options), without letting the user pick it anew elsewhere.+ def saved_merchant_values(rule)+ rule.actions.select { |action| action.persisted? && action.action_type == "set_transaction_merchant" }+ .map { |action| action.value_was.to_s }+ end+# nil means free text (no fixed list of values).def allowed_values(key)case key@@ -252,7 +261,7 @@ module Assistant::Function::RuleSupportwhen *CATEGORY_KEYS then family.categories.pluck(:id).map(&:to_s)when *TAG_KEYS then family.tags.pluck(:id).map(&:to_s)when "transaction_merchant" then family.available_merchants_for(user).pluck(:id).map(&:to_s)- when "set_transaction_merchant" then family.merchants.pluck(:id).map(&:to_s)+ when "set_transaction_merchant" then family.assignable_merchants_for(user).pluck(:id).map(&:to_s)when "transaction_type" then %w[income expense transfer]when "set_investment_activity_label" then Transaction::ACTIVITY_LABELSenddiff --git a/app/models/family.rb b/app/models/family.rbindex f23fe86105..828e19a192 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -487,6 +487,17 @@ class Family < ApplicationRecordMerchant.where(id: merchant_ids)end+ # Merchants a rule can set on transactions: the family's own plus the+ # provider merchants already on transactions the user can see. Unlike+ # available_merchants_for, recently unlinked merchants are left out, since a+ # rule that set one again would undo the unlink.+ def assignable_merchants_for(user)+ assigned_ids = Transaction.joins(:entry)+ .where(entries: { account_id: accounts.accessible_by(user).select(:id) })+ .select(:merchant_id)+ Merchant.where(id: merchants.select(:id)).or(Merchant.where(type: "ProviderMerchant", id: assigned_ids))+ end+def available_merchants_for(user)assigned_ids = Transaction.joins(:entry).where(entries: { account_id: accounts.accessible_by(user).select(:id) })diff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rbindex aec967c0e9..a4801cdd4b 100644--- a/app/models/family/data_exporter.rb+++ b/app/models/family/data_exporter.rb@@ -804,7 +804,7 @@ class Family::DataExporter# Map merchant UUIDs to names for portabilityif condition.condition_type == "transaction_merchant"- return rule_operand(condition.value, type: "Merchant", relation: :merchants)+ return rule_operand(condition.value, type: "Merchant", relation: :available_merchants)end# Map tag UUIDs to names for portability@@ -825,7 +825,7 @@ class Family::DataExporter# Map merchant UUIDs to names for portabilityif action.action_type == "set_transaction_merchant"- return rule_operand(action.value, type: "Merchant", relation: :merchants, fallback_to_name: true)+ return rule_operand(action.value, type: "Merchant", relation: :available_merchants, fallback_to_name: true)end# Map tag UUIDs to names for portability. Stored as a comma-separateddiff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex 3bb4dc4673..9ea1648e21 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -1519,7 +1519,7 @@ class Family::DataImporter# Map merchant names to IDsif condition_type == "transaction_merchant"- return find_or_create_rule_merchant(value).id+ return resolve_rule_merchant_id(condition_data, value)end# Map tag names to IDs@@ -1551,7 +1551,7 @@ class Family::DataImporter# Map merchant names to IDsif action_type == "set_transaction_merchant"- return find_or_create_rule_merchant(value).id+ return resolve_rule_merchant_id(action_data, value)endvalue@@ -1629,6 +1629,18 @@ class Family::DataImporter)end+ # A merchant this import already mapped (a FamilyMerchant, or a reused+ # ProviderMerchant, see import_provider_merchants) keeps the rule on the same+ # record as the restored transactions. Anything else is found or created by+ # name.+ def resolve_rule_merchant_id(data, name)+ value_ref = data["value_ref"]+ ref_id = value_ref["id"] if value_ref.is_a?(Hash) && value_ref["type"] == "Merchant"+ mapped = mapped_id(:merchants, ref_id.to_s, record_type: "Rule", required: false) if ref_id.present?++ mapped || find_or_create_rule_merchant(name).id+ end+def find_or_create_rule_merchant(name)rule_merchants_by_name[name] ||= @family.merchants.create!(name: name)enddiff --git a/app/models/merchant/merger.rb b/app/models/merchant/merger.rbindex 4c57e4844b..5ac26e1148 100644--- a/app/models/merchant/merger.rb+++ b/app/models/merchant/merger.rb@@ -54,6 +54,8 @@ class Merchant::Merger@merged_count += 1end++ Rule.replace_merchant_references!(family, from: source_merchants.map(&:id), to: target_merchant.id)endtruediff --git a/app/models/provider_merchant.rb b/app/models/provider_merchant.rbindex 4bbdfc1891..2683f0bf2e 100644--- a/app/models/provider_merchant.rb+++ b/app/models/provider_merchant.rb@@ -107,6 +107,7 @@ class ProviderMerchant < Merchant# Update only this family's transactions to point to new merchantscope.update_all(merchant_id: family_merchant.id)+ Rule.replace_merchant_references!(family, from: id, to: family_merchant.id)family_merchantenddiff --git a/app/models/rule.rb b/app/models/rule.rbindex 3486faa0b3..0309d02e2b 100644--- a/app/models/rule.rb+++ b/app/models/rule.rb@@ -185,6 +185,37 @@ class Rule < ApplicationRecord[ family.rules.maximum(:position).to_i, family.rule_groups.maximum(:position).to_i ].max + 1end+ # Points the family's merchant conditions and actions at another merchant+ # after its transactions moved there (a provider merchant converted to a+ # family merchant, or merchants merged). Otherwise a rule would keep matching+ # or setting the old merchant and undo the move on its next run.+ def self.replace_merchant_references!(family, from:, to:)+ from_ids = Array(from).map { |id| id.to_s.downcase }+ return if from_ids.empty?++ rule_ids = family.rules.select(:id)+ conditions = Rule::Condition.where(condition_type: "transaction_merchant").where("LOWER(rule_conditions.value) IN (?)", from_ids)+ rewritten = conditions+ .where(rule_id: rule_ids)+ .or(conditions.where(parent_id: Rule::Condition.where(rule_id: rule_ids).select(:id)))+ rewritten_rule_ids = rewritten.where.not(rule_id: nil).pluck(:rule_id) |+ Rule::Condition.where(id: rewritten.where.not(parent_id: nil).select(:parent_id)).pluck(:rule_id)+ rewritten.update_all(value: to.to_s, updated_at: Time.current)++ Rule::Action.where(rule_id: rule_ids, action_type: "set_transaction_merchant")+ .where("LOWER(rule_actions.value) IN (?)", from_ids)+ .update_all(value: to.to_s, updated_at: Time.current)++ # update_all skips the callback that re-takes an email rule's baseline when+ # its conditions change. Without it, a merge would email the target+ # merchant's past transactions as new matches.+ family.rules.where(id: rewritten_rule_ids).find_each(&:reseed_notification_baseline!)+ end++ def reseed_notification_baseline!+ seed_notification_baseline+ end+# Excludes transaction ids with one array parameter. where.not(id: ids) sends# one bind per id, which breaks beyond PostgreSQL's 65,535 bind limit when a# broad rule claims or stops many transactions.diff --git a/app/models/rule/action.rb b/app/models/rule/action.rbindex 5969e1eb0f..c95b231505 100644--- a/app/models/rule/action.rb+++ b/app/models/rule/action.rb@@ -32,6 +32,13 @@ class Rule::Action < ApplicationRecordvalidates_with DatabaseTextValidator, attributes: %i[action_type value]before_validation :build_split_value, if: -> { action_type == "split_transaction" && split_rows.present? }validate :split_config_valid, if: -> { action_type == "split_transaction" }+ # The rule runs for the whole family, so the merchant a user picks must be one+ # they can see. Checked only when a user sets the value; a merchant another+ # member saved stays as it is (see #options).+ validate :merchant_assignable_by_user, if: -> {+ action_type == "set_transaction_merchant" && Current.user && value.present? &&+ (new_record? || will_save_change_to_value? || will_save_change_to_action_type?)+ }# Pre-seed (watermark): when an EMAIL_NOTIFICATION action is created — on a# new rule OR added to an existing one — record all currently-matching@@ -94,7 +101,14 @@ class Rule::Action < ApplicationRecordenddef options- rule.option_list([ :action, action_type ]) { executor.options }+ executor_options = rule.option_list([ :action, action_type ]) { executor.options }+ return executor_options if executor_options.nil? || value.blank?+ return executor_options if executor_options.any? { |_label, id| id.to_s == value.to_s }++ # Shared across the rules of a page (see Rule.share_option_lists), so a+ # saved value outside the options is looked up once per request.+ saved_option = rule.option_list([ :saved_action_option, action_type, value.to_s ]) { executor.option_for(value) }+ saved_option ? executor_options + [ saved_option ] : executor_optionsenddef claimed_attributes@@ -127,6 +141,12 @@ class Rule::Action < ApplicationRecordendprivate+ def merchant_assignable_by_user+ return if UuidFormat.valid?(value) && rule&.family&.assignable_merchants_for(Current.user)&.exists?(id: value)++ errors.add(:value, :invalid)+ end+def execution_valueexecutor.type == "multi_select" ? value.to_s.split(",") : valueenddiff --git a/app/models/rule/action_executor.rb b/app/models/rule/action_executor.rbindex b21884172f..3e32f2af7b 100644--- a/app/models/rule/action_executor.rb+++ b/app/models/rule/action_executor.rb@@ -25,6 +25,14 @@ class Rule::ActionExecutornilend+ # The option for a saved value that options leaves out (e.g. a merchant only+ # on accounts the current user can't see, or one no longer assigned), so+ # editing the rule keeps the value instead of silently switching to the+ # first option. nil if the value doesn't refer to a record at all.+ def option_for(value)+ nil+ end+# Attributes this action sets. When several rules set the same attribute on# a transaction, the rule highest in the list wins (see Rule::Runner), so the# action skips transactions a rule above already claimed. Additive actionsdiff --git a/app/models/rule/action_executor/set_transaction_merchant.rb b/app/models/rule/action_executor/set_transaction_merchant.rbindex 7f07b24646..726c92e8be 100644--- a/app/models/rule/action_executor/set_transaction_merchant.rb+++ b/app/models/rule/action_executor/set_transaction_merchant.rb@@ -4,7 +4,25 @@ class Rule::ActionExecutor::SetTransactionMerchant < Rule::ActionExecutorenddef options- family.merchants.alphabetically.pluck(:name, :id)+ family.assignable_merchants_for(Current.user).alphabetically.pluck(:name, :id)+ end++ # A saved merchant outside the current user's options stays selected and is+ # marked instead of the form silently switching to another merchant. Its+ # name is only shown while the family still has a record of the unlink: a+ # merchant on accounts the user can't see, another family's merchant and an+ # unknown id all get a label without a name.+ def option_for(value)+ return if value.blank?++ label = if assignable_merchant(value)+ I18n.t("rule.actions.set_transaction_merchant.not_accessible")+ elsif (unlinked = FamilyMerchantAssociation.find_by(family: family, merchant_id: value)&.merchant)+ I18n.t("rule.actions.set_transaction_merchant.unassigned", name: unlinked.name)+ else+ I18n.t("rule.actions.set_transaction_merchant.unavailable")+ end+ [ label, value ]enddef claimed_attributes@@ -12,11 +30,11 @@ class Rule::ActionExecutor::SetTransactionMerchant < Rule::ActionExecutorenddef actionable?(value)- family.merchants.exists?(id: value)+ assignable_merchant(value).present?enddef execute(transaction_scope, value: nil, ignore_attribute_locks: false, rule_run: nil)- merchant = family.merchants.find_by_id(value)+ merchant = assignable_merchant(value)return 0 unless merchantscope = transaction_scope@@ -34,4 +52,15 @@ class Rule::ActionExecutor::SetTransactionMerchant < Rule::ActionExecutor)endend++ private+ # Rules run in the background without a user, so this checks the whole+ # family: one of its own merchants, or a provider merchant that is still on+ # one of its transactions.+ def assignable_merchant(value)+ return unless UuidFormat.valid?(value)++ family.merchants.find_by(id: value) ||+ (ProviderMerchant.find_by(id: value) if family.transactions.exists?(merchant_id: value))+ endenddiff --git a/app/models/rule_import.rb b/app/models/rule_import.rbindex 911f561f95..aa526007fb 100644--- a/app/models/rule_import.rb+++ b/app/models/rule_import.rb@@ -342,7 +342,9 @@ class RuleImport < Importcase kindwhen :category then find_or_create_category(name).id- when :merchant then find_or_create_merchant(name).id+ # A split child is set like a manual split, which only offers the+ # family's own merchants.+ when :merchant then find_or_create_family_merchant(name).idwhen :tag then find_or_create_tag(name).idendend@@ -361,8 +363,19 @@ class RuleImport < Import@categories_by_name ||= family.categories.index_by(&:name)end- def merchants_by_name- @merchants_by_name ||= family.merchants.index_by(&:name)+ def family_merchants_by_name+ @family_merchants_by_name ||= family.merchants.index_by(&:name)+ end++ # An exported rule may name a provider merchant (see Family::DataExporter);+ # reuse it while it is still on the family's transactions, so the rule+ # keeps matching them. A name shared by several provider merchants is+ # ambiguous and left out.+ def provider_merchants_by_name+ @provider_merchants_by_name ||= ProviderMerchant.where(id: family.transactions.select(:merchant_id))+ .group_by(&:name)+ .filter_map { |name, merchants| [ name, merchants.first ] if merchants.one? }+ .to_henddef tags_by_name@@ -377,8 +390,13 @@ class RuleImport < Import)end+ # The family's own merchant wins on a name clash.def find_or_create_merchant(name)- merchants_by_name[name] ||= family.merchants.create!(name: name)+ family_merchants_by_name[name] || provider_merchants_by_name[name] || find_or_create_family_merchant(name)+ end++ def find_or_create_family_merchant(name)+ family_merchants_by_name[name] ||= family.merchants.create!(name: name)enddef find_or_create_tag(name)diff --git a/config/locales/models/rule/de.yml b/config/locales/models/rule/de.ymlindex 494e04d52e..5feccb1ae4 100644--- a/config/locales/models/rule/de.yml+++ b/config/locales/models/rule/de.yml@@ -29,5 +29,10 @@ de:fixed_requires_exact_amount_condition: "Splits mit festen Beträgen benötigen eine Regel-Bedingung mit exaktem Transaktionsbetrag (z. B. Betrag = 42,00), sonst können die Anteile nicht zuverlässig für jede passende Transaktion aufgehen"fixed_shares_must_equal_condition_amount: "Die Split-Anteile müssen in Summe %{amount} ergeben – den exakten Betrag, den die Bedingung dieser Regel vorgibt"rule:+ actions:+ set_transaction_merchant:+ not_accessible: "Händler auf einem Konto ohne Zugriff"+ unassigned: "%{name} (nicht mehr zugeordnet)"+ unavailable: "Händler nicht mehr verfügbar"conditions:unsupported_label: "Nicht unterstützt (%{type})"diff --git a/config/locales/models/rule/en.yml b/config/locales/models/rule/en.ymlindex dd2e36a0e8..72c7d7ec52 100644--- a/config/locales/models/rule/en.yml+++ b/config/locales/models/rule/en.yml@@ -37,5 +37,10 @@ en:regex_too_long: "is too long (maximum is %{count} characters)"regex_backreference: "cannot use back-references (\\1 to \\9)"rule:+ actions:+ set_transaction_merchant:+ not_accessible: "Merchant on an account you can't access"+ unassigned: "%{name} (no longer assigned)"+ unavailable: "Merchant no longer available"conditions:unsupported_label: "Unsupported (%{type})"diff --git a/test/models/assistant/function/create_rule_test.rb b/test/models/assistant/function/create_rule_test.rbindex 1d35cd9866..97e75ea767 100644--- a/test/models/assistant/function/create_rule_test.rb+++ b/test/models/assistant/function/create_rule_test.rb@@ -38,6 +38,37 @@ class Assistant::Function::CreateRuleTest < ActiveSupport::TestCaseassert_equal 1, result[:preview][:match_count]end+ test "accepts a provider merchant on the user's transactions for the set merchant action" do+ provider_merchant = ProviderMerchant.create!(name: "ZXQ Synced Merchant", source: "plaid")+ create_transaction(name: "ZXQ Synced", merchant: provider_merchant)++ result = @fn.call(+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq" } ],+ "actions" => [ { "action_type" => "set_transaction_merchant", "value" => provider_merchant.id } ]+ )++ assert result[:success], result.inspect+ assert_equal provider_merchant.id, @family.rules.find(result[:rule][:id]).actions.first.value+ end++ test "rejects a provider merchant only on accounts the user can't access" do+ provider_merchant = ProviderMerchant.create!(name: "ZXQ Hidden Merchant", source: "plaid")+ hidden_account = @family.accounts.create!(name: "Admin only", balance: 0, currency: "USD", accountable: Depository.new, owner: @user)+ create_transaction(account: hidden_account, name: "ZXQ Hidden", merchant: provider_merchant)+ member = users(:family_member)+ assert_not Account.accessible_by(member).exists?(hidden_account.id), "precondition: the member can't see the account"++ result = nil+ assert_no_difference "@family.rules.count" do+ result = Assistant::Function::CreateRule.new(member).call(+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq" } ],+ "actions" => [ { "action_type" => "set_transaction_merchant", "value" => provider_merchant.id } ]+ )+ end++ assert_not result[:success], result.inspect+ end+test "points split actions at the rules settings" dosplit = { splits: [ { type: "percentage", name: "A", share: "50" }, { type: "percentage", name: "B", share: "50" } ] }diff --git a/test/models/assistant/function/update_rule_test.rb b/test/models/assistant/function/update_rule_test.rbindex fbb3097105..137799f8f5 100644--- a/test/models/assistant/function/update_rule_test.rb+++ b/test/models/assistant/function/update_rule_test.rb@@ -18,6 +18,23 @@ class Assistant::Function::UpdateRuleTest < ActiveSupport::TestCase)end+ test "keeps a saved merchant the user can't see when replacing actions" do+ hidden = ProviderMerchant.create!(name: "ZXQ Hidden Merchant", source: "plaid")+ private_account = @family.accounts.create!(name: "Private", balance: 0, currency: "USD", accountable: Depository.new, owner: @user)+ create_transaction(account: private_account, name: "ZXQ hidden", merchant: hidden)+ @rule.actions.create!(action_type: "set_transaction_merchant", value: hidden.id)+ fn = Assistant::Function::UpdateRule.new(users(:family_member))+ assert_not_includes @family.assignable_merchants_for(users(:family_member)).ids, hidden.id++ result = fn.call("rule_id" => @rule.id, "actions" => [+ { "action_type" => "set_transaction_category", "value" => @category.id },+ { "action_type" => "set_transaction_merchant", "value" => hidden.id }+ ])++ assert result[:success], result.inspect+ assert_equal hidden.id, @rule.reload.actions.find_by!(action_type: "set_transaction_merchant").value+ end+test "renaming keeps an active rule active" doresult = @fn.call("rule_id" => @rule.id, "name" => "Morning coffee")diff --git a/test/models/family/data_exporter_test.rb b/test/models/family/data_exporter_test.rbindex 4ca8e6bc63..8d2485f722 100644--- a/test/models/family/data_exporter_test.rb+++ b/test/models/family/data_exporter_test.rb@@ -608,6 +608,33 @@ class Family::DataExporterTest < ActiveSupport::TestCaseendend+ test "exports provider merchant rule operands by name" do+ provider_merchant = ProviderMerchant.create!(name: "Synced Grocer", source: "plaid")+ @account.entries.create!(+ date: Date.current, amount: 10, name: "Groceries", currency: "USD",+ entryable: Transaction.new(merchant: provider_merchant)+ )+ rule = @family.rules.build(name: "Provider Merchant Rule", resource_type: "transaction", active: true)+ rule.conditions.build(condition_type: "transaction_merchant", operator: "=", value: provider_merchant.id)+ rule.actions.build(action_type: "set_transaction_merchant", value: provider_merchant.id)+ rule.save!++ zip_data = @exporter.generate_export++ Zip::File.open_buffer(zip_data) do |zip|+ rule_data = zip.read("all.ndjson").split("\n").filter_map do |line|+ parsed = JSON.parse(line)+ parsed if parsed["type"] == "Rule" && parsed["data"]["name"] == "Provider Merchant Rule"+ end.first++ expected_ref = { "type" => "Merchant", "id" => provider_merchant.id, "name" => "Synced Grocer" }+ assert_equal "Synced Grocer", rule_data["data"]["conditions"].first["value"]+ assert_equal expected_ref, rule_data["data"]["conditions"].first["value_ref"]+ assert_equal "Synced Grocer", rule_data["data"]["actions"].first["value"]+ assert_equal expected_ref, rule_data["data"]["actions"].first["value_ref"]+ end+ end+test "rule operand lookup matches uppercase UUID values" dooperand = @exporter.send(:rule_operand,diff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex e590dc5c80..c3cc73fb11 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -2341,6 +2341,41 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert_equal category.id, second_rule.actions.first.valueend+ test "points imported merchant rules at a reused provider merchant" do+ provider_merchant = ProviderMerchant.create!(name: "Synced Grocer", source: "plaid", provider_merchant_id: "plaid_synced_grocer")+ value_ref = { type: "Merchant", id: "old-provider-merchant", name: "Synced Grocer" }++ ndjson = build_ndjson([+ {+ type: "ProviderMerchant",+ data: { id: "old-provider-merchant", name: "Synced Grocer", source: "plaid", provider_merchant_id: "plaid_synced_grocer" }+ },+ {+ type: "Rule",+ version: 1,+ data: {+ name: "Grocer rule",+ resource_type: "transaction",+ active: true,+ conditions: [+ { condition_type: "transaction_merchant", operator: "=", value: "Synced Grocer", value_ref: value_ref }+ ],+ actions: [+ { action_type: "set_transaction_merchant", value: "Synced Grocer", value_ref: value_ref }+ ]+ }+ }+ ])++ assert_no_difference -> { @family.merchants.count } do+ Family::DataImporter.new(@family, ndjson).import!+ end++ rule = @family.rules.find_by!(name: "Grocer rule")+ assert_equal provider_merchant.id, rule.conditions.first.value+ assert_equal provider_merchant.id, rule.actions.first.value+ end+test "reuses a merchant created for an earlier rule within the same import" dondjson = build_ndjson([{diff --git a/test/models/merchant/merger_test.rb b/test/models/merchant/merger_test.rbindex cc50b4950b..425c918758 100644--- a/test/models/merchant/merger_test.rb+++ b/test/models/merchant/merger_test.rb@@ -23,6 +23,33 @@ class Merchant::MergerTest < ActiveSupport::TestCaseassert entry.user_modified?, "merged transaction's entry must be flagged so provider sync won't revert it"end+ test "merge! points the family's rules at the target merchant" do+ rule = @family.rules.build(resource_type: "transaction")+ rule.conditions.build(condition_type: "transaction_merchant", operator: "=", value: @source.id)+ rule.actions.build(action_type: "set_transaction_merchant", value: @source.id)+ rule.save!++ Merchant::Merger.new(family: @family, target_merchant: @target, source_merchants: [ @source ]).merge!++ rule.reload+ assert_equal @target.id, rule.conditions.first.value+ assert_equal @target.id, rule.actions.first.value+ end++ test "merge! re-takes the notification baseline of an email rule matching the source merchant" do+ target_entry = create_transaction(merchant: @target)+ rule = @family.rules.build(resource_type: "transaction", active: true)+ rule.conditions.build(condition_type: "transaction_merchant", operator: "=", value: @source.id)+ rule.actions.build(action_type: "send_email_notification")+ rule.save!+ assert_not_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), target_entry.entryable_id++ Merchant::Merger.new(family: @family, target_merchant: @target, source_merchants: [ @source ]).merge!++ assert_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), target_entry.entryable_id,+ "the target merchant's past transactions must not be emailed as new matches"+ end+test "merge! does not touch entries of unrelated merchants" doother = create_transaction(merchant: @target)assert_not other.user_modified?diff --git a/test/models/provider_merchant_test.rb b/test/models/provider_merchant_test.rbindex 395f9e6f65..1267592863 100644--- a/test/models/provider_merchant_test.rb+++ b/test/models/provider_merchant_test.rb@@ -35,6 +35,33 @@ class ProviderMerchantTest < ActiveSupport::TestCaseassert entry.user_modified?, "unlinked transaction's entry must be flagged so provider sync won't re-link it"end+ test "convert_to_family_merchant_for points the family's rules at the new merchant" do+ create_transaction(merchant: @provider_merchant)+ rule = @family.rules.build(resource_type: "transaction")+ rule.conditions.build(condition_type: "transaction_merchant", operator: "=", value: @provider_merchant.id)+ compound = rule.conditions.build(condition_type: "compound", operator: "or")+ compound.sub_conditions.build(condition_type: "transaction_merchant", operator: "=", value: @provider_merchant.id)+ rule.actions.build(action_type: "set_transaction_merchant", value: @provider_merchant.id)+ rule.save!++ other_rule = families(:empty).rules.build(resource_type: "transaction")+ other_rule.conditions.build(condition_type: "transaction_merchant", operator: "=", value: @provider_merchant.id)+ other_compound = other_rule.conditions.build(condition_type: "compound", operator: "or")+ other_compound.sub_conditions.build(condition_type: "transaction_merchant", operator: "=", value: @provider_merchant.id)+ other_rule.actions.build(action_type: "set_transaction_merchant", value: @provider_merchant.id)+ other_rule.save!++ family_merchant = @provider_merchant.convert_to_family_merchant_for(@family)++ rule.reload+ assert_equal family_merchant.id, rule.conditions.find_by(parent_id: nil, condition_type: "transaction_merchant").value+ assert_equal family_merchant.id, compound.sub_conditions.first.reload.value+ assert_equal family_merchant.id, rule.actions.first.value+ assert_equal @provider_merchant.id, other_rule.actions.first.reload.value, "other families' rules keep the shared merchant"+ assert_equal @provider_merchant.id, other_rule.conditions.find_by(parent_id: nil, condition_type: "transaction_merchant").value+ assert_equal @provider_merchant.id, other_compound.sub_conditions.first.reload.value+ end+test "find_by_import_data prefers provider_merchant_id over name, scoped to source" doby_id = ProviderMerchant.create!(name: "Renamed Upstream", source: "plaid", provider_merchant_id: "plaid_acme")ProviderMerchant.create!(name: "Acme", source: "lunchflow")diff --git a/test/models/rule/action_test.rb b/test/models/rule/action_test.rbindex 59e293b867..5db15929bb 100644--- a/test/models/rule/action_test.rb+++ b/test/models/rule/action_test.rb@@ -200,6 +200,132 @@ class Rule::ActionTest < ActiveSupport::TestCaseendend+ test "set_transaction_merchant assigns a provider merchant already on the family's transactions" do+ provider_merchant = ProviderMerchant.create!(name: "Rule test provider merchant", source: "plaid")+ @txn1.update!(merchant: provider_merchant)++ action = Rule::Action.new(+ rule: @transaction_rule,+ action_type: "set_transaction_merchant",+ value: provider_merchant.id+ )++ assert action.reserves_claimed_attributes?+ action.apply(@rule_scope)++ [ @txn2, @txn3 ].each do |transaction|+ assert_equal provider_merchant.id, transaction.reload.merchant_id+ end+ end++ test "set_transaction_merchant ignores a provider merchant the family's transactions don't carry" do+ provider_merchant = ProviderMerchant.create!(name: "Other family's provider merchant", source: "plaid")+ other_account = families(:empty).accounts.create!(name: "Other", balance: 0, currency: "USD", accountable: Depository.new)+ create_transaction(account: other_account, merchant: provider_merchant)++ action = Rule::Action.new(+ rule: @transaction_rule,+ action_type: "set_transaction_merchant",+ value: provider_merchant.id+ )++ assert_not action.reserves_claimed_attributes?+ assert_equal 0, action.apply(@rule_scope)+ assert_nil @txn2.reload.merchant_id+ end++ test "set_transaction_merchant offers family merchants and provider merchants on the user's transactions" do+ assigned = ProviderMerchant.create!(name: "Assigned provider merchant", source: "plaid")+ unlinked = ProviderMerchant.create!(name: "Unlinked provider merchant", source: "plaid")+ foreign = ProviderMerchant.create!(name: "Foreign provider merchant", source: "plaid")+ @txn1.update!(merchant: assigned)+ FamilyMerchantAssociation.create!(family: @family, merchant: unlinked, unlinked_at: 1.day.ago)+ other_account = families(:empty).accounts.create!(name: "Other", balance: 0, currency: "USD", accountable: Depository.new)+ create_transaction(account: other_account, merchant: foreign)++ action = Rule::Action.new(rule: @transaction_rule, action_type: "set_transaction_merchant")+ Current.stubs(:user).returns(users(:family_admin))+ option_ids = action.options.map(&:last)++ assert_includes option_ids, assigned.id+ assert_includes option_ids, @whole_foods_merchant.id+ assert_not_includes option_ids, unlinked.id+ assert_not_includes option_ids, foreign.id+ end++ test "set_transaction_merchant keeps a saved merchant the current user can't see in the options" do+ hidden = ProviderMerchant.create!(name: "Hidden provider merchant", source: "plaid")+ @txn1.update!(merchant: hidden)++ action = Rule::Action.new(rule: @transaction_rule, action_type: "set_transaction_merchant", value: hidden.id)+ Current.stubs(:user).returns(users(:family_member))++ assert_not_includes action.executor.options.map(&:last), hidden.id+ assert_includes action.options.map(&:last), hidden.id+ assert_equal I18n.t("rule.actions.set_transaction_merchant.not_accessible"), action.value_display+ end++ test "set_transaction_merchant keeps an unlinked provider merchant in the options, marked as no longer assigned" do+ unlinked = ProviderMerchant.create!(name: "Unlinked provider merchant", source: "plaid")+ @txn1.update!(merchant: unlinked)+ unlinked.unlink_from_family(@family)++ action = Rule::Action.new(rule: @transaction_rule, action_type: "set_transaction_merchant", value: unlinked.id)+ Current.stubs(:user).returns(users(:family_admin))++ assert_not action.reserves_claimed_attributes?+ assert_includes action.options.map(&:last), unlinked.id+ assert_equal I18n.t("rule.actions.set_transaction_merchant.unassigned", name: "Unlinked provider merchant"), action.value_display+ end++ test "set_transaction_merchant keeps a saved merchant the family no longer knows without revealing its name" do+ foreign = ProviderMerchant.create!(name: "Foreign provider merchant", source: "plaid")+ other_account = families(:empty).accounts.create!(name: "Other", balance: 0, currency: "USD", accountable: Depository.new)+ create_transaction(account: other_account, merchant: foreign)++ action = Rule::Action.new(rule: @transaction_rule, action_type: "set_transaction_merchant", value: foreign.id)+ Current.stubs(:user).returns(users(:family_admin))++ assert_includes action.options.map(&:last), foreign.id+ assert_equal I18n.t("rule.actions.set_transaction_merchant.unavailable"), action.value_display+ end++ test "set_transaction_merchant rejects a merchant the user picks but can't access, and keeps a saved one" do+ hidden = ProviderMerchant.create!(name: "Hidden provider merchant", source: "plaid")+ @txn1.update!(merchant: hidden)+ Current.stubs(:user).returns(users(:family_member))+ assert_not @transaction_rule.family.assignable_merchants_for(users(:family_member)).exists?(id: hidden.id), "precondition"++ action = @transaction_rule.actions.build(action_type: "set_transaction_merchant", value: hidden.id)+ assert_not action.valid?+ assert action.errors[:value].any?++ action.value = @whole_foods_merchant.id+ assert action.valid?++ Current.stubs(:user).returns(nil)+ saved = @transaction_rule.actions.create!(action_type: "set_transaction_merchant", value: hidden.id)+ Current.stubs(:user).returns(users(:family_member))+ assert saved.reload.valid?, "a merchant another member saved stays valid while unchanged"++ other = @transaction_rule.actions.create!(action_type: "set_transaction_name", value: hidden.id)+ other.action_type = "set_transaction_merchant"+ assert_not other.valid?, "switching an action to set the merchant checks the value too"++ malformed = @transaction_rule.actions.build(action_type: "set_transaction_merchant", value: "not-a-uuid")+ assert_not malformed.valid?+ assert_not Rule::ActionExecutor::SetTransactionMerchant.new(@transaction_rule).actionable?("not-a-uuid")+ end++ test "set_transaction_merchant marks an unknown saved id like another family's merchant" do+ unknown = SecureRandom.uuid+ action = Rule::Action.new(rule: @transaction_rule, action_type: "set_transaction_merchant", value: unknown)+ Current.stubs(:user).returns(users(:family_admin))++ assert_includes action.options.map(&:last), unknown+ assert_equal I18n.t("rule.actions.set_transaction_merchant.unavailable"), action.value_display+ end+test "set_transaction_name" donew_name = "Renamed Transaction"diff --git a/test/models/rule_import_test.rb b/test/models/rule_import_test.rbindex e6be63dd86..fac2d1d597 100644--- a/test/models/rule_import_test.rb+++ b/test/models/rule_import_test.rb@@ -42,6 +42,47 @@ class RuleImportTest < ActiveSupport::TestCaseassert_equal 1, auto_rule.actions.countend+ test "reuses a provider merchant on the family's transactions instead of creating a family merchant" do+ provider_merchant = ProviderMerchant.create!(name: "Synced Coffee", source: "plaid")+ account = @family.accounts.first+ account.entries.create!(name: "Coffee", date: Date.current, amount: 4, currency: "USD", entryable: Transaction.new(merchant: provider_merchant))+ csv = <<~CSV+ name,resource_type,active,effective_date,conditions,actions+ "Coffee","transaction",true,,"[{\"condition_type\":\"transaction_merchant\",\"operator\":\"=\",\"value\":\"Synced Coffee\"}]","[{\"action_type\":\"set_transaction_merchant\",\"value\":\"Synced Coffee\"}]"+ CSV+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")+ import.generate_rows_from_csv++ assert_no_difference -> { @family.merchants.count } do+ import.send(:import!)+ end++ rule = Rule.find_by!(family: @family, name: "Coffee")+ assert_equal provider_merchant.id, rule.conditions.first.value+ assert_equal provider_merchant.id, rule.actions.first.value+ end++ test "creates a family merchant for a provider merchant name that is ambiguous or used in a split" do+ account = @family.accounts.first+ [ [ "Shared Name", "plaid" ], [ "Shared Name", "simplefin" ], [ "Split Shop", "plaid" ] ].each do |name, source|+ merchant = ProviderMerchant.create!(name: name, source: source)+ account.entries.create!(name: name, date: Date.current, amount: 4, currency: "USD", entryable: Transaction.new(merchant: merchant))+ end+ split = { splits: [ { type: "percentage", name: "Shop", share: "60", merchant: "Split Shop" }, { type: "percentage", name: "Rest", share: "40" } ] }.to_json+ csv = CSV.generate do |rows|+ rows << %w[name resource_type active effective_date conditions actions]+ rows << [ "Ambiguous", "transaction", "true", "", '[{"condition_type":"transaction_name","operator":"like","value":"x"}]', '[{"action_type":"set_transaction_merchant","value":"Shared Name"}]' ]+ rows << [ "Split", "transaction", "true", "", '[{"condition_type":"transaction_name","operator":"like","value":"y"}]', [ { action_type: "split_transaction", value: JSON.parse(split) } ].to_json ]+ end+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")+ import.generate_rows_from_csv+ import.send(:import!)++ assert_equal @family.merchants.find_by!(name: "Shared Name").id, Rule.find_by!(family: @family, name: "Ambiguous").actions.sole.value+ split_merchant_id = JSON.parse(Rule.find_by!(family: @family, name: "Split").actions.sole.value)["splits"].first["merchant_id"]+ assert_equal @family.merchants.find_by!(name: "Split Shop").id, split_merchant_id+ end+test "imports rule conditions correctly" doimport = @family.imports.create!(type: "RuleImport", raw_file_str: @csv, col_sep: ",")import.generate_rows_from_csv