Skip to content

Commit

Permalink
Fix creating store credit with amount in foreign format
Browse files Browse the repository at this point in the history
The numericality validation in rails cannot handle prices
in non-float based amounts (Ie. 100,00 EUR).

Using `Spree::LocalizedNumber` to convert the amount before validation.
  • Loading branch information
tvdeyen committed May 30, 2022
1 parent 3c72462 commit 7c4c7cd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions core/app/models/spree/store_credit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ class Spree::StoreCredit < Spree::PaymentSource
extend Spree::DisplayMoney
money_methods :amount, :amount_used, :amount_authorized

# Sets this store credit's amount to a new value,
# parsing it as a localized number if the new value is a string.
#
# @param number [String, #to_d] a new amount
def amount=(number)
self[:amount] = Spree::LocalizedNumber.parse(number)
end

def amount_remaining
return 0.0.to_d if invalidated?
amount - amount_used - amount_authorized
Expand Down
32 changes: 32 additions & 0 deletions core/spec/models/spree/store_credit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,38 @@
end
end

describe "#amount=" do
let(:store_credit) { described_class.new(amount: amount) }

context "with an imperial price format" do
let(:amount) { "1,000.50" }

before do
expect(I18n).to receive(:t).with(:'number.currency.format.separator') do
"."
end
end

it "sets the correct amount" do
expect(store_credit.amount).to eq(1000.5)
end
end

context "with an european price format" do
let(:amount) { "1.000,50" }

before do
expect(I18n).to receive(:t).with(:'number.currency.format.separator') do
","
end
end

it "sets the correct amount" do
expect(store_credit.amount).to eq(1000.5)
end
end
end

describe "#amount_remaining" do
context "invalidated" do
before { allow(store_credit).to receive(:invalidated?) { true } }
Expand Down

0 comments on commit 7c4c7cd

Please sign in to comment.