Sha256: dcb9fc0d76bd50760b5c75a60da2fe7dfd42b98774795f82538831f1870036a8

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 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 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

1 entries across 1 versions & 1 rubygems

Version Path
solidus_core-2.1.0.beta1 app/models/spree/calculator/tiered_percent.rb