diff --git a/app/services/spree_cm_commissioner/discount_cap_calculator.rb b/app/services/spree_cm_commissioner/discount_cap_calculator.rb new file mode 100644 index 000000000..a791ab7ae --- /dev/null +++ b/app/services/spree_cm_commissioner/discount_cap_calculator.rb @@ -0,0 +1,15 @@ +module SpreeCmCommissioner + class DiscountCapCalculator + def initialize(order_amount, percentage_discount, discount_cap) + @order_amount = order_amount + @percentage_discount = percentage_discount + @discount_cap = discount_cap + end + + def calculate_discount + calculated_discount = (@order_amount * @percentage_discount) / 100 + final_discount = [calculated_discount, @discount_cap].min + final_discount.to_f + end + end +end diff --git a/spec/services/spree_cm_commissioner/discount_cap_calculator_spec.rb b/spec/services/spree_cm_commissioner/discount_cap_calculator_spec.rb new file mode 100644 index 000000000..f83eba824 --- /dev/null +++ b/spec/services/spree_cm_commissioner/discount_cap_calculator_spec.rb @@ -0,0 +1,26 @@ +require "spec_helper" + +RSpec.describe SpreeCmCommissioner::DiscountCapCalculator do + let(:order1) { create(:order, total: 100 ) } + let(:order2) { create(:order, total: 30 ) } + let(:percentage_discount) {50} + let(:discount_cap) {20} + + describe '#calculate_discount' do + it 'calculates the discount with a cap' do + subject = described_class.new(order1.total, percentage_discount, discount_cap) + + final_discount = subject.calculate_discount + + expect(final_discount).to eq(20.0) + end + + it 'calculates the discount without a cap' do + subject = described_class.new(order2.total, percentage_discount, discount_cap) + + final_discount = subject.calculate_discount + + expect(final_discount).to eq(15.0) + end + end +end