Sha256: 326b0fce304c27170bb06d2a76aea761f5f007e3a14dcee2c63b5e73006d9049

Contents?: true

Size: 1.28 KB

Versions: 43

Compression:

Stored size: 1.28 KB

Contents

# frozen_string_literal: true

require_dependency 'spree/calculator'

module Spree
  class Calculator::TieredFlatRate < Calculator
    preference :base_amount, :decimal, default: 0
    preference :tiers, :hash, default: {}
    preference :currency, :string, default: -> { Spree::Config[:currency] }

    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|
          [cast_to_d(k.to_s), cast_to_d(v.to_s)]
        end.to_h
      end
    end

    validate :preferred_tiers_content

    def compute(object)
      _base, amount = preferred_tiers.sort.reverse.detect do |b, _|
        object.amount >= b
      end

      if preferred_currency.casecmp(object.currency).zero?
        amount || preferred_base_amount
      else
        0
      end
    end

    private

    def cast_to_d(value)
      value.to_s.to_d
    rescue ArgumentError
      BigDecimal(0)
    end

    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
      else
        errors.add(:preferred_tiers, :should_be_hash)
      end
    end
  end
end

Version data entries

43 entries across 43 versions & 2 rubygems

Version Path
solidus_core-2.9.6 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.8.6 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.9.5 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.9.4 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.6.6 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.7.4 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.8.5 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.9.3 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.9.2 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.10.0.beta1 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.7.3 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.6.5 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.9.1 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.9.0 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.9.0.rc.1 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.8.4 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.8.3 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.7.2 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.6.4 app/models/spree/calculator/tiered_flat_rate.rb
solidus_core-2.8.2 app/models/spree/calculator/tiered_flat_rate.rb