Sha256: 0536016612902f92fdc462a4aa4807a3f28f50687447b89706947f8720fb84c3

Contents?: true

Size: 1.43 KB

Versions: 2

Compression:

Stored size: 1.43 KB

Contents

module Spree
  module Cart
    class AddItem
      prepend Spree::ServiceModule::Base

      def call(order:, variant:, quantity: nil, options: {})
        ApplicationRecord.transaction do
          run :add_to_line_item
          run Spree::Cart::Recalculate
        end
      end

      private

      def add_to_line_item(order:, variant:, quantity: nil, options: {})
        options ||= {}
        quantity ||= 1

        line_item = Spree::LineItems::FindByVariant.new.execute(order: order, variant: variant, options: options)

        line_item_created = line_item.nil?
        if line_item.nil?
          opts = ::Spree::PermittedAttributes.line_item_attributes.flatten.each_with_object({}) do |attribute, result|
            result[attribute] = options[attribute]
          end.merge(currency: order.currency).delete_if { |_key, value| value.nil? }

          line_item = order.line_items.new(quantity: quantity,
                                           variant: variant,
                                           options: opts)
        else
          line_item.quantity += quantity.to_i
        end

        line_item.target_shipment = options[:shipment] if options.key? :shipment

        return failure(line_item) unless line_item.save

        ::Spree::TaxRate.adjust(order, [line_item.reload]) if line_item_created
        success(order: order, line_item: line_item, line_item_created: line_item_created, options: options)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
spree_core-3.7.0.rc2 app/services/spree/cart/add_item.rb
spree_core-3.7.0.rc1 app/services/spree/cart/add_item.rb