Sha256: a66e398c46567427006c5883fefc2b53593b01609092674683b2660b0b0039ea

Contents?: true

Size: 1.35 KB

Versions: 8

Compression:

Stored size: 1.35 KB

Contents

require_dependency 'spree/calculator'

module Spree
  class Calculator::TieredPercent < Calculator
    preference :base_percent, :decimal, default: 0
    preference :tiers, :hash, default: {}

    before_validation do
      # Convert tier values to decimals. Strings don't do us much good.
      if preferred_tiers.is_a?(Hash)
        self.preferred_tiers = preferred_tiers.map do |k, v|
          [BigDecimal.new(k.to_s), BigDecimal.new(v.to_s)]
        end.to_h
      end
    end

    validates :preferred_base_percent, numericality: {
      greater_than_or_equal_to: 0,
      less_than_or_equal_to: 100
    }
    validate :preferred_tiers_content

    def compute(object)
      order = object.is_a?(Order) ? object : object.order
      _base, percent = preferred_tiers.sort.reverse.detect{ |b, _| order.item_total >= b }
      (object.amount * (percent || preferred_base_percent) / 100).round(2)
    end

    private

    def preferred_tiers_content
      if preferred_tiers.is_a? Hash
        unless preferred_tiers.keys.all?{ |k| k.is_a?(Numeric) && k > 0 }
          errors.add(:base, :keys_should_be_positive_number)
        end
        unless preferred_tiers.values.all?{ |k| k.is_a?(Numeric) && k >= 0 && k <= 100 }
          errors.add(:base, :values_should_be_percent)
        end
      else
        errors.add(:preferred_tiers, :should_be_hash)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
solidus_core-2.2.2 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.1.1 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.2.1 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.2.0 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.2.0.rc1 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.2.0.beta1 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.1.0 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.1.0.rc1 app/models/spree/calculator/tiered_percent.rb