Sha256: 4c1561f127878270780949158de5df764b3ae87cc4644cad8295d71aaa55686a

Contents?: true

Size: 1.64 KB

Versions: 2

Compression:

Stored size: 1.64 KB

Contents

module Spree
  # This class has basically the same functionality of Spree core OrderInventory
  # except that it takes account of bundle parts and properly creates and
  # removes inventory unit for each parts of a bundle
  class OrderInventoryAssembly < OrderInventory
    attr_reader :product

    def initialize(line_item)
      @order = line_item.order
      @line_item = line_item
      @product = line_item.product
    end

    def verify(shipment = nil)
      if order.completed? || shipment.present?
        line_item.quantity_by_variant.each do |part, total_parts|
          existing_parts = line_item.inventory_units.where(variant: part).count

          self.variant = part

          verify_parts(shipment, total_parts, existing_parts)
        end
      end
    end

    private

    def verify_parts(shipment, total_parts, existing_parts)
      if existing_parts < total_parts
        verifiy_add_to_shipment(shipment, total_parts, existing_parts)
      elsif existing_parts > total_parts
        verify_remove_from_shipment(shipment, total_parts, existing_parts)
      end
    end

    def verifiy_add_to_shipment(shipment, total_parts, existing_parts)
      shipment = determine_target_shipment unless shipment
      add_to_shipment(shipment, total_parts - existing_parts)
    end

    def verify_remove_from_shipment(shipment, total_parts, existing_parts)
      quantity = existing_parts - total_parts

      if shipment.present?
        remove_from_shipment(shipment, quantity)
      else
        order.shipments.each do |shpment|
          break if quantity == 0
          quantity -= remove_from_shipment(shpment, quantity)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
solidus_product_bundle-1.0.1 app/models/spree/order_inventory_assembly.rb
solidus_product_bundle-1.0.0 app/models/spree/order_inventory_assembly.rb