Sha256: f73d49940a560938999eb6cd42a019abc30f6cc65ac8c923cb9f5e4bc0e566c2

Contents?: true

Size: 1.3 KB

Versions: 1

Compression:

Stored size: 1.3 KB

Contents

# frozen_string_literal: true

module SolidusEasypost
  module Spree
    module ShipmentDecorator
      def self.prepended(mod)
        mod.state_machine.before_transition(
          to: :shipped,
          do: :buy_easypost_rate,
          if: -> { SolidusEasypost.configuration.purchase_labels }
        )
      end

      def easypost_shipment
        if selected_easy_post_shipment_id
          @ep_shipment ||= ::EasyPost::Shipment.retrieve(selected_easy_post_shipment_id)
        else
          @ep_shipment = build_easypost_shipment
        end
      end

      private

      def selected_easy_post_rate_id
        selected_shipping_rate.easy_post_rate_id
      end

      def selected_easy_post_shipment_id
        selected_shipping_rate.easy_post_shipment_id
      end

      def build_easypost_shipment
        ::EasyPost::Shipment.create(
          to_address: order.ship_address.easypost_address,
          from_address: stock_location.easypost_address,
          parcel: to_package.easypost_parcel
        )
      end

      def buy_easypost_rate
        rate = easypost_shipment.rates.find do |sr|
          sr.id == selected_easy_post_rate_id
        end

        easypost_shipment.buy(rate)
        self.tracking = easypost_shipment.tracking_code
      end

      ::Spree::Shipment.prepend self
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
solidus_easypost-2.0.0 app/decorators/models/solidus_easypost/spree/shipment_decorator.rb