The personal finance app for everyone (by everyone)
Ruby
fix(bills): match recurring transfers to the transfers that pay them (#3932)
scragnog00dd977fbad5
diff --git a/app/helpers/bills_helper.rb b/app/helpers/bills_helper.rbindex df5febe322..bc360d6ca0 100644--- a/app/helpers/bills_helper.rb+++ b/app/helpers/bills_helper.rb@@ -409,6 +409,7 @@ module BillsHelperreasons << t("bills.match.same_merchant") if signals[:merchant]reasons << t("bills.match.name_matches") if signals[:name]+ reasons << t("bills.match.same_transfer") if signals[:transfer]# Guarded: the review queue can hold an allocation whose entry has been# nullified out from under it, so neither figure is guaranteed.diff --git a/app/models/recurring_transaction/matcher.rb b/app/models/recurring_transaction/matcher.rbindex ebbaa9d2d3..cbdb57d1d7 100644--- a/app/models/recurring_transaction/matcher.rb+++ b/app/models/recurring_transaction/matcher.rb@@ -229,7 +229,7 @@ class RecurringTransactionfamily.recurring_occurrences.open_status.includes(recurring_transaction: :recurrence_rules)- .reject { |occurrence| occurrence.recurring_transaction.transfer? }+ .to_aenddef rejected_pairs@@ -251,22 +251,60 @@ class RecurringTransactionend# One query over the envelope of every open occurrence's window.+ # Transfer legs are left out, except the outflow side of a transfer that+ # a recurring transfer series could be paid by.def entries_for(occurrences, include_closed_window)window_min = occurrences.map { |occurrence| window_for(occurrence).begin }.minwindow_max = occurrences.map { |occurrence| window_for(occurrence).end }.maxwindow_max = Date.current if !include_closed_window && window_max > Date.current+ source_account_ids = occurrences.map(&:recurring_transaction).select(&:transfer?).map(&:account_id).uniq+ preload_transfer_destinations(source_account_ids, window_min..window_max)+family.entries.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id").where(entryable_type: "Transaction").where(excluded: false).where(date: window_min..window_max)- .where.not(transactions: { kind: Transaction::TRANSFER_KINDS })+ .where("transactions.kind NOT IN (?) OR transactions.id IN (?)", Transaction::TRANSFER_KINDS, transfer_destinations.keys).where.not(id: RecurringAllocation.where.not(entry_id: nil).where(state: "confirmed").select(:entry_id)).includes(:entryable).to_aend+ # Outflow transaction id => the account its transfer pays into, for the+ # transfers leaving the given accounts in the window. Every entry+ # candidate collection scores is in that window, so once this has run the+ # map is complete and a missing entry is simply not a transfer outflow.+ def preload_transfer_destinations(account_ids, dates)+ @transfer_destinations_complete = true+ return if account_ids.empty?++ Transfer+ .joins(outflow_transaction: :entry)+ .joins("INNER JOIN entries inflow_entries ON inflow_entries.entryable_id = transfers.inflow_transaction_id AND inflow_entries.entryable_type = 'Transaction'")+ .where(entries: { account_id: account_ids, date: dates })+ .pluck(:outflow_transaction_id, "inflow_entries.account_id")+ .each { |outflow_id, account_id| transfer_destinations[outflow_id] = account_id }+ end++ def transfer_destinations+ @transfer_destinations ||= {}+ end++ # The account the entry pays into when it is the outflow of a transfer.+ # Read from the preload during candidate collection; looked up on demand+ # for explain and orphan repair, which handle one entry at a time.+ def transfer_destination(entry)+ transaction_id = entry.entryable_id+ return transfer_destinations[transaction_id] if transfer_destinations.key?(transaction_id) || @transfer_destinations_complete++ transfer_destinations[transaction_id] = Transfer+ .where(outflow_transaction_id: transaction_id)+ .joins(inflow_transaction: :entry)+ .pick("entries.account_id")+ end+# The occurrence's date window, snooze-aware and clamped so adjacent# occurrences of one series can never both claim the same entry: each# side caps at just under half the cycle length. Overdue occurrences@@ -298,6 +336,10 @@ class RecurringTransaction# keeps the merchant when it has one, and its name stays kin to the old# descriptor rather than equal to it.def repair_identity?(series, entry)+ # A transfer leg's name is generic ("Transfer", a bank reference), so+ # the account pair is the identity here too, as in identity_matches?.+ return transfer_destination(entry) == series.destination_account_id if series.transfer?+if series.merchant_id.present? && entry.entryable.merchant_id.present?return entry.entryable.merchant_id == series.merchant_idend@@ -310,7 +352,10 @@ class RecurringTransaction# Hard filters: right sign, right currency, right account when the# series is account-scoped, and the identifier at least plausibly- # related (same merchant, or a name the series knows).+ # related (same merchant, or a name the series knows). A recurring+ # transfer is identified by its account pair instead: the entry must be+ # the outflow of a transfer into the series' destination account. Any+ # other series never matches a transfer leg.def identity_matches?(series, entry)return false unless entry.currency == series.currencyreturn false if series.account_id.present? && entry.account_id != series.account_id@@ -318,6 +363,9 @@ class RecurringTransactionexpense_series = series.amount.positive?return false if expense_series != entry.amount.positive?+ return transfer_destination(entry) == series.destination_account_id if series.transfer?+ return false if entry.entryable.transfer?+if series.merchant_id.present?entry.entryable.merchant_id == series.merchant_idelse@@ -348,7 +396,9 @@ class RecurringTransactionsignals = {}expected = expected_for(occurrence)- if series.merchant_id.present?+ if series.transfer?+ signals[:transfer] = 0.40+ elsif series.merchant_id.present?signals[:merchant] = 0.40elsesignals[:name] = 0.35diff --git a/config/locales/views/bills/en.yml b/config/locales/views/bills/en.ymlindex c791177f9a..8ec840ee11 100644--- a/config/locales/views/bills/en.yml+++ b/config/locales/views/bills/en.yml@@ -97,6 +97,7 @@ en:match:same_merchant: Same merchantname_matches: Name matches+ same_transfer: Transfer to the same accountexact_amount: Exact amountamount_off: "%{amount} off"due_date: Due-date matchdiff --git a/test/helpers/bills_helper_test.rb b/test/helpers/bills_helper_test.rbindex 0acbb08ffd..7a0edc57cc 100644--- a/test/helpers/bills_helper_test.rb+++ b/test/helpers/bills_helper_test.rb@@ -35,6 +35,12 @@ class BillsHelperTest < ActionView::TestCase], reasonsend+ test "a recurring transfer's match reads as a transfer to the same account" do+ reasons = bills_match_reasons({ transfer: 0.40, account: 0.10 }, currency: "USD")++ assert_equal [ I18n.t("bills.match.same_transfer") ], reasons+ end+# signals[:account] is a constant 0.10 on every candidate, because# identity_matches? has already rejected everything on another account. A# reason that never distinguishes anything is decoration.diff --git a/test/models/recurring_transaction/matcher_test.rb b/test/models/recurring_transaction/matcher_test.rbindex ec5518ca23..75a68c909d 100644--- a/test/models/recurring_transaction/matcher_test.rb+++ b/test/models/recurring_transaction/matcher_test.rb@@ -215,6 +215,35 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCaseassert_equal replacement.id, allocation.reload.entry_idend+ test "repair re-attaches a recurring transfer's payment by its account pair, not its name" do+ series = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))+ occurrence = series.recurring_occurrences.order(:due_on).first+ original = create_transfer(amount: 500, date: Date.current, to: accounts(:loan), name: "LOAN DD 1234")+ @matcher.run!+ allocation = occurrence.allocations.sole++ original.destroy!+ assert_nil allocation.reload.entry_id++ create_transfer(amount: 500, date: allocation.paid_on, to: accounts(:credit_card), name: "LOAN DD 1234")+ replacement = create_transfer(amount: 500, date: allocation.paid_on, to: accounts(:loan), name: "REF 998877")+ Matcher.new(@family).repair_orphans!++ assert_equal replacement.id, allocation.reload.entry_id+ end++ test "candidate collection looks up no transfer per ordinary charge" do+ create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))+ create_transfer(amount: 500, date: Date.current, to: accounts(:loan))+ 3.times { |i| create_entry(amount: 500, date: Date.current - i, name: "charge #{i}") }++ lookups = 0+ count_lookups = ->(*, payload) { lookups += 1 if payload[:sql].match?(/FROM "transfers".*LIMIT/m) }+ ActiveSupport::Notifications.subscribed(count_lookups, "sql.active_record") { @matcher.run! }++ assert_equal 0, lookups, "the batch preload already answers every entry in the window"+ end+test "manually attaching an alien-named entry teaches an alias" doseries = create_series(name: "Watson Property", amount: 2150, day_offset: 5)occurrence = series.recurring_occurrences.order(:due_on).first@@ -333,14 +362,68 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCaseassert_nil allocation.reload.entry_id, "a stranger with the same price is not the bill"end+ test "a recurring transfer is paid by the transfer into its destination account" do+ series = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))+ occurrence = series.recurring_occurrences.order(:due_on).first+ outflow = create_transfer(amount: 500, date: Date.current, to: accounts(:loan))++ assert_equal 1, @matcher.run!++ allocation = occurrence.allocations.sole+ assert allocation.allocation_confirmed?+ assert_equal outflow.id, allocation.entry_id+ assert allocation.match_signals.key?("transfer")+ assert occurrence.reload.paid?+ end++ test "a recurring transfer ignores transfers into another account and plain charges" do+ series = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))+ create_transfer(amount: 500, date: Date.current, to: accounts(:credit_card))+ create_entry(amount: 500, date: Date.current, name: "Payment to Loan")++ assert_equal 0, @matcher.run!+ assert_empty series.recurring_occurrences.flat_map(&:allocations)+ end++ test "an ordinary bill never matches a transfer leg, even with the same name" do+ series = create_series(name: "MORTGAGE DD", amount: 500, day_offset: 0)+ create_transfer(amount: 500, date: Date.current, to: accounts(:loan), name: "MORTGAGE DD")++ assert_equal 0, @matcher.run!+ assert_empty series.recurring_occurrences.flat_map(&:allocations)+ end++ test "backfill closes a recurring transfer's past occurrence from its transfer" do+ series = create_series(name: "Payment to Loan", amount: 500, day_offset: -30, destination: accounts(:loan))+ occurrence = series.recurring_occurrences.order(:due_on).first+ create_transfer(amount: 500, date: occurrence.due_on, to: accounts(:loan))++ @matcher.run_backfill!++ assert occurrence.reload.paid?+ end++ test "explain scores a recurring transfer's own transfer and refuses others" do+ series = create_series(name: "Payment to Loan", amount: 500, day_offset: 0, destination: accounts(:loan))+ occurrence = series.recurring_occurrences.order(:due_on).first+ own = create_transfer(amount: 500, date: Date.current, to: accounts(:loan))+ other = create_transfer(amount: 500, date: Date.current, to: accounts(:credit_card))++ explanation = Matcher.new(@family).explain(occurrence, own)+ assert_operator explanation.confidence, :>=, Matcher::EXACT_TIER+ assert explanation.signals.key?(:transfer)+ assert_nil Matcher.new(@family).explain(occurrence, other)+ end+private- def create_series(amount:, day_offset:, name: nil, merchant: nil, dedup_scope: "", preset: "monthly", bill_type: "bill")+ def create_series(amount:, day_offset:, name: nil, merchant: nil, dedup_scope: "", preset: "monthly", bill_type: "bill", destination: nil)due = Date.current + day_offsetseries = @family.recurring_transactions.create!(name: name,merchant: merchant,account: @account,+ destination_account: destination,amount: amount,currency: "USD",bill_type: bill_type,@@ -361,6 +444,18 @@ class RecurringTransaction::MatcherTest < ActiveSupport::TestCaseseriesend+ # The outflow leg of a confirmed transfer from @account into `to`.+ def create_transfer(amount:, date:, to:, name: "Transfer")+ outflow = create_entry(amount: amount, date: date, name: name)+ outflow.entryable.update!(kind: "loan_payment")+ inflow = to.entries.create!(+ date: date, amount: -amount, currency: "USD", name: name,+ entryable: Transaction.new(kind: "funds_movement")+ )+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "confirmed")+ outflow+ end+def create_entry(amount:, date:, name: "charge", merchant: nil, extra: {})@account.entries.create!(date: date,