mirror of
https://github.com/maybe-finance/maybe.git
synced 2025-08-05 05:25:24 +02:00
Handle missing exchange rate provider, allow fallback for missing rates (#955)
* Clean up exchange rate logic * Remove stale method
This commit is contained in:
parent
bef335c631
commit
6767aaed1d
20 changed files with 383 additions and 609 deletions
|
@ -1,29 +1,29 @@
|
|||
class ExchangeRate < ApplicationRecord
|
||||
include Provided
|
||||
|
||||
validates :base_currency, :converted_currency, presence: true
|
||||
validates :from_currency, :to_currency, :date, :rate, presence: true
|
||||
|
||||
class << self
|
||||
def find_rate(from:, to:, date:)
|
||||
find_by \
|
||||
base_currency: Money::Currency.new(from).iso_code,
|
||||
converted_currency: Money::Currency.new(to).iso_code,
|
||||
def find_rate(from:, to:, date:, cache: true)
|
||||
result = find_by \
|
||||
from_currency: from,
|
||||
to_currency: to,
|
||||
date: date
|
||||
|
||||
result || fetch_rate_from_provider(from:, to:, date:, cache:)
|
||||
end
|
||||
|
||||
def find_rate_or_fetch(from:, to:, date:)
|
||||
find_rate(from:, to:, date:) || fetch_rate_from_provider(from:, to:, date:)&.tap(&:save!)
|
||||
end
|
||||
def find_rates(from:, to:, start_date:, end_date: Date.current, cache: true)
|
||||
rates = self.where(from_currency: from, to_currency: to, date: start_date..end_date).to_a
|
||||
all_dates = (start_date..end_date).to_a.to_set
|
||||
existing_dates = rates.map(&:date).to_set
|
||||
missing_dates = all_dates - existing_dates
|
||||
|
||||
def get_rates(from, to, dates)
|
||||
where(base_currency: from, converted_currency: to, date: dates).order(:date)
|
||||
end
|
||||
if missing_dates.any?
|
||||
rates += fetch_rates_from_provider(from:, to:, dates: missing_dates, cache:)
|
||||
end
|
||||
|
||||
def convert(value:, from:, to:, date:)
|
||||
rate = ExchangeRate.find_by(base_currency: from, converted_currency: to, date:)
|
||||
raise "Conversion from: #{from} to: #{to} on: #{date} not found" unless rate
|
||||
|
||||
value * rate.rate
|
||||
rates
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue