Sha256: da4e3477b1145736940740783233aed5aef4b4ab049ceedeb707fa29360bc4cc

Contents?: true

Size: 1.35 KB

Versions: 17

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 = Hash[*preferred_tiers.flatten.map(&:to_f)]
      end
    end

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

    def self.description
      Spree.t(:tiered_percent)
    end

    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

17 entries across 17 versions & 1 rubygems

Version Path
solidus_core-2.0.3 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.4.2 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.3.2 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.0.2 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.4.1 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.0.1 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.0.0 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.4.0 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.0.0.rc1 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.4.0.rc1 app/models/spree/calculator/tiered_percent.rb
solidus_core-2.0.0.beta1 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.4.0.beta1 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.3.1 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.3.0 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.3.0.rc2 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.3.0.rc1 app/models/spree/calculator/tiered_percent.rb
solidus_core-1.3.0.beta1 app/models/spree/calculator/tiered_percent.rb