Merge pull request #2178 from HugsDaniel/2172_flexi_rate_miscalculated

Fixing flexible rate miscalculation
This commit is contained in:
Maikel
2018-04-04 15:47:33 +10:00
committed by GitHub
2 changed files with 28 additions and 13 deletions

View File

@@ -15,12 +15,12 @@ module Spree
sum = 0
max = self.preferred_max_items.to_i
items_count = line_items_for(object).map(&:quantity).sum
items_count.times do |i|
# check max value to avoid divide by 0 errors
if (max == 0 && i == 0) || (max > 0) && (i % max == 0)
sum += self.preferred_first_item.to_f
else
sum += self.preferred_additional_item.to_f
# check max value to avoid divide by 0 errors
unless max == 0
if items_count > max
sum += (max - 1) * self.preferred_additional_item.to_f + self.preferred_first_item.to_f
elsif items_count <= max
sum += (items_count - 1) * self.preferred_additional_item.to_f + self.preferred_first_item.to_f
end
end

View File

@@ -1,14 +1,29 @@
require 'spec_helper'
describe Spree::Calculator::FlexiRate do
let(:calculator) { Spree::Calculator::FlexiRate.new }
let(:line_item) { instance_double(Spree::LineItem, amount: 10, quantity: 4) }
let(:line_item) { instance_double(Spree::LineItem, amount: 10, quantity: quantity) }
let(:calculator) do
Spree::Calculator::FlexiRate.new(
preferred_first_item: 2,
preferred_additional_item: 1,
preferred_max_items: 3
)
end
describe "computing for a single line item" do
it "returns the first item rate" do
calculator.stub preferred_first_item: 1.0
calculator.compute(line_item).round(2).should == 1.0
end
context 'when nb of items ordered is above preferred max' do
let(:quantity) { 4.0 }
it "returns the first item rate" do
expect(calculator.compute(line_item).round(2)).to eq(4.0)
end
end
context 'when nb of items ordered is below preferred max' do
let(:quantity) { 2.0 }
it "returns the first item rate" do
expect(calculator.compute(line_item).round(2)).to eq(3.0)
end
end
it "allows creation of new object with all the attributes" do