From def594ab81ffcfcada9e2d43abaadb590d843a69 Mon Sep 17 00:00:00 2001 From: Gaetan Craig-Riou Date: Mon, 3 Jul 2023 14:03:48 +1000 Subject: [PATCH] Refactor voucher: 2 FlatRate voucher --- app/models/vouchers/flat_rate.rb | 19 ++++++++++++++ spec/factories/voucher_factory.rb | 6 ++--- spec/models/vouchers/flat_rate_spec.rb | 34 ++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 app/models/vouchers/flat_rate.rb create mode 100644 spec/models/vouchers/flat_rate_spec.rb diff --git a/app/models/vouchers/flat_rate.rb b/app/models/vouchers/flat_rate.rb new file mode 100644 index 0000000000..05c70bbc34 --- /dev/null +++ b/app/models/vouchers/flat_rate.rb @@ -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 diff --git a/spec/factories/voucher_factory.rb b/spec/factories/voucher_factory.rb index 5acea9959f..7c1a7ce706 100644 --- a/spec/factories/voucher_factory.rb +++ b/spec/factories/voucher_factory.rb @@ -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 diff --git a/spec/models/vouchers/flat_rate_spec.rb b/spec/models/vouchers/flat_rate_spec.rb new file mode 100644 index 0000000000..543a564d1c --- /dev/null +++ b/spec/models/vouchers/flat_rate_spec.rb @@ -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