The personal finance app for everyone (by everyone)
Ruby
Stop converting amounts at 1 when an exchange rate is missing (#3983)
jaysbeekay0a3ee468b38b
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex a671129e4d..cd63bcb285 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -382,6 +382,28 @@ class ReportsController < ApplicationControllertrendsend+ # An entry's amount in family currency at the rate the summary totals use:+ # ExchangeRate.rate_sql, the stored rate nearest the entry's date, however+ # old, as IncomeStatement::ScopedTransactionsQuery reads it. Nil when there+ # is none, so the entry is left out, as the summary leaves it out, rather+ # than counted at 1. No provider is called.+ def report_amount_converter(family_currency)+ rates = {}+ rate_query = "SELECT #{ExchangeRate.rate_sql(from: ':from', to: ':to', on: 'CAST(:on AS date)')}"+ lambda do |entry|+ amount = entry.amount.abs+ next amount if entry.currency == family_currency++ key = [ entry.date, entry.currency ]+ unless rates.key?(key)+ sql = ExchangeRate.sanitize_sql_array([ rate_query, { from: entry.currency, to: family_currency, on: entry.date } ])+ value = ExchangeRate.connection.select_value(sql)+ rates[key] = value && BigDecimal(value.to_s)+ end+ rates[key] && amount * rates[key]+ end+ end+def build_transactions_breakdown# Base query: all transactions in the period# Exclude transfers, one-time, and CC payments (matching income_statement logic)@@ -454,13 +476,11 @@ class ReportsController < ApplicationControllerend# Helper to process an entry (transaction or trade)+ convert = report_amount_converter(family_currency)process_entry = ->(category, entry, is_trade) dotype = entry.amount > 0 ? "expense" : "income"- begin- converted_amount = Money.new(entry.amount.abs, entry.currency).exchange_to(family_currency).amount- rescue Money::ConversionError- converted_amount = entry.amount.abs- end+ converted_amount = convert.call(entry)+ next if converted_amount.nil?if category.nil?# Uncategorized or Other Investments (for trades)@@ -580,11 +600,18 @@ class ReportsController < ApplicationControllerto_numeric = ->(value) { value.is_a?(Money) ? value.amount : value }# Unrealized gains mark holdings to market, so convert at today's FX.+ # Both conversions return nil when there is no rate, since converting+ # at 1 would report a ¥1,000,000 gain as $1,000,000. A figure that+ # cannot be converted is left out of the total and counted, so the card+ # can say the total is partial.foreign_holding_currencies = current_holdings.map(&:currency).compact.uniq.reject { |c| c == currency }holding_rates = ExchangeRate.rates_for(foreign_holding_currencies, to: currency, date: Date.current)convert_current = ->(amount, from) {numeric = to_numeric.call(amount)- from == currency ? numeric : numeric * (holding_rates[from] || 1)+ next numeric if from == currency++ rate = holding_rates[from]+ rate && numeric * rate}# Realized gains are locked at trade time, so convert each at its own@@ -606,7 +633,10 @@ class ReportsController < ApplicationControllerendconvert_trade = ->(amount, from, date) {numeric = to_numeric.call(amount)- from == currency ? numeric : numeric * (rates_by_trade_date.dig(date, from) || 1)+ next numeric if from == currency++ rate = rates_by_trade_date.dig(date, from)+ rate && numeric * rate}# Build metrics per treatment@@ -614,19 +644,37 @@ class ReportsController < ApplicationControllerholdings = holdings_by_treatment[treatment] || []trades = trades_by_treatment[treatment] || []- # Sum unrealized gains from holdings (only those with known cost basis)+ # Sum unrealized gains from holdings (only those with known cost basis+ # and a rate into family currency)+ unconverted = 0+ unrealized_by_holding = {}unrealized = holdings.sum do |h|trend = h.trend- trend ? convert_current.call(trend.value, h.currency) : 0+ next 0 unless trend++ converted = convert_current.call(trend.value, h.currency)+ unconverted += 1 if converted.nil?+ unrealized_by_holding[h.id] = Money.new(converted, currency) if converted+ converted || 0end# Sum realized gains from sell trades, each converted from the currency# its own figure carries.realized_by_trade = trades.each_with_object({}) do |t, memo|gain = t.realized_gain_loss- next if gain.nil?+ if gain.nil?+ # A sale with no rate between its own two currencies is left out+ # too, and counted; one with no cost basis never had a figure.+ unconverted += 1 if t.realized_gain_unconvertible?+ next+ endconverted = convert_trade.call(gain.value, gain.value.currency.iso_code, t.entry.date)+ if converted.nil?+ unconverted += 1+ next+ end+memo[t.id] = Money.new(converted, currency)end@@ -644,6 +692,11 @@ class ReportsController < ApplicationController# and the card's own total are the same arithmetic. The partial used# to re-label `gain.value` as family currency without converting it.realized_gain_by_trade: realized_by_trade,+ # The same for each holding's unrealised gain; one with no rate has+ # no entry, and its line says so.+ unrealized_gain_by_holding: unrealized_by_holding,+ # Holdings and sells left out of the totals for want of a rate.+ unconverted_count: unconverted,total_gain: Money.new(unrealized + realized, currency)}end@@ -831,6 +884,7 @@ class ReportsController < ApplicationController# Group by category, type, and monthbreakdown = {}family_currency = Current.family.currency+ convert = report_amount_converter(family_currency)# Process transactionstransactions.each do |transaction|@@ -840,12 +894,9 @@ class ReportsController < ApplicationControllercategory_name = transaction.category&.name || "Uncategorized"month_key = entry.date.beginning_of_month- # Convert to family currency- begin- converted_amount = Money.new(entry.amount.abs, entry.currency).exchange_to(family_currency).amount- rescue Money::ConversionError- converted_amount = entry.amount.abs- end+ # Convert to family currency, leaving out what has no rate+ converted_amount = convert.call(entry)+ next if converted_amount.nil?key = [ category_name, type ]breakdown[key] ||= { category: category_name, type: type, months: {}, total: 0 }diff --git a/app/models/account/chartable.rb b/app/models/account/chartable.rbindex 357ccd7620..ddc8becda7 100644--- a/app/models/account/chartable.rb+++ b/app/models/account/chartable.rb@@ -1,6 +1,6 @@module Account::Chartableextend ActiveSupport::Concern- SPARKLINE_CACHE_VERSION = "v4"+ SPARKLINE_CACHE_VERSION = "v4-#{ExchangeRate::CONVERSION_CACHE_VERSION}"def favorable_directionclassification == "asset" ? "up" : "down"diff --git a/app/models/balance/chart_series_builder.rb b/app/models/balance/chart_series_builder.rbindex ccb3c9ab7f..dce9f8dea7 100644--- a/app/models/balance/chart_series_builder.rb+++ b/app/models/balance/chart_series_builder.rb@@ -149,8 +149,12 @@ class Balance::ChartSeriesBuilderfavorable_direction == "down" ? -1 : 1end+ # 1 for an account already in the target currency, else the rate the+ # lateral join below found. NULL when the currency has no usable rate, so+ # the account drops out of the day's sum rather than counting at 1.+ # Strict conversion raises on that same gap instead (see missing_currency).def balance_rate_sql- @strict_currency_conversion ? "CASE WHEN accounts.currency = :target_currency THEN 1 WHEN er.rate > 0 THEN er.rate END" : "COALESCE(er.rate, 1)"+ "CASE WHEN accounts.currency = :target_currency THEN 1 WHEN er.rate > 0 THEN er.rate END"enddef query@@ -223,6 +227,7 @@ class Balance::ChartSeriesBuilderWHERE er.from_currency = accounts.currencyAND er.to_currency = :target_currencyAND er.date <= d.date+ AND er.rate > 0ORDER BY er.date DESCLIMIT 1),(SELECT er.rate@@ -230,6 +235,7 @@ class Balance::ChartSeriesBuilderWHERE er.from_currency = accounts.currencyAND er.to_currency = :target_currencyAND er.date > d.date+ AND er.rate > 0ORDER BY er.date ASCLIMIT 1)) AS rate@@ -274,7 +280,7 @@ class Balance::ChartSeriesBuilderCOALESCE(SUM(CASEWHEN last_basis.cost_basis IS NOT NULL- THEN (last_h.amount - (last_basis.cost_basis * last_h.qty)) * COALESCE(er.rate, 1)+ THEN (last_h.amount - (last_basis.cost_basis * last_h.qty)) * CASE WHEN last_h.currency = :target_currency THEN 1 ELSE er.rate ENDELSE 0END), 0) AS gains@@ -313,6 +319,7 @@ class Balance::ChartSeriesBuilderWHERE er.from_currency = last_h.currencyAND er.to_currency = :target_currencyAND er.date <= d.date+ AND er.rate > 0ORDER BY er.date DESCLIMIT 1),(SELECT er.rate@@ -320,6 +327,7 @@ class Balance::ChartSeriesBuilderWHERE er.from_currency = last_h.currencyAND er.to_currency = :target_currencyAND er.date > d.date+ AND er.rate > 0ORDER BY er.date ASCLIMIT 1)) AS ratediff --git a/app/models/balance_sheet/account_totals.rb b/app/models/balance_sheet/account_totals.rbindex a3769bf6d1..969a84c5ec 100644--- a/app/models/balance_sheet/account_totals.rb+++ b/app/models/balance_sheet/account_totals.rb@@ -99,11 +99,14 @@ class BalanceSheet::AccountTotalsend# Converts an account's balance to the family's currency using pre-fetched exchange rates.+ # An account in a currency with no rate at all converts to 0, so it is+ # left out of every total rather than counted at 1; its row still+ # shows its own balance, and the page says the currency is missing.# @return [BigDecimal] balance in the family's currencydef converted_balance_for(account)return account.balance if account.currency == family.currencyrate = exchange_rates[account.currency]- account.balance * rate+ rate ? account.balance * rate : BigDecimal(0)endenddiff --git a/app/models/balance_sheet/net_worth_breakdown_series_builder.rb b/app/models/balance_sheet/net_worth_breakdown_series_builder.rbindex 6e21093f39..f0ac9ea3a2 100644--- a/app/models/balance_sheet/net_worth_breakdown_series_builder.rb+++ b/app/models/balance_sheet/net_worth_breakdown_series_builder.rb@@ -135,6 +135,9 @@ class BalanceSheet::NetWorthBreakdownSeriesBuilderkey = ["balance_sheet_net_worth_breakdown_series",CACHE_VERSION,+ ExchangeRate::CONVERSION_CACHE_VERSION,+ # A rate stored later can bring back an account the series left out.+ ExchangeRate.maximum(:updated_at)&.to_i,user&.id,shares_version,period.start_date,diff --git a/app/models/balance_sheet/net_worth_series_builder.rb b/app/models/balance_sheet/net_worth_series_builder.rbindex 58f97d321e..b987d80660 100644--- a/app/models/balance_sheet/net_worth_series_builder.rb+++ b/app/models/balance_sheet/net_worth_series_builder.rb@@ -46,6 +46,9 @@ class BalanceSheet::NetWorthSeriesBuildershares_version = user ? AccountShare.where(user: user).maximum(:updated_at)&.to_i : nilkey = ["balance_sheet_net_worth_series_historical",+ ExchangeRate::CONVERSION_CACHE_VERSION,+ # A rate stored later can bring back an account the series left out.+ ExchangeRate.maximum(:updated_at)&.to_i,user&.id,shares_version,period.start_date,diff --git a/app/models/concerns/accountable.rb b/app/models/concerns/accountable.rbindex 1ff0096a74..07b4cec51f 100644--- a/app/models/concerns/accountable.rb+++ b/app/models/concerns/accountable.rb@@ -99,7 +99,9 @@ module Accountableif account.currency == family.currencyaccount.balanceelse- account.balance * (rates[account.currency] || 1)+ # No rate at all: left out, not counted at 1.+ rate = rates[account.currency]+ rate ? account.balance * rate : 0end}enddiff --git a/app/models/exchange_rate.rb b/app/models/exchange_rate.rbindex c7751807c2..98f4dd3ba3 100644--- a/app/models/exchange_rate.rb+++ b/app/models/exchange_rate.rb@@ -1,6 +1,12 @@class ExchangeRate < ApplicationRecordinclude Provided+ # Part of the cache key of every cached figure converted into the family+ # currency. Those keys follow entries and syncs, not the conversion rule, so+ # a change to the rule bumps this or old figures outlive the deploy.+ # "fx2": a missing rate leaves an amount out rather than counting it at 1.+ CONVERSION_CACHE_VERSION = "fx2"+validates :from_currency, :to_currency, :date, :rate, presence: truevalidates :date, uniqueness: { scope: %i[from_currency to_currency] }validate :rate_must_convert_amounts, if: -> { rate.present? }diff --git a/app/models/exchange_rate/provided.rb b/app/models/exchange_rate/provided.rbindex 0d96038daf..4145ddaf77 100644--- a/app/models/exchange_rate/provided.rb+++ b/app/models/exchange_rate/provided.rb@@ -11,8 +11,11 @@ module ExchangeRate::Provided# Maximum number of days to look back for a cached rate before calling the provider.NEAREST_RATE_LOOKBACK_DAYS = 5+ # A stored rate of zero or below is skipped, as everywhere else (see+ # #usable_rates), so the provider is still asked; its answer replaces the+ # unusable row rather than leaving it to be skipped on every request.def find_or_fetch_rate(from:, to:, date: Date.current, cache: true)- rate = find_by(from_currency: from, to_currency: to, date: date)+ rate = usable_rates.find_by(from_currency: from, to_currency: to, date: date)return rate if rate.present?# Reuse the nearest recently-cached rate before hitting the provider.@@ -20,7 +23,7 @@ module ExchangeRate::Provided# (e.g. Friday for a Saturday request) and save it under that date, so# subsequent requests for the weekend date always miss the exact lookup# and trigger redundant API calls.- nearest = where(from_currency: from, to_currency: to)+ nearest = usable_rates.where(from_currency: from, to_currency: to).where(date: (date - NEAREST_RATE_LOOKBACK_DAYS)..date).order(date: :desc).first@@ -33,43 +36,68 @@ module ExchangeRate::Providedreturn nil unless response.success? # Provider errorrate = response.data+ return rate unless cache+begin- ExchangeRate.find_or_create_by!(+ stored = ExchangeRate.find_or_create_by!(from_currency: rate.from,to_currency: rate.to,date: rate.date) do |exchange_rate|exchange_rate.rate = rate.rate- end if cache+ endrescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid# Race condition: another process inserted between our SELECT and INSERT.# RecordNotUnique = DB unique constraint; RecordInvalid = model uniqueness# validation fired before the DB got a chance to reject it. Both are safe- # to handle by reading back the record that the other process just saved.- return ExchangeRate.find_by!(+ # to handle by reading back the record that the other process just saved,+ # unless what it saved is unusable; then the provider's answer stands.+ stored = ExchangeRate.find_by!(from_currency: rate.from,to_currency: rate.to,date: rate.date- ) if cache+ )+ return stored.rate.to_d.positive? ? stored : rate+ end++ # Replace an unusable row with the provider's answer. Outside the race+ # rescue above, and best-effort: if the write fails, the provider's rate+ # is still the answer, never the row it could not replace.+ if !stored.rate.to_d.positive? && rate.rate.to_d.positive?+ begin+ stored.update!(rate: rate.rate)+ rescue ActiveRecord::ActiveRecordError => e+ Rails.logger.warn("Could not replace unusable exchange rate #{rate.from}/#{rate.to} on #{rate.date}: #{e.message}")+ endendrateend# Batch-fetches exchange rates for multiple source currencies.- # Returns a hash mapping each currency to its numeric rate, defaulting to 1 when unavailable.+ # Returns a hash mapping each currency to its numeric rate: the day's,+ # then a recent one, then the provider's, then the latest stored one+ # however old, then the earliest stored one after the day (as the balance+ # chart does). A currency with no stored rate at all is left out rather+ # than given 1: "no rate" and "parity" are different facts, and a caller+ # that cannot tell them apart reports a ¥1,000,000 gain as $1,000,000.+ # Each caller decides what an absent rate means for its figure.+ #+ # A stored rate of zero or below is no rate: multiplying by it books an+ # amount as nothing, or flips its sign. `to` itself converts at 1.def rates_for(currencies, to:, date: Date.current)- unique_currencies = currencies.uniq- return {} if unique_currencies.empty?+ unique_currencies = currencies.uniq - [ to ]+ same = currencies.include?(to) ? { to => 1 } : {}+ return same if unique_currencies.empty?# Batch-load exact-date matches in a single query- exact_rates = where(from_currency: unique_currencies, to_currency: to, date: date)+ exact_rates = usable_rates.where(from_currency: unique_currencies, to_currency: to, date: date).index_by(&:from_currency)missing = unique_currencies - exact_rates.keys# For currencies without an exact match, batch-load the nearest recent ratenearest_rates = if missing.any?- where(from_currency: missing, to_currency: to)+ usable_rates.where(from_currency: missing, to_currency: to).where(date: (date - NEAREST_RATE_LOOKBACK_DAYS)..date).order(date: :desc).to_a@@ -82,23 +110,83 @@ module ExchangeRate::Providedstill_missing = missing - nearest_rates.keys- # Only hit the provider for currencies with no cached rate at all+ # Only hit the provider for currencies with no cached rate at all. A+ # provider rate counts only once it is stored as usable: #rate_sql and+ # #currencies_without_rate read the table, and a rate they cannot see+ # would put an amount in these totals that theirs leave out. Looked up+ # on the rate's own date, since a provider can answer with the nearest+ # trading day.fetched_rates = still_missing.each_with_object({}) do |currency, map|rate = find_or_fetch_rate(from: currency, to: to, date: date)- map[currency] = rate if rate+ next unless rate&.rate.to_d.positive?+ next unless usable_rates.exists?(from_currency: currency, to_currency: to, date: rate.date)++ map[currency] = rateend- unique_currencies.each_with_object({}) do |currency, result|- rate = exact_rates[currency] || nearest_rates[currency] || fetched_rates[currency]+ # A rate from any distance is closer to the truth than 1.+ unfetched = still_missing - fetched_rates.keys+ stored_rates = unfetched.any? ? any_stored_rates(unfetched, to: to, date: date) : {}++ unique_currencies.each_with_object(same) do |currency, result|+ rate = exact_rates[currency] || nearest_rates[currency] || fetched_rates[currency] || stored_rates[currency]if rate.nil?- Rails.logger.warn("No exchange rate found for #{currency}/#{to} on #{date}, using 1")+ Rails.logger.warn("No exchange rate found for #{currency}/#{to} on #{date}")+ nextelsif rate.date != dateRails.logger.debug("FX rate #{currency}/#{to}: using #{rate.date} for #{date} (gap=#{(date - rate.date).to_i}d)")end- result[currency] = rate&.rate || 1+ result[currency] = rate.rateendend+ # SQL for the rate that converts `from` into `to` on `on`, by the same rule+ # as #rates_for without the provider: 1 for the same currency, else the+ # latest stored rate on or before the day, else the earliest after it, else+ # NULL. Amounts multiplied by a NULL rate drop out of a SUM, which is the+ # point: an amount with no rate is left out, never counted at parity.+ #+ # Arguments are SQL expressions, so a caller passes column names or named+ # binds (`:target_currency`), not values.+ def rate_sql(from:, to:, on:)+ <<~SQL.squish+ CASE WHEN #{from} = #{to} THEN 1 ELSE COALESCE(+ (SELECT fx.rate FROM exchange_rates fx+ WHERE fx.from_currency = #{from} AND fx.to_currency = #{to} AND fx.date <= #{on} AND fx.rate > 0+ ORDER BY fx.date DESC LIMIT 1),+ (SELECT fx.rate FROM exchange_rates fx+ WHERE fx.from_currency = #{from} AND fx.to_currency = #{to} AND fx.date > #{on} AND fx.rate > 0+ ORDER BY fx.date ASC LIMIT 1)+ ) END+ SQL+ end++ # Of `currencies`, those with no stored rate into `to` on any date. #rate_sql+ # leaves these amounts out; #rates_for does too unless the provider+ # supplies a rate.+ def currencies_without_rate(currencies, to:)+ candidates = currencies.compact.uniq - [ to ]+ return [] if candidates.empty?++ candidates - usable_rates.where(from_currency: candidates, to_currency: to).distinct.pluck(:from_currency)+ end++ # Of `currencies`, those whose newest stored rate into `to` is older than+ # the lookback #rates_for treats as current, with that rate's date. Today's+ # figures in them convert at that older rate. A currency with no rate at+ # all is not here; see #currencies_without_rate.+ def stale_rate_dates(currencies, to:, as_of: Date.current)+ candidates = currencies.compact.uniq - [ to ]+ return {} if candidates.empty?++ # Rows dated after as_of are left out: today converts at the latest rate+ # on or before today, so a future row must not hide that it is old.+ usable_rates.where(from_currency: candidates, to_currency: to, date: ..as_of)+ .group(:from_currency)+ .maximum(:date)+ .select { |_, date| date < as_of - NEAREST_RATE_LOOKBACK_DAYS }+ end+# @return [Integer] The number of exchange rates synceddef import_provider_rates(from:, to:, start_date:, end_date:, clear_cache: false)unless provider.present?@@ -138,5 +226,27 @@ module ExchangeRate::ProvidedRails.cache.delete(lock_key) if Rails.cache.read(lock_key) == lock_tokenendend++ private+ # Rows a conversion may use. ExchangeRate validates presence only, so a+ # provider or an import can leave a 0 behind.+ def usable_rates+ where("exchange_rates.rate > 0")+ end++ # The latest stored rate on or before `date` for each currency, else the+ # earliest after it, in two queries.+ def any_stored_rates(currencies, to:, date:)+ before = usable_rates.where(from_currency: currencies, to_currency: to).where("date <= ?", date)+ .select("DISTINCT ON (from_currency) *").order(:from_currency, date: :desc)+ .index_by(&:from_currency)+ rest = currencies - before.keys+ return before if rest.empty?++ after = usable_rates.where(from_currency: rest, to_currency: to).where("date > ?", date)+ .select("DISTINCT ON (from_currency) *").order(:from_currency, :date)+ .index_by(&:from_currency)+ before.merge(after)+ endendenddiff --git a/app/models/family.rb b/app/models/family.rbindex 8c7bab53c1..029b779cfa 100644--- a/app/models/family.rb+++ b/app/models/family.rb@@ -750,6 +750,28 @@ class Family < ApplicationRecord(requires_exchange_rates_data_provider? && ExchangeRate.provider.nil?)end+ # Currencies the family's accounts, entries or holdings use that have no+ # stored exchange rate into the family currency on any date. Totals built on+ # #rate_sql leave amounts in them out rather than counting them at 1;+ # totals built on #rates_for include them only if the provider supplies a+ # rate, which is then stored. The pages that show those totals say so.+ #+ # Pass the viewer's accounts so the note covers the totals they see: only+ # visible accounts count, and a member is not told about the currency of an+ # account shared with someone else.+ def currencies_without_exchange_rate(accounts: self.accounts)+ ExchangeRate.currencies_without_rate(currencies_in_use(accounts), to: currency)+ end++ # Currencies today's totals convert whose newest rate into the family+ # currency is too old to count as today's, mapped to that rate's date. Today's+ # totals use it, and the same pages say so. Only balances and current holdings+ # count: a currency only old entries use is converted at its own date's rate,+ # so an old newest rate is not out of date for it.+ def stale_exchange_rate_dates(accounts: self.accounts)+ ExchangeRate.stale_rate_dates(currencies_held_now(accounts), to: currency)+ end+# Returns securities with plan restrictions for a specific provider# @param provider [String] The provider name (e.g., "TwelveData")# @return [Array<Hash>] Array of hashes with ticker, name, required_plan, provider@@ -922,6 +944,31 @@ class Family < ApplicationRecordprivate_constant :INVALID_TIMEZONE_LOG_INTERVALprivate+ # Currencies of the given visible accounts' balances, and of each+ # account's holdings on its latest holding date.+ def currencies_held_now(scope)+ account_ids = self.accounts.visible.where(id: scope.select(:id)).select(:id)+ latest = Holding.where(account_id: account_ids).group(:account_id).select("account_id, MAX(date) AS date")+ (+ Account.where(id: account_ids).distinct.pluck(:currency) ++ Holding.joins("JOIN (#{latest.to_sql}) latest ON latest.account_id = holdings.account_id AND latest.date = holdings.date")+ .distinct.pluck(:currency)+ ).compact.uniq+ end++ # Currencies used by the given accounts that are visible, by their entries,+ # their trades and their holdings. Memoised per scope, so repeated reads in+ # one render share one set of queries.+ def currencies_in_use(scope)+ account_ids = self.accounts.visible.where(id: scope.select(:id)).pluck(:id).sort+ @currencies_in_use ||= {}+ @currencies_in_use[account_ids] ||= (+ Account.where(id: account_ids).distinct.pluck(:currency) ++ Entry.where(account_id: account_ids).distinct.pluck(:currency) ++ Trade.joins(:entry).where(entries: { account_id: account_ids }).distinct.pluck("trades.currency") ++ Holding.where(account_id: account_ids).distinct.pluck(:currency)+ ).compact.uniq+ enddef log_invalid_timezone_oncecache_key = [ "invalid_family_timezone", id, timezone ]diff --git a/app/models/income_statement.rb b/app/models/income_statement.rbindex 3b726d6698..e5bf6bab8d 100644--- a/app/models/income_statement.rb+++ b/app/models/income_statement.rb@@ -264,7 +264,7 @@ class IncomeStatementdef unfiltered_daily_expense_series(period)Rails.cache.fetch([- "income_statement", "daily_expense_series", family.id, user&.id,+ "income_statement", "daily_expense_series", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id,included_account_ids_hash, period.start_date, period.end_date,*cache_freshness_key]) do@@ -284,7 +284,7 @@ class IncomeStatementdef daily_expense_by_category(period)@daily_expense_by_category ||= {}@daily_expense_by_category[period_cache_key(period)] ||= Rails.cache.fetch([- "income_statement", "daily_expense_by_category", family.id, user&.id,+ "income_statement", "daily_expense_by_category", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id,included_account_ids_hash, period.start_date, period.end_date,*cache_freshness_key]) do@@ -315,14 +315,14 @@ class IncomeStatementdef family_stats(interval: "month")@family_stats ||= {}@family_stats[interval] ||= Rails.cache.fetch([- "income_statement", "family_stats", family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key+ "income_statement", "family_stats", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key]) { FamilyStats.new(family, interval:, account_ids: included_account_ids).call }enddef category_stats(interval: "month")@category_stats ||= {}@category_stats[interval] ||= Rails.cache.fetch([- "income_statement", "category_stats", family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key+ "income_statement", "category_stats", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key]) { CategoryStats.new(family, interval:, account_ids: included_account_ids).call }end@@ -358,7 +358,7 @@ class IncomeStatementsql_hash = Digest::MD5.hexdigest(transactions_scope.to_sql)Rails.cache.fetch([- "income_statement", "totals_query", "v2", family.id, user&.id, included_account_ids_hash, sql_hash, date_range.begin, date_range.end, *cache_freshness_key+ "income_statement", "totals_query", "v2", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, included_account_ids_hash, sql_hash, date_range.begin, date_range.end, *cache_freshness_key]) { Totals.new(family, transactions_scope: transactions_scope, date_range: date_range, included_account_ids: included_account_ids).call }enddiff --git a/app/models/income_statement/category_stats.rb b/app/models/income_statement/category_stats.rbindex 4530e7b71e..738507bbcd 100644--- a/app/models/income_statement/category_stats.rb+++ b/app/models/income_statement/category_stats.rb@@ -46,7 +46,6 @@ class IncomeStatement::CategoryStats#{entries_join_sql("t")}#{accounts_join_sql}LEFT JOIN categories c ON c.id = t.category_id- #{exchange_rates_join_sql}WHERE a.family_id = :family_idAND t.kind NOT IN (#{budget_excluded_kinds_sql})AND ae.excluded = falsediff --git a/app/models/income_statement/daily_expense_totals.rb b/app/models/income_statement/daily_expense_totals.rbindex 1e57b791f3..cc885c8166 100644--- a/app/models/income_statement/daily_expense_totals.rb+++ b/app/models/income_statement/daily_expense_totals.rb@@ -54,11 +54,10 @@ class IncomeStatement::DailyExpenseTotalsae.date as day,#{category_column_sql("at.category_id as category_id")}#{classification_sql("at")} as classification,- ABS(SUM(#{converted_amount_sql("at")})) as total+ ABS(COALESCE(SUM(#{converted_amount_sql("at")}), 0)) as totalFROM (#{@transactions_scope.to_sql}) at#{entries_join_sql("at")}#{accounts_join_sql}- #{exchange_rates_join_sql}WHERE at.kind NOT IN (#{budget_excluded_kinds_sql})#{investment_activity_label_sql("at")}AND ae.excluded = falsediff --git a/app/models/income_statement/family_stats.rb b/app/models/income_statement/family_stats.rbindex f63df617ad..13de874361 100644--- a/app/models/income_statement/family_stats.rb+++ b/app/models/income_statement/family_stats.rb@@ -43,7 +43,6 @@ class IncomeStatement::FamilyStatsFROM transactions t#{entries_join_sql("t")}#{accounts_join_sql}- #{exchange_rates_join_sql}WHERE a.family_id = :family_idAND t.kind NOT IN (#{budget_excluded_kinds_sql})AND ae.excluded = falsediff --git a/app/models/income_statement/scoped_transactions_query.rb b/app/models/income_statement/scoped_transactions_query.rbindex d18bb64597..ff26113db5 100644--- a/app/models/income_statement/scoped_transactions_query.rb+++ b/app/models/income_statement/scoped_transactions_query.rb@@ -20,11 +20,16 @@ module IncomeStatement::ScopedTransactionsQuery"CASE WHEN #{t}.kind = 'investment_contribution' THEN '#{contribution}' WHEN #{t}.kind = 'loan_payment' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END"end- # Entry amount converted to the family currency at the day's exchange- # rate. Contribution/loan-payment outflows are flipped positive so they- # add to expense totals.+ # Entry amount converted to the family currency (see ExchangeRate.rate_sql).+ # Contribution/loan-payment outflows are flipped positive so they add to+ # expense totals. NULL for a currency with no rate at all, so the entry is+ # left out of a SUM rather than counted at 1. Totals wrap their SUM+ # in COALESCE so a group with nothing convertible reads 0; the stats leave+ # it NULL, so a period with nothing convertible is skipped by the median+ # and average rather than counted as a period with no spending.def converted_amount_sql(t)- "CASE WHEN #{t}.kind IN ('investment_contribution', 'loan_payment') THEN ABS(ae.amount * COALESCE(er.rate, 1)) ELSE ae.amount * COALESCE(er.rate, 1) END"+ rate = ExchangeRate.rate_sql(from: "ae.currency", to: ":target_currency", on: "ae.date")+ "CASE WHEN #{t}.kind IN ('investment_contribution', 'loan_payment') THEN ABS(ae.amount * #{rate}) ELSE ae.amount * #{rate} END"enddef entries_join_sql(t)@@ -35,16 +40,6 @@ module IncomeStatement::ScopedTransactionsQuery"JOIN accounts a ON a.id = ae.account_id"end- def exchange_rates_join_sql- <<~SQL.chomp- LEFT JOIN exchange_rates er ON (- er.date = ae.date AND- er.from_currency = ae.currency AND- er.to_currency = :target_currency- )- SQL- end-# Investment activity rows that move money within a portfolio# (transfers, sweeps, exchanges) are neither income nor expenses.def investment_activity_label_sql(t)diff --git a/app/models/income_statement/totals.rb b/app/models/income_statement/totals.rbindex 34fe35a560..61add0d8c5 100644--- a/app/models/income_statement/totals.rb+++ b/app/models/income_statement/totals.rb@@ -63,14 +63,13 @@ class IncomeStatement::Totalsc.id as category_id,c.parent_id as parent_category_id,#{classification_sql("at")} as classification,- ABS(SUM(#{converted_amount_sql("at")})) as total,+ ABS(COALESCE(SUM(#{converted_amount_sql("at")}), 0)) as total,COUNT(ae.id) as transactions_count,false as is_uncategorized_investmentFROM (#{@transactions_scope.to_sql}) at#{entries_join_sql("at")}#{accounts_join_sql}LEFT JOIN categories c ON c.id = at.category_id- #{exchange_rates_join_sql}WHERE at.kind NOT IN (#{budget_excluded_kinds_sql})AND ae.excluded = falseAND a.family_id = :family_id@@ -88,14 +87,13 @@ class IncomeStatement::Totalsc.id as category_id,c.parent_id as parent_category_id,#{classification_sql("at")} as classification,- ABS(SUM(#{converted_amount_sql("at")})) as total,+ ABS(COALESCE(SUM(#{converted_amount_sql("at")}), 0)) as total,COUNT(ae.id) as entry_count,false as is_uncategorized_investmentFROM (#{@transactions_scope.to_sql}) at#{entries_join_sql("at")}#{accounts_join_sql}LEFT JOIN categories c ON c.id = at.category_id- #{exchange_rates_join_sql}WHERE at.kind NOT IN (#{budget_excluded_kinds_sql})#{investment_activity_label_sql("at")}AND ae.excluded = falsediff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rbindex 3a61c867f2..35fad18d38 100644--- a/app/models/investment_statement.rb+++ b/app/models/investment_statement.rb@@ -266,14 +266,9 @@ class InvestmentStatementabsolute_return = ActiveRecord::Base.connection.select_value(ActiveRecord::Base.sanitize_sql_array([<<~SQL.squish,- SELECT COALESCE(SUM(b.net_market_flows * COALESCE(er.rate, 1)), 0)+ SELECT COALESCE(SUM(b.net_market_flows * #{ExchangeRate.rate_sql(from: "b.currency", to: ":currency", on: "b.date")}), 0)FROM balances bJOIN accounts a ON a.id = b.account_id- LEFT JOIN exchange_rates er ON (- er.date = b.date- AND er.from_currency = b.currency- AND er.to_currency = :currency- )WHERE a.id IN (:account_ids)AND a.family_id = :family_idAND a.status IN ('draft', 'active')@@ -298,14 +293,9 @@ class InvestmentStatementstart_value = ActiveRecord::Base.connection.select_value(ActiveRecord::Base.sanitize_sql_array([<<~SQL.squish,- SELECT COALESCE(SUM(b.end_balance * COALESCE(er.rate, 1)), 0)+ SELECT COALESCE(SUM(b.end_balance * #{ExchangeRate.rate_sql(from: "b.currency", to: ":currency", on: ":period_start")}), 0)FROM accounts aINNER JOIN balances b ON b.account_id = a.id- LEFT JOIN exchange_rates er ON (- er.date = :period_start- AND er.from_currency = b.currency- AND er.to_currency = :currency- )INNER JOIN (SELECT b2.account_id, MAX(b2.date) AS max_dateFROM balances b2@@ -424,12 +414,16 @@ class InvestmentStatement# `Money * numeric` preserves the source currency — so multiplying a# foreign-currency Money by a rate would FX-scale the amount but keep the# wrong currency label, corrupting downstream sums.+ #+ # A currency with no rate at all converts to 0: the amount is left out of+ # every sum here rather than counted at 1. Both sides of a trend+ # come from the same holding, so they drop out together.def convert_to_family_currency(amount, from_currency)return amount if amount.nil?numeric = amount.is_a?(Money) ? amount.amount : amountreturn numeric if from_currency == family.currency- rate = exchange_rates[from_currency] || 1- numeric * rate+ rate = exchange_rates[from_currency]+ rate ? numeric * rate : 0enddef all_time_totals@@ -818,8 +812,10 @@ class InvestmentStatementaccount_ids_hash = Digest::MD5.hexdigest(account_ids.sort.join(","))Rails.cache.fetch([- "investment_statement", "totals_query/v2", family.id, user&.id, family.currency,- account_ids_hash, date_range.begin, date_range.end, family.entries_cache_version+ "investment_statement", "totals_query/v2", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, family.currency,+ account_ids_hash, date_range.begin, date_range.end, family.entries_cache_version,+ # A rate stored later can complete totals that left an amount out.+ ExchangeRate.maximum(:updated_at)&.to_i]) { Totals.new(family, account_ids: account_ids, date_range: date_range).call }enddiff --git a/app/models/investment_statement/totals.rb b/app/models/investment_statement/totals.rbindex cd44bfa0b9..c6c62f128c 100644--- a/app/models/investment_statement/totals.rb+++ b/app/models/investment_statement/totals.rb@@ -62,7 +62,9 @@ class InvestmentStatement::Totals# relying on qty: 0 to keep the buckets disjoint. Without this guard such# a row would be counted twice: once by direction and once as income.#- # Missing FX rates preserve InvestmentStatement's existing 1:1 fallback.+ # A row in a currency with no rate at all is left out, not counted at 1,+ # as in InvestmentStatement; ExchangeRate.rate_sql gives the+ # nearest stored rate otherwise.## account_ids is already scoped to the family's visible (draft/active)# investment accounts, so the query trusts that input and skips a join back@@ -73,21 +75,18 @@ class InvestmentStatement::Totalsenddef aggregation_sql+ rate = ExchangeRate.rate_sql(from: "entries.currency", to: ":target_currency", on: "entries.date")+<<~SQLSELECT- COALESCE(SUM(CASE WHEN trades.qty > 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as contributions,- COALESCE(SUM(CASE WHEN trades.qty < 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as withdrawals,- COALESCE(-SUM(CASE WHEN #{label_sql} = 'Dividend' THEN entries.amount * COALESCE(er.rate, 1) ELSE 0 END), 0) as dividends,- COALESCE(-SUM(CASE WHEN #{label_sql} = 'Interest' THEN entries.amount * COALESCE(er.rate, 1) ELSE 0 END), 0) as interest,+ COALESCE(SUM(CASE WHEN trades.qty > 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as contributions,+ COALESCE(SUM(CASE WHEN trades.qty < 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as withdrawals,+ COALESCE(-SUM(CASE WHEN #{label_sql} = 'Dividend' THEN entries.amount * #{rate} ELSE 0 END), 0) as dividends,+ COALESCE(-SUM(CASE WHEN #{label_sql} = 'Interest' THEN entries.amount * #{rate} ELSE 0 END), 0) as interest,COUNT(trades.id) as trades_countFROM entriesLEFT JOIN trades ON trades.id = entries.entryable_id AND entries.entryable_type = 'Trade'LEFT JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'- LEFT JOIN exchange_rates er ON (- er.date = entries.date AND- er.from_currency = entries.currency AND- er.to_currency = :target_currency- )WHERE entries.account_id IN (:account_ids)AND entries.date BETWEEN :start_date AND :end_dateAND entries.excluded = falsediff --git a/app/models/trade.rb b/app/models/trade.rbindex 297a6753ad..f2490200d2 100644--- a/app/models/trade.rb+++ b/app/models/trade.rb@@ -101,6 +101,7 @@ class Trade < ApplicationRecorddef preloaded_exchange_rates=(value)@preloaded_exchange_rates = valueremove_instance_variable(:@realized_gain_loss) if defined?(@realized_gain_loss)+ @realized_gain_unconvertible = falseend# One query for every rate a set of disposals can need, instead of one per@@ -161,9 +162,19 @@ class Trade < ApplicationRecorddef realized_gain_lossreturn @realized_gain_loss if defined?(@realized_gain_loss)+ @realized_gain_unconvertible = false@realized_gain_loss = calculate_realized_gain_lossend+ # True when #realized_gain_loss is nil only because the proceeds' currency+ # has no usable rate into the basis currency for the disposal's day, as+ # opposed to a buy, a transfer or an unknown cost basis. A caller summing+ # gains counts these as left out.+ def realized_gain_unconvertible?+ realized_gain_loss+ @realized_gain_unconvertible+ end+# Trades are always excluded from expense budgets# They represent portfolio management, not living expensesdef excluded_from_budget?@@ -223,7 +234,10 @@ class Trade < ApplicationRecord# No rate for that day means the gain is unknown, not zero and not the# figure a rate of 1.0 would give.- return nil if sale_proceeds.nil?+ if sale_proceeds.nil?+ @realized_gain_unconvertible = true+ return nil+ endTrend.new(current: sale_proceeds, previous: cost_basis)enddiff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rbindex e8f690dc27..091b2fe802 100644--- a/app/models/transaction/search.rb+++ b/app/models/transaction/search.rb@@ -212,7 +212,7 @@ class Transaction::Search# deploy, disagreeing with the (uncached) transactions_scope list# until entries_cache_version next changes for that family.# v4: Totals gained excluded_scheduled_count.- Rails.cache.fetch("transaction_search_totals/v4/#{cache_key_base}") do+ Rails.cache.fetch("transaction_search_totals/v4/#{ExchangeRate::CONVERSION_CACHE_VERSION}/#{cache_key_base}") doscope = transactions_scopeexcluded_scheduled_count = 0@@ -236,32 +236,33 @@ class Transaction::Searchtax_advantaged_ids = family.tax_advantaged_account_idsscope = scope.where.not(accounts: { id: tax_advantaged_ids }) if tax_advantaged_ids.present?+ # Left out, not counted at 1, when the currency has no rate.+ rate = ExchangeRate.rate_sql(+ from: "entries.currency",+ to: ActiveRecord::Base.connection.quote(family.currency),+ on: "entries.date"+ )+result = scope.select(ActiveRecord::Base.sanitize_sql_array([- "COALESCE(SUM(CASE WHEN entries.amount >= 0 AND transactions.kind NOT IN (?) THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as expense_total",+ "COALESCE(SUM(CASE WHEN entries.amount >= 0 AND transactions.kind NOT IN (?) THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as expense_total",Transaction::TRANSFER_KINDS]),ActiveRecord::Base.sanitize_sql_array([- "COALESCE(SUM(CASE WHEN entries.amount < 0 AND transactions.kind NOT IN (?) THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as income_total",+ "COALESCE(SUM(CASE WHEN entries.amount < 0 AND transactions.kind NOT IN (?) THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as income_total",Transaction::TRANSFER_KINDS]),ActiveRecord::Base.sanitize_sql_array([- "COALESCE(SUM(CASE WHEN entries.amount < 0 AND transactions.kind IN (?) THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as transfer_inflow_total",+ "COALESCE(SUM(CASE WHEN entries.amount < 0 AND transactions.kind IN (?) THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as transfer_inflow_total",Transaction::TRANSFER_KINDS]),ActiveRecord::Base.sanitize_sql_array([- "COALESCE(SUM(CASE WHEN entries.amount >= 0 AND transactions.kind IN (?) THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as transfer_outflow_total",+ "COALESCE(SUM(CASE WHEN entries.amount >= 0 AND transactions.kind IN (?) THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as transfer_outflow_total",Transaction::TRANSFER_KINDS]),"COUNT(entries.id) as transactions_count")- .joins(- ActiveRecord::Base.sanitize_sql_array([- "LEFT JOIN exchange_rates er ON (er.date = entries.date AND er.from_currency = entries.currency AND er.to_currency = ?)",- family.currency- ])- ).takeTotals.new(@@ -283,6 +284,7 @@ class Transaction::Searchfamily.currency,Digest::SHA256.hexdigest(attributes.sort.to_h.to_json), # cached by filtersfamily.entries_cache_version,+ ExchangeRate.maximum(:updated_at)&.to_i, # a rate stored later can complete the totalsDigest::SHA256.hexdigest(family.tax_advantaged_account_ids.sort.to_json), # stable across processesaccessible_account_ids ? Digest::SHA256.hexdigest(accessible_account_ids.sort.to_json) : "all",Date.current # totals exclude scheduled entries as of "today" -- must roll over dailydiff --git a/app/views/pages/dashboard.html.erb b/app/views/pages/dashboard.html.erbindex e4850ca484..30fc6f92ae 100644--- a/app/views/pages/dashboard.html.erb+++ b/app/views/pages/dashboard.html.erb@@ -58,6 +58,8 @@<% end %><%= turbo_frame_tag "dashboard_sections", target: "_top" do %>+ <%= render "shared/exchange_rate_notes", family: Current.family, classes: "mb-4" %>+<% if accessible_accounts.any? %><div class="flex items-center justify-end mb-4"><%# Keeps the widgets' own months and filters; a preset replaces any custom range. %>diff --git a/app/views/reports/_investment_performance.html.erb b/app/views/reports/_investment_performance.html.erbindex 7dc47cf343..dd13d2d2d8 100644--- a/app/views/reports/_investment_performance.html.erb+++ b/app/views/reports/_investment_performance.html.erb@@ -132,7 +132,7 @@<div class="flex flex-wrap gap-4"><% investment_metrics[:gains_by_tax_treatment].each do |treatment, data| %>- <div class="bg-container-inset rounded-lg p-4 space-y-3 flex-1 min-w-64">+ <div class="bg-container-inset rounded-lg p-4 space-y-3 flex-1 min-w-64" data-testid="tax-treatment-gains"><div class="flex items-center justify-between"><%= render DS::Pill.new(label: t("accounts.tax_treatments.#{treatment}"),@@ -157,6 +157,13 @@</div></div>+ <% if data[:unconverted_count].to_i > 0 %>+ <p class="text-xs text-secondary flex items-center gap-1" data-testid="unconverted-gains-note">+ <%= icon("info", size: "sm") %>+ <%= t("reports.investment_performance.unconverted_note", count: data[:unconverted_count], currency: Current.family.currency) %>+ </p>+ <% end %>+<% if treatment == :taxable && data[:realized_gain].amount > 0 %><p class="text-xs text-warning flex items-center gap-1"><%= icon("alert-triangle", size: "sm") %>@@ -178,10 +185,11 @@<div class="space-y-1"><p class="text-secondary font-medium"><%= t("reports.investment_performance.holdings") %></p><% data[:holdings].first(5).each do |holding| %>+ <% gain = data[:unrealized_gain_by_holding][holding.id] %><div class="flex justify-between pl-2"><span class="text-primary"><%= holding.ticker %></span>- <span class="<%= holding.trend ? "" : "text-secondary" %>" style="<%= holding.trend ? "color: #{holding.trend.color}" : "" %>">- <%= holding.trend ? format_money(Money.new(holding.trend.value, Current.family.currency)) : t("reports.investment_performance.no_data") %>+ <span class="<%= gain ? "" : "text-secondary" %>" style="<%= gain ? "color: #{holding.trend.color}" : "" %>">+ <%= gain ? format_money(gain) : t("reports.investment_performance.no_data") %></span></div><% end %>diff --git a/app/views/reports/index.html.erb b/app/views/reports/index.html.erbindex 88f740571d..d70a870dba 100644--- a/app/views/reports/index.html.erb+++ b/app/views/reports/index.html.erb@@ -128,6 +128,8 @@<% end %><div class="w-full space-y-6 lg:pb-6">+ <%= render "shared/exchange_rate_notes", family: Current.family %>+<% if Current.family.transactions.any? %><%# Summary Dashboard - Always visible, not collapsible %><section>diff --git a/app/views/shared/_exchange_rate_notes.html.erb b/app/views/shared/_exchange_rate_notes.html.erbnew file mode 100644index 0000000000..9472739d3c--- /dev/null+++ b/app/views/shared/_exchange_rate_notes.html.erb@@ -0,0 +1,31 @@+<%# locals: (family:, classes: nil) %>+<% accounts = Current.accessible_accounts || family.accounts %>+<% missing = family.currencies_without_exchange_rate(accounts: accounts) %>+<% stale = family.stale_exchange_rate_dates(accounts: accounts) %>+<% if missing.any? || stale.any? %>+ <div class="space-y-2 <%= classes %>">+ <% if missing.any? %>+ <div data-testid="missing-exchange-rates">+ <%= render DS::Alert.new(+ variant: :warning,+ message: t("shared.exchange_rate_notes.missing",+ count: missing.size,+ currencies: missing.sort.to_sentence,+ currency: family.currency)+ ) %>+ </div>+ <% end %>++ <% if stale.any? %>+ <div data-testid="stale-exchange-rates">+ <%= render DS::Alert.new(+ variant: :info,+ message: t("shared.exchange_rate_notes.stale",+ count: stale.size,+ currency: family.currency,+ rates: stale.sort.map { |from, date| t("shared.exchange_rate_notes.stale_rate", from: from, date: l(date, format: :long)) }.to_sentence)+ ) %>+ </div>+ <% end %>+ </div>+<% end %>diff --git a/app/views/transactions/index.html.erb b/app/views/transactions/index.html.erbindex 54c7bc463f..6ed2cb2f02 100644--- a/app/views/transactions/index.html.erb+++ b/app/views/transactions/index.html.erb@@ -48,6 +48,7 @@</div></header>+ <%= render "shared/exchange_rate_notes", family: Current.family %><%= render "summary", totals: @search.totals, transactions_count: @pagy.count %><% if Current.family.recurring_transactions_disabled? %><%= render "transactions/list", transactions: @transactions, projected_recurring: @projected_recurring, q: params[:q], pagy: @pagy %>diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.ymlindex 562353d282..05f5445002 100644--- a/config/locales/views/reports/en.yml+++ b/config/locales/views/reports/en.yml@@ -185,6 +185,9 @@ en:realized_gains: Realized Gainstotal_gains: Total Gainstaxable_realized_note: These gains may be subject to taxes+ unconverted_note:+ one: "%{count} gain is not included: no exchange rate to %{currency}"+ other: "%{count} gains are not included: no exchange rate to %{currency}"no_data: "-"view_details: View detailsholdings_count:diff --git a/config/locales/views/shared/en.yml b/config/locales/views/shared/en.ymlindex 8dfef1ec7e..0220afa81a 100644--- a/config/locales/views/shared/en.yml+++ b/config/locales/views/shared/en.yml@@ -5,6 +5,14 @@ en:redis_configured: "Redis is now configured properly! You can now setup your Sure application."shared:preview: Preview+ exchange_rate_notes:+ missing:+ one: "No exchange rate from %{currencies} to %{currency} is stored yet, so some totals may leave out amounts in %{currencies}."+ other: "No exchange rates from %{currencies} to %{currency} are stored yet, so some totals may leave out amounts in those currencies."+ stale:+ one: "The latest exchange rate to %{currency} is out of date: %{rates}. Today's totals use it."+ other: "The latest exchange rates to %{currency} are out of date: %{rates}. Today's totals use them."+ stale_rate: "%{from} from %{date}"dot_separator: "·"sync_toast:message: "New data available"diff --git a/test/controllers/pages_controller_test.rb b/test/controllers/pages_controller_test.rbindex 5aa310363c..6f0c4455f3 100644--- a/test/controllers/pages_controller_test.rb+++ b/test/controllers/pages_controller_test.rb@@ -1127,6 +1127,48 @@ class PagesControllerTest < ActionDispatch::IntegrationTestendend+ test "dashboard says which currencies are left out of its totals" do+ @family.accounts.create!(name: "KRW Savings", balance: 1_000_000, currency: "KRW", accountable: Depository.new)++ get root_path+ assert_response :ok++ assert_select "[data-testid='missing-exchange-rates']", text: /No exchange rate from KRW to USD is stored yet, so some totals may leave out amounts in KRW/+ end++ test "dashboard does not name the currency of an account the member cannot see" do+ @family.accounts.create!(name: "Admin KRW", owner: users(:family_admin), balance: 1_000_000, currency: "KRW", accountable: Depository.new)+ sign_in users(:family_member)++ get root_path+ assert_response :ok++ assert_select "[data-testid='missing-exchange-rates']", count: 0+ end++ test "dashboard shows no exchange rate notes when every rate is current" do+ @family.accounts.create!(name: "EUR Savings", balance: 100, currency: "EUR", accountable: Depository.new)+ ExchangeRate.create!(from_currency: "EUR", to_currency: @family.currency, date: Date.current, rate: 1.1)++ get root_path+ assert_response :ok++ assert_select "[data-testid='missing-exchange-rates']", count: 0+ assert_select "[data-testid='stale-exchange-rates']", count: 0+ end++ test "dashboard says when today's totals use an out-of-date rate" do+ rate_date = 30.days.ago.to_date+ @family.accounts.create!(name: "JPY Savings", balance: 1_000_000, currency: "JPY", accountable: Depository.new)+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: rate_date, rate: 0.0067)++ get root_path+ assert_response :ok++ assert_select "[data-testid='stale-exchange-rates']", text: /JPY from #{Regexp.escape(I18n.l(rate_date, format: :long))}/+ assert_select "[data-testid='missing-exchange-rates']", count: 0+ end+test "dashboard spending trend category filter narrows both months and the header totals" doaccount, selected_month, previous_month = spending_trend_filter_setupfood = @family.categories.create!(name: "Spending Filter Food")diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex f56e9ac392..93308ed5b4 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -147,6 +147,102 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestassert_no_match(/\$40\.00/, line, "$40.00 is the GBP figure converted at parity")end+ # No JPY->USD rate for the day of a disposal in a JPY account. The gain is+ # ¥100,000 and there is nothing to convert it with: converted at 1 it read+ # as $100,000.00 (#3640). It is left out of the total, its own line shows no+ # figure, and the card says a gain is missing.+ test "a disposal with no rate into family currency is left out and the card says so" do+ ExchangeRate.stubs(:provider).returns(nil)+ date = Date.current.beginning_of_month+ account = @family.accounts.create!(name: "Brokerage JPY", balance: 1_000_000,+ currency: "JPY", accountable: Investment.new)+ security = Security.create!(ticker: "JPX#{SecureRandom.hex(3)}", name: "Tokyo Listed")+ ExchangeRate.where(from_currency: "JPY", to_currency: "USD").delete_all++ account.holdings.create!(security: security, date: date, qty: 5, price: 150_000,+ amount: BigDecimal(750_000), currency: "JPY", cost_basis: 100_000)+ create_trade(security, account: account, qty: -2, date: date, price: 150_000, currency: "JPY")++ get reports_path+ assert_response :ok++ line = css_select("[data-testid='realized-gain-line']").map(&:text)+ .find { |text| text.include?(security.ticker) }++ assert line, "the disposal must be listed at all, or this proves nothing"+ assert_no_match(/\$100,000\.00/, line, "$100,000.00 is the yen figure converted at parity")+ assert_select "[data-testid='unconverted-gains-note']", text: /no exchange rate to USD/+ assert_no_match(/\$100,000\.00/, response.body, "nor is it in any total")+ end++ # A sale priced in EUR from a USD position, with no EUR->USD rate on any+ # date: Trade has no figure for it. The card used to skip it as though it+ # had no cost basis, so its total was partial without saying so.+ test "a sale with no rate between its own currencies is counted as left out" do+ ExchangeRate.stubs(:provider).returns(nil)+ date = Date.current.beginning_of_month+ account = @family.accounts.create!(name: "Brokerage USD", balance: 10_000,+ currency: "USD", accountable: Investment.new)+ security = Security.create!(ticker: "EUX#{SecureRandom.hex(3)}", name: "Euro Listed")+ ExchangeRate.where(from_currency: "EUR", to_currency: "USD").delete_all++ account.holdings.create!(security: security, date: date, qty: 5, price: 150,+ amount: BigDecimal(750), currency: "USD", cost_basis: 100)+ create_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR")++ get reports_path+ assert_response :ok++ assert_select "[data-testid='unconverted-gains-note']", text: /1 gain is not included/+ end++ # The same for an open position: a JPY holding showing a ¥250,000 gain with+ # no JPY->USD rate is not $250,000 of unrealised gain. At parity the gains+ # card and the Total Return card both read $250,010.00, the yen figure plus+ # the fixtures' $10, and Portfolio Value read $1,020,000.00.+ test "a holding with no rate into family currency is left out of unrealised gains" do+ ExchangeRate.stubs(:provider).returns(nil)+ account = @family.accounts.create!(name: "Brokerage JPY", balance: 1_000_000,+ currency: "JPY", accountable: Investment.new)+ security = Security.create!(ticker: "JPX#{SecureRandom.hex(3)}", name: "Tokyo Listed")+ ExchangeRate.where(from_currency: "JPY", to_currency: "USD").delete_all++ account.holdings.create!(security: security, date: Date.current, qty: 5, price: 150_000,+ amount: BigDecimal(750_000), currency: "JPY", cost_basis: 100_000)++ get reports_path+ assert_response :ok++ assert_no_match(/\$250,0\d\d\.\d\d/, response.body, "the yen gain is in a total, converted at parity")+ assert_no_match(/\$1,020,000\.00/, response.body, "the yen account is in Portfolio Value, converted at parity")+ assert_select "[data-testid='unconverted-gains-note']", text: /1 gain is not included/+ assert_select "[data-testid='missing-exchange-rates']", text: /No exchange rate from JPY to USD is stored yet, so some totals may leave out amounts in JPY/+ end++ # Each holding's line under the card is the same arithmetic as the card's+ # total: converted into family currency, or "no data" without a rate. It+ # used to re-label the yen figure as dollars.+ test "a holding's gain line is converted, or shows no data without a rate" do+ ExchangeRate.stubs(:provider).returns(nil)+ account = @family.accounts.create!(name: "Brokerage JPY", balance: 1_000_000,+ currency: "JPY", accountable: Investment.new)+ security = Security.create!(ticker: "JPL#{SecureRandom.hex(3)}", name: "Tokyo Listed")+ account.holdings.create!(security: security, date: Date.current, qty: 5, price: 150_000,+ amount: BigDecimal(750_000), currency: "JPY", cost_basis: 100_000)+ ExchangeRate.where(from_currency: "JPY", to_currency: "USD").delete_all++ get reports_path+ line = css_select("div.pl-2").find { |div| div.text.include?(security.ticker) }+ assert line, "the holding is listed"+ assert_match(/#{Regexp.escape(I18n.t("reports.investment_performance.no_data"))}/, line.text)+ assert_no_match(/\$250,000\.00/, line.text, "the yen gain re-labelled as dollars")++ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: Date.current, rate: 0.0067)+ get reports_path+ line = css_select("div.pl-2").find { |div| div.text.include?(security.ticker) }+ assert_match(/\$1,675\.00/, line.text, "250,000 JPY at 0.0067")+ end+# The rates a page of disposals needs come from one query, not one per# foreign disposal. The conversion itself is covered in TradeTest, which# counts the queries directly; what has to hold HERE is that the card asks@@ -741,6 +837,50 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestassert_match(/\$100\.00/, other_investments_rows.first.text)end+ # The summary leaves out an amount in a currency with no rate; the+ # breakdown under it and the CSV export must leave it out too, not count+ # ₩130,000 as $130,000.+ test "the activity breakdown leaves out an expense in a currency with no rate" do+ category = @family.categories.create!(name: "Won Rent", color: "#111111")+ krw = @family.accounts.create!(owner: @user, name: "Seoul", balance: 0, currency: "KRW", accountable: Depository.new)+ create_transaction(account: krw, name: "Rent", amount: 130_000, currency: "KRW", category: category)++ get reports_path(period_type: :monthly)+ assert_response :ok++ assert_select "tr[data-category='category-#{category.id}']", count: 0+ assert_no_match(/130,000/, @response.body)+ end++ test "the export leaves out an expense in a currency with no rate" do+ category = @family.categories.create!(name: "Won Export Rent", color: "#111111")+ krw = @family.accounts.create!(owner: @user, name: "Seoul", balance: 0, currency: "KRW", accountable: Depository.new)+ create_transaction(account: krw, name: "Rent", amount: 130_000, currency: "KRW", category: category)++ get export_transactions_reports_path(format: :csv, period_type: :monthly,+ start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ assert_response :ok++ assert_no_match(/Won Export Rent/, @response.body)+ assert_no_match(/130000/, @response.body)+ end++ # The summary uses the latest stored rate however old; the breakdown used+ # Money#exchange_to, which looks back five days and then converts at 1.+ test "the activity breakdown converts at a stored rate older than five days" do+ category = @family.categories.create!(name: "Yen Rent", color: "#111111")+ jpy = @family.accounts.create!(owner: @user, name: "Tokyo", balance: 0, currency: "JPY", accountable: Depository.new)+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 30.days.ago.to_date, rate: 0.0067)+ create_transaction(account: jpy, name: "Rent", amount: 10_000, currency: "JPY", category: category)++ get reports_path(period_type: :monthly)+ assert_response :ok++ row = css_select("tr[data-category='category-#{category.id}']").first+ assert row, "the converted expense is listed"+ assert_match(/\$67\.00/, row.text)+ end+test "monthly period navigation shows previous month link" doget reports_path(period_type: :monthly)assert_response :okdiff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 6a31c26a0f..29e58c15da 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -2363,6 +2363,16 @@ endassert_no_match(/ai_status/, response.location)end+ test "index says which currencies are left out of its totals" do+ family = @user.family+ family.accounts.create!(name: "KRW Savings", balance: 1_000_000, currency: "KRW", accountable: Depository.new)++ get transactions_path+ assert_response :ok++ assert_select "[data-testid='missing-exchange-rates']", text: /No exchange rate from KRW to USD is stored yet, so some totals may leave out amounts in KRW/+ end+test "index with attachment_status=with lists only transactions that have a file" do@entry.entryable.attachments.attach(io: StringIO.new("invoice"), filename: "invoice.pdf", content_type: "application/pdf")diff --git a/test/models/balance/chart_series_builder_test.rb b/test/models/balance/chart_series_builder_test.rbindex a78aa117db..41decb5575 100644--- a/test/models/balance/chart_series_builder_test.rb+++ b/test/models/balance/chart_series_builder_test.rb@@ -258,6 +258,27 @@ class Balance::ChartSeriesBuilderTest < ActiveSupport::TestCaseassert_equal [ 1100, 1320 ], series.map { |v| v.value.amount }end+ # The series is the sum of every account's converted balance. An account in+ # a currency with no rate on any date drops out of it rather than counting+ # at 1 (#3640).+ test "an account in a currency with no rate at all is left out of the series" do+ family = families(:dylan_family)+ usd = family.accounts.create!(name: "USD", balance: 100, currency: "USD", accountable: Depository.new)+ krw = family.accounts.create!(name: "KRW", balance: 1_000_000, currency: "KRW", accountable: Depository.new)+ [ usd, krw ].each { |account| account.balances.destroy_all }+ create_balance(account: usd, date: Date.current, balance: 100)+ create_balance(account: krw, date: Date.current, balance: 1_000_000)++ series = Balance::ChartSeriesBuilder.new(+ account_ids: [ usd.id, krw.id ],+ currency: "USD",+ period: Period.custom(start_date: Date.current, end_date: Date.current),+ interval: "1 day"+ ).balance_series++ assert_equal [ 100 ], series.map { |v| v.value.amount }+ end+test "linked account with orphaned currency balances shows correct values after cleanup" do# This test reproduces the original bug scenario:# 1. Linked account created with initial sync before correct currency was knowndiff --git a/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb b/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rbindex 7e74c5e90f..f0ac8443a8 100644--- a/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb+++ b/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb@@ -108,6 +108,20 @@ class BalanceSheet::NetWorthBreakdownSeriesBuilderTest < ActiveSupport::TestCaseassert_not_equal before, afterend+ # An account with no rate is left out of the series. A rate stored later,+ # by the market data import or a provider lookup on the balance sheet,+ # must reach the chart as it reaches the totals beside it.+ test "cache key changes when an exchange rate is stored" do+ period = Period.last_30_days+ before = BalanceSheet::NetWorthBreakdownSeriesBuilder.new(@family).send(:cache_key, period)+ travel 1.second do+ ExchangeRate.create!(from_currency: "KRW", to_currency: @family.currency, date: Date.current, rate: 0.00075)+ end+ after = BalanceSheet::NetWorthBreakdownSeriesBuilder.new(@family.reload).send(:cache_key, period)++ assert_not_equal before, after+ end+test "cache key changes through the account deletion lifecycle and does not revert" doperiod = Period.last_30_daysdiff --git a/test/models/balance_sheet/net_worth_series_builder_test.rb b/test/models/balance_sheet/net_worth_series_builder_test.rbindex 2f53df7441..e7c40b068c 100644--- a/test/models/balance_sheet/net_worth_series_builder_test.rb+++ b/test/models/balance_sheet/net_worth_series_builder_test.rb@@ -18,6 +18,20 @@ class BalanceSheet::NetWorthSeriesBuilderTest < ActiveSupport::TestCaseassert_not_equal before, afterend+ # An account with no rate is left out of the series. A rate stored later,+ # by the market data import or a provider lookup on the balance sheet,+ # must reach the chart as it reaches the totals beside it.+ test "cache key changes when an exchange rate is stored" do+ period = Period.last_30_days+ before = BalanceSheet::NetWorthSeriesBuilder.new(@family).send(:cache_key, period)+ travel 1.second do+ ExchangeRate.create!(from_currency: "KRW", to_currency: @family.currency, date: Date.current, rate: 0.00075)+ end+ after = BalanceSheet::NetWorthSeriesBuilder.new(@family.reload).send(:cache_key, period)++ assert_not_equal before, after+ end+test "net worth series cache key changes through the account deletion lifecycle and does not revert" doperiod = Period.last_30_daysdiff --git a/test/models/balance_sheet_test.rb b/test/models/balance_sheet_test.rbindex 7f188e19c1..1cc7ebeda6 100644--- a/test/models/balance_sheet_test.rb+++ b/test/models/balance_sheet_test.rb@@ -36,6 +36,25 @@ class BalanceSheetTest < ActiveSupport::TestCaseassert_equal 50000 - 1000, BalanceSheet.new(@family).net_worthend+ # Counted at 1, ¥1,000,000 added $1,000,000 to net worth (#3640).+ test "an account in a currency with no rate at all is left out of totals" do+ ExchangeRate.stubs(:provider).returns(nil)+ create_account(balance: 50000, accountable: Depository.new)+ create_account(balance: 1_000_000, currency: "JPY", accountable: Depository.new)++ assert_equal 50000, BalanceSheet.new(@family).net_worth+ assert_equal 50000, BalanceSheet.new(@family).assets.total+ end++ test "an account converts at the latest stored rate however old" do+ ExchangeRate.stubs(:provider).returns(nil)+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 60.days.ago.to_date, rate: 0.007)+ create_account(balance: 50000, accountable: Depository.new)+ create_account(balance: 1_000_000, currency: "JPY", accountable: Depository.new)++ assert_equal 57000, BalanceSheet.new(@family).net_worth+ end+test "disabled accounts do not affect totals" docreate_account(balance: 1000, accountable: CreditCard.new)create_account(balance: 10000, accountable: Depository.new)diff --git a/test/models/exchange_rate_test.rb b/test/models/exchange_rate_test.rbindex 3c3ac66a28..b41f309897 100644--- a/test/models/exchange_rate_test.rb+++ b/test/models/exchange_rate_test.rb@@ -82,6 +82,145 @@ class ExchangeRateTest < ActiveSupport::TestCaseassert_equal friday, result.dateend+ # A pair with no rate anywhere -- not stored, not within the lookback, not+ # from the provider -- is left out. It used to come back as 1, which every+ # caller read as parity: a ¥1,000,000 gain reported as $1,000,000 (#3640).+ test "rates_for leaves out a currency it has no rate for, rather than returning 1" do+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.08)+ ExchangeRate.where(from_currency: "JPY", to_currency: "USD").delete_all++ @provider.expects(:fetch_exchange_rate)+ .with(from: "JPY", to: "USD", date: Date.current)+ .returns(provider_error_response(StandardError.new("no rate")))++ rates = ExchangeRate.rates_for(%w[EUR JPY], to: "USD", date: Date.current)++ assert_equal({ "EUR" => 1.08 }, rates.transform_values(&:to_f))+ assert_not rates.key?("JPY")+ end++ # Outside the 5-day lookback and with nothing from the provider, the last+ # stored rate is still a better answer than 1.+ test "rates_for falls back to the latest stored rate however old" do+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 90.days.ago.to_date, rate: 0.0067)+ @provider.expects(:fetch_exchange_rate).returns(provider_error_response(StandardError.new("no rate")))++ assert_equal 0.0067, ExchangeRate.rates_for(%w[JPY], to: "USD", date: Date.current)["JPY"].to_f+ end++ # A date before the pair's first stored rate takes that first rate, as the+ # balance chart already does.+ test "rates_for falls back to the earliest later rate when there is none before" do+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 10.days.ago.to_date, rate: 0.0068)+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 5.days.ago.to_date, rate: 0.0069)+ @provider.expects(:fetch_exchange_rate).returns(provider_error_response(StandardError.new("no rate")))++ assert_equal 0.0068, ExchangeRate.rates_for(%w[JPY], to: "USD", date: 30.days.ago.to_date)["JPY"].to_f+ end++ test "rate_sql is 1 for the same currency, the latest earlier rate, else the earliest later, else NULL" do+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 10.days.ago.to_date, rate: 0.0068)+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 5.days.ago.to_date, rate: 0.0069)++ rate_on = ->(from, on) {+ sql = ExchangeRate.rate_sql(from: ":from", to: ":to", on: "CAST(:on AS date)")+ ActiveRecord::Base.connection.select_value(+ ActiveRecord::Base.sanitize_sql_array([ "SELECT #{sql}", { from: from, to: "USD", on: on } ])+ )&.to_d+ }++ assert_equal 1, rate_on.call("USD", Date.current)+ assert_equal BigDecimal("0.0069"), rate_on.call("JPY", Date.current)+ assert_equal BigDecimal("0.0068"), rate_on.call("JPY", 7.days.ago.to_date)+ assert_equal BigDecimal("0.0068"), rate_on.call("JPY", 30.days.ago.to_date)+ assert_nil rate_on.call("KRW", Date.current)+ end++ test "currencies_without_rate names the currencies with no stored rate on any date" do+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 400.days.ago.to_date, rate: 0.009)++ assert_equal %w[KRW], ExchangeRate.currencies_without_rate(%w[USD JPY KRW KRW] + [ nil ], to: "USD")+ end++ # Older than the lookback rates_for treats as current: today's figures use+ # a rate from some other day. Within it (a weekend, a holiday) is current.+ test "stale_rate_dates names currencies whose newest rate is older than the lookback" do+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 30.days.ago.to_date, rate: 0.0067)+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: ExchangeRate::NEAREST_RATE_LOOKBACK_DAYS.days.ago.to_date, rate: 0.73)+ ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: 40.days.ago.to_date, rate: 0.71)++ stale = ExchangeRate.stale_rate_dates(%w[USD JPY CAD KRW], to: "USD")++ assert_equal({ "JPY" => 30.days.ago.to_date }, stale, "CAD is current, KRW has no rate at all, USD needs none")+ end++ # Today converts at the latest rate on or before today, so a future-dated row+ # must not hide that the rate in use is old. A currency with only future rows+ # has no older rate to name and stays out, as before.+ test "stale_rate_dates ignores rates dated after as_of" do+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 30.days.ago.to_date, rate: 0.0067)+ ExchangeRate.create!(from_currency: "JPY", to_currency: "USD", date: 3.days.from_now.to_date, rate: 0.0068)+ ExchangeRate.create!(from_currency: "CHF", to_currency: "USD", date: 3.days.from_now.to_date, rate: 1.1)++ sql = ExchangeRate.rate_sql(from: "'JPY'", to: "'USD'", on: "CURRENT_DATE")+ assert_equal BigDecimal("0.0067"), ActiveRecord::Base.connection.select_value("SELECT #{sql}").to_d++ assert_equal({ "JPY" => 30.days.ago.to_date }, ExchangeRate.stale_rate_dates(%w[JPY CHF], to: "USD"))+ end++ # The read-back after a lost insert race only answers with a usable row;+ # otherwise the provider's rate stands. The table rejects a 0 since #3790,+ # so the unusable row is built in memory rather than stored.+ test "find_or_fetch_rate returns the provider's rate when a racing writer saved an unusable one" do+ @provider.expects(:fetch_exchange_rate).returns(+ provider_success_response(OpenStruct.new(from: "JPY", to: "USD", date: Date.current, rate: 0.0067))+ )+ ExchangeRate.stubs(:find_or_create_by!).raises(ActiveRecord::RecordNotUnique)+ ExchangeRate.stubs(:find_by!).returns(ExchangeRate.new(from_currency: "JPY", to_currency: "USD", date: Date.current, rate: 0))++ assert_equal 0.0067, ExchangeRate.find_or_fetch_rate(from: "JPY", to: "USD").rate.to_f+ end++ # Replacing an unusable row is best-effort: a failed write leaves the+ # provider's rate as the answer, not the row it could not replace. Built in+ # memory, as above.+ test "find_or_fetch_rate returns the provider's rate when replacing an unusable row fails" do+ @provider.expects(:fetch_exchange_rate).returns(+ provider_success_response(OpenStruct.new(from: "JPY", to: "USD", date: Date.current, rate: 0.0067))+ )+ ExchangeRate.stubs(:find_or_create_by!).returns(ExchangeRate.new(from_currency: "JPY", to_currency: "USD", date: Date.current, rate: 0))+ ExchangeRate.any_instance.stubs(:update!).raises(ActiveRecord::RecordInvalid.new(ExchangeRate.new))++ assert_equal 0.0067, ExchangeRate.find_or_fetch_rate(from: "JPY", to: "USD").rate.to_f+ end++ # rate_sql and currencies_without_rate read only stored rows, so a provider+ # rate that never reached the table must not count in rates_for either, or a+ # Ruby total includes an amount the SQL totals and the notice leave out.+ # Once it is stored, it counts.+ test "rates_for leaves out a provider rate it could not store" do+ @provider.stubs(:fetch_exchange_rate).returns(+ provider_success_response(OpenStruct.new(from: "JPY", to: "USD", date: Date.current, rate: 0.0067))+ )+ ExchangeRate.stubs(:find_or_create_by!).returns(ExchangeRate.new(from_currency: "JPY", to_currency: "USD", date: Date.current, rate: 0))+ ExchangeRate.any_instance.stubs(:update!).raises(ActiveRecord::RecordInvalid.new(ExchangeRate.new))++ assert_equal({}, ExchangeRate.rates_for(%w[JPY], to: "USD"))+ assert_equal %w[JPY], ExchangeRate.currencies_without_rate(%w[JPY], to: "USD")++ ExchangeRate.unstub(:find_or_create_by!)+ ExchangeRate.any_instance.unstub(:update!)++ assert_equal({ "JPY" => 0.0067 }, ExchangeRate.rates_for(%w[JPY], to: "USD").transform_values(&:to_f))+ assert_empty ExchangeRate.currencies_without_rate(%w[JPY], to: "USD")+ end++ test "rates_for converts the target currency itself at 1" do+ @provider.expects(:fetch_exchange_rate).never++ assert_equal({ "USD" => 1 }, ExchangeRate.rates_for(%w[USD], to: "USD"))+ end+test "does not reuse cached rate outside lookback window" doold_date = (ExchangeRate::NEAREST_RATE_LOOKBACK_DAYS + 1).days.ago.to_dateExchangeRate.create!(from_currency: "USD", to_currency: "JPY", date: old_date, rate: 140.0)diff --git a/test/models/family_test.rb b/test/models/family_test.rbindex f255d9cedd..a59ef11ff4 100644--- a/test/models/family_test.rb+++ b/test/models/family_test.rb@@ -815,6 +815,81 @@ class FamilyTest < ActiveSupport::TestCaseassert_raises(ArgumentError) { family.resolved_categorization_provider }end+ # The currencies whose amounts every converted total leaves out (#3640).+ test "currencies_without_exchange_rate names used currencies with no rate on any date" do+ family = families(:empty)+ family.accounts.create!(name: "JPY", balance: 1, currency: "JPY", accountable: Depository.new)+ family.accounts.create!(name: "KRW", balance: 1, currency: "KRW", accountable: Depository.new)+ family.accounts.create!(name: "Home", balance: 1, currency: family.currency, accountable: Depository.new)+ ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 400.days.ago.to_date, rate: 0.009)++ assert_equal %w[KRW], family.currencies_without_exchange_rate+ end++ test "stale_exchange_rate_dates names used currencies whose newest rate is out of date" do+ family = families(:empty)+ family.accounts.create!(name: "JPY", balance: 1, currency: "JPY", accountable: Depository.new)+ family.accounts.create!(name: "CAD", balance: 1, currency: "CAD", accountable: Depository.new)+ ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 30.days.ago.to_date, rate: 0.0067)+ ExchangeRate.create!(from_currency: "CAD", to_currency: family.currency, date: Date.current, rate: 0.73)++ assert_equal({ "JPY" => 30.days.ago.to_date }, family.stale_exchange_rate_dates)+ end++ # The stale note says today's totals use the old rate, so it names only+ # currencies today's totals convert: account balances and current holdings.+ # A trip's yen spending from long ago still has an old newest rate, but+ # nothing converts it today.+ test "stale_exchange_rate_dates ignores a currency only old entries use" do+ family = families(:empty)+ home = family.accounts.create!(name: "Home", balance: 1, currency: family.currency, accountable: Depository.new)+ home.entries.create!(name: "Tokyo dinner", date: 400.days.ago.to_date, amount: 5_000, currency: "JPY",+ entryable: Transaction.new)+ ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 400.days.ago.to_date, rate: 0.0067)++ assert_empty family.stale_exchange_rate_dates+ end++ test "stale_exchange_rate_dates names the currency of a current holding" do+ family = families(:empty)+ account = family.accounts.create!(name: "Brokerage", balance: 1, currency: family.currency, accountable: Investment.new)+ security = Security.create!(ticker: "JPH#{SecureRandom.hex(2)}", name: "Tokyo Listed")+ account.holdings.create!(security: security, date: Date.current, qty: 1, price: 1_000, amount: 1_000, currency: "JPY")+ ExchangeRate.create!(from_currency: "JPY", to_currency: family.currency, date: 30.days.ago.to_date, rate: 0.0067)++ assert_equal({ "JPY" => 30.days.ago.to_date }, family.stale_exchange_rate_dates)+ end++ # A trade can be priced in a currency neither its entry nor its account+ # uses, and holding cost converts that currency.+ test "currencies_without_exchange_rate includes currencies only a trade uses" do+ family = families(:empty)+ account = family.accounts.create!(name: "Brokerage", balance: 1, currency: family.currency, accountable: Investment.new)+ security = Security.create!(ticker: "SEK#{SecureRandom.hex(2)}", name: "Stockholm Listed")+ account.entries.create!(name: "Buy", date: Date.current, amount: 100, currency: family.currency,+ entryable: Trade.new(security: security, qty: 1, price: 1000, currency: "SEK"))++ assert_equal %w[SEK], family.currencies_without_exchange_rate+ end++ test "a disabled account's currency is not named" do+ family = families(:empty)+ family.accounts.create!(name: "Old KRW", balance: 1, currency: "KRW", accountable: Depository.new, status: "disabled")++ assert_empty family.currencies_without_exchange_rate+ end++ # The pages pass the viewer's accounts, so a member is not told about an+ # account they cannot see, and the note matches the totals they get.+ test "currencies_without_exchange_rate names only the given accounts' currencies" do+ family = families(:empty)+ home = family.accounts.create!(name: "Home", balance: 1, currency: family.currency, accountable: Depository.new)+ family.accounts.create!(name: "KRW", balance: 1, currency: "KRW", accountable: Depository.new)++ assert_equal %w[KRW], family.currencies_without_exchange_rate+ assert_empty family.currencies_without_exchange_rate(accounts: family.accounts.where(id: home.id))+ end+test "earliest_activity_date ignores valuations, using earliest Transaction/Trade entry" dofamily = families(:empty)account = family.accounts.create!(name: "Checking", balance: 0, currency: "USD", accountable: Depository.new)diff --git a/test/models/income_statement/daily_expense_totals_test.rb b/test/models/income_statement/daily_expense_totals_test.rbindex 270b053a61..940ba64c99 100644--- a/test/models/income_statement/daily_expense_totals_test.rb+++ b/test/models/income_statement/daily_expense_totals_test.rb@@ -59,12 +59,23 @@ class IncomeStatement::DailyExpenseTotalsTest < ActiveSupport::TestCaseassert_equal 200, daily_series.first.totalend- test "falls back to no conversion when the day's rate is missing" do+ test "uses the latest earlier rate when the day's rate is missing" doeur_account = @family.accounts.create! name: "EUR Checking", currency: "EUR", balance: 1000, accountable: Depository.new+ ExchangeRate.create! from_currency: "EUR", to_currency: @family.currency, date: 30.days.ago.to_date, rate: 2create_transaction(account: eur_account, amount: 100, currency: "EUR", date: Date.current)- assert_equal 100, daily_series.first.total+ assert_equal 200, daily_series.first.total+ end++ # Counted at 1 it read as 100 (#3640).+ test "leaves out an expense in a currency with no rate at all" do+ eur_account = @family.accounts.create! name: "EUR Checking", currency: "EUR", balance: 1000, accountable: Depository.new++ create_transaction(account: eur_account, amount: 100, currency: "EUR", date: Date.current)+ create_transaction(account: @checking, amount: 10, date: Date.current)++ assert_equal 10, daily_series.first.totalendtest "returns days in chronological order" dodiff --git a/test/models/income_statement/scoped_transactions_query_equivalence_test.rb b/test/models/income_statement/scoped_transactions_query_equivalence_test.rbindex dd34643cab..571ed9e6c1 100644--- a/test/models/income_statement/scoped_transactions_query_equivalence_test.rb+++ b/test/models/income_statement/scoped_transactions_query_equivalence_test.rb@@ -40,7 +40,10 @@ class IncomeStatement::ScopedTransactionsQueryEquivalenceTest < ActiveSupport::TExchangeRate.create! from_currency: "EUR", to_currency: "USD", date: 5.days.ago.to_date, rate: 2create_transaction(account: @eur, amount: 40, currency: "EUR", date: 5.days.ago.to_date)- create_transaction(account: @eur, amount: 10, currency: "EUR", date: 10.days.ago.to_date) # no rate row, falls back to 1+ # Its own rate, so the legacy copy (no rate: 1) and the current rule (no+ # rate that day: the nearest stored one) convert it the same way.+ ExchangeRate.create! from_currency: "EUR", to_currency: "USD", date: 10.days.ago.to_date, rate: 1.5+ create_transaction(account: @eur, amount: 10, currency: "EUR", date: 10.days.ago.to_date)create_transaction(account: @retirement, amount: 300, date: 5.days.ago.to_date) # tax-advantaged, excludedcreate_transaction(account: @unreported, amount: 45, date: 5.days.ago.to_date) # exclude_from_reports, excludeddiff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex 44cb2f4cca..2490a4fec8 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -372,6 +372,23 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal 600.0, income_statement.avg_expense(interval: "month")end+ # A month whose only expense has no exchange rate at all has no measurable+ # spending, which is not the same as spending nothing. Counted as 0 it pulled+ # the average and the median down to 50.+ test "a month with nothing convertible is skipped by the average and median" do+ Entry.joins(:account).where(accounts: { family_id: @family.id }).destroy_all+ krw_account = @family.accounts.create! name: "KRW Checking", currency: "KRW", balance: 0, accountable: Depository.new++ create_transaction(account: @checking_account, amount: 100, category: @groceries_category, date: Date.current.beginning_of_month)+ create_transaction(account: krw_account, amount: 130_000, currency: "KRW", category: @groceries_category,+ date: Date.current.beginning_of_month.prev_month)++ income_statement = IncomeStatement.new(@family)+ assert_equal 100.0, income_statement.avg_expense(interval: "month")+ assert_equal 100.0, income_statement.median_expense(interval: "month")+ assert_equal 100.0, income_statement.avg_expense(interval: "month", category: @groceries_category)+ end+test "calculates category-specific median expense" do# Clear existing transactions by deleting entriesEntry.joins(:account).where(accounts: { family_id: @family.id }).destroy_alldiff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rbindex 45dfee7d5b..2431182f30 100644--- a/test/models/investment_statement_test.rb+++ b/test/models/investment_statement_test.rb@@ -34,12 +34,22 @@ class InvestmentStatementTest < ActiveSupport::TestCaseassert_in_delta 2083.92, @statement.holdings_value, 0.001end- test "portfolio_value falls back to 1:1 when FX rate is missing" do+ # At 1 the EUR account added 1,000 and portfolio_value read 2,921.92 (#3640).+ test "portfolio_value leaves out an account in a currency with no rate at all" do+ ExchangeRate.stubs(:provider).returns(nil)create_investment_account(balance: 1921.92, currency: "USD")create_investment_account(balance: 1000, currency: "EUR")- # No ExchangeRate row → rates_for defaults to 1- assert_in_delta 2921.92, @statement.portfolio_value, 0.001+ assert_in_delta 1921.92, @statement.portfolio_value, 0.001+ end++ test "portfolio_value uses the latest stored rate however old" do+ ExchangeRate.stubs(:provider).returns(nil)+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: 60.days.ago.to_date, rate: 1.1)+ create_investment_account(balance: 1921.92, currency: "USD")+ create_investment_account(balance: 1000, currency: "EUR")++ assert_in_delta 3021.92, @statement.portfolio_value, 0.001endtest "current_holdings includes holdings from every investment account regardless of currency" do@@ -462,6 +472,21 @@ class InvestmentStatementTest < ActiveSupport::TestCaseassert_equal 0, totals.trades_countend+ # A buy in a currency with no rate is not a $1-per-unit contribution (#3640).+ test "totals leave out a trade in a currency with no rate at all" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ usd_account = create_investment_account(balance: 500)+ krw_account = create_investment_account(balance: 500_000, currency: "KRW")++ create_trade(account: usd_account, qty: 2, amount: 120, date: period.start_date)+ create_trade(account: krw_account, qty: 1, amount: 500_000, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(120, "USD"), totals.contributions+ assert_equal 2, totals.trades_count+ end+test "totals aggregate directly from trade entries" do# Use the full current month: a month-to-date period collapses to a single# day on the 1st, which would drop the start_date + 1.day trade below.@@ -597,6 +622,36 @@ class InvestmentStatementTest < ActiveSupport::TestCaseassert_equal Money.new(110, "USD"), totals.dividendsend+ # Income follows the same rule as contributions (#3640): no rate at all+ # leaves the amount out rather than counting it at 1.+ test "a dividend in a currency with no rate is left out of investment income, not counted at 1" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ usd_account = create_investment_account(balance: 500)+ krw_account = create_investment_account(balance: 500_000, currency: "KRW")++ create_income_trade(account: usd_account, label: "Dividend", amount: 50, date: period.start_date)+ create_income_trade(account: usd_account, label: "Interest", amount: 5, date: period.start_date)+ create_income_trade(account: krw_account, label: "Dividend", amount: 100_000, date: period.start_date)+ create_income_transaction(account: krw_account, label: "Interest", amount: 20_000, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(50, "USD"), totals.dividends+ assert_equal Money.new(5, "USD"), totals.interest+ end++ test "a dividend with no rate on its day uses the nearest stored rate" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 500, currency: "EUR")+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: period.start_date - 60.days, rate: 1.2)++ create_income_trade(account: account, label: "Dividend", amount: 100, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(120, "USD"), totals.dividends+ end+test "total_dividends and total_interest expose all-time income" doaccount = create_investment_account(balance: 500)@@ -738,6 +793,20 @@ class InvestmentStatementTest < ActiveSupport::TestCaseInvestmentStatement.new(@family.reload).totals(period: period)end+ test "totals cache invalidates when an exchange rate is stored" do+ create_investment_account(balance: 500)+ period = Period.last_30_days++ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ dummy_result = { contributions: 0, withdrawals: 0, dividends: 0, interest: 0, trades_count: 0 }+ InvestmentStatement::Totals.expects(:new).twice.returns(stub(call: dummy_result))++ InvestmentStatement.new(@family).totals(period: period)++ ExchangeRate.create!(from_currency: "KRW", to_currency: "USD", date: Date.current, rate: 0.00075)+ InvestmentStatement.new(@family.reload).totals(period: period)+ end+# Two parcels of one security, materialised the way a sync does: 60 bought on# 2024-01-10 at $12 and 40 on 2024-03-05 at $20 (blended $15.20), then 40 sold# on 2024-06-01 at $25 and priced at $30 the day after. Average cost relievesdiff --git a/test/models/trade_test.rb b/test/models/trade_test.rbindex cdffb1a812..c74613ea6d 100644--- a/test/models/trade_test.rb+++ b/test/models/trade_test.rb@@ -56,6 +56,17 @@ class TradeTest < ActiveSupport::TestCasesell = cross_currency_disposal(rate: 1.5, rate_date: Date.new(2026, 3, 9))assert_nil sell.realized_gain_loss, "a neighbouring day's rate is not this day's"+ assert sell.realized_gain_unconvertible?+ end++ # No rate on any date means the gain is unknown, not zero and not the figure+ # a rate of 1.0 would produce, and the caller can tell why.+ test "a cross-currency disposal with no rate at all has no figure and says why" do+ sell = cross_currency_disposal(rate: 1.5)+ ExchangeRate.where(from_currency: "EUR", to_currency: "USD").delete_all++ assert_nil sell.realized_gain_loss+ assert sell.realized_gain_unconvertible?end# `exchange_rates` no longer stores a 0 or a negative, but the conversiondiff --git a/test/models/transaction/search_test.rb b/test/models/transaction/search_test.rbindex 6f4a749021..3211cd6676 100644--- a/test/models/transaction/search_test.rb+++ b/test/models/transaction/search_test.rb@@ -464,9 +464,10 @@ class Transaction::SearchTest < ActiveSupport::TestCasesearch = Transaction::Search.new(@family)totals = search.totals+ # Still counted as a transaction, but its amount is left out of the+ # totals: at 1 it read as $100 (#3640).assert_equal 1, totals.count- # Should use rate of 1 when exchange rate is missing- assert_equal Money.new(100, "USD"), totals.expense_money # EUR 100 * 1+ assert_equal Money.new(0, "USD"), totals.expense_moneyassert_equal Money.new(0, "USD"), totals.income_moneyend@@ -518,6 +519,22 @@ class Transaction::SearchTest < ActiveSupport::TestCaseassert_equal "EUR", totals_eur.expense_money.currency.iso_codeend+ # An amount with no rate is left out of the totals. A rate stored after the+ # first render must reach them, or the totals stay short once the+ # missing-rate notice has gone.+ test "totals include an amount once its rate is stored after the first render" do+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ krw = @family.accounts.create!(name: "Seoul", balance: 0, currency: "KRW", accountable: Depository.new)+ create_transaction(account: krw, amount: 130_000, currency: "KRW", category: categories(:food_and_drink), kind: "standard")++ before = Transaction::Search.new(@family, filters: {}).totals.expense_money++ ExchangeRate.create!(from_currency: "KRW", to_currency: "USD", date: Date.current, rate: 0.00075)+ after = Transaction::Search.new(@family.reload, filters: {}).totals.expense_money++ assert_equal Money.new(97.5, "USD"), after - before, "the KRW expense at its new rate"+ end+test "totals is served from cache when nothing has changed" docache = ActiveSupport::Cache::MemoryStore.newRails.stubs(:cache).returns(cache)@@ -530,7 +547,7 @@ class Transaction::SearchTest < ActiveSupport::TestCasekey2 = search2.cache_key_baseassert_equal key1, key2- assert_not_nil cache.read("transaction_search_totals/v4/#{key2}")+ assert_not_nil cache.read("transaction_search_totals/v4/#{ExchangeRate::CONVERSION_CACHE_VERSION}/#{key2}")assert_equal result1, search2.totalsend