mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-02-09 23:06:06 +00:00
Refactor voucher: 2 FlatRate voucher
This commit is contained in:
19
app/models/vouchers/flat_rate.rb
Normal file
19
app/models/vouchers/flat_rate.rb
Normal file
@@ -0,0 +1,19 @@
|
||||
# frozen_string_literal: false
|
||||
|
||||
module Vouchers
|
||||
class FlatRate < Voucher
|
||||
validates :amount,
|
||||
presence: true,
|
||||
numericality: { greater_than: 0 }
|
||||
|
||||
def display_value
|
||||
Spree::Money.new(amount)
|
||||
end
|
||||
|
||||
# We limit adjustment to the maximum amount needed to cover the order, ie if the voucher
|
||||
# covers more than the order.total we only need to create an adjustment covering the order.total
|
||||
def compute_amount(order)
|
||||
-amount.clamp(0, order.pre_discount_total)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -6,9 +6,7 @@ FactoryBot.define do
|
||||
amount { 10 }
|
||||
end
|
||||
|
||||
factory :voucher_percentage, class: Voucher do
|
||||
enterprise { build(:distributor_enterprise) }
|
||||
voucher_type { Voucher::PERCENTAGE_RATE }
|
||||
amount { rand(1..100) }
|
||||
factory :voucher_flat_rate, parent: :voucher, class: Vouchers::FlatRate do
|
||||
amount { 15 }
|
||||
end
|
||||
end
|
||||
|
||||
34
spec/models/vouchers/flat_rate_spec.rb
Normal file
34
spec/models/vouchers/flat_rate_spec.rb
Normal file
@@ -0,0 +1,34 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
require 'spec_helper'
|
||||
|
||||
describe Vouchers::FlatRate do
|
||||
let(:enterprise) { build(:enterprise) }
|
||||
|
||||
describe 'validations' do
|
||||
subject { build(:voucher_flat_rate, code: 'new_code', enterprise: enterprise) }
|
||||
|
||||
it { is_expected.to validate_presence_of(:amount) }
|
||||
it { is_expected.to validate_numericality_of(:amount).is_greater_than(0) }
|
||||
end
|
||||
|
||||
describe '#compute_amount' do
|
||||
let(:order) { create(:order_with_totals) }
|
||||
|
||||
context 'when order total is more than the voucher' do
|
||||
subject { create(:voucher_flat_rate, code: 'new_code', enterprise: enterprise, amount: 5) }
|
||||
|
||||
it 'uses the voucher total' do
|
||||
expect(subject.compute_amount(order).to_f).to eq(-5)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when order total is less than the voucher' do
|
||||
subject { create(:voucher_flat_rate, code: 'new_code', enterprise: enterprise, amount: 20) }
|
||||
|
||||
it 'matches the order total' do
|
||||
expect(subject.compute_amount(order).to_f).to eq(-10)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user