The personal finance app for everyone (by everyone)
Ruby
Derive transfer match FX rates via the family currency (#3701)
Andrei Shkarin5c55e881d14d
diff --git a/app/models/account/market_data_importer.rb b/app/models/account/market_data_importer.rbindex 5e7ae61820..cfe7e37116 100644--- a/app/models/account/market_data_importer.rb+++ b/app/models/account/market_data_importer.rb@@ -15,20 +15,27 @@ class Account::MarketDataImporterreturn unless ExchangeRate.providerpair_dates = {}+ family_currency = account.family.primary_currency_code- # 1. ENTRY-BASED PAIRS – currencies that differ from the account currency+ # 1. ENTRY-BASED PAIRS – currencies that differ from the account currency.+ # Each is also fetched against the family currency: transfer matching derives+ # cross rates through it and does not chain entry -> account -> family rates.account.entries.where.not(currency: account.currency).group(:currency).minimum(:date).each do |source_currency, date|- key = [ source_currency, account.currency ]- pair_dates[key] = [ pair_dates[key], date ].compact.min+ [ account.currency, family_currency ].uniq.each do |target_currency|+ next if target_currency == source_currency++ key = [ source_currency, target_currency ]+ pair_dates[key] = [ pair_dates[key], date ].compact.min+ endend# 2. ACCOUNT-BASED PAIR – convert the account currency to the family currency (if different)if foreign_account?- key = [ account.currency, account.family.currency ]+ key = [ account.currency, family_currency ]pair_dates[key] = [ pair_dates[key], account.start_date ].compact.minend@@ -122,6 +129,6 @@ class Account::MarketDataImporterdef foreign_account?return false if account.family.nil?- account.currency != account.family.currency+ account.currency != account.family.primary_currency_codeendenddiff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rbindex 1d4dd7b886..579633d207 100644--- a/app/models/family/auto_transfer_matchable.rb+++ b/app/models/family/auto_transfer_matchable.rb@@ -46,6 +46,7 @@ module Family::AutoTransferMatchable{date_window:,family_id: id,+ family_currency: primary_currency_code,inflow_transaction_id:,outflow_transaction_id:,account_id:,@@ -193,6 +194,21 @@ module Family::AutoTransferMatchable# 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.#+ # The cross-currency branch prefers the direct pair rate. Exchange rates are only+ # synced from each account currency to the family currency, so a transfer between+ # two non-family currencies (e.g. RUB -> THB in a USD family) has no direct rate;+ # the cross rate is then derived through the family currency+ # (RUB -> USD / THB -> USD). The rates are plain LEFT JOINs on the unique+ # (from, to, date) index, so each joins at most one row and the planner can hash+ # 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.+ #+ # 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+ # one day closer would claim a transaction whose real exact-amount counterpart+ # appears one day later.+ ## 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.@@ -204,6 +220,7 @@ module Family::AutoTransferMatchableinflow_candidates.entryable_id AS inflow_transaction_id,outflow_candidates.entryable_id AS outflow_transaction_id,ABS(inflow_candidates.date - outflow_candidates.date) AS date_diff,+ 0 AS match_rank,rejected_transfers.id AS rejected_transfer_idFROM entries inflow_candidatesJOIN accounts inflow_accounts ON inflow_accounts.id = inflow_candidates.account_id@@ -243,6 +260,7 @@ module Family::AutoTransferMatchableinflow_candidates.entryable_id AS inflow_transaction_id,outflow_candidates.entryable_id AS outflow_transaction_id,ABS(inflow_candidates.date - outflow_candidates.date) AS date_diff,+ 1 AS match_rank,rejected_transfers.id AS rejected_transfer_idFROM entries inflow_candidatesJOIN accounts inflow_accounts ON inflow_accounts.id = inflow_candidates.account_id@@ -255,10 +273,20 @@ module Family::AutoTransferMatchableoutflow_candidates.currency <> inflow_candidates.currency)JOIN accounts outflow_accounts ON outflow_accounts.id = outflow_candidates.account_id- JOIN exchange_rates ON (- exchange_rates.date = outflow_candidates.date AND- exchange_rates.from_currency = outflow_candidates.currency AND- exchange_rates.to_currency = inflow_candidates.currency+ LEFT JOIN exchange_rates direct_rates ON (+ direct_rates.date = outflow_candidates.date AND+ direct_rates.from_currency = outflow_candidates.currency AND+ direct_rates.to_currency = inflow_candidates.currency+ )+ LEFT JOIN exchange_rates outflow_family_rates ON (+ outflow_family_rates.date = outflow_candidates.date AND+ outflow_family_rates.from_currency = outflow_candidates.currency AND+ outflow_family_rates.to_currency = :family_currency+ )+ LEFT JOIN exchange_rates inflow_family_rates ON (+ inflow_family_rates.date = outflow_candidates.date AND+ inflow_family_rates.from_currency = inflow_candidates.currency AND+ inflow_family_rates.to_currency = :family_currency)LEFT JOIN transfers existing_transfers ON (existing_transfers.inflow_transaction_id = inflow_candidates.entryable_id OR@@ -278,7 +306,11 @@ module Family::AutoTransferMatchableoutflow_accounts.status IN ('draft', 'active') ANDexisting_transfers.id IS NULL AND(:account_id IS NULL OR inflow_candidates.account_id = :account_id OR outflow_candidates.account_id = :account_id) AND- ABS(inflow_candidates.amount / NULLIF(outflow_candidates.amount * exchange_rates.rate, 0))+ ABS(inflow_candidates.amount / NULLIF(outflow_candidates.amount * COALESCE(+ NULLIF(direct_rates.rate, 0),+ (CASE WHEN outflow_candidates.currency = :family_currency THEN 1 ELSE outflow_family_rates.rate END) /+ NULLIF(CASE WHEN inflow_candidates.currency = :family_currency THEN 1 ELSE inflow_family_rates.rate END, 0)+ ), 0))BETWEEN :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@@ -288,7 +320,7 @@ module Family::AutoTransferMatchable(#{linked_account_sql("inflow_accounts")} AND #{linked_account_sql("outflow_accounts")}))) transfer_match_candidates- ORDER BY transfer_match_candidates.date_diff ASC+ ORDER BY transfer_match_candidates.match_rank ASC, transfer_match_candidates.date_diff ASCSQLenddiff --git a/app/models/market_data_importer.rb b/app/models/market_data_importer.rbindex 56244dc571..742e88fc30 100644--- a/app/models/market_data_importer.rb+++ b/app/models/market_data_importer.rb@@ -68,29 +68,44 @@ class MarketDataImporterdef required_exchange_rate_pairspair_dates = {} # { [source, target] => earliest_date }- # 1. ENTRY-BASED PAIRS – we need rates from the first entry date- Entry.joins(:account)+ # 1. ENTRY-BASED PAIRS – we need rates from the first entry date.+ # Each entry currency is also fetched against the normalized family currency:+ # transfer matching derives cross rates through it and does not chain+ # entry -> account -> family rates.+ Entry.joins(account: :family).where.not("entries.currency = accounts.currency")- .group("entries.currency", "accounts.currency")+ .group("entries.currency", "accounts.currency", "families.currency").minimum("entries.date")- .each do |(source, target), date|- key = [ source, target ]- pair_dates[key] = [ pair_dates[key], date ].compact.min+ .each do |(source, account_currency, family_currency), date|+ family_target = Family.normalize_currency_code(family_currency) || "USD"++ [ account_currency, family_target ].uniq.each do |target|+ next if target == source++ key = [ source, target ]+ pair_dates[key] = [ pair_dates[key], date ].compact.min+ endend# 2. ACCOUNT-BASED PAIRS – use the account's oldest entry date.# The earliest entry date per account is resolved in SQL to avoid loading a# potentially large Hash of all account IDs into Ruby memory.+ # The target is the family's normalized primary currency (USD when the column+ # is blank or NULL), the same currency transfer matching converts through.+ # IS DISTINCT FROM keeps NULL-currency families; the exact check happens in Ruby.Account.joins(:family).joins("LEFT JOIN (SELECT account_id, MIN(date) AS first_entry_date FROM entries GROUP BY account_id) AS entry_mins ON entry_mins.account_id = accounts.id")- .where.not("families.currency = accounts.currency")- .select("accounts.id, accounts.currency AS source, families.currency AS target, entry_mins.first_entry_date")+ .where("families.currency IS DISTINCT FROM accounts.currency")+ .select("accounts.id, accounts.currency AS source, families.currency AS family_currency, entry_mins.first_entry_date").find_each do |account|+ target = Family.normalize_currency_code(account.family_currency) || "USD"+ next if target == account.source+earliest_entry_date = account.first_entry_datechosen_date = [ earliest_entry_date, default_start_date ].compact.min- key = [ account.source, account.target ]+ key = [ account.source, target ]pair_dates[key] = [ pair_dates[key], chosen_date ].compact.minenddiff --git a/test/models/account/market_data_importer_test.rb b/test/models/account/market_data_importer_test.rbindex 8717c8cdb2..7f6ee0ba10 100644--- a/test/models/account/market_data_importer_test.rb+++ b/test/models/account/market_data_importer_test.rb@@ -62,6 +62,44 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCase"Inverse rates should be computed automatically"end+ test "imports account exchange rates into the primary currency when the family currency is blank" do+ family = Family.create!(name: "Smith", currency: "")++ account = family.accounts.create!(+ name: "Chequing",+ currency: "CAD",+ balance: 100,+ accountable: Depository.new+ )++ @provider.expects(:fetch_exchange_rates)+ .with(from: "CAD", to: "USD", start_date: anything, end_date: anything)+ .returns(provider_success_response([]))++ Account::MarketDataImporter.new(account).import_all+ end++ test "fetches foreign entry currencies against the family currency as well as the account currency" do+ family = Family.create!(name: "Smith", currency: "USD")++ account = family.accounts.create!(+ name: "Chequing",+ currency: "CAD",+ balance: 100,+ accountable: Depository.new+ )+ account.entries.create!(date: 10.days.ago.to_date, amount: 10, currency: "GBP", name: "Card payment", entryable: Transaction.new)++ [ %w[GBP CAD], %w[GBP USD], %w[CAD USD] ].each do |from, to|+ @provider.expects(:fetch_exchange_rates)+ .with(from: from, to: to, start_date: anything, end_date: anything)+ .once+ .returns(provider_success_response([]))+ end++ Account::MarketDataImporter.new(account).import_exchange_rates+ end+test "syncs security prices for securities traded by the account" dofamily = Family.create!(name: "Smith", currency: "USD")diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rbindex c2bbeb802d..d828624d48 100644--- a/test/models/family/auto_transfer_matchable_test.rb+++ b/test/models/family/auto_transfer_matchable_test.rb@@ -179,13 +179,107 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseoutflow = 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 ]+ assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]+ end++ test "suggests cross-currency pairs through family currency rates when no direct rate exists" do+ load_family_currency_rates++ # 400 GBP = 500 USD ~= 694.44 CAD; the provider paid out 680 CAD (-2%)+ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -680, currency: "CAD")++ assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]+ end++ test "auto-matches linked cross-currency transfers through family currency rates" do+ load_family_currency_rates+ link_account!(@depository)+ link_account!(@credit_card)++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -680, currency: "CAD")++ 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 "derives family currency cross rates through the primary currency when the family currency is blank" do+ @family.update_column(:currency, nil)+ load_family_currency_rates++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -680, currency: "CAD")++ assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]+ end++ test "does not auto-match family currency cross rates when either account is manual" do+ load_family_currency_rates++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -680, currency: "CAD")++ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end++ link_account!(@depository)++ assert_no_difference -> { Transfer.count } do+ @family.auto_match_transfers!+ end++ link_account!(@credit_card)++ 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 zero direct rate does not mask a usable family currency cross rate" do+ load_family_currency_rates+ ExchangeRate.create!(from_currency: "GBP", to_currency: "CAD", date: 1.day.ago.to_date, rate: 0)++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -680, currency: "CAD")+assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]end+ test "an exact same-currency match is not displaced by a closer cross-currency candidate" do+ load_family_currency_rates+ link_account!(@depository)+ link_account!(@credit_card)++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")+ # The real counterpart arrives a day later with the exact amount...+ real_inflow = create_transaction(date: Date.current, account: @credit_card, amount: -400, currency: "GBP")+ # ...while an unrelated CAD credit on the same day falls inside the FX tolerance band.+ coincidental_inflow = create_transaction(date: 1.day.ago.to_date, account: @credit_card, amount: -680, currency: "CAD")++ assert_difference -> { Transfer.count } => 1 do+ @family.auto_match_transfers!+ end++ assert Transfer.exists?(inflow_transaction_id: real_inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)+ assert_not Transfer.exists?(inflow_transaction_id: coincidental_inflow.entryable_id)+ end++ test "does not suggest a family currency cross rate outside the exchange rate tolerance" do+ load_family_currency_rates++ outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -600, currency: "CAD")++ assert_not_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" doload_exchange_pricesoutflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 1000)@@ -524,7 +618,8 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert_includes sql, "outflow_candidates.excluded = FALSE"assert_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, "LEFT JOIN exchange_rates direct_rates"+ assert_includes sql, "to_currency = :family_currency"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"@@ -595,6 +690,18 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseAccountProvider.create!(account: account, provider: plaid_account)end+ def candidate_pairs+ @family.transfer_match_candidates.map do |candidate|+ [ candidate.inflow_transaction_id, candidate.outflow_transaction_id ]+ end+ end++ # Only rates to the family currency (USD) are synced; there is no direct GBP -> CAD rate+ def load_family_currency_rates+ ExchangeRate.create!(from_currency: "GBP", to_currency: "USD", date: 1.day.ago.to_date, rate: 1.25)+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: 1.day.ago.to_date, rate: 0.72)+ end+def load_exchange_pricesrates = {4.days.ago.to_date => 1.36,diff --git a/test/models/market_data_importer_test.rb b/test/models/market_data_importer_test.rbindex 27c4f5f0b6..1a85c3c5be 100644--- a/test/models/market_data_importer_test.rb+++ b/test/models/market_data_importer_test.rb@@ -60,6 +60,41 @@ class MarketDataImporterTest < ActiveSupport::TestCaseassert_operator after, :>, before + 1, "Should insert at least two new exchange-rate rows (forward + computed inverse)"end+ test "syncs account exchange rates into the primary currency when the family currency is blank or NULL" do+ blank_family = Family.create!(name: "Blank", currency: "")+ null_family = Family.create!(name: "Null", currency: "USD")+ null_family.update_column(:currency, nil)++ [ blank_family, null_family ].each do |family|+ family.accounts.create!(name: "Chequing", currency: "CAD", balance: 100, accountable: Depository.new)+ family.accounts.create!(name: "Savings", currency: "USD", balance: 100, accountable: Depository.new)+ end++ # One CAD→USD fetch covers both families; the USD accounts already match the+ # USD fallback and need no rates.+ @provider.expects(:fetch_exchange_rates)+ .with(from: "CAD", to: "USD", start_date: anything, end_date: anything)+ .once+ .returns(provider_success_response([]))++ MarketDataImporter.new(mode: :snapshot).import_exchange_rates+ end++ test "syncs foreign entry currencies against the family currency as well as the account currency" do+ family = Family.create!(name: "Smith", currency: "USD")+ account = family.accounts.create!(name: "Chequing", currency: "CAD", balance: 100, accountable: Depository.new)+ account.entries.create!(date: 10.days.ago.to_date, amount: 10, currency: "GBP", name: "Card payment", entryable: Transaction.new)++ [ %w[GBP CAD], %w[GBP USD], %w[CAD USD] ].each do |from, to|+ @provider.expects(:fetch_exchange_rates)+ .with(from: from, to: to, start_date: anything, end_date: anything)+ .once+ .returns(provider_success_response([]))+ end++ MarketDataImporter.new(mode: :snapshot).import_exchange_rates+ end+test "syncs security prices" dosecurity = Security.create!(ticker: "AAPL", exchange_operating_mic: "XNAS")