Sha256: 1a1a40e8e59eae856dd21e0d0ef52f832483e6cf50c1939ca56371e868906a2e

Contents?: true

Size: 1.64 KB

Versions: 4

Compression:

Stored size: 1.64 KB

Contents

module SolidusTecEstimator
  class Estimator

    def shipping_rates(package, _frontend_only = true)

      rates = shipping_methods(package).map do |shipping_method|
        cost = shipping_method.calculator.compute(package)
        if cost
          rate = shipping_method.shipping_rates.new(
            cost: cost,
            shipment: package.shipment
          )
          rate
        end
      end.compact
      rates += providers(package).map do |provider|
        provider_shipping_methods = provider.spree_shipping_methods.available_in_stock_location(package.stock_location)
        provider.class_name.constantize.new(package, provider_shipping_methods).shipping_rates
      end.flatten.compact

      choose_default_shipping_rate(rates)
      rates
    end

    private

    def choose_default_shipping_rate(shipping_rates)
      unless shipping_rates.empty?
        default_shipping_rate = Spree::Config.shipping_rate_selector_class.new(shipping_rates).find_default
        default_shipping_rate.selected = true
      end
    end

    def shipping_methods(package)
      package.shipping_methods
        .available_to_store(package.shipment.order.store)
        .available_for_address(package.shipment.order.ship_address)
        .where(available_to_users: true)
        .includes(:calculator)
        .to_a.select do |ship_method|
          calculator = ship_method.calculator
          calculator.available?(package) && (calculator.preferences[:currency].blank? || calculator.preferences[:currency] == package.shipment.order.currency)
        end
    end

    def providers(package)
      SolidusTecEstimator::Provider.where(active: true)
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
solidus_tec_estimator-1.0.1 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-1.0.0 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-0.0.3 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-0.0.2 app/models/solidus_tec_estimator/estimator.rb