The personal finance app for everyone (by everyone)
Ruby
fix(bills): preload recurrence rules and accounts when claiming recurring patterns (#4136)
sentry[bot]b8c5d122ed59
diff --git a/app/models/recurring_transaction/identifier.rb b/app/models/recurring_transaction/identifier.rbindex d45d5bfa0d..cca171c08f 100644--- a/app/models/recurring_transaction/identifier.rb+++ b/app/models/recurring_transaction/identifier.rb@@ -115,9 +115,10 @@ class RecurringTransaction# row, and it lands as `suggested`, awaiting confirmation.existing_by_identity = family.recurring_transactions.to_a.group_by { |recurring| identity_key(recurring) }+ preload_series_to_refresh(recurring_patterns, existing_by_identity)+recurring_patterns.each do |pattern|- identity = [ pattern[:merchant_id] ? [ :merchant, pattern[:merchant_id] ] : [ :name, pattern[:name] ],- pattern[:currency], pattern[:account_id], nil ]+ identity = pattern_identity(pattern)candidates = existing_by_identity[identity] || []claimed = nearest_within_tolerance(candidates, pattern[:expected_amount_avg])@@ -331,6 +332,32 @@ class RecurringTransaction.min_by { |recurring| (recurring.amount - target_amount).abs }end+ # update_claimed_series reads each series' recurrence_rules+ # (sync_monthly_rule_day, Schedule.for) and accounts+ # (accounts_belong_to_family on update!). Batch-load them for only the+ # series this run will refresh -- not the manual/ended tombstones or+ # unmatched rows that stay in existing_by_identity purely for claiming.+ # Read-only and best-effort: a series missed here just loads lazily.+ def preload_series_to_refresh(recurring_patterns, existing_by_identity)+ to_refresh = recurring_patterns.filter_map do |pattern|+ claimed = nearest_within_tolerance(existing_by_identity[pattern_identity(pattern)] || [], pattern[:expected_amount_avg])+ claimed unless claimed.nil? || claimed.manual? || claimed.ended?+ end.uniq++ return if to_refresh.empty?++ ActiveRecord::Associations::Preloader.new(+ records: to_refresh,+ associations: [ :recurrence_rules, :account, :destination_account ]+ ).call+ end++ # Same shape as identity_key, built from a detected pattern.+ def pattern_identity(pattern)+ [ pattern[:merchant_id] ? [ :merchant, pattern[:merchant_id] ] : [ :name, pattern[:name] ],+ pattern[:currency], pattern[:account_id], nil ]+ end+# Refreshes a claimed series' cadence bookkeeping and variance band.# Amount and status are left alone (price changes belong to# PriceChangeDetector), and so is the due day once the user has pinneddiff --git a/test/models/recurring_transaction/identifier_test.rb b/test/models/recurring_transaction/identifier_test.rbindex 6c46c60ae7..7e7a58edd4 100644--- a/test/models/recurring_transaction/identifier_test.rb+++ b/test/models/recurring_transaction/identifier_test.rb@@ -484,6 +484,44 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCaseendend+ test "refreshes claimed series without per-series recurrence rule or account lookups" do+ account = @family.accounts.first+ names = Array.new(3) { |index| "Claimed Performance Subscription #{index}" }++ names.each_with_index do |name, index|+ create_name_pattern_entries(account: account, name: name, amount: 40 + index, day: 5)++ @family.recurring_transactions.create!(+ account: account,+ name: name,+ amount: 40 + index,+ currency: "USD",+ expected_day_of_month: 5,+ last_occurrence_date: 4.months.ago.to_date,+ next_expected_date: 1.month.from_now.to_date,+ occurrence_count: 1,+ status: "active"+ )+ end++ queries = nil+ assert_no_difference -> { @family.recurring_transactions.count } do+ queries = capture_sql_queries do+ @identifier.identify_recurring_patterns+ end+ end++ # One batched preload is fine; a query per claimed series is the N+1.+ rule_queries = queries.grep(/\ASELECT .*FROM "recurrence_rules"/)+ account_queries = queries.grep(/\ASELECT "accounts"\.\* FROM "accounts" WHERE "accounts"\."id"/)++ assert_operator rule_queries.size, :<=, 1, rule_queries.join(" | ")+ assert_operator account_queries.size, :<=, 1, account_queries.join(" | ")+ @family.recurring_transactions.where(name: names).each do |recurring|+ assert_equal 3, recurring.occurrence_count+ end+ end+test "updates manual recurring variance without per-recurring entry lookups" doaccount = @family.accounts.firstnames = Array.new(4) { |index| "Manual Performance Subscription #{index}" }