Sha256: 24a5dee24783b9ee368e9f3d039c861a6e4696ba2c365b42f8f940fe72640d6a

Contents?: true

Size: 1.85 KB

Versions: 13

Compression:

Stored size: 1.85 KB

Contents

module Spree
  class OrderContents
    attr_accessor :order, :currency

    def initialize(order)
      @order = order
    end

    # Get current line item for variant if exists
    # Add variant qty to line_item
    def add(variant, quantity = 1, currency = nil, shipment = nil)
      line_item = order.find_line_item_by_variant(variant)
      add_to_line_item(line_item, variant, quantity, currency, shipment)
    end

    # Get current line item for variant
    # Remove variant qty from line_item
    def remove(variant, quantity = 1, shipment = nil)
      line_item = order.find_line_item_by_variant(variant)

      unless line_item
        raise ActiveRecord::RecordNotFound, "Line item not found for variant #{variant.sku}"
      end

      remove_from_line_item(line_item, variant, quantity, shipment)
    end

    private

    def add_to_line_item(line_item, variant, quantity, currency=nil, shipment=nil)
      if line_item
        line_item.target_shipment = shipment
        line_item.quantity += quantity.to_i
        line_item.currency = currency unless currency.nil?
      else
        line_item = order.line_items.new(quantity: quantity, variant: variant)
        line_item.target_shipment = shipment
        if currency
          line_item.currency = currency unless currency.nil?
          line_item.price    = variant.price_in(currency).amount
        else
          line_item.price    = variant.price
        end
      end

      line_item.save
      order.reload
      line_item
    end

    def remove_from_line_item(line_item, variant, quantity, shipment=nil)
      line_item.quantity += -quantity
      line_item.target_shipment= shipment

      if line_item.quantity == 0
        Spree::OrderInventory.new(order).verify(line_item, shipment)
        line_item.destroy
      else
        line_item.save!
      end

      order.reload
      line_item
    end

  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
spree_core-2.1.12 app/models/spree/order_contents.rb
spree_core-2.1.11 app/models/spree/order_contents.rb
spree_core-2.1.10 app/models/spree/order_contents.rb
spree_core-2.1.9 app/models/spree/order_contents.rb
spree_core-2.1.8 app/models/spree/order_contents.rb
spree_core-2.1.7 app/models/spree/order_contents.rb
spree_core-2.1.6 app/models/spree/order_contents.rb
spree_core-2.1.5 app/models/spree/order_contents.rb
spree_core-2.1.4 app/models/spree/order_contents.rb
spree_core-2.1.3 app/models/spree/order_contents.rb
spree_core-2.1.2 app/models/spree/order_contents.rb
spree_core-2.1.1 app/models/spree/order_contents.rb
spree_core-2.1.0 app/models/spree/order_contents.rb