The personal finance app for everyone (by everyone)
Ruby
Skip cross-currency auto-matches across categories (#5138)
jaysbeekay6f25c2669aa5
diff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rbindex a253058d39..575cdf87c9 100644--- a/app/models/family/auto_transfer_matchable.rb+++ b/app/models/family/auto_transfer_matchable.rb@@ -46,7 +46,8 @@ module Family::AutoTransferMatchableinclude_rejected: true,restrict_cross_currency_to_linked_accounts: false,require_common_writer: false,- exclude_same_wise_item: false+ exclude_same_connection_pairs: false,+ require_compatible_categories: false)date_window = coerce_transfer_match_date_window!(date_window)exchange_rate_tolerance = coerce_transfer_match_exchange_rate_tolerance!(exchange_rate_tolerance)@@ -66,7 +67,8 @@ module Family::AutoTransferMatchableinclude_rejected:,restrict_cross_currency_to_linked_accounts:,require_common_writer:,- exclude_same_wise_item:,+ exclude_same_connection_pairs:,+ require_compatible_categories:,lower_exchange_rate_bound: 1 - exchange_rate_tolerance,upper_exchange_rate_bound: 1 + exchange_rate_tolerance}@@ -129,12 +131,16 @@ module Family::AutoTransferMatchable# Only pair accounts that at least one member can write to on both sides, so# someone can always confirm or reject the match.require_common_writer: true,- # Two balances of one Wise connection move money between each other only- # through conversions and Jar moves, which WiseItem#link_jar_transfers!- # links from Wise's own activity feed. Any other pair across them is a- # coincidence (a GBP top-up "matching" a USD payout), so it is never- # suggested here; the manual dialog still offers it.- exclude_same_wise_item: true+ # Pairs a provider already links from its own feed, such as two balances+ # of one connection (Provider::Base.auto_match_exclusion_sql), are never+ # guessed here; the manual dialog still offers them.+ exclude_same_connection_pairs: true,+ # A cross-currency guess between two categorized transactions in different+ # categories (a fuel purchase against an income) is not one movement of+ # money. One uncategorized leg still matches, since providers often+ # categorize only one side. Exact same-currency pairs, and pairs on a route+ # the user has confirmed before, are not affected.+ require_compatible_categories: true)# Track which transactions we've already matched to avoid duplicates@@ -290,28 +296,18 @@ module Family::AutoTransferMatchableSQLend- # With :exclude_same_wise_item, drops pairs whose two accounts are linked to- # balances (WiseAccounts) of the same WiseItem. Applied in both UNION branches,- # since two balances of one item may share a currency (a balance and its Jar)- # or not. Only auto_match_transfers! sets it (see the comment there); the- # manual "match as transfer" dialog leaves it off.- def same_wise_item_condition_sql- <<~SQL.squish- (:exclude_same_wise_item = FALSE OR NOT EXISTS (- SELECT 1- FROM account_providers inflow_wise_links- JOIN wise_accounts inflow_wise_accounts ON inflow_wise_accounts.id = inflow_wise_links.provider_id- JOIN account_providers outflow_wise_links ON (- outflow_wise_links.account_id = outflow_accounts.id AND- outflow_wise_links.provider_type = 'WiseAccount'- )- JOIN wise_accounts outflow_wise_accounts ON outflow_wise_accounts.id = outflow_wise_links.provider_id- WHERE- inflow_wise_links.account_id = inflow_accounts.id AND- inflow_wise_links.provider_type = 'WiseAccount' AND- outflow_wise_accounts.wise_item_id = inflow_wise_accounts.wise_item_id- ))- SQL+ # With :exclude_same_connection_pairs, drops pairs that any registered provider+ # adapter excludes through Provider::Base.auto_match_exclusion_sql. Applied in+ # both UNION branches, since two balances of one connection may share a+ # currency or not. Only auto_match_transfers! sets it (see the comment there);+ # the manual "match as transfer" dialog leaves it off.+ def provider_exclusion_condition_sql+ exclusions = Provider::Factory.registered_adapters.filter_map do |adapter|+ adapter.auto_match_exclusion_sql("inflow_accounts", "outflow_accounts")+ end+ return "TRUE" if exclusions.empty?++ "(:exclude_same_connection_pairs = FALSE OR NOT (#{exclusions.map { |sql| "(#{sql})" }.join(" OR ")}))"end# Mirrors Account.writable_by for the `writers` row: owner or full_control share.@@ -356,6 +352,12 @@ module Family::AutoTransferMatchable# them; a missing rate leaves the tolerance check NULL, which drops the pair.# A zero direct rate is treated as missing so it cannot mask a usable derived rate.#+ # With :require_compatible_categories, the cross-currency branch also drops pairs+ # whose legs are both categorized, in different categories, unless they lie on a+ # confirmed route (computed only with :restrict_cross_currency_to_linked_accounts).+ # Only auto_match_transfers! sets it; the exact same-currency branch, the manual+ # dialog and the hint (which filters categories itself, more strictly) leave it off.+ ## Candidates are ordered by match_rank before date_diff: exact same-currency matches# (rank 0) come before FX-tolerance guesses (rank 1). auto_match_transfers! consumes# candidates greedily, so without the rank a coincidental cross-currency candidate@@ -366,6 +368,8 @@ module Family::AutoTransferMatchable# 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+ provider_exclusion_condition = provider_exclusion_condition_sql+<<~SQL.squishSELECT transfer_match_candidates.*FROM (@@ -409,7 +413,7 @@ module Family::AutoTransferMatchable(:outflow_transaction_id IS NULL OR outflow_candidates.entryable_id = :outflow_transaction_id) AND(:filter_transaction_ids = FALSE OR inflow_candidates.entryable_id IN (:transaction_ids) OR outflow_candidates.entryable_id IN (:transaction_ids)) AND(:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND- #{same_wise_item_condition_sql} AND+ #{provider_exclusion_condition} AND#{common_writer_condition_sql}UNION ALLSELECT@@ -429,6 +433,8 @@ module Family::AutoTransferMatchableoutflow_candidates.currency <> inflow_candidates.currency)JOIN accounts outflow_accounts ON outflow_accounts.id = outflow_candidates.account_id+ JOIN transactions inflow_txns ON inflow_txns.id = inflow_candidates.entryable_id+ JOIN transactions outflow_txns ON outflow_txns.id = outflow_candidates.entryable_idLEFT JOIN exchange_rates direct_rates ON (direct_rates.date = outflow_candidates.date ANDdirect_rates.from_currency = outflow_candidates.currency AND@@ -499,7 +505,14 @@ module Family::AutoTransferMatchable(#{linked_account_sql("inflow_accounts")} AND #{linked_account_sql("outflow_accounts")}) ORconfirmed_routes.outflow_account_id IS NOT NULL) AND- #{same_wise_item_condition_sql} AND+ (+ :require_compatible_categories = FALSE OR+ confirmed_routes.outflow_account_id IS NOT NULL OR+ inflow_txns.category_id IS NULL OR+ outflow_txns.category_id IS NULL OR+ inflow_txns.category_id = outflow_txns.category_id+ ) AND+ #{provider_exclusion_condition} AND#{common_writer_condition_sql}) transfer_match_candidatesORDER BY transfer_match_candidates.match_rank ASC, transfer_match_candidates.date_diff ASCdiff --git a/app/models/provider/base.rb b/app/models/provider/base.rbindex 20bf2b3265..0adbbbc22e 100644--- a/app/models/provider/base.rb+++ b/app/models/provider/base.rb@@ -69,6 +69,17 @@ class Provider::Baseklass.respond_to?(:member_connectable?) && klass.member_connectable?end+ # SQL that is true when automatic transfer matching must not pair the two+ # accounts behind these aliases, because this provider already links the+ # transfers between them from its own feed (for example, two balances of one+ # connection). Nil when the provider has no such pairs.+ # @param inflow_accounts_alias [String] SQL alias of the inflow's accounts row+ # @param outflow_accounts_alias [String] SQL alias of the outflow's accounts row+ # @return [String, nil]+ def self.auto_match_exclusion_sql(inflow_accounts_alias, outflow_accounts_alias)+ nil+ end+# Returns the provider type (class name)# @return [String] The provider account class namedef provider_typediff --git a/app/models/provider/wise_adapter.rb b/app/models/provider/wise_adapter.rbindex e920141e30..90af3bbc3c 100644--- a/app/models/provider/wise_adapter.rb+++ b/app/models/provider/wise_adapter.rb@@ -24,6 +24,29 @@ class Provider::WiseAdapter < Provider::Base"wise"end+ # Two balances of one Wise connection move money between each other only+ # through conversions and Jar moves, which WiseItem#link_jar_transfers! links+ # from Wise's own activity feed. Any other pair across them is a coincidence+ # (a GBP top-up "matching" a USD payout).+ def self.auto_match_exclusion_sql(inflow_accounts_alias, outflow_accounts_alias)+ <<~SQL.squish+ EXISTS (+ SELECT 1+ FROM account_providers inflow_wise_links+ JOIN wise_accounts inflow_wise_accounts ON inflow_wise_accounts.id = inflow_wise_links.provider_id+ JOIN account_providers outflow_wise_links ON (+ outflow_wise_links.account_id = #{outflow_accounts_alias}.id AND+ outflow_wise_links.provider_type = 'WiseAccount'+ )+ JOIN wise_accounts outflow_wise_accounts ON outflow_wise_accounts.id = outflow_wise_links.provider_id+ WHERE+ inflow_wise_links.account_id = #{inflow_accounts_alias}.id AND+ inflow_wise_links.provider_type = 'WiseAccount' AND+ outflow_wise_accounts.wise_item_id = inflow_wise_accounts.wise_item_id+ )+ SQL+ end+def self.build_provider(family: nil, wise_item_id: nil)return nil unless family.present?diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rbindex 08b7fbd2fa..33d86a3b9d 100644--- a/test/models/family/auto_transfer_matchable_test.rb+++ b/test/models/family/auto_transfer_matchable_test.rb@@ -312,6 +312,118 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert_not Transfer.exists?(inflow_transaction_id: coincidental_inflow.entryable_id)end+ test "does not auto-match a cross-currency pair whose legs have different categories" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 500, category: categories(:food_and_drink))+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -700, currency: "CAD", category: categories(:income))++ # Otherwise eligible: the automatic path's other restrictions still offer the pair.+ eligible = @family.transfer_match_candidates(include_rejected: false, restrict_cross_currency_to_linked_accounts: true, require_common_writer: true)+ assert_includes eligible.map { |c| [ c.inflow_transaction_id, c.outflow_transaction_id ] }, [ inflow.entryable_id, outflow.entryable_id ]++ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end+ end++ # A route the user confirmed is a stronger signal than the categories, which an+ # auto-categorizer can get wrong on one leg.+ test "auto-matches a cross-currency pair with different categories on a confirmed route" do+ load_family_currency_rates+ confirm_transfer!(from: @depository, to: @other_asset)++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP", category: categories(:food_and_drink))+ inflow = create_transaction(date: Date.current, account: @other_asset, amount: -680, currency: "CAD", category: categories(:income))++ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ assert Transfer.exists?(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)+ end++ # The category filter removes one row, not the inflow's slot: the greedy matcher+ # then takes the next eligible candidate, as it does after a rejected pair.+ test "a category-blocked cross-currency candidate leaves the inflow to the next eligible one" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -700, currency: "CAD", category: categories(:income))+ blocked_outflow = create_transaction(date: Date.current, account: @depository, amount: 500, category: categories(:food_and_drink))+ next_outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 505)++ # Without the category filter the blocked outflow, one day closer, ranks first.+ unfiltered = @family.transfer_match_candidates(include_rejected: false, restrict_cross_currency_to_linked_accounts: true, require_common_writer: true)+ assert_equal [ blocked_outflow.entryable_id, next_outflow.entryable_id ],+ unfiltered.select { |c| c.inflow_transaction_id == inflow.entryable_id }.map(&:outflow_transaction_id)++ @family.auto_match_transfers!++ assert Transfer.exists?(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: next_outflow.entryable_id)+ assert_not Transfer.exists?(outflow_transaction_id: blocked_outflow.entryable_id)+ end++ test "auto-matches a cross-currency pair when either leg is uncategorized" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ uncategorized_inflow_out = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 500, category: categories(:food_and_drink))+ uncategorized_inflow_in = create_transaction(date: Date.current, account: @credit_card, amount: -700, currency: "CAD")++ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ assert Transfer.exists?(inflow_transaction_id: uncategorized_inflow_in.entryable_id, outflow_transaction_id: uncategorized_inflow_out.entryable_id)++ uncategorized_outflow_out = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1000)+ uncategorized_outflow_in = create_transaction(date: Date.current, account: @credit_card, amount: -1400, currency: "CAD", category: categories(:income))++ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ assert Transfer.exists?(inflow_transaction_id: uncategorized_outflow_in.entryable_id, outflow_transaction_id: uncategorized_outflow_out.entryable_id)+ end++ test "auto-matches a cross-currency pair whose legs share a category" do+ load_exchange_prices+ link_account!(@depository)+ link_account!(@credit_card)++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 500, category: categories(:food_and_drink))+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -700, currency: "CAD", category: categories(:food_and_drink))++ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ assert Transfer.exists?(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)+ end++ test "auto-matches a same-currency exact pair whose legs have different categories" do+ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 500, category: categories(:food_and_drink))+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500, category: categories(:income))++ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end+ assert Transfer.exists?(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)+ end++ test "a cross-currency pair with different categories can still be matched by hand" do+ load_exchange_prices+ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 500, category: categories(:food_and_drink))+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -700, currency: "CAD", category: categories(:income))++ assert_includes inflow.transaction.transfer_match_candidates.map(&:outflow_transaction_id), outflow.entryable_id++ transfer = Transfer::Matcher.new(inflow.transaction).match_with!(outflow.transaction)+ assert transfer.confirmed?+ assert_equal [ inflow.entryable_id, outflow.entryable_id ], [ transfer.inflow_transaction_id, transfer.outflow_transaction_id ]+ end+test "does not suggest a family currency cross rate outside the exchange rate tolerance" doload_family_currency_rates@@ -843,7 +955,7 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert_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"assert_equal 2, sql.scan(":require_common_writer = FALSE").size- assert_equal 2, sql.scan(":exclude_same_wise_item = FALSE").size+ assert_equal 2, sql.scan(":exclude_same_connection_pairs = FALSE").sizeend# Moves between one Wise connection's balances are linked from Wise's own@@ -891,6 +1003,34 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert Transfer.exists?(inflow_transaction_id: move_in.entryable_id, outflow_transaction_id: move_out.entryable_id)end+ test "the same-connection exclusion comes from the provider adapter" do+ wise_item = wise_items(:one)+ jar_out = create_transaction(date: Date.current, account: link_wise_balance!(wise_item, "EUR"), amount: 250.75, currency: "EUR")+ jar_in = create_transaction(date: Date.current, account: link_wise_balance!(wise_item, "EUR"), amount: -250.75, currency: "EUR")+ Provider::WiseAdapter.stubs(:auto_match_exclusion_sql).returns(nil)++ @family.auto_match_transfers!++ assert Transfer.exists?(inflow_transaction_id: jar_in.entryable_id, outflow_transaction_id: jar_out.entryable_id)+ end++ test "one provider adapter's exclusion does not lift another's" do+ wise_item = wise_items(:one)+ jar_out = create_transaction(date: Date.current, account: link_wise_balance!(wise_item, "EUR"), amount: 250.75, currency: "EUR")+ jar_in = create_transaction(date: Date.current, account: link_wise_balance!(wise_item, "EUR"), amount: -250.75, currency: "EUR")+ link_account!(@depository)+ link_account!(@credit_card)+ create_transaction(date: Date.current, account: @depository, amount: 500)+ create_transaction(date: Date.current, account: @credit_card, amount: -500)+ Provider::PlaidAdapter.stubs(:auto_match_exclusion_sql).with("inflow_accounts", "outflow_accounts")+ .returns("inflow_accounts.id = '#{@credit_card.id}'")++ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end+ assert_not Transfer.exists?(inflow_transaction_id: jar_in.entryable_id, outflow_transaction_id: jar_out.entryable_id)+ end+test "does not auto-match transfers when the family has disabled auto match" do@family.update!(auto_match_transfers_disabled: true)