Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Stop emailing old matches after an email rule's conditions widen (#4150)

jaysbeekay3ae36a699553
diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rb
index 464bf04a1e..27e7db9e5a 100644
--- a/app/models/family/data_importer.rb
+++ b/app/models/family/data_importer.rb
@@ -1387,7 +1387,9 @@ class Family::DataImporter
stop_processing: data["stop_processing"] || false
)
- rule.conditions.destroy_all unless created
+ # 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
rule.actions.destroy_all unless created
# Build conditions
diff --git a/app/models/rule.rb b/app/models/rule.rb
index 4a87e26392..5e7e73f52f 100644
--- a/app/models/rule.rb
+++ b/app/models/rule.rb
@@ -38,13 +38,29 @@ class Rule < ApplicationRecord
# (by the toggle, the form, Apply or an import) would otherwise email every match
# from before, including those from while it was off.
#
+ # The baseline also describes the match set of the conditions and effective date it
+ # was taken under. An edit that changes them can bring older transactions into
+ # range, and the next run would email them as new, so the baseline is taken
+ # again. Active or not: Apply all runs inactive rules too, and the action's own
+ # seed does not check `active` either.
+ #
+ # The change is noted before the update, while nested attributes still hold it
+ # in memory: once autosave has run, a destroyed condition is gone from the
+ # association and a saved one no longer reports a pending change.
+ #
+ # A condition reporting a change is then checked against the stored criteria,
+ # one query, since the importers replace every condition on each re-import. An
+ # identical re-import must not re-seed: that would record a match still waiting
+ # for the next run as delivered, and it would never be emailed.
+ #
# after_update, not after_update_commit: it runs inside the save's transaction,
- # after the nested conditions and actions are written, so the baseline is taken
- # from the conditions as saved and is committed together with `active`. Nothing
- # can see the rule switched on without its baseline. Declared after the nested
- # attributes so it runs after their autosave. A new rule needs no callback:
- # creating its email action seeds the baseline.
- after_update :seed_notification_baseline, if: :switched_on?
+ # after the nested conditions and actions are written (it is declared after
+ # accepts_nested_attributes_for, so it runs after their autosave), and reads
+ # them on the same connection as saved. The new baseline commits together with
+ # the edit, so nothing can see the new conditions without it, and if writing it
+ # fails the edit rolls back rather than leaving a stale baseline behind.
+ before_update :note_match_criteria_change
+ after_update :seed_notification_baseline, if: :notification_baseline_out_of_date?
# Set when this save's after_update took the baseline, or tried to and timed
# out. Rule::Action's commit callback for an email action added in the same
@@ -56,8 +72,9 @@ class Rule < ApplicationRecord
@notification_baseline_taken == true
end
- # True when the last save asked to switch the rule on, or gave it an email
- # action, but the baseline query timed out, so the rule was left off.
+ # True when the last save asked to switch the rule on, changed what it matches,
+ # or gave it an email action, but the baseline query timed out, so the rule was
+ # left off.
def notification_baseline_timed_out?
@notification_baseline_timed_out == true
end
@@ -326,6 +343,63 @@ class Rule < ApplicationRecord
end
end
+ def note_match_criteria_change
+ @match_criteria_changed = will_save_change_to_effective_date? ||
+ (association(:conditions).target.any?(&:match_criteria_changing?) && condition_criteria_changing?)
+ end
+
+ # Whether the criteria this save leaves differ from the stored ones. The
+ # importers replace every condition, so each one reads as changing even when
+ # the new set holds the same criteria; only a different set re-seeds.
+ #
+ # Compares two signatures: the conditions as stored (one query), and the same
+ # rows with this save's pending changes laid over them. Order does not count
+ # (top-level conditions all apply, and a group's and/or reads its members
+ # either way), and neither does nil against "" (see
+ # Rule::Condition#match_criteria_changing?).
+ def condition_criteria_changing?
+ top_level_ids = Rule::Condition.where(rule_id: id).select(:id)
+ stored = Rule::Condition.where(rule_id: id).or(Rule::Condition.where(parent_id: top_level_ids)).to_a
+ stored_children = stored.group_by(&:parent_id)
+ stored_top_level = stored.select { |condition| condition.rule_id == id }
+
+ before = criteria_signature(stored_top_level) { |condition| stored_children[condition.id].to_a }
+ after = criteria_signature(pending_conditions(stored_top_level, association(:conditions).target)) do |condition|
+ stored_for_condition = condition.new_record? ? [] : stored_children[condition.id].to_a
+ pending_conditions(stored_for_condition, condition.association(:sub_conditions).target)
+ end
+
+ before != after
+ end
+
+ # The stored conditions as this save leaves them: in-memory copies replace
+ # their stored rows, new ones join, and those marked for destruction drop out.
+ def pending_conditions(stored, in_memory)
+ in_memory_by_id = in_memory.reject(&:new_record?).index_by(&:id)
+
+ (stored.map { |condition| in_memory_by_id.fetch(condition.id, condition) } + in_memory.select(&:new_record?))
+ .reject(&:marked_for_destruction?)
+ end
+
+ def criteria_signature(conditions, &children)
+ conditions.map do |condition|
+ [
+ condition.condition_type.to_s,
+ condition.operator.to_s,
+ condition.value.presence.to_s,
+ criteria_signature(children.call(condition)) { [] }
+ ]
+ end.sort
+ end
+
+ def match_criteria_changed?
+ @match_criteria_changed == true
+ end
+
+ def notification_baseline_out_of_date?
+ switched_on? || match_criteria_changed?
+ end
+
def switched_on?
saved_change_to_active?(from: false, to: true)
end
diff --git a/app/models/rule/condition.rb b/app/models/rule/condition.rb
index 1374c9def0..4132c522ae 100644
--- a/app/models/rule/condition.rb
+++ b/app/models/rule/condition.rb
@@ -33,6 +33,24 @@ class Rule::Condition < ApplicationRecord
condition_type == "compound"
end
+ # Whether saving this condition would change which resources it matches: it is
+ # new, it is about to be destroyed, its type, operator or value is changing, or
+ # one of its sub-conditions is. Reads only what is in memory, which is where
+ # nested attributes put pending changes, so it costs no query.
+ #
+ # The edit form resubmits every condition with its current values; those are
+ # not changes. Nor is a value moving between nil and "": the form sends a
+ # valueless condition's hidden value field back as "" where an import stored
+ # nil, and no filter reads a blank value (validation requires one for every
+ # operator that does).
+ def match_criteria_changing?
+ return true if new_record? || marked_for_destruction?
+ return true if will_save_change_to_condition_type? || will_save_change_to_operator?
+ return true if will_save_change_to_value? && value_in_database.presence != value.presence
+
+ association(:sub_conditions).target.any?(&:match_criteria_changing?)
+ end
+
def regex?
Rule::ConditionFilter::REGEX_OPERATORS.include?(operator)
end
diff --git a/app/models/rule_import.rb b/app/models/rule_import.rb
index 3f5be2e23e..924f1b9499 100644
--- a/app/models/rule_import.rb
+++ b/app/models/rule_import.rb
@@ -165,8 +165,10 @@ class RuleImport < Import
rule.active = row.active || false
rule.effective_date = parse_date(row.effective_date)
- # Clear existing conditions and actions
- rule.conditions.destroy_all
+ # 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).
+ rule.conditions.each(&:mark_for_destruction)
rule.actions.destroy_all
# Create conditions
diff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rb
index 72a33ebaed..1c2a7009b7 100644
--- a/test/controllers/rules_controller_test.rb
+++ b/test/controllers/rules_controller_test.rb
@@ -710,6 +710,38 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
assert_equal "connection refused", entry.metadata["error_message"]
end
+ # The edit form resubmits every condition and action id with its current
+ # values, so these tests submit exactly what the rendered form holds (read back
+ # from the edit page) rather than a hand-picked subset.
+ test "editing an email rule's condition through the form does not email existing matches" do
+ rule, tea = email_rule_with_baseline
+
+ fields = edit_form_fields(rule)
+ condition_value = fields.keys.find { |name| name.match?(/\Arule\[conditions_attributes\]\[\d+\]\[value\]\z/) }
+ assert_equal "coffee", fields[condition_value]
+ patch rule_url(rule), params: fields.merge(condition_value => "house")
+ assert_redirected_to rules_url
+
+ emailed = emailed_ids(rule) { perform_enqueued_jobs(only: RuleJob) { post apply_rule_url(rule) } }
+
+ assert_equal [], emailed
+ assert_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), tea.id
+ end
+
+ test "saving the form with unchanged conditions does not re-seed" do
+ rule, _tea = email_rule_with_baseline
+ coffee_bar = Entry.create!(account: @baseline_account, name: "Coffee bar", date: Date.current, amount: 5, currency: "USD", entryable: Transaction.new).transaction
+
+ assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
+ patch rule_url(rule), params: edit_form_fields(rule)
+ end
+ assert_redirected_to rules_url
+
+ emailed = emailed_ids(rule) { perform_enqueued_jobs(only: RuleJob) { post apply_rule_url(rule) } }
+
+ assert_equal [ coffee_bar.id ], emailed, "a match that arrived since the last run is still emailed"
+ end
+
private
# A regex condition, so a stubbed timeout reaches the baseline query, and one
# matching transaction, so a recorded baseline is visible as a delivery.
@@ -738,4 +770,57 @@ class RulesControllerTest < ActionDispatch::IntegrationTest
create_transaction(date: Date.current, account: account, name: "Baseline match zq")
rule
end
+
+ # An active email rule matching "Coffee shop", with its baseline taken, and a
+ # "Tea house" transaction it does not match yet.
+ def email_rule_with_baseline
+ family = @user.family
+ @baseline_account = family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
+ Entry.create!(account: @baseline_account, name: "Coffee shop", date: 90.days.ago.to_date, amount: 10, currency: "USD", entryable: Transaction.new)
+ tea = Entry.create!(account: @baseline_account, name: "Tea house", date: 60.days.ago.to_date, amount: 20, currency: "USD", entryable: Transaction.new).transaction
+
+ rule = family.rules.create!(
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ],
+ actions_attributes: [ { action_type: "send_email_notification" } ]
+ )
+ # Rule::Action's create-time seed does not run today (its after_update_commit
+ # names the same method and replaces it), so take that baseline here.
+ rule.actions.first.send(:seed_notification_baseline)
+
+ [ rule, tea ]
+ end
+
+ # The name/value pairs the browser would submit from the rule's edit form:
+ # every input and select outside the Stimulus <template>s, checked radios
+ # only, and a select's selected option.
+ def edit_form_fields(rule)
+ get edit_rule_url(rule)
+ assert_response :success
+
+ form = Nokogiri::HTML(response.body).at_css("form[action='#{rule_path(rule)}']")
+ form.css("input, select").each_with_object({}) do |field, fields|
+ next if field.ancestors("template").any? || field["name"].blank?
+ next if %w[_method authenticity_token commit].include?(field["name"])
+ next if field["type"] == "radio" && !field.has_attribute?("checked")
+
+ fields[field["name"]] = if field.name == "select"
+ (field.at_css("option[selected]") || field.at_css("option"))&.[]("value")
+ else
+ field["value"].to_s
+ end
+ end
+ end
+
+ 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
new file mode 100644
index 0000000000..1f9e0d4257
--- /dev/null
+++ b/test/models/rule/notification_baseline_on_edit_test.rb
@@ -0,0 +1,275 @@
+require "test_helper"
+
+# An email rule records the transactions it already matches as delivered, so it
+# only ever emails what appears afterwards. These tests cover edits that change
+# WHICH transactions the rule matches: the baseline has to be taken again, or the
+# next run emails every older transaction the edited rule now reaches.
+class Rule::NotificationBaselineOnEditTest < ActiveSupport::TestCase
+ include EntriesTestHelper, ActiveJob::TestHelper
+
+ setup do
+ @family = families(:dylan_family)
+ @account = @family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
+ @coffee = create_transaction(date: 90.days.ago.to_date, account: @account, amount: 10, name: "Coffee shop").transaction
+ @tea = create_transaction(date: 60.days.ago.to_date, account: @account, amount: 20, name: "Tea house").transaction
+ end
+
+ test "widening an active email rule's condition does not email existing matches" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ])
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+
+ rows_before = NotificationDelivery.where(rule: rule).count
+ assert rule.update(conditions_attributes: [ { id: rule.conditions.first.id, value: "house" } ])
+ rows_after_edit = NotificationDelivery.where(rule: rule).count
+
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_equal 1, rows_after_edit - rows_before, "the edit should record the newly matched transaction"
+ assert_equal [ @coffee.id, @tea.id ].sort, delivered_ids(rule)
+ end
+
+ test "clearing the effective date does not email existing matches" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ], effective_date: 30.days.ago.to_date)
+ assert_equal [], delivered_ids(rule), "Coffee shop is older than the effective date, so the baseline is empty"
+
+ assert rule.update(effective_date: nil)
+
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+ end
+
+ test "moving the effective date earlier does not email existing matches" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ], effective_date: 30.days.ago.to_date)
+ assert_equal [], delivered_ids(rule)
+
+ assert rule.update(effective_date: 120.days.ago.to_date)
+
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+ end
+
+ test "a new transaction after the widening edit is still emailed" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ])
+ assert rule.update(conditions_attributes: [ { id: rule.conditions.first.id, value: "house" } ])
+
+ guest_house = create_transaction(date: Date.current, account: @account, amount: 30, name: "Guest house").transaction
+
+ assert_equal [ guest_house.id ], emailed_ids(rule) { run_rule(rule) }
+ end
+
+ test "changing a condition's operator does not email existing matches" do
+ # "=" is an exact match, so "house" matches nothing until it becomes "contains".
+ rule = create_email_rule(conditions: [ name_condition("house", operator: "=") ])
+ assert_equal [], delivered_ids(rule)
+
+ assert rule.update(conditions_attributes: [ { id: rule.conditions.first.id, operator: "like" } ])
+
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_equal [ @tea.id ], delivered_ids(rule)
+ end
+
+ test "changing a condition's type does not email existing matches" do
+ # No transaction has notes, so the notes condition matches nothing.
+ rule = create_email_rule(conditions: [ { condition_type: "transaction_notes", operator: "like", value: "house" } ])
+ assert_equal [], delivered_ids(rule)
+
+ assert rule.update(conditions_attributes: [ { id: rule.conditions.first.id, condition_type: "transaction_name" } ])
+
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_equal [ @tea.id ], delivered_ids(rule)
+ end
+
+ test "removing a condition does not email existing matches" do
+ rule = create_email_rule(conditions: [ name_condition("o"), name_condition("coffee") ])
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+ narrowing = rule.conditions.find_by!(value: "coffee")
+
+ assert rule.update(conditions_attributes: [ { id: narrowing.id, _destroy: "1" } ])
+
+ assert_not_includes emailed_ids(rule) { run_rule(rule) }, @tea.id
+ assert_includes delivered_ids(rule), @tea.id
+ end
+
+ test "widening a compound sub-condition does not email existing matches" do
+ rule = create_email_rule(conditions: [ compound_condition("and", name_condition("coffee")) ])
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+ group = rule.conditions.first
+
+ assert rule.update(conditions_attributes: [
+ { id: group.id, sub_conditions_attributes: [ { id: group.sub_conditions.first.id, value: "house" } ] }
+ ])
+
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_equal [ @coffee.id, @tea.id ].sort, delivered_ids(rule)
+ end
+
+ test "adding a sub-condition to an any-of group does not email existing matches" do
+ rule = create_email_rule(conditions: [ compound_condition("or", name_condition("coffee")) ])
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+
+ assert rule.update(conditions_attributes: [
+ { id: rule.conditions.first.id, sub_conditions_attributes: [ name_condition("house") ] }
+ ])
+
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_equal [ @coffee.id, @tea.id ].sort, delivered_ids(rule)
+ end
+
+ test "editing an inactive email rule then applying all rules does not email history" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ], active: false)
+ assert rule.update(conditions_attributes: [ { id: rule.conditions.first.id, value: "house" } ])
+
+ emailed = emailed_ids(rule) { ApplyAllRulesJob.perform_now(@family) }
+
+ assert_equal [], emailed
+ assert_not rule.reload.active?
+ end
+
+ test "the new baseline is written inside the edit's transaction" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ])
+
+ Rule.transaction do
+ assert rule.update(conditions_attributes: [ { id: rule.conditions.first.id, value: "house" } ])
+
+ # Before the edit commits, the new conditions already come with their baseline.
+ assert_includes delivered_ids(rule), @tea.id
+ end
+ end
+
+ # Review of we-promise/sure#4150 (Codex, P1). Family::DataImporter clears an
+ # existing rule's conditions with destroy_all before it saves, so an import with
+ # no conditions left nothing for the rule to see changing, and a rule with no
+ # conditions matches every transaction.
+ test "a Sure re-import that removes every condition does not email existing matches" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ])
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+
+ session = @family.import_sessions.create!(expected_chunks: 1)
+ session.source_mappings.create!(family: @family, source_type: "Rule", source_id: "rule-1", target: rule)
+ ndjson = {
+ type: "Rule", version: 1,
+ data: { id: "rule-1", name: "Everything", resource_type: "transaction", active: true,
+ conditions: [], actions: [ { action_type: "send_email_notification" } ] }
+ }.to_json
+ Family::DataImporter.new(@family, ndjson, import_session: session).import!
+ assert_empty rule.reload.conditions, "precondition: the import left the rule with no conditions"
+
+ # With no conditions the rule matches every transaction the family has, so the
+ # new baseline holds more than these two; Tea house joining it is the change.
+ assert_equal [], emailed_ids(rule) { run_rule(rule) }
+ assert_includes delivered_ids(rule), @tea.id
+ end
+
+ # Review of we-promise/sure#4150 (CodeRabbit). The importer replaces every
+ # condition, so each one reads as changing even when the record holds the same
+ # criteria. Re-seeding then would record a match still waiting for the next run
+ # as delivered, and it would never be emailed.
+ test "an identical Sure re-import still emails a pending match" do
+ rule = create_email_rule(conditions: [ compound_condition("and", name_condition("coffee"), name_condition("o")) ])
+ assert_equal [ @coffee.id ], delivered_ids(rule)
+ coffee_bar = create_transaction(date: Date.current, account: @account, amount: 5, name: "Coffee bar").transaction
+
+ session = @family.import_sessions.create!(expected_chunks: 1)
+ session.source_mappings.create!(family: @family, source_type: "Rule", source_id: "rule-1", target: rule)
+ ndjson = {
+ type: "Rule", version: 1,
+ data: { id: "rule-1", name: "Coffee alerts", resource_type: "transaction", active: true,
+ conditions: [ { condition_type: "compound", operator: "and",
+ sub_conditions: [ name_condition("o"), name_condition("coffee") ] } ],
+ actions: [ { action_type: "send_email_notification" } ] }
+ }.to_json
+
+ assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
+ Family::DataImporter.new(@family, ndjson, import_session: session).import!
+ end
+ assert_equal "Coffee alerts", rule.reload.name, "precondition: the import updated this rule"
+
+ assert_equal [ coffee_bar.id ], emailed_ids(rule) { run_rule(rule) }
+ end
+
+ test "renaming an email rule does not re-seed" do
+ rule = create_email_rule(conditions: [ name_condition("coffee") ])
+ coffee_bar = create_transaction(date: Date.current, account: @account, amount: 5, name: "Coffee bar").transaction
+
+ assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
+ assert rule.update(name: "Coffee alerts")
+ end
+
+ assert_equal [ coffee_bar.id ], emailed_ids(rule) { run_rule(rule) }
+ end
+
+ test "resubmitting a valueless condition's blank value does not re-seed" do
+ # An import stores a valueless condition's value as nil; the form's hidden
+ # value field sends it back as "". Both mean "no value".
+ rule = create_email_rule(conditions: [ name_condition("coffee"), { condition_type: "transaction_notes", operator: "is_null", value: nil } ])
+ valueless = rule.conditions.find_by!(condition_type: "transaction_notes")
+ assert_nil valueless.value
+ coffee_bar = create_transaction(date: Date.current, account: @account, amount: 5, name: "Coffee bar").transaction
+
+ assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
+ assert rule.update(conditions_attributes: [ { id: valueless.id, condition_type: "transaction_notes", operator: "is_null", value: "" } ])
+ end
+
+ assert_equal [ coffee_bar.id ], emailed_ids(rule) { run_rule(rule) }
+ end
+
+ test "editing a rule without an email action writes no notification deliveries" do
+ category = @family.categories.first
+ rule = @family.rules.create!(
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ name_condition("coffee") ],
+ actions_attributes: [ { action_type: "set_transaction_category", value: category.id } ]
+ )
+
+ assert_no_difference -> { NotificationDelivery.count } do
+ assert rule.update(conditions_attributes: [ { id: rule.conditions.first.id, value: "house" } ])
+ end
+ end
+
+ private
+ def create_email_rule(conditions:, active: true, effective_date: nil)
+ rule = @family.rules.create!(
+ resource_type: "transaction",
+ active: active,
+ effective_date: effective_date,
+ conditions_attributes: conditions,
+ 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
+
+ def name_condition(value, operator: "like")
+ { condition_type: "transaction_name", operator: operator, value: value }
+ end
+
+ def compound_condition(operator, *sub_conditions)
+ { condition_type: "compound", operator: operator, sub_conditions_attributes: sub_conditions }
+ end
+
+ # A run as RuleJob performs it, on a freshly loaded rule.
+ def run_rule(rule)
+ RuleJob.perform_now(Rule.find(rule.id))
+ 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_import_test.rb b/test/models/rule_import_test.rb
index dd7522e818..4cc3099913 100644
--- a/test/models/rule_import_test.rb
+++ b/test/models/rule_import_test.rb
@@ -1,6 +1,8 @@
require "test_helper"
class RuleImportTest < ActiveSupport::TestCase
+ include ActiveJob::TestHelper
+
setup do
@family = families(:dylan_family)
@category = @family.categories.create!(
@@ -308,6 +310,118 @@ class RuleImportTest < ActiveSupport::TestCase
assert_equal "auto_categorize", action.action_type
end
+ test "re-importing an email rule with wider conditions does not email existing matches" do
+ account = @family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
+ Entry.create!(account: account, name: "Coffee shop", date: 90.days.ago.to_date, amount: 10, currency: "USD", entryable: Transaction.new)
+ tea = Entry.create!(account: account, name: "Tea house", date: 60.days.ago.to_date, amount: 20, currency: "USD", entryable: Transaction.new).transaction
+
+ rule = @family.rules.create!(
+ name: "Coffee alerts",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ],
+ actions_attributes: [ { action_type: "send_email_notification" } ]
+ )
+ # Rule::Action's create-time seed does not run today (its after_update_commit
+ # names the same method and replaces it), so take that baseline here.
+ rule.actions.first.send(:seed_notification_baseline)
+
+ csv = <<~CSV
+ name,resource_type,active,effective_date,conditions,actions
+ "Coffee alerts","transaction",true,,"[{\"condition_type\":\"transaction_name\",\"operator\":\"like\",\"value\":\"house\"}]","[{\"action_type\":\"send_email_notification\"}]"
+ CSV
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+
+ assert_no_enqueued_jobs only: RuleEmailNotificationJob do
+ RuleJob.perform_now(Rule.find(rule.id))
+ end
+ assert_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), tea.id
+ end
+
+ # Review of we-promise/sure#4150 (Codex, P1). The import clears the rule's
+ # conditions with destroy_all before it saves, so a row with no conditions left
+ # nothing for the rule to see changing, and a rule with no conditions matches
+ # every transaction.
+ test "re-importing an email rule with no conditions does not email existing matches" do
+ account = @family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
+ Entry.create!(account: account, name: "Coffee shop", date: 90.days.ago.to_date, amount: 10, currency: "USD", entryable: Transaction.new)
+ tea = Entry.create!(account: account, name: "Tea house", date: 60.days.ago.to_date, amount: 20, currency: "USD", entryable: Transaction.new).transaction
+
+ rule = @family.rules.create!(
+ name: "Coffee alerts",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ],
+ actions_attributes: [ { action_type: "send_email_notification" } ]
+ )
+ rule.actions.first.send(:seed_notification_baseline)
+ assert_not_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), tea.id, "precondition: Tea house is outside the baseline"
+
+ csv = <<~CSV
+ name,resource_type,active,effective_date,conditions,actions
+ "Coffee alerts","transaction",true,,"[]","[{\"action_type\":\"send_email_notification\"}]"
+ CSV
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+ assert_empty rule.reload.conditions, "precondition: the import left the rule with no conditions"
+
+ assert_no_enqueued_jobs only: RuleEmailNotificationJob do
+ RuleJob.perform_now(Rule.find(rule.id))
+ end
+ assert_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), tea.id
+ end
+
+ # Review of we-promise/sure#4150 (CodeRabbit). The import replaces every
+ # condition, so each one reads as changing even when the row holds the same
+ # criteria. Re-seeding then would record a match still waiting for the next run
+ # as delivered, and it would never be emailed.
+ test "re-importing an email rule with identical conditions still emails a pending match" do
+ rule, coffee_bar = email_rule_with_pending_match(conditions: [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ])
+
+ assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
+ import_rule_rows(rule.name, [ { condition_type: "transaction_name", operator: "like", value: "coffee" } ])
+ end
+
+ assert_equal [ coffee_bar.id ], emailed_transaction_ids(rule)
+ end
+
+ test "re-importing an email rule's conditions in a different order still emails a pending match" do
+ rule, coffee_bar = email_rule_with_pending_match(conditions: [
+ { condition_type: "transaction_name", operator: "like", value: "coffee" },
+ { condition_type: "transaction_name", operator: "like", value: "bar" }
+ ])
+
+ assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
+ import_rule_rows(rule.name, [
+ { condition_type: "transaction_name", operator: "like", value: "bar" },
+ { condition_type: "transaction_name", operator: "like", value: "coffee" }
+ ])
+ end
+
+ assert_equal [ coffee_bar.id ], emailed_transaction_ids(rule)
+ end
+
+ test "re-importing a valueless condition with a blank value still emails a pending match" do
+ rule, coffee_bar = email_rule_with_pending_match(conditions: [
+ { condition_type: "transaction_name", operator: "like", value: "coffee" },
+ { condition_type: "transaction_notes", operator: "is_null", value: nil }
+ ])
+ assert_nil rule.conditions.find_by!(condition_type: "transaction_notes").value
+
+ assert_no_difference -> { NotificationDelivery.where(rule: rule).count } do
+ import_rule_rows(rule.name, [
+ { condition_type: "transaction_name", operator: "like", value: "coffee" },
+ { condition_type: "transaction_notes", operator: "is_null", value: "" }
+ ])
+ end
+ assert_equal "", rule.reload.conditions.find_by!(condition_type: "transaction_notes").value, "precondition: the import stored the blank value"
+
+ assert_equal [ coffee_bar.id ], emailed_transaction_ids(rule)
+ end
+
test "validates resource_type" do
csv = <<~CSV
name,resource_type,active,effective_date,conditions,actions
@@ -538,4 +652,46 @@ class RuleImportTest < ActiveSupport::TestCase
assert_equal 'C:\new\test', condition.value
end
+
+ private
+ # An email rule with its baseline taken, plus a later Coffee bar transaction
+ # the rule has not run against yet.
+ def email_rule_with_pending_match(conditions:)
+ account = @family.accounts.create!(name: "Baseline test", balance: 1000, currency: "USD", accountable: Depository.new)
+ Entry.create!(account: account, name: "Coffee shop", date: 90.days.ago.to_date, amount: 10, currency: "USD", entryable: Transaction.new)
+ rule = @family.rules.create!(
+ name: "Coffee alerts",
+ resource_type: "transaction",
+ active: true,
+ conditions_attributes: conditions,
+ actions_attributes: [ { action_type: "send_email_notification" } ]
+ )
+ rule.actions.first.send(:seed_notification_baseline)
+ coffee_bar = Entry.create!(account: account, name: "Coffee bar", date: Date.current, amount: 5, currency: "USD", entryable: Transaction.new).transaction
+ assert_not_includes NotificationDelivery.where(rule: rule).pluck(:transaction_id), coffee_bar.id, "precondition: Coffee bar is outside the baseline"
+
+ [ Rule.find(rule.id), coffee_bar ]
+ end
+
+ def import_rule_rows(name, conditions)
+ csv = CSV.generate do |rows|
+ rows << %w[name resource_type active effective_date conditions actions]
+ rows << [ name, "transaction", "true", nil, conditions.to_json, [ { action_type: "send_email_notification" } ].to_json ]
+ end
+ import = @family.imports.create!(type: "RuleImport", raw_file_str: csv, col_sep: ",")
+ import.generate_rows_from_csv
+ import.send(:import!)
+ end
+
+ # The transaction ids a RuleJob run enqueues for emailing, for this rule only.
+ def emailed_transaction_ids(rule)
+ before = enqueued_jobs.size
+ RuleJob.perform_now(Rule.find(rule.id))
+ 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