Sha256: 532f2e9d72b81776994492b0c8c06dae674f8cb5f04d5ade5fcee86298383cde

Contents?: true

Size: 1.56 KB

Versions: 5

Compression:

Stored size: 1.56 KB

Contents

module Spree
  module Stock
    class Estimator
      attr_reader :order, :currency

      def initialize(order)
        @order = order
        @currency = order.currency
      end

      def shipping_rates(package, frontend_only = true)
        shipping_rates = Array.new
        shipping_methods = shipping_methods(package)
        return [] unless shipping_methods

        shipping_methods.each do |shipping_method|
          cost = calculate_cost(shipping_method, package)
          shipping_rates << shipping_method.shipping_rates.new(:cost => cost) unless cost.nil?
        end

        shipping_rates.sort_by! { |r| r.cost || 0 }

        unless shipping_rates.empty?
          if frontend_only
            shipping_rates.each do |rate|
              rate.selected = true and break if rate.shipping_method.frontend?
            end
          else
            shipping_rates.first.selected = true
          end
        end

        shipping_rates
      end

      private
      def shipping_methods(package)
        shipping_methods = package.shipping_methods
        shipping_methods.delete_if { |ship_method| !ship_method.calculator.available?(package) }
        shipping_methods.delete_if { |ship_method| !ship_method.include?(order.ship_address) }
        shipping_methods.delete_if { |ship_method| !(ship_method.calculator.preferences[:currency].nil? || ship_method.calculator.preferences[:currency] == currency) }
        shipping_methods
      end

      def calculate_cost(shipping_method, package)
        shipping_method.calculator.compute(package)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
spree_core-2.0.7 app/models/spree/stock/estimator.rb
spree_core-2.0.6 app/models/spree/stock/estimator.rb
spree_core-2.1.1 app/models/spree/stock/estimator.rb
spree_core-2.0.5 app/models/spree/stock/estimator.rb
spree_core-2.1.0 app/models/spree/stock/estimator.rb