The personal finance app for everyone (by everyone)
Ruby
fix(transfers): tighten cross-currency auto-match and exclude manual accounts (#3309)
jaysbeekaycc525da7527c
diff --git a/.env.example b/.env.exampleindex 1380e90537..e72599c43d 100644--- a/.env.example+++ b/.env.example@@ -106,6 +106,14 @@ TWELVE_DATA_API_KEY=# EXCHANGE_RATE_PROVIDER=twelve_data# SECURITIES_PROVIDER=twelve_data+# Optional: how far a cross-currency pair may drift from the cached daily exchange+# rate and still be auto-matched as a transfer, as a fraction (0.1 = 10%). Only+# accounts linked to a provider are auto-matched across currencies. Lower it if+# unrelated round-number transactions are being linked; values above 0.5 are capped,+# and an unusable value falls back to the default. The manual "match as transfer"+# dialog always searches at least 10%.+# TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE=0.1+# Alternative: Use Yahoo Finance as provider (free, no API key required)EXCHANGE_RATE_PROVIDER=yahoo_financeSECURITIES_PROVIDER=yahoo_financediff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rbindex e75155dbf2..1d4dd7b886 100644--- a/app/models/family/auto_transfer_matchable.rb+++ b/app/models/family/auto_transfer_matchable.rb@@ -1,11 +1,42 @@module Family::AutoTransferMatchable+ # The automatic path's cross-currency tolerance when TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE+ # is unset or unusable. 10% is the long-standing default. Real-world FX slippage between+ # a transaction's timestamp and the cached daily rate is typically 1-3%, so an operator+ # seeing coincidental matches on round-number amounts can tighten it without a code change.+ DEFAULT_EXCHANGE_RATE_TOLERANCE = 0.1++ # Beyond this the band stops meaning anything: at 1.0 the lower bound reaches zero and+ # any two cross-currency amounts inside the date window would match.+ MAX_EXCHANGE_RATE_TOLERANCE = 0.5++ # The manual "match as transfer" dialog (Transaction#transfer_match_candidates) is never+ # narrower than this: a user is confirming the match themselves, and FX slippage or+ # card-network markup on a manual-account leg can be wide. Mirrors the same+ # date_window: 30 vs. 4 widening that dialog already applies.+ MANUAL_MATCH_EXCHANGE_RATE_TOLERANCE = 0.1++ # Read at call time rather than frozen into a constant at boot, so a bad value falls back+ # instead of raising inside every sync: Family::Syncer and Account::Syncer both call+ # auto_match_transfers! without a tolerance of their own.+ def self.exchange_rate_tolerance+ tolerance = Float(ENV["TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE"], exception: false)+ return DEFAULT_EXCHANGE_RATE_TOLERANCE if tolerance.nil? || !tolerance.finite? || tolerance.negative?++ [ tolerance, MAX_EXCHANGE_RATE_TOLERANCE ].min+ end++ def self.manual_match_exchange_rate_tolerance+ [ MANUAL_MATCH_EXCHANGE_RATE_TOLERANCE, exchange_rate_tolerance ].max+ end+def transfer_match_candidates(date_window: 4,- exchange_rate_tolerance: 0.1,+ exchange_rate_tolerance: Family::AutoTransferMatchable.exchange_rate_tolerance,inflow_transaction_id: nil,outflow_transaction_id: nil,account_id: nil,- include_rejected: true+ include_rejected: true,+ restrict_cross_currency_to_linked_accounts: false)date_window = coerce_transfer_match_date_window!(date_window)exchange_rate_tolerance = coerce_transfer_match_exchange_rate_tolerance!(exchange_rate_tolerance)@@ -19,15 +50,27 @@ module Family::AutoTransferMatchableoutflow_transaction_id:,account_id:,include_rejected:,+ restrict_cross_currency_to_linked_accounts:,lower_exchange_rate_bound: 1 - exchange_rate_tolerance,upper_exchange_rate_bound: 1 + exchange_rate_tolerance}])end- def auto_match_transfers!(account: nil)- # Exclude already matched transfers- candidates_scope = transfer_match_candidates(account_id: account&.id, include_rejected: false)+ def auto_match_transfers!(account: nil, exchange_rate_tolerance: Family::AutoTransferMatchable.exchange_rate_tolerance)+ # Exclude already matched transfers. Cross-currency FX-tolerance matching is+ # restricted to provider-linked accounts ONLY on this automatic path -- a+ # coincidental amount/FX-rate match applied here has no human reviewing it+ # first. The manual "match as transfer" dialog goes through+ # Transaction#transfer_match_candidates, which calls transfer_match_candidates+ # directly without this restriction, so a user can still find and confirm a+ # real cross-currency transfer that happens to involve a manual account.+ candidates_scope = transfer_match_candidates(+ account_id: account&.id,+ include_rejected: false,+ exchange_rate_tolerance:,+ restrict_cross_currency_to_linked_accounts: true+ )transaction_ids = candidates_scope.flat_map do |match|[ match.inflow_transaction_id, match.outflow_transaction_id ]end.uniq@@ -134,6 +177,25 @@ module Family::AutoTransferMatchabletoleranceend+ # The second UNION branch below (cross-currency, FX-rate-tolerance matching) is a+ # coincidence guess -- amount x FX-rate within a tolerance band, not an exact amount+ # match -- and a manual account has no institution behind it confirming money actually+ # moved, so an unrelated pair of round-number transactions can land inside the tolerance+ # band purely by chance. When :restrict_cross_currency_to_linked_accounts is true, that+ # branch additionally requires both accounts to have a live provider connection+ # (Plaid/SimpleFIN/account_providers). Manual accounts always participate in the first+ # branch's exact-amount, same-currency matching, which carries no such ambiguity.+ #+ # The restriction is opt-in (default false) rather than baked into the branch+ # unconditionally: Family#auto_match_transfers! passes true because a coincidental match+ # there is applied automatically with no human reviewing it first, but+ # Transaction#transfer_match_candidates (the manual "match as transfer" dialog) leaves it+ # off so a user can still find and confirm a real cross-currency transfer that happens to+ # involve a manual account, rather than being forced into creating a duplicate.+ #+ # NOTE: this is passed through `.squish`, which collapses all whitespace (including+ # newlines) into single spaces -- a `--` SQL line comment anywhere in this heredoc would+ # swallow the remainder of the query. Put explanatory comments here in Ruby instead.def transfer_match_candidates_sql<<~SQL.squishSELECT transfer_match_candidates.*@@ -220,9 +282,27 @@ module Family::AutoTransferMatchableBETWEEN :lower_exchange_rate_bound AND :upper_exchange_rate_bound AND(:inflow_transaction_id IS NULL OR inflow_candidates.entryable_id = :inflow_transaction_id) AND(:outflow_transaction_id IS NULL OR outflow_candidates.entryable_id = :outflow_transaction_id) AND- (:include_rejected = TRUE OR rejected_transfers.id IS NULL)+ (:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND+ (+ :restrict_cross_currency_to_linked_accounts = FALSE OR+ (#{linked_account_sql("inflow_accounts")} AND #{linked_account_sql("outflow_accounts")})+ )) transfer_match_candidatesORDER BY transfer_match_candidates.date_diff ASCSQLend++ # The inverse of Account#manual? / the Account.manual scope, inlined as SQL so+ # it can run against the inflow/outflow account aliases in the same query+ # rather than round-tripping through AR. Keep in sync with Account#manual? if+ # what counts as "linked" ever changes (e.g. a new provider type).+ def linked_account_sql(accounts_alias)+ <<~SQL.squish+ (+ #{accounts_alias}.plaid_account_id IS NOT NULL OR+ #{accounts_alias}.simplefin_account_id IS NOT NULL OR+ EXISTS (SELECT 1 FROM account_providers WHERE account_providers.account_id = #{accounts_alias}.id)+ )+ SQL+ endenddiff --git a/app/models/transaction/transferable.rb b/app/models/transaction/transferable.rbindex 7f96e4491a..56354aa32d 100644--- a/app/models/transaction/transferable.rb+++ b/app/models/transaction/transferable.rb@@ -14,11 +14,14 @@ module Transaction::Transferabletransfer_as_inflow || transfer_as_outflowend- def transfer_match_candidates(date_window: 30)+ def transfer_match_candidates(+ date_window: 30,+ exchange_rate_tolerance: Family::AutoTransferMatchable.manual_match_exchange_rate_tolerance+ )candidates_scope = if self.entry.amount.negative?- family_matches_scope(date_window: date_window, inflow_transaction_id: self.id)+ family_matches_scope(date_window: date_window, exchange_rate_tolerance: exchange_rate_tolerance, inflow_transaction_id: self.id)else- family_matches_scope(date_window: date_window, outflow_transaction_id: self.id)+ family_matches_scope(date_window: date_window, exchange_rate_tolerance: exchange_rate_tolerance, outflow_transaction_id: self.id)endcandidates_scope.map do |match|diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rbindex ab07b16164..c2bbeb802d 100644--- a/test/models/family/auto_transfer_matchable_test.rb+++ b/test/models/family/auto_transfer_matchable_test.rb@@ -104,8 +104,11 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert_raises(ActiveRecord::RecordInvalid) { @family.auto_match_transfers! }end- test "auto-matches multi-currency transfers" do+ test "auto-matches multi-currency transfers between linked accounts" doload_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)+create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 500)create_transaction(date: Date.current, account: @credit_card, amount: -700, currency: "CAD")@@ -113,33 +116,225 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCase@family.auto_match_transfers!end- # test match within lower 10% bound+ # test match within lower bound of an explicitly widened tolerancecreate_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1000)create_transaction(date: Date.current, account: @credit_card, amount: -1330, currency: "CAD")assert_difference -> { Transfer.count } => 1 do- @family.auto_match_transfers!+ @family.auto_match_transfers!(exchange_rate_tolerance: 0.1)end- # test match within upper 10% bound+ # test match within upper bound of an explicitly widened tolerancecreate_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1500)create_transaction(date: Date.current, account: @credit_card, amount: -2189, currency: "CAD")assert_difference -> { Transfer.count } => 1 do- @family.auto_match_transfers!+ @family.auto_match_transfers!(exchange_rate_tolerance: 0.1)end- # test no match outside of slippage tolerance+ # test no match outside of slippage tolerance, even when widenedcreate_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1000)create_transaction(date: Date.current, account: @credit_card, amount: -1250, currency: "CAD")assert_difference -> { Transfer.count } => 0 do+ @family.auto_match_transfers!(exchange_rate_tolerance: 0.1)+ end+ end++ test "does not auto-match cross-currency transfers within the default tolerance when either account is manual" do+ load_exchange_prices+ # Neither @depository nor @credit_card is linked to a provider in this test,+ # so they're both "manual" -- FX-tolerance matching should not apply to them+ # even though the amounts fall within the default tolerance.+ create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1000)+ create_transaction(date: Date.current, account: @credit_card, amount: -1400, currency: "CAD")++ assert_no_difference -> { Transfer.count } do@family.auto_match_transfers!end++ link_account!(@depository)++ # Still one manual leg (credit_card) -- still excluded.+ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end++ link_account!(@credit_card)++ # Both sides now linked -- the same pair matches.+ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ end++ test "transfer_match_candidates does not restrict cross-currency matches to linked accounts by default" do+ load_exchange_prices+ # Neither account is linked. auto_match_transfers! would exclude this pair+ # (see the test above), but a direct transfer_match_candidates call -- what+ # the manual "match as transfer" dialog uses via+ # Transaction#transfer_match_candidates -- must still surface it so a user+ # can find and confirm a real cross-currency transfer involving a manual+ # account, instead of being forced into creating a duplicate transaction.+ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1000)+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -1400, currency: "CAD")++ candidate_pairs = @family.transfer_match_candidates.map do |candidate|+ [ candidate.inflow_transaction_id, candidate.outflow_transaction_id ]+ end++ assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]+ end++ test "the manual match dialog can still find a cross-currency counterpart on a manual account" do+ load_exchange_prices+ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1000)+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -1400, currency: "CAD")++ # Transaction#transfer_match_candidates is what TransferMatchesController#new+ # uses to populate the "match an existing transaction" selector.+ candidates = inflow.transaction.transfer_match_candidates+ assert_includes candidates.map(&:outflow_transaction_id), outflow.entryable_id+ end++ test "the manual match dialog surfaces cross-currency matches beyond the tight automatic tolerance" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ # 5% FX slippage off the cached 1.40 rate: outside an operator-tightened 3%+ # automatic tolerance, but within the 10% tolerance the manual dialog uses.+ outflow = create_transaction(date: Date.current, account: @depository, amount: 1000)+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -1470, currency: "CAD")++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => "0.03") do+ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end++ candidates = inflow.transaction.transfer_match_candidates+ assert_includes candidates.map(&:outflow_transaction_id), outflow.entryable_id+ end+ end++ test "automatic cross-currency matching defaults to a 10% tolerance" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ # 5% off the cached 1.40 rate.+ create_transaction(date: Date.current, account: @depository, amount: 1000)+ create_transaction(date: Date.current, account: @credit_card, amount: -1470, currency: "CAD")++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => nil) do+ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ end+ end++ test "TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE sets the automatic tolerance" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ # 15% off the cached 1.40 rate: outside the 10% default.+ create_transaction(date: Date.current, account: @depository, amount: 1000)+ create_transaction(date: Date.current, account: @credit_card, amount: -1610, currency: "CAD")++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => nil) do+ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end+ end++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => "0.2") do+ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ end+ end++ # A bad value must not fail every sync: Family::Syncer and Account::Syncer both+ # call auto_match_transfers! without a tolerance of their own.+ test "an unusable TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE falls back to the default" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ [ "wide", "", "-0.1", "Infinity", "NaN" ].each do |value|+ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => value) do+ assert_in_delta 0.1, Family::AutoTransferMatchable.exchange_rate_tolerance, 1e-9, "for #{value.inspect}"+ end+ end++ # 5% off the cached 1.40 rate, inside the 10% fallback.+ create_transaction(date: Date.current, account: @depository, amount: 1000)+ create_transaction(date: Date.current, account: @credit_card, amount: -1470, currency: "CAD")++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => "wide") do+ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ end+ end++ # At 1.0 or more the lower bound reaches zero and any two cross-currency+ # amounts within the date window would match.+ test "TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE is capped at 50%" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => "5") do+ assert_in_delta 0.5, Family::AutoTransferMatchable.exchange_rate_tolerance, 1e-9+ end++ # Three times the cached 1.40 rate.+ create_transaction(date: Date.current, account: @depository, amount: 1000)+ create_transaction(date: Date.current, account: @credit_card, amount: -4200, currency: "CAD")++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => "5") do+ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end+ end+ end++ test "the manual match dialog is never narrower than the automatic tolerance" do+ load_exchange_prices++ # 15% off the cached 1.40 rate: outside the dialog's own 10%.+ outflow = create_transaction(date: Date.current, account: @depository, amount: 1000)+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -1610, currency: "CAD")++ with_env_overrides("TRANSFER_MATCH_EXCHANGE_RATE_TOLERANCE" => "0.2") do+ candidates = inflow.transaction.transfer_match_candidates+ assert_includes candidates.map(&:outflow_transaction_id), outflow.entryable_id+ end+ end++ # linked_account_sql inlines the inverse of Account#manual?; this keeps the two+ # from drifting apart.+ test "linked_account_sql agrees with Account#manual?" do+ plain = accounts(:depository)+ via_provider = accounts(:credit_card)+ link_account!(via_provider)++ linked_ids = Account.where(id: [ plain.id, via_provider.id ])+ .where(@family.send(:linked_account_sql, "accounts"))+ .pluck(:id)++ [ plain, via_provider ].each do |account|+ assert_equal !account.reload.manual?, linked_ids.include?(account.id), account.name+ endendtest "only matches inflow with correct currency when duplicate amounts exist" doload_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)+create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 500)create_transaction(date: Date.current, account: @credit_card, amount: -500, currency: "CAD")create_transaction(date: Date.current, account: @credit_card, amount: -500)@@ -330,6 +525,9 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert_includes sql, ":account_id IS NULL OR inflow_candidates.account_id = :account_id OR outflow_candidates.account_id = :account_id"assert_includes sql, "outflow_candidates.amount = -inflow_candidates.amount"assert_includes sql, "JOIN exchange_rates"+ assert_includes sql, "EXISTS (SELECT 1 FROM account_providers WHERE account_providers.account_id = inflow_accounts.id)"+ assert_includes sql, "EXISTS (SELECT 1 FROM account_providers WHERE account_providers.account_id = outflow_accounts.id)"+ assert_includes sql, ":restrict_cross_currency_to_linked_accounts = FALSE"end# Regression tests for loan transfer kind assignment bug@@ -381,6 +579,22 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseendprivate+ # Simulates a live provider connection so `Account#manual?` (and the SQL+ # query's equivalent check) treats the account as linked. `AccountProvider`+ # validates its polymorphic `provider` association is present, so this needs+ # a real (if otherwise-unused) PlaidAccount row rather than an arbitrary id.+ def link_account!(account)+ plaid_account = PlaidAccount.create!(+ plaid_item: plaid_items(:one),+ plaid_id: "acc_mock_#{SecureRandom.hex(6)}",+ name: "Linked #{account.name}",+ plaid_type: "depository",+ currency: account.currency,+ current_balance: 0+ )+ AccountProvider.create!(account: account, provider: plaid_account)+ end+def load_exchange_pricesrates = {4.days.ago.to_date => 1.36,