Sha256: 6f95dc3153308955ccb52d702f8fb9cd548cdf22ce871842a17519d6303a6494

Contents?: true

Size: 1.88 KB

Versions: 6

Compression:

Stored size: 1.88 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 = remove_unavailable_methods(shipping_methods: provider.spree_shipping_methods, package: package)
        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)
      remove_unavailable_methods(shipping_methods: package.shipping_methods, package: package)
        .where(provider_id: nil)
        .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

    def remove_unavailable_methods shipping_methods:, package:
      shipping_methods.available_to_store(package.shipment.order.store)
      .available_in_stock_location(package.stock_location)
      .available_for_address(package.shipment.order.ship_address)
      .where(available_to_users: true)
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
solidus_tec_estimator-2.1.0 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-2.0.0 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-1.0.6 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-1.0.5 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-1.0.4 app/models/solidus_tec_estimator/estimator.rb
solidus_tec_estimator-1.0.3 app/models/solidus_tec_estimator/estimator.rb