Class: Spree::Carts::UpsertItems
- Inherits:
-
Object
- Object
- Spree::Carts::UpsertItems
- Includes:
- ServiceModule::Base
- Defined in:
- app/services/spree/carts/upsert_items.rb
Overview
Bulk upsert line items on a cart.
For each entry in items:
-
If a line item for the variant already exists -> sets its quantity
-
If no line item exists -> creates one with the given quantity
After all items are processed the cart is recalculated once.
Instance Method Summary collapse
Methods included from ServiceModule::Base
Instance Method Details
#call(cart:, items:) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'app/services/spree/carts/upsert_items.rb', line 23 def call(cart:, items:) items = Array(items) return success(cart) if items.empty? store = cart.store || Spree::Current.store ApplicationRecord.transaction do items.each do |item_params| item_params = item_params.to_h.deep_symbolize_keys variant = resolve_variant(store, item_params[:variant_id]) next unless variant quantity = (item_params[:quantity] || 1).to_i return failure(variant, "#{variant.name} is not available in #{cart.currency}") if variant.amount_in(cart.currency).nil? line_item = Spree.line_item_by_variant_finder.new.execute(order: cart, variant: variant) if line_item line_item.quantity = quantity line_item. = line_item..merge(item_params[:metadata].to_h) if item_params[:metadata].present? else line_item = cart.items.new(quantity: quantity, variant: variant, options: { currency: cart.currency }) line_item. = item_params[:metadata].to_h if item_params[:metadata].present? end return failure(line_item) unless line_item.save end cart.update_with_updater! end success(cart) end |