Refactor voucher: 2 FlatRate voucher

This commit is contained in:
Gaetan Craig-Riou
2023-07-03 14:03:48 +10:00
parent 204f3933d0
commit def594ab81
3 changed files with 55 additions and 4 deletions

View 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

View File

@@ -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

View 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