Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Record an email action's baseline when it is created (#4176)

jaysbeekay7e65c52757ed
diff --git a/app/models/assistant/function/rule_support.rb b/app/models/assistant/function/rule_support.rb
index 9534c72333..664de32008 100644
--- a/app/models/assistant/function/rule_support.rb
+++ b/app/models/assistant/function/rule_support.rb
@@ -137,10 +137,14 @@ module Assistant::Function::RuleSupport
if params.key?("actions")
actions = params["actions"]
if actions.is_a?(Array)
+ # An email action replacing the rule's own keeps the baseline it recorded
+ # (see Rule::Action#keep_notification_baseline).
+ had_email_action = rule.stored_email_notification_action?
rule.actions.each(&:mark_for_destruction)
actions.each_with_index do |action, index|
problems.concat(build_action(rule, action, "actions[#{index}]"))
end
+ rule.actions.select(&:new_record?).each { |a| a.keep_notification_baseline = had_email_action }
else
problems << "actions must be an array."
end
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index e9eaaacfd4..8a53f5d821 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -1368,6 +1368,7 @@ class Family::DataImporter
position = Integer(record.dig("data", "position"), exception: false)
[ position || Float::INFINITY, index ]
end.map(&:first)
+ with_stored_email_action = Rule.ids_with_stored_email_notification_action(@family.rules)
records.each do |record|
data = record["data"]
@@ -1387,6 +1388,11 @@ class Family::DataImporter
stop_processing: data["stop_processing"] || false
)
+ # An email action replacing the rule's own keeps the baseline it recorded
+ # (see Rule::Action#keep_notification_baseline), as stored before this
+ # import: not one an earlier record of it wrote.
+ had_email_action = rule.persisted? && with_stored_email_action.include?(rule.id)
+
# Marked rather than destroyed now, so the rule's save removes them and
# sees its conditions change (Rule re-seeds an email rule's baseline then).
rule.conditions.each(&:mark_for_destruction) unless created
@@ -1399,7 +1405,7 @@ class Family::DataImporter
# Build actions
(data["actions"] || []).each do |action_data|
- build_rule_action(rule, action_data)
+ build_rule_action(rule, action_data).keep_notification_baseline = had_email_action
end
rule.save!
diff --git a/app/models/rule.rb b/app/models/rule.rb
index 4900d74b47..6ac6c43217 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -122,6 +122,26 @@ class Rule < ApplicationRecord
0
end
+ # Whether the rule, as stored, has an email action. Read from the database,
+ # so actions built or marked for destruction in memory do not change it. The
+ # assistant reads it before replacing a rule's actions, so a replacement email
+ # action keeps the baseline the old one recorded (see
+ # Rule::Action#keep_notification_baseline). Each of its calls commits on its
+ # own; the importers, which do not, use .ids_with_stored_email_notification_action.
+ def stored_email_notification_action?
+ persisted? && actions.email_notifications.exists?
+ end
+
+ # The ids of the rules in `rules` that have an email action as stored now.
+ # An import writes every row in one transaction, so a rule named twice would
+ # see, on its second row, the email action its first row has only just
+ # written; that one is replaced before it commits and never records a
+ # baseline. The importers take this before writing anything and ask it
+ # instead of #stored_email_notification_action?.
+ def self.ids_with_stored_email_notification_action(rules)
+ rules.joins(:actions).merge(Rule::Action.email_notifications).distinct.pluck(:id).to_set
+ end
+
# Reads the currently-matching transaction ids WITHOUT running executors
# (e.g. the notification baseline pre-seed).
def matching_transaction_ids
@@ -421,7 +441,7 @@ class Rule < ApplicationRecord
def seed_notification_baseline
@notification_baseline_timed_out = false
- return unless actions.exists?(action_type: "send_email_notification")
+ return unless actions.email_notifications.exists?
@notification_baseline_taken = true
NotificationDelivery.record_for(rule_id: id, transaction_ids: matching_transaction_ids)
diff --git a/app/models/rule/action.rb b/app/models/rule/action.rb
index 3a25661dad..8989ed1654 100644
--- a/app/models/rule/action.rb
+++ b/app/models/rule/action.rb
@@ -1,8 +1,15 @@
class Rule::Action < ApplicationRecord
+ # The action_type of the "Send email notification" action: the key of
+ # Rule::ActionExecutor::SendEmailNotification, which is derived from its class
+ # name. Rule::ActionTest checks the two agree.
+ EMAIL_NOTIFICATION = "send_email_notification"
+
belongs_to :rule, touch: true
SUPPORTED_ACTION_TYPES = Rule::Registry::TransactionResource.action_executor_keys.freeze
+ scope :email_notifications, -> { where(action_type: EMAIL_NOTIFICATION) }
+
# Virtual attribute for the split_transaction form: `value` is a single string column, so the
# split builder UI posts real, individually-named fields here instead of driving a JSON blob
# through custom JS. build_split_value assembles them into `value` before validation runs.
@@ -26,22 +33,31 @@ class Rule::Action < ApplicationRecord
before_validation :build_split_value, if: -> { action_type == "split_transaction" && split_rows.present? }
validate :split_config_valid, if: -> { action_type == "split_transaction" }
- # Pre-seed (watermark): when a send_email_notification action is created — on a
+ # Pre-seed (watermark): when an EMAIL_NOTIFICATION action is created — on a
# new rule OR added to an existing one — record all currently-matching
# transactions as already-delivered WITHOUT sending, so the rule only ever
# emails about transactions that appear AFTER the action exists.
#
- # Uses after_create_commit (not after_create): nested children persist before
- # the parent rule commits, and the pre-seed reads the rule's conditions, which
+ # Uses after_commit (not after_save): nested children persist before the
+ # parent rule commits, and the pre-seed reads the rule's conditions, which
# must be committed first.
#
- # after_update_commit covers the edit flow: the action_type select is editable
+ # The update event covers the edit flow: the action_type select is editable
# for persisted actions (see rules_controller#rule_params), so an existing
- # action can be CHANGED to send_email_notification. Without re-seeding, the
+ # action can be CHANGED to EMAIL_NOTIFICATION. Without re-seeding, the
# next apply/sync would email every historical match. Guard on the type change
- # so we only watermark when an action actually becomes email-notify.
- after_create_commit :seed_notification_baseline
- after_update_commit :seed_notification_baseline, if: :saved_change_to_action_type?
+ # so we only watermark when an action actually becomes email-notify; on create
+ # the type changes from nil, so the same guard admits every new action.
+ #
+ # One callback for both events: after_create_commit and after_update_commit
+ # naming the same method would leave only the last one registered.
+ after_commit :seed_notification_baseline, on: %i[create update], if: :saved_change_to_action_type?
+
+ # Set by the importers and the assistant's update_rule on an email action that
+ # replaces one the rule already had. The rule's baseline is still recorded
+ # under its id, so taking it again would mark a match still waiting for the
+ # next run as delivered.
+ attr_accessor :keep_notification_baseline
# Accepts an Array (e.g. from a multi-select tag input) and stores it as a
# comma-separated string in the existing `value` column, so multi-value
@@ -106,6 +122,10 @@ class Rule::Action < ApplicationRecord
rule.registry.get_executor!(action_type)
end
+ def email_notification?
+ action_type == EMAIL_NOTIFICATION
+ end
+
private
def execution_value
executor.type == "multi_select" ? value.to_s.split(",") : value
@@ -182,7 +202,8 @@ class Rule::Action < ApplicationRecord
end
def seed_notification_baseline
- return unless action_type == "send_email_notification"
+ return unless email_notification?
+ return if keep_notification_baseline
return if rule.notification_baseline_taken_in_this_save?
NotificationDelivery.record_for(
diff --git a/app/models/rule_import.rb b/app/models/rule_import.rb
index 44aa8d8e7f..d264f22697 100644
--- a/app/models/rule_import.rb
+++ b/app/models/rule_import.rb
@@ -1,6 +1,7 @@
class RuleImport < Import
def import!
transaction do
+ @rules_with_stored_email_action = Rule.ids_with_stored_email_notification_action(family.rules)
rows.each do |row|
create_or_update_rule_from_row(row)
end
@@ -174,6 +175,11 @@ class RuleImport < Import
rule.active = row.active || false
rule.effective_date = parse_date(row.effective_date)
+ # An email action replacing the rule's own keeps the baseline it recorded
+ # (see Rule::Action#keep_notification_baseline), as stored before this
+ # import: not one an earlier row of it wrote.
+ had_email_action = rule.persisted? && @rules_with_stored_email_action.include?(rule.id)
+
# Clear existing conditions and actions. The conditions are marked rather
# than destroyed now, so the rule's save removes them and sees its
# conditions change (Rule re-seeds an email rule's baseline then).
@@ -187,7 +193,7 @@ class RuleImport < Import
# Create actions
actions_data.each do |action_data|
- build_action(rule, action_data)
+ build_action(rule, action_data).keep_notification_baseline = had_email_action
end
rule.save!
diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rb
index 2d6858bc77..6b178f2283 100644
--- a/test/controllers/rules_controller_test.rb
+++ b/test/controllers/rules_controller_test.rb
@@ -92,6 +92,26 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
assert_redirected_to confirm_rule_url(rule, reload_on_close: true)
end
+ test "creating an email rule through the form records its current matches as the baseline" do
+ account = @user.family.accounts.create!(name: "Baseline", balance: 1000, currency: "USD", accountable: Depository.new)
+ match = account.entries.create!(
+ name: "Baseline cafe", date: Date.current, amount: 10, currency: "USD", entryable: Transaction.new
+ ).transaction
+
+ post rules_url, params: {
+ rule: {
+ name: "Baseline cafe alerts",
+ resource_type: "transaction",
+ conditions_attributes: { "0" => { condition_type: "transaction_name", operator: "like", value: "baseline cafe" } },
+ actions_attributes: { "0" => { action_type: "send_email_notification" } }
+ }
+ }
+
+ rule = @user.family.rules.find_by!(name: "Baseline cafe alerts")
+ assert_redirected_to confirm_rule_url(rule, reload_on_close: true)
+ assert_equal [ match.id ], NotificationDelivery.where(rule: rule).pluck(:transaction_id)
+ end
+
test "creates rule with a split_transaction action from split_rows params" do
category = categories(:food_and_drink)
diff --git a/test/models/assistant/function/create_rule_test.rb b/test/models/assistant/function/create_rule_test.rb
index 1119d1bd98..1d35cd9866 100644
--- a/test/models/assistant/function/create_rule_test.rb
+++ b/test/models/assistant/function/create_rule_test.rb
@@ -109,6 +109,19 @@ class Assistant::Function::CreateRuleTest < ActiveSupport::TestCase
assert @fn.call(params)[:success]
end
+ test "a new email rule records its current matches as the baseline" do
+ old = create_transaction(name: "ZXQ Coffee Old").transaction
+
+ result = @fn.call(
+ "name" => "Coffee alerts",
+ "conditions" => [ { "condition_type" => "transaction_name", "operator" => "like", "value" => "zxq coffee" } ],
+ "actions" => [ { "action_type" => "send_email_notification" } ]
+ )
+
+ assert result[:success], result.inspect
+ assert_equal [ old.id ], NotificationDelivery.where(rule_id: result[:rule][:id]).pluck(:transaction_id)
+ end
+
# The rule is saved before the preview runs, so a timeout there must still
# say the rule exists, inactive.
test "a pattern that times out in the preview reports the saved rule with a regex_timeout error" do
diff --git a/test/models/assistant/function/update_rule_test.rb b/test/models/assistant/function/update_rule_test.rb
index 3bfd25a254..fbb3097105 100644
--- a/test/models/assistant/function/update_rule_test.rb
+++ b/test/models/assistant/function/update_rule_test.rb
@@ -1,7 +1,7 @@
require "test_helper"
class Assistant::Function::UpdateRuleTest < ActiveSupport::TestCase
- include EntriesTestHelper
+ include EntriesTestHelper, ActiveJob::TestHelper
setup do
@user = users(:family_admin)
@@ -97,6 +97,35 @@ class Assistant::Function::UpdateRuleTest < ActiveSupport::TestCase
assert result.dig(:preview, :preview_token).present?
end
+ test "resending an unchanged email action keeps the baseline, so a pending match is still emailed" do
+ old = create_transaction(name: "ZXQ Coffee Old").transaction
+ rule = email_rule
+ assert_equal [ old.id ], NotificationDelivery.where(rule: rule).pluck(:transaction_id)
+ pending = create_transaction(name: "ZXQ Coffee New").transaction
+
+ result = @fn.call("rule_id" => rule.id, "actions" => [ { "action_type" => "send_email_notification" } ])
+
+ assert result[:success], result.inspect
+ assert_equal [ old.id ], NotificationDelivery.where(rule: rule).pluck(:transaction_id)
+ # update_rule leaves a changed rule inactive, and apply_rule switches it back
+ # on before running it. Do the same here without callbacks, so only the
+ # baseline update_rule left is under test.
+ rule.update_columns(active: true)
+ assert_enqueued_with(job: RuleEmailNotificationJob, args: [ rule.id, [ pending.id ] ]) do
+ Rule.find(rule.id).apply
+ end
+ end
+
+ test "replacing a rule's actions with an email action records the baseline" do
+ old = create_transaction(name: "ZXQ Coffee Old").transaction
+
+ result = @fn.call("rule_id" => @rule.id, "actions" => [ { "action_type" => "send_email_notification" } ])
+
+ assert result[:success], result.inspect
+ assert_equal [ old.id ], NotificationDelivery.where(rule: @rule).pluck(:transaction_id)
+ assert_no_enqueued_jobs(only: RuleEmailNotificationJob) { Rule.find(@rule.id).apply }
+ end
+
test "a pattern that times out in the preview reports the updated rule with a regex_timeout error" do
Rule.any_instance.stubs(:matching_scope).raises(Rule::SafeRegex::TimeoutError)
@@ -110,4 +139,15 @@ class Assistant::Function::UpdateRuleTest < ActiveSupport::TestCase
assert_equal [ "zxq" ], @rule.reload.conditions.map(&:value)
assert_not result[:rule][:active]
end
+
+ private
+ def email_rule
+ @family.rules.create!(
+ name: "Coffee alerts",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "zxq coffee" } ],
+ actions_attributes: [ { action_type: "send_email_notification" } ]
+ )
+ end
end
diff --git a/test/models/rule/action_executor/send_email_notification_test.rb b/test/models/rule/action_executor/send_email_notification_test.rb
index f7fa97ba14..b462cec6ac 100644
--- a/test/models/rule/action_executor/send_email_notification_test.rb
+++ b/test/models/rule/action_executor/send_email_notification_test.rb
@@ -75,21 +75,16 @@ class Rule::ActionExecutor::SendEmailNotificationTest < ActiveSupport::TestCase
end
test "pre-seed watermark records existing matches without sending so history never emails" do
- # after_create_commit does not fire under transactional tests (the wrapping
- # transaction never commits), so invoke the seeding path directly to verify
- # the watermark behavior the callback performs in production.
- rule = @family.rules.create!(
- resource_type: "transaction",
- active: true,
- actions_attributes: [ { action_type: "send_email_notification" } ]
- )
- seed_action = rule.actions.first
-
+ rule = nil
assert_no_enqueued_jobs only: RuleEmailNotificationJob do
- seed_action.send(:seed_notification_baseline)
+ rule = @family.rules.create!(
+ resource_type: "transaction",
+ active: true,
+ actions_attributes: [ { action_type: "send_email_notification" } ]
+ )
end
- # Pre-existing @txn1 is now watermarked, so a subsequent run sends nothing.
+ # Creating the action watermarked the pre-existing @txn1, so a run sends nothing.
result = nil
assert_no_enqueued_jobs only: RuleEmailNotificationJob do
result = Rule::Action.new(rule: rule, action_type: "send_email_notification").apply(@scope)
diff --git a/test/models/rule/action_test.rb b/test/models/rule/action_test.rb
index b47cbb1fc5..59e293b867 100644
--- a/test/models/rule/action_test.rb
+++ b/test/models/rule/action_test.rb
@@ -293,6 +293,21 @@ class Rule::ActionTest < ActiveSupport::TestCase
assert_nil @txn1.reload.investment_activity_label
end
+ # The executor's key is derived from its class name, so a rename would leave
+ # the constant pointing at an action type nothing executes.
+ test "the email action type is the email executor's key" do
+ assert_equal Rule::ActionExecutor::SendEmailNotification.new(@transaction_rule).key, Rule::Action::EMAIL_NOTIFICATION
+ end
+
+ test "email_notifications selects only the email actions" do
+ assert_empty @transaction_rule.actions.email_notifications
+
+ email = @transaction_rule.actions.create!(action_type: Rule::Action::EMAIL_NOTIFICATION)
+
+ assert_equal [ email.id ], @transaction_rule.actions.email_notifications.pluck(:id)
+ assert_operator @transaction_rule.actions.count, :>, 1, "the rule's other action should be left out"
+ end
+
test "split_transaction builds value from split_rows form fields" do
tag = @family.tags.create!(name: "Split test tag")
diff --git a/test/models/rule/notification_baseline_on_create_test.rb b/test/models/rule/notification_baseline_on_create_test.rb
new file mode 100644
index 0000000000..91781b5c96
--- /dev/null
+++ b/test/models/rule/notification_baseline_on_create_test.rb
@@ -0,0 +1,224 @@
+require "test_helper"
+
+# A "Send email notification" action records the transactions its rule already
+# matches as delivered when it is created, so the rule only ever emails what
+# appears afterwards. These tests cover the moments an email action comes into
+# being: a new rule, an action added to an existing rule, and the importers.
+class Rule::NotificationBaselineOnCreateTest < ActiveSupport::TestCase
+ include EntriesTestHelper, ActiveJob::TestHelper
+
+ setup do
+ @family = families(:empty)
+ @account = @family.accounts.create!(name: "Baseline", balance: 1000, currency: "USD", accountable: Depository.new)
+ @cafe = create_transaction(date: 10.days.ago.to_date, account: @account, amount: 10, name: "Corner cafe").transaction
+ @bakery = create_transaction(date: 5.days.ago.to_date, account: @account, amount: 20, name: "Cafe bakery").transaction
+ @shop = create_transaction(date: 5.days.ago.to_date, account: @account, amount: 30, name: "Hardware shop").transaction
+ end
+
+ test "creating a rule with an email action records its current matches as the baseline" do
+ rule = nil
+
+ assert_difference -> { NotificationDelivery.count }, 2 do
+ assert_no_enqueued_jobs(only: RuleEmailNotificationJob) do
+ rule = create_rule(actions: [ { action_type: "send_email_notification" } ])
+ end
+ end
+
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ end
+
+ test "a new email rule's first run emails nothing that matched before it" do
+ rule = create_rule(actions: [ { action_type: "send_email_notification" } ])
+
+ assert_equal [], emailed_ids(rule) { RuleJob.perform_now(Rule.find(rule.id)) }
+ end
+
+ test "a match that appears after the email rule is created is still emailed" do
+ rule = create_rule(actions: [ { action_type: "send_email_notification" } ])
+ later = create_transaction(date: Date.current, account: @account, amount: 5, name: "Cafe express").transaction
+
+ assert_equal [ later.id ], emailed_ids(rule) { RuleJob.perform_now(Rule.find(rule.id)) }
+ end
+
+ test "adding an email action to an existing rule records the baseline" do
+ rule = create_rule(actions: [ { action_type: "exclude_transaction" } ])
+ assert_equal [], delivered_ids(rule)
+
+ assert rule.update(actions_attributes: [ { action_type: "send_email_notification" } ])
+
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ assert_equal [], emailed_ids(rule) { RuleJob.perform_now(Rule.find(rule.id)) }
+ end
+
+ test "changing an existing action's type to email still records the baseline" do
+ rule = create_rule(actions: [ { action_type: "exclude_transaction" } ])
+ action = rule.actions.first
+
+ assert rule.update(actions_attributes: [ { id: action.id, action_type: "send_email_notification" } ])
+
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ end
+
+ test "creating a rule without an email action records nothing" do
+ Rule.any_instance.expects(:matching_transaction_ids).never
+
+ assert_no_difference -> { NotificationDelivery.count } do
+ create_rule(actions: [ { action_type: "exclude_transaction" } ])
+ end
+ end
+
+ test "editing an email action without changing its type does not record the baseline again" do
+ rule = create_rule(actions: [ { action_type: "send_email_notification" } ])
+ later = create_transaction(date: Date.current, account: @account, amount: 5, name: "Cafe express").transaction
+ action = rule.actions.first
+
+ Rule.any_instance.expects(:matching_transaction_ids).never
+ assert rule.update(name: "Renamed", actions_attributes: [ { id: action.id, value: "" } ])
+
+ assert_not_includes delivered_ids(rule), later.id
+ end
+
+ test "RuleImport records the baseline for a new email rule" do
+ import_rules_csv("cafe")
+
+ rule = @family.rules.find_by!(name: "Cafe alerts")
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ assert_equal [], emailed_ids(rule) { RuleJob.perform_now(rule) }
+ end
+
+ test "an identical RuleImport re-import keeps the baseline, so a pending match is still emailed" do
+ import_rules_csv("cafe")
+ rule = @family.rules.find_by!(name: "Cafe alerts")
+ pending = create_transaction(date: Date.current, account: @account, amount: 5, name: "Cafe express").transaction
+
+ import_rules_csv("cafe")
+
+ assert_not_includes delivered_ids(rule), pending.id
+ assert_equal [ pending.id ], emailed_ids(rule) { RuleJob.perform_now(Rule.find(rule.id)) }
+ end
+
+ test "a RuleImport re-import that adds an email action to an existing rule records the baseline" do
+ import_rules_csv("cafe", action_type: "exclude_transaction")
+ rule = @family.rules.find_by!(name: "Cafe alerts")
+ assert_equal [], delivered_ids(rule)
+
+ import_rules_csv("cafe")
+
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ end
+
+ # Every row of an import shares one transaction. The second row for a rule
+ # sees the email action the first row has only just written, uncommitted; the
+ # first action is replaced before it commits, so nothing has recorded a
+ # baseline for the second to keep.
+ test "a RuleImport naming a new email rule twice still records its baseline" do
+ import_rules_csv("cafe", rows: 2)
+
+ rule = @family.rules.find_by!(name: "Cafe alerts")
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ assert_equal [], emailed_ids(rule) { RuleJob.perform_now(rule) }
+ end
+
+ test "a Sure import naming a new email rule twice still records its baseline" do
+ Family::DataImporter.new(@family, [ rule_ndjson("cafe"), rule_ndjson("cafe") ].join("\n")).import!
+
+ rule = @family.rules.find_by!(name: "Cafe alerts")
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ assert_equal [], emailed_ids(rule) { RuleJob.perform_now(rule) }
+ end
+
+ test "a Sure import records the baseline for a new email rule" do
+ Family::DataImporter.new(@family, rule_ndjson("cafe")).import!
+
+ rule = @family.rules.find_by!(name: "Cafe alerts")
+ assert_equal [ @bakery.id, @cafe.id ].sort, delivered_ids(rule)
+ end
+
+ test "an identical Sure re-import keeps the baseline, so a pending match is still emailed" do
+ session = @family.import_sessions.create!(expected_chunks: 2)
+ Family::DataImporter.new(@family, rule_ndjson("cafe"), import_session: session).import!
+ rule = @family.rules.find_by!(name: "Cafe alerts")
+ pending = create_transaction(date: Date.current, account: @account, amount: 5, name: "Cafe express").transaction
+
+ Family::DataImporter.new(@family, rule_ndjson("cafe"), import_session: session).import!
+
+ assert_equal rule.id, @family.rules.find_by!(name: "Cafe alerts").id, "the re-import should update the same rule"
+ assert_not_includes delivered_ids(rule), pending.id
+ assert_equal [ pending.id ], emailed_ids(rule) { RuleJob.perform_now(Rule.find(rule.id)) }
+ end
+
+ test "a rule reports a stored email action, even once it is marked for replacement" do
+ rule = Rule.find(create_rule(actions: [ { action_type: "send_email_notification" } ]).id)
+
+ rule.actions.each(&:mark_for_destruction)
+
+ assert rule.stored_email_notification_action?
+ end
+
+ test "an email action that is only built, not stored, does not count as the rule's" do
+ rule = create_rule(actions: [ { action_type: "exclude_transaction" } ])
+ assert_not rule.stored_email_notification_action?
+
+ rule.actions.build(action_type: "send_email_notification")
+ assert_not rule.stored_email_notification_action?
+
+ new_rule = @family.rules.build(resource_type: "transaction")
+ new_rule.actions.build(action_type: "send_email_notification")
+ assert_not new_rule.stored_email_notification_action?
+ end
+
+ private
+ def create_rule(actions:)
+ @family.rules.create!(
+ name: "Cafe alerts",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "cafe" } ],
+ actions_attributes: actions
+ )
+ end
+
+ def import_rules_csv(value, action_type: "send_email_notification", rows: 1)
+ conditions = [ { condition_type: "transaction_name", operator: "like", value: value } ].to_json
+ actions = [ { action_type: action_type } ].to_json
+ csv = CSV.generate do |csv_rows|
+ csv_rows << %w[name resource_type active effective_date conditions actions]
+ rows.times { csv_rows << [ "Cafe alerts", "transaction", "true", "", conditions, actions ] }
+ end
+
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+ end
+
+ def rule_ndjson(value)
+ {
+ type: "Rule",
+ version: 1,
+ data: {
+ id: "rule-cafe",
+ name: "Cafe alerts",
+ resource_type: "transaction",
+ active: true,
+ conditions: [ { condition_type: "transaction_name", operator: "like", value: value } ],
+ actions: [ { action_type: "send_email_notification" } ]
+ }
+ }.to_json
+ end
+
+ def delivered_ids(rule)
+ NotificationDelivery.where(rule: rule).pluck(:transaction_id).sort
+ end
+
+ # The transaction ids the block enqueued for emailing, for this rule only.
+ def emailed_ids(rule)
+ before = enqueued_jobs.size
+ yield
+ enqueued_jobs.drop(before)
+ .select { |job| job[:job] == RuleEmailNotificationJob }
+ .map { |job| ActiveJob::Arguments.deserialize(job[:args]) }
+ .select { |rule_id, _| rule_id == rule.id }
+ .flat_map(&:second)
+ .sort
+ end
+end
diff --git a/test/models/rule/notification_baseline_on_edit_test.rb b/test/models/rule/notification_baseline_on_edit_test.rb
index 1f9e0d4257..a202fb6f68 100644
--- a/test/models/rule/notification_baseline_on_edit_test.rb
+++ b/test/models/rule/notification_baseline_on_edit_test.rb
@@ -236,11 +236,6 @@ class Rule::NotificationBaselineOnEditTest < ActiveSupport::TestCase
actions_attributes: [ { action_type: "send_email_notification" } ]
)
- # Take the baseline the action's create-time seed describes. That seed does
- # not run today: Rule::Action's after_update_commit names the same method,
- # which replaces its after_create_commit. Seeding is idempotent, so this
- # stays correct once that is fixed.
- rule.actions.first.send(:seed_notification_baseline)
Rule.find(rule.id)
end
diff --git a/test/models/rule/notification_baseline_on_enable_test.rb b/test/models/rule/notification_baseline_on_enable_test.rb
index 87b7fc89e5..9918e565f9 100644
--- a/test/models/rule/notification_baseline_on_enable_test.rb
+++ b/test/models/rule/notification_baseline_on_enable_test.rb
@@ -170,10 +170,9 @@ class Rule::NotificationBaselineOnEnableTest < ActiveSupport::TestCase
rule.update!(name: "Renamed")
NotificationDelivery.where(rule: rule).delete_all
- action = rule.actions.create!(action_type: "send_email_notification")
-
+ # Creating the action seeds its baseline from its own commit callback.
assert_difference -> { NotificationDelivery.where(rule: rule).count }, 1 do
- action.send(:seed_notification_baseline)
+ rule.actions.create!(action_type: "send_email_notification")
end
end