diff --git a/app/models/currency_conversion.rb b/app/models/currency_conversion.rb index 896b1e337..165b98b42 100644 --- a/app/models/currency_conversion.rb +++ b/app/models/currency_conversion.rb @@ -25,4 +25,15 @@ class CurrencyConversion < ApplicationRecord belongs_to :conference validates :rate, numericality: { greater_than: 0 } validates :from_currency, uniqueness: { scope: :to_currency }, on: :create + + def self.convert_currency(conference, amount, from_currency, to_currency) + conversion = conference.currency_conversions.find_by(from_currency: from_currency, to_currency: to_currency) + if conversion + Money.add_rate(from_currency, to_currency, conversion.rate) + amount.exchange_to(to_currency) + else + # If no conversion is found. Should not be possible with the currency design of fixed allowed currencies. + amount + end + end end diff --git a/spec/models/currency_conversion_spec.rb b/spec/models/currency_conversion_spec.rb index 0e012594e..4ce719f1e 100644 --- a/spec/models/currency_conversion_spec.rb +++ b/spec/models/currency_conversion_spec.rb @@ -24,6 +24,7 @@ describe CurrencyConversion do let!(:conference) { create(:conference, title: 'ExampleCon') } + let(:amount) { Money.from_amount(10.00, 'USD') } describe 'validations' do before do @@ -34,4 +35,26 @@ it { is_expected.to validate_uniqueness_of(:from_currency).scoped_to(:to_currency).on(:create) } end + + describe 'convert currency functionality' do + context 'when conversion rate exists' do + before do + conference.currency_conversions << create(:currency_conversion, from_currency: 'USD', to_currency: 'EUR', rate: 0.89) + conference.currency_conversions << create(:currency_conversion, from_currency: 'USD', to_currency: 'GBP', rate: 0.75) + end + + it 'converts currency using existing rate' do + converted_amount = described_class.convert_currency(conference, amount, 'USD', 'EUR') + expect(converted_amount.currency).to eq('EUR') + expect(converted_amount.cents).to eq(890) + end + end + + context 'when conversion rate does not exist' do + it 'returns the original amount if no conversion is found' do + original_amount = described_class.convert_currency(conference, amount, 'USD', 'INR') + expect(original_amount.cents).to eq(1000) + end + end + end end