Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Stop Money from silently mixing currencies (#4219)

GFRe1b3f4231744
diff --git a/config/initializers/money.rb b/config/initializers/money.rb
new file mode 100644
index 0000000000..5c1bc54018
--- /dev/null
+++ b/config/initializers/money.rb
@@ -0,0 +1,6 @@
+# Mixing currencies in Money arithmetic raises in development and test, so new
+# code that forgets a conversion fails loudly there. Production reports it
+# instead (see Money#ensure_same_currency!).
+Rails.application.config.to_prepare do
+ Money.strict_currency = Rails.env.local?
+end
diff --git a/docs/llm-guides/architecture.md b/docs/llm-guides/architecture.md
index e2c82188b8..00a65808c6 100644
--- a/docs/llm-guides/architecture.md
+++ b/docs/llm-guides/architecture.md
@@ -40,7 +40,12 @@ preferred currency is used to normalize reports; it does not mean every stored
amount is already in that currency. [Money](../../lib/money.rb) handles monetary
operations and formatting, with [ExchangeRate](../../app/models/exchange_rate.rb)
and its [Provided concern](../../app/models/exchange_rate/provided.rb) supplying
-dated conversion rates.
+dated conversion rates. `Money` never converts on its own: adding, subtracting,
+dividing or ordering two amounts in different currencies raises
+`Money::CurrencyMismatchError` in development and test (production reports it
+and keeps the old result). Convert with `exchange_to(currency, date:)` first,
+at the date that fits the figure. Mixed-currency paths are covered in
+[test/integration/mixed_currency_test.rb](../../test/integration/mixed_currency_test.rb).
## Accounts, balances and entries
diff --git a/lib/money.rb b/lib/money.rb
index 3d0384a499..b8bb23fafa 100644
--- a/lib/money.rb
+++ b/lib/money.rb
@@ -14,6 +14,24 @@ class Money
end
end
+ # Raised (strict mode) or reported (otherwise) when an operation combines
+ # two amounts in different currencies. The operators can't convert: they
+ # don't know which date the rate is for, and that differs per caller (trade
+ # date, price date, today). Callers convert with `exchange_to` first.
+ class CurrencyMismatchError < StandardError
+ attr_reader :left_currency, :right_currency, :operation
+
+ def initialize(left_currency:, right_currency:, operation:)
+ @left_currency = left_currency
+ @right_currency = right_currency
+ @operation = operation
+
+ super("Can't apply #{operation} to #{left_currency} and #{right_currency} amounts; convert one with exchange_to first")
+ end
+ end
+
+ REPORTED_MISMATCHES_LIMIT = 500
+
attr_reader :amount, :currency, :store
validate :source_must_be_of_known_type
@@ -26,6 +44,30 @@ class Money
def default_currency=(object)
@default = Money::Currency.new(object)
end
+
+ # On in development and test (config/initializers/money.rb): mixing
+ # currencies raises. Off in production: the mismatch is reported and the
+ # operation keeps its legacy result, so a page that shows a wrong figure
+ # today doesn't start failing.
+ attr_writer :strict_currency
+
+ def strict_currency?
+ @strict_currency == true
+ end
+
+ # Once the memory is full it starts over instead of going quiet, so a
+ # long-running process still reports new call sites (known ones may be
+ # reported once more).
+ def first_mismatch_report?(key)
+ @reported_mismatches ||= Concurrent::Set.new
+ @reported_mismatches.clear if @reported_mismatches.size >= REPORTED_MISMATCHES_LIMIT
+
+ !@reported_mismatches.add?(key).nil?
+ end
+
+ def reset_reported_mismatches!
+ @reported_mismatches = nil
+ end
end
def initialize(obj, currency = Money.default_currency, store: ExchangeRate)
@@ -75,12 +117,21 @@ class Money
{ amount: amount, currency: currency.iso_code, formatted: format }.as_json
end
+ # Amounts in different currencies are simply not equal; only ordering them
+ # (<, >, <=>) needs a conversion.
+ def ==(other)
+ return false if other.is_a?(Money) && currency != other.currency
+
+ super
+ end
+
def <=>(other)
raise TypeError, "Money can only be compared with other Money objects except for 0" unless other.is_a?(Money) || other.eql?(0)
if other.is_a?(Numeric)
amount <=> other
else
+ ensure_same_currency!(other, :<=>)
amount_comparison = amount <=> other.amount
if amount_comparison == 0
@@ -92,6 +143,21 @@ class Money
end
private
+ def ensure_same_currency!(other, operation)
+ return if currency == other.currency
+
+ error = CurrencyMismatchError.new(left_currency: currency.iso_code, right_currency: other.currency.iso_code, operation: operation)
+ raise error if self.class.strict_currency?
+
+ # Once per call site and process: a sort or a long sync would otherwise
+ # report the same mismatch thousands of times.
+ call_site = caller_locations(2, 1).first&.to_s
+ return unless self.class.first_mismatch_report?([ operation, error.left_currency, error.right_currency, call_site ])
+
+ Rails.error.report(error, handled: true, severity: :warning, source: "money", context: { call_site: call_site })
+ Rails.logger.warn("[Money] #{error.message} (#{call_site})")
+ end
+
def source_must_be_of_known_type
unless @source.is_a?(Money) || @source.is_a?(Numeric) || @source.is_a?(BigDecimal)
errors.add :source, "must be a Money, Numeric, or BigDecimal"
diff --git a/lib/money/arithmetic.rb b/lib/money/arithmetic.rb
index 03183e41a4..bb287db85d 100644
--- a/lib/money/arithmetic.rb
+++ b/lib/money/arithmetic.rb
@@ -3,6 +3,7 @@ module Money::Arithmetic
def +(other)
if other.is_a?(Money)
+ ensure_same_currency!(other, :+)
self.class.new(amount + other.amount, currency)
else
value = other.is_a?(CoercedNumeric) ? other.value : other
@@ -12,6 +13,7 @@ module Money::Arithmetic
def -(other)
if other.is_a?(Money)
+ ensure_same_currency!(other, :-)
self.class.new(amount - other.amount, currency)
else
value = other.is_a?(CoercedNumeric) ? other.value : other
@@ -31,6 +33,7 @@ module Money::Arithmetic
def /(other)
if other.is_a?(self.class)
+ ensure_same_currency!(other, :/)
amount / other.amount
else
raise TypeError, "can't divide Numeric by Money" if other.is_a?(CoercedNumeric)
diff --git a/test/integration/mixed_currency_test.rb b/test/integration/mixed_currency_test.rb
new file mode 100644
index 0000000000..2b04dcabf9
--- /dev/null
+++ b/test/integration/mixed_currency_test.rb
@@ -0,0 +1,128 @@
+require "test_helper"
+
+# Every other fixture is USD, so the suite never combines two currencies and
+# Money's currency guard would find nothing. This family mixes three: EUR
+# family currency, a EUR and a GBP account next to USD ones, and a security
+# priced in EUR. Each path below must convert before it adds, subtracts or
+# compares.
+#
+# Strict mode is off here on purpose: syncs and insight generators rescue
+# errors broadly, which would swallow a raised mismatch. In report mode every
+# mismatch reaches Rails.error, so the tests assert that none was reported.
+class MixedCurrencyTest < ActionDispatch::IntegrationTest
+ setup do
+ @strict_currency = Money.strict_currency?
+ Money.strict_currency = false
+ Money.reset_reported_mismatches!
+
+ @user = users(:family_admin)
+ @family = @user.family
+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
+
+ @family.update!(currency: "EUR")
+ switch_currency(accounts(:depository), "EUR")
+ switch_currency(accounts(:credit_card), "GBP")
+ Security::Price.where(security: securities(:aapl)).update_all(currency: "EUR")
+
+ rates = { %w[USD EUR] => 0.9, %w[EUR USD] => 1.1, %w[GBP EUR] => 1.2, %w[EUR GBP] => 0.83, %w[USD GBP] => 0.75, %w[GBP USD] => 1.3 }
+ rows = ((Date.current - 2.years)..Date.current).flat_map do |date|
+ rates.map { |(from, to), rate| { from_currency: from, to_currency: to, date: date, rate: rate } }
+ end
+ ExchangeRate.upsert_all(rows, unique_by: %i[from_currency to_currency date])
+ end
+
+ teardown do
+ Money.strict_currency = @strict_currency
+ Money.reset_reported_mismatches!
+ end
+
+ test "syncs, transfer matching and insights convert before combining amounts" do
+ assert_no_currency_mismatch do
+ @family.accounts.each do |account|
+ syncer = Account::Syncer.new(account)
+ syncer.perform_sync(Sync.create!(syncable: account))
+ syncer.perform_post_sync
+ end
+ @family.auto_match_transfers!
+
+ Insight::GeneratorRegistry::GENERATORS.each do |generator|
+ generator.new(@family).generate
+ end
+ end
+ end
+
+ test "assistant read functions convert before combining amounts" do
+ calls = {
+ Assistant::Function::GetAccounts => { "include_balance_series" => true },
+ Assistant::Function::GetBalanceSheet => {},
+ Assistant::Function::GetHoldings => { "page" => 1 },
+ Assistant::Function::GetIncomeStatement => { "start_date" => 1.year.ago.to_date.iso8601, "end_date" => Date.current.iso8601 },
+ Assistant::Function::GetTransactions => {},
+ Assistant::Function::GetBudget => {},
+ Assistant::Function::GetInsights => {},
+ Assistant::Function::GetRecurringTransactions => {},
+ Assistant::Function::GetValuations => {},
+ Assistant::Function::GetBills => {}
+ }
+
+ assert_no_currency_mismatch do
+ calls.each do |function, params|
+ result = function.new(@user).call(params)
+ assert_not result.is_a?(Hash) && result.with_indifferent_access[:error].present?, "#{function.name.demodulize} returned an error"
+ end
+ end
+ end
+
+ test "pages convert before combining amounts" do
+ sign_in @user
+
+ # The trade page is left out: its unrealized gain still subtracts a cost
+ # basis in the trade's currency from a price in the security's. That
+ # call site is fixed in a separate change.
+ paths = %w[/ /accounts /transactions /reports /reports?period_type=quarterly /plan /goals /bills /insights /recurring_transactions]
+ paths << budget_path(Budget.date_to_param(Date.current))
+ paths += @family.accounts.map { |account| account_path(account) }
+ paths += Holding.where(account: @family.accounts).map { |holding| holding_path(holding) }
+ paths += Entry.where(account: @family.accounts, entryable_type: %w[Transaction Valuation]).map do |entry|
+ entry.entryable_type == "Transaction" ? transaction_path(entry) : valuation_path(entry)
+ end
+ paths += @family.goals.map { |goal| goal_path(goal) }
+
+ assert_no_currency_mismatch do
+ paths.each do |path|
+ get path
+ assert_response :success, "GET #{path}"
+ end
+ end
+ end
+
+ test "API reads convert before combining amounts" do
+ api_key = ApiKey.create!(user: @user, name: "Mixed currency", scopes: [ "read" ], source: "web",
+ display_key: "mixed_currency_#{SecureRandom.hex(8)}")
+
+ assert_no_currency_mismatch do
+ %w[accounts balance_sheet holdings trades transactions insights budgets recurring_transactions balances valuations].each do |resource|
+ get "/api/v1/#{resource}", headers: api_headers(api_key)
+ assert_response :success, "GET /api/v1/#{resource}"
+ end
+ end
+ end
+
+ test "the probe sees a mismatch in report mode" do
+ reports = capture_error_reports(Money::CurrencyMismatchError) { Money.new(200, :usd) - Money.new(180, :eur) }
+
+ assert_equal 1, reports.size, "the probe must be able to see a mismatch, or the tests above prove nothing"
+ end
+
+ private
+ def switch_currency(account, currency)
+ account.update_columns(currency: currency)
+ account.entries.update_all(currency: currency)
+ account.balances.update_all(currency: currency)
+ end
+
+ def assert_no_currency_mismatch(&block)
+ reports = capture_error_reports(Money::CurrencyMismatchError, &block)
+ assert_empty reports.map { |report| "#{report.error.message} at #{report.context[:call_site]}" }
+ end
+end
diff --git a/test/lib/money_test.rb b/test/lib/money_test.rb
index dd217f76cc..d19e41f674 100644
--- a/test/lib/money_test.rb
+++ b/test/lib/money_test.rb
@@ -58,6 +58,57 @@ class MoneyTest < ActiveSupport::TestCase
assert_raise(TypeError) { 1000 / Money.new(2) }
end
+ test "mixing currencies raises in strict mode" do
+ usd = Money.new(200, :usd)
+ eur = Money.new(180, :eur)
+
+ assert Money.strict_currency?, "development and test run in strict mode"
+
+ %i[+ - / <=> > < >= <=].each do |operator|
+ error = assert_raises(Money::CurrencyMismatchError, "#{operator} must not mix currencies") { usd.public_send(operator, eur) }
+ assert_equal "USD", error.left_currency
+ assert_equal "EUR", error.right_currency
+ end
+ end
+
+ test "amounts in different currencies are not equal, without raising" do
+ assert_not_equal Money.new(100, :usd), Money.new(100, :eur)
+ assert_not Money.new(100, :usd) == Money.new(100, :eur)
+ end
+
+ test "same currency and Numeric operands are unaffected by strict mode" do
+ assert_equal Money.new(380, :eur), Money.new(200, :eur) + Money.new(180, :eur)
+ assert_equal Money.new(20, :eur), Money.new(200, :eur) - 180
+ assert_operator Money.new(1, :eur), :>, 0
+ end
+
+ test "outside strict mode a mismatch is reported once per call site and keeps the legacy result" do
+ strict = Money.strict_currency?
+ Money.strict_currency = false
+ Money.reset_reported_mismatches!
+
+ results = []
+ reports = capture_error_reports(Money::CurrencyMismatchError) do
+ 3.times { results << Money.new(200, :usd) - Money.new(180, :eur) }
+ end
+
+ assert_equal [ Money.new(20, :usd) ] * 3, results
+ assert_equal 1, reports.size
+ ensure
+ Money.strict_currency = strict
+ Money.reset_reported_mismatches!
+ end
+
+ test "mismatch reports keep coming once the per-process memory is full" do
+ Money.reset_reported_mismatches!
+ Money::REPORTED_MISMATCHES_LIMIT.times { |i| assert Money.first_mismatch_report?([ :-, "USD", "EUR", "site #{i}" ]) }
+
+ assert Money.first_mismatch_report?([ :-, "USD", "EUR", "a new call site" ]), "a new call site must still be reported"
+ assert_not Money.first_mismatch_report?([ :-, "USD", "EUR", "a new call site" ])
+ ensure
+ Money.reset_reported_mismatches!
+ end
+
test "operator order does not matter" do
assert_equal Money.new(1000) + 1000, 1000 + Money.new(1000)
assert_equal Money.new(1000) - 1000, 1000 - Money.new(1000)