Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Route every non-increment cart item mutation through one workflow
Damian Legawiecc3b1b2835292
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rbindex cf7e897aaa..1d95d801d3 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/cart_resolvable.rb@@ -40,9 +40,15 @@ module Spreeend# Render the cart as JSON using the cart serializer.- def render_cart(status: :ok)+ # @param warnings [Array<Spree::Carts::ItemWarning>] items a batch+ # upsert did not apply. Present only when something was dropped, so+ # a client that ignores the key sees an unchanged payload.+ def render_cart(status: :ok, warnings: [])@cart = @cart.remove_out_of_stock_items!- render json: Spree.api.cart_serializer.new(@cart, params: serializer_params).to_h, status: status+ payload = Spree.api.cart_serializer.new(@cart, params: serializer_params).to_h+ payload[:warnings] = warnings.map(&:to_h) if warnings.present?++ render json: payload, status: statusend# Render the order as JSON using the order serializer (for complete action).diff --git a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rbindex 2b172ce390..8b85140a9e 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts/items_controller.rb@@ -23,7 +23,7 @@ module Spreeif result.success?render_cart(status: :created)else- render_service_error(result.error, code: ERROR_CODES[:insufficient_stock])+ render_result_error(result)endendend@@ -36,16 +36,16 @@ module Spree@line_item.metadata = @line_item.metadata.merge(permitted_params[:metadata].to_h) if permitted_params[:metadata].present?if permitted_params[:quantity].present?- result = Spree.cart_set_item_quantity_service.call(+ workflow = Spree.cart_upsert_items_workflow.new+ result = workflow.call(cart: @cart,- line_item: @line_item,- quantity: permitted_params[:quantity]+ items: [{ variant_id: @line_item.variant_id, quantity: permitted_params[:quantity] }])if result.success?- render_cart+ render_cart(warnings: workflow.warnings)else- render_service_error(result.error, code: ERROR_CODES[:invalid_quantity])+ render_result_error(result)endelsif @line_item.changed?@line_item.save!@@ -61,12 +61,17 @@ module Spreewith_order_lock do@line_item = @cart.line_items.find_by_prefix_id!(params[:id])- Spree.cart_remove_line_item_service.call(+ workflow = Spree.cart_upsert_items_workflow.new+ result = workflow.call(cart: @cart,- line_item: @line_item+ items: [{ variant_id: @line_item.variant_id, quantity: 0 }])- render_cart+ if result.success?+ render_cart(warnings: workflow.warnings)+ else+ render_result_error(result)+ endendenddiff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rbindex 1dfca9e147..ba5e190618 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb@@ -30,7 +30,8 @@ module Spree# Creates a new shopping cart (order)# Can be created by guests or authenticated customersdef create- result = Spree::Carts::Create.call(+ service = Spree::Carts::Create.new+ result = service.call(params: permitted_params.merge(user: current_user,store: current_store,@@ -42,7 +43,7 @@ module Spreeif result.success?@cart = result.value- render_cart(status: :created)+ render_cart(status: :created, warnings: service.item_warnings)elserender_service_error(result.error.to_s)end@@ -55,13 +56,14 @@ module Spreefind_cart!with_order_lock do- result = Spree::Carts::Update.call(+ service = Spree::Carts::Update.new+ result = service.call(cart: @cart,params: permitted_params)if result.success?- render_cart+ render_cart(warnings: service.item_warnings)elserender_service_error(result.error, code: ERROR_CODES[:validation_error])enddiff --git a/spree/core/app/jobs/spree/variants/remove_line_item_job.rb b/spree/core/app/jobs/spree/variants/remove_line_item_job.rbindex d2d1395e3b..dbe13527c4 100644--- a/spree/core/app/jobs/spree/variants/remove_line_item_job.rb+++ b/spree/core/app/jobs/spree/variants/remove_line_item_job.rb@@ -4,7 +4,10 @@ module Spreequeue_as Spree.queues.variantsdef perform(line_item:)- Spree.cart_remove_line_item_service.call(order: line_item.order, line_item: line_item)+ Spree.cart_upsert_items_workflow.call(+ cart: line_item.owner,+ items: [{ variant_id: line_item.variant_id, quantity: 0 }]+ )endendenddiff --git a/spree/core/app/models/spree/carts/item_warning.rb b/spree/core/app/models/spree/carts/item_warning.rbnew file mode 100644index 0000000000..b9662bc6d0--- /dev/null+++ b/spree/core/app/models/spree/carts/item_warning.rb@@ -0,0 +1,20 @@+module Spree+ module Carts+ # An item a batch upsert did not apply — vetoed by a :validate handler or+ # unavailable in the cart's currency. The batch still succeeds, so this is+ # how the caller learns which lines were dropped and why.+ class ItemWarning+ include ActiveModel::Model+ include ActiveModel::Attributes++ attribute :item_index, :integer+ attribute :code, :string+ attribute :message, :string+ attr_accessor :variant++ def to_h+ { item_index: item_index, variant_id: variant&.prefixed_id, code: code, message: message }+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/carts/resolved_item.rb b/spree/core/app/models/spree/carts/resolved_item.rbnew file mode 100644index 0000000000..9ba0c6fdbf--- /dev/null+++ b/spree/core/app/models/spree/carts/resolved_item.rb@@ -0,0 +1,23 @@+module Spree+ module Carts+ # One entry of an upsert batch after its variant has been looked up:+ # what Spree::Carts::UpsertItems validates and applies.+ class ResolvedItem+ include ActiveModel::Model+ include ActiveModel::Attributes++ attribute :quantity, :integer, default: 1+ attr_accessor :variant, :metadata++ def metadata+ @metadata ||= {}+ end++ # Zero (or less) is how a batch says "this line is gone", which is what+ # lets one request carry edits and removals together.+ def remove?+ quantity <= 0+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/carts/create.rb b/spree/core/app/services/spree/carts/create.rbindex a97fe7b0a3..4848d70d1b 100644--- a/spree/core/app/services/spree/carts/create.rb+++ b/spree/core/app/services/spree/carts/create.rb@@ -19,8 +19,11 @@ module Spree# Delegate all attribute/address/item processing to Carts::Updateif @params.present?- result = Spree::Carts::Update.call(cart: cart, params: @params)+ update = Spree::Carts::Update.new+ result = update.call(cart: cart, params: @params)return result if result.failure?++ @item_warnings = update.item_warningsendsuccess(cart.reload)@@ -29,6 +32,13 @@ module Spreerescue StandardError => efailure(nil, e.message)end++ # Items the batch did not apply — see Spree::Carts::Update#item_warnings.+ #+ # @return [Array<Spree::Carts::ItemWarning>]+ def item_warnings+ @item_warnings ||= []+ endendendenddiff --git a/spree/core/app/services/spree/carts/remove_line_item.rb b/spree/core/app/services/spree/carts/remove_line_item.rbindex 742b0aca12..6672d98c44 100644--- a/spree/core/app/services/spree/carts/remove_line_item.rb+++ b/spree/core/app/services/spree/carts/remove_line_item.rb@@ -1,31 +1,25 @@module Spreemodule Carts+ # @deprecated Removing an item is an upsert with quantity zero. Call+ # Spree::Carts::UpsertItems so the removal passes the same+ # 'carts.upsert_items.validate' hook every other item mutation does.+ # Removed in Spree 6.1.class RemoveLineItemprepend Spree::ServiceModule::Basedef call(cart: nil, order: nil, line_item: nil, options: nil)- if order- Spree::Deprecation.warn('Calling Spree::Carts::RemoveLineItem with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')- cart ||= order- end- options ||= {}- ActiveRecord::Base.transaction do- cart.line_items.destroy(line_item)+ Spree::Deprecation.warn(+ 'Spree::Carts::RemoveLineItem is deprecated and will be removed in Spree 6.1. ' \+ 'Use Spree::Carts::UpsertItems with quantity: 0 instead.'+ )+ cart ||= order- # LineItem dependent: :destroy removes its own reservation row;- # remaining items may need a fresh reservation pass when in checkout.- if cart.in_checkout? && cart.line_items.any?- result = Spree::StockReservations::Reserve.call(cart: cart)- raise Spree::StockReservations::InsufficientStockError.new(nil, result.error.to_s) if result.failure?- end+ result = Spree.cart_upsert_items_workflow.call(+ cart: cart,+ items: [{ variant_id: line_item.variant_id, quantity: 0 }]+ )- Spree.cart_recalculate_workflow.new.call(cart: cart,- line_item: line_item,- options: options)- end- success(line_item)- rescue Spree::StockReservations::InsufficientStockError => e- failure(line_item, e.message)+ result.success? ? success(line_item) : failure(line_item, result.error)endendenddiff --git a/spree/core/app/services/spree/carts/remove_out_of_stock_items.rb b/spree/core/app/services/spree/carts/remove_out_of_stock_items.rbindex 7989a59a37..aa6b291f80 100644--- a/spree/core/app/services/spree/carts/remove_out_of_stock_items.rb+++ b/spree/core/app/services/spree/carts/remove_out_of_stock_items.rb@@ -16,8 +16,13 @@ module Spreeline_items = cart.line_items.includes(variant: [:product, :stock_locations, { stock_items: [:stock_location, :active_stock_reservations] }])ActiveRecord::Base.transaction do- line_items.each do |line_item|- cart_remove_line_item_service.call(cart: cart, line_item: line_item) if !valid_status?(line_item) || !stock_available?(line_item)+ removals = line_items.reject { |line_item| valid_status?(line_item) && stock_available?(line_item) }++ if removals.any?+ Spree.cart_upsert_items_workflow.call(+ cart: cart,+ items: removals.map { |line_item| { variant_id: line_item.variant_id, quantity: 0 } }+ )endend@@ -60,10 +65,6 @@ module Spreeendtrueend-- def cart_remove_line_item_service- Spree.cart_remove_line_item_service- endendendenddiff --git a/spree/core/app/services/spree/carts/set_quantity.rb b/spree/core/app/services/spree/carts/set_quantity.rbindex b8cc714193..f7e6b8121f 100644--- a/spree/core/app/services/spree/carts/set_quantity.rb+++ b/spree/core/app/services/spree/carts/set_quantity.rb@@ -1,36 +1,25 @@module Spreemodule Carts+ # @deprecated Setting a quantity is a one-item upsert. Call+ # Spree::Carts::UpsertItems so the change passes the same+ # 'carts.upsert_items.validate' hook every other item mutation does.+ # Removed in Spree 6.1.class SetQuantityprepend Spree::ServiceModule::Basedef call(cart: nil, order: nil, line_item: nil, quantity: nil)- if order- Spree::Deprecation.warn('Calling Spree::Carts::SetQuantity with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')- cart ||= order- end- rewrite_input!(remove: [:order], cart: cart)- ActiveRecord::Base.transaction do- run :change_item_quantity- run :handle_stock_reservations- run Spree.cart_recalculate_workflow- end- end-- private-- def change_item_quantity(cart:, line_item:, quantity: nil)- return failure(line_item) unless line_item.update(quantity: quantity)-- success(cart: cart, line_item: line_item)- end+ Spree::Deprecation.warn(+ 'Spree::Carts::SetQuantity is deprecated and will be removed in Spree 6.1. ' \+ 'Use Spree::Carts::UpsertItems (quantity is set, not added) instead.'+ )+ cart ||= order- def handle_stock_reservations(cart:, line_item:)- if cart.in_checkout?- result = Spree::StockReservations::Reserve.call(cart: cart)- return failure(line_item, result.error) if result.failure?- end+ result = Spree.cart_upsert_items_workflow.call(+ cart: cart,+ items: [{ variant_id: line_item.variant_id, quantity: quantity }]+ )- success(cart: cart, line_item: line_item)+ result.success? ? success(line_item.reload) : failure(line_item, result.error)endendenddiff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rbindex a0604e7bcb..fab33f412d 100644--- a/spree/core/app/services/spree/carts/update.rb+++ b/spree/core/app/services/spree/carts/update.rb@@ -31,6 +31,15 @@ module Spreefailure(cart, e.message)end+ # Items the batch did not apply (vetoed by a :validate handler, or+ # unavailable in the cart's currency). The update still succeeds — the+ # caller surfaces these so the customer learns what was dropped.+ #+ # @return [Array<Spree::Carts::ItemWarning>]+ def item_warnings+ @item_warnings ||= []+ end+privateattr_reader :cart, :params@@ -115,12 +124,12 @@ module Spreedef process_itemsreturn unless params[:items].is_a?(Array)- result = Spree::Carts::UpsertItems.call(- cart: cart,- items: params[:items]- )+ workflow = Spree.cart_upsert_items_workflow.new+ result = workflow.call(cart: cart, items: params[:items])raise StandardError, result.error.to_s if result.failure?++ @item_warnings = workflow.warningsend# Legacy `before_transition to: :address` parity: once a signed-indiff --git a/spree/core/app/services/spree/carts/upsert_items.rb b/spree/core/app/services/spree/carts/upsert_items.rbdeleted file mode 100644index 7c55188070..0000000000--- a/spree/core/app/services/spree/carts/upsert_items.rb+++ /dev/null@@ -1,76 +0,0 @@-module Spree- module Carts- # 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.- #- # @example- # Spree::Carts::UpsertItems.new.call(- # cart: cart,- # items: [- # { variant_id: "variant_k5nR8xLq", quantity: 2 },- # { variant_id: "variant_m3Rp9wXz", quantity: 1 }- # ]- # )- #- class UpsertItems- prepend Spree::ServiceModule::Base-- 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(owner: cart, variant: variant)-- if line_item- line_item.quantity = quantity- line_item.metadata = line_item.metadata.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.metadata = item_params[:metadata].to_h if item_params[:metadata].present?- end-- return failure(line_item) unless line_item.save- end-- cart.recalculate_totals!- end-- success(cart)- end-- private-- def resolve_variant(store, variant_id)- return nil if variant_id.blank?-- variant = store.variants.find_by_param(variant_id)-- raise ActiveRecord::RecordNotFound.new(- "Variant '#{variant_id}' not found in this store",- 'Spree::Variant',- 'id',- variant_id- ) unless variant-- variant- end- end- end-enddiff --git a/spree/core/app/services/spree/orders/upsert_items.rb b/spree/core/app/services/spree/orders/upsert_items.rbdeleted file mode 100644index 96a3f9ea57..0000000000--- a/spree/core/app/services/spree/orders/upsert_items.rb+++ /dev/null@@ -1,82 +0,0 @@-module Spree- module Orders- # Bulk upsert line items on an order. Mirrors Spree::Carts::UpsertItems- # but is admin/order-side (separate from the cart pipeline per the 6.0- # cart/order split — see docs/plans/6.0-cart-order-split.md).- #- # 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- # - Quantity zero (or less) removes the line item when one exists, and is- # ignored otherwise. That is what lets an admin submit a whole edited- # order in one request: the rows the merchant struck out arrive as zeros- # alongside the ones they changed, and the caller's transaction applies- # the lot or none of it.- #- # Order totals are NOT recalculated here. Callers (Spree::Orders::Create- # and Spree::Orders::Update) are responsible for running shipment- # rebuilding and a final `order.recalculate_totals!` once their- # full pipeline (items, shipments, coupons) has run.- class UpsertItems- prepend Spree::ServiceModule::Base-- def call(order:, items:)- items = Array(items)- return success(order) if items.empty?-- store = order.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- line_item = Spree.line_item_by_variant_finder.new.execute(owner: order, variant: variant)-- if quantity <= 0- # Zero removes what is there and means nothing when there is- # not, so an order arriving with its struck-out rows as zeros- # settles in one pass while a create with a zero still adds- # nothing.- line_item&.destroy!- next- end-- return failure(variant, "#{variant.name} is not available in #{order.currency}") if variant.amount_in(order.currency).nil?-- if line_item- line_item.quantity = quantity- line_item.metadata = line_item.metadata.merge(item_params[:metadata].to_h) if item_params[:metadata].present?- else- line_item = order.line_items.new(quantity: quantity, variant: variant, options: { currency: order.currency })- line_item.metadata = item_params[:metadata].to_h if item_params[:metadata].present?- end-- return failure(line_item) unless line_item.save- end- end-- success(order)- end-- private-- def resolve_variant(store, variant_id)- return nil if variant_id.blank?-- variant = store.variants.find_by_param(variant_id)-- raise ActiveRecord::RecordNotFound.new(- "Variant '#{variant_id}' not found in this store",- 'Spree::Variant',- 'id',- variant_id- ) unless variant-- variant- end- end- end-enddiff --git a/spree/core/app/workflows/spree/carts/upsert_items.rb b/spree/core/app/workflows/spree/carts/upsert_items.rbnew file mode 100644index 0000000000..d99a16aee4--- /dev/null+++ b/spree/core/app/workflows/spree/carts/upsert_items.rb@@ -0,0 +1,190 @@+module Spree+ module Carts+ # Applies a batch of item changes to a cart in one pass — the single gate+ # for every item mutation that is not a plain add-increment (bulk+ # payloads, a quantity edit, a removal). AddItem stays the increment+ # ("add 2 more"); this workflow SETS quantity, and quantity zero removes.+ #+ # Two things make it worth a workflow rather than a loop over AddItem.+ # Extensions get one veto point covering every non-increment path, and+ # the cart recalculates ONCE for the whole batch instead of once per+ # item — the money math is the expensive part, so a dozen items cost+ # roughly one item's work.+ #+ # Rejections are per item, not per batch: a validate handler that vetoes+ # one line skips that line and the rest still apply, so a customer+ # restoring a saved cart keeps everything still purchasable and hears+ # about what was dropped. The skipped items come back as +warnings++ # (see Spree::Carts::ItemWarning) beside a successful result.+ class UpsertItems < Spree::Workflow+ hooks :validate, :after_items_upserted++ # Readers a :validate handler uses. variant/quantity/metadata describe+ # the item currently being validated — the same reader names AddItem+ # exposes, so one handler class registers on both keys unchanged.+ # +items+ is the whole resolved batch, for rules that need to see it+ # (a per-order unit cap, a mixed-category restriction).+ attr_reader :variant, :quantity, :metadata, :items, :warnings++ # @param cart [Spree::Cart, Spree::Order]+ # @param items [Array<Hash>] :variant_id (prefixed or raw), :quantity,+ # :metadata. Quantity defaults to 1; zero or less removes.+ # @return [Spree::ServiceModule::Result] value is the cart+ def perform(cart:, items:)+ super+ @warnings = []++ step :resolve_items+ return success(cart) if resolved_items.empty?++ ApplicationRecord.transaction do+ step :apply_items+ step :handle_stock_reservations if cart.in_checkout?+ step :recalculate, with: -> { Spree.cart_recalculate_workflow } if recalculate?+ run_hooks :after_items_upserted+ end++ success(cart.reload)+ end++ private++ attr_reader :resolved_items++ # The cart side recalculates here because nothing else will. The order+ # side overrides this: admin edits run items, fulfillments and coupons+ # as one pipeline and recalculate once at the end of it.+ def recalculate?+ true+ end++ # A customer restoring a saved cart should keep whatever is still+ # purchasable, so a bad line becomes a warning. A merchant editing an+ # order should not: a struck-out or repriced row silently not applying+ # is worse than the edit failing, so the order twin turns this off.+ def partial_success?+ true+ end++ # One pass for lookup and currency checks, before anything is written,+ # so a batch naming an unknown variant fails before it has half+ # applied.+ def resolve_items+ store = cart.store || Spree::Current.store++ @resolved_items = Array(items).filter_map do |item_params|+ item_params = item_params.to_h.deep_symbolize_keys+ quantity = (item_params[:quantity] || 1).to_i+ variant = resolve_variant(store, item_params[:variant_id], removing: quantity <= 0)+ next if variant.nil?++ Spree::Carts::ResolvedItem.new(+ variant: variant,+ quantity: quantity,+ metadata: item_params[:metadata].to_h+ )+ end+ end++ def apply_items+ resolved_items.each_with_index do |item, index|+ next unless validated?(item, index)++ line_item = Spree.line_item_by_variant_finder.new.execute(owner: cart, variant: item.variant)++ if item.remove?+ line_item&.destroy!+ next+ end++ if item.variant.amount_in(cart.currency).nil?+ message = Spree.t('cart_line_item.currency_unavailable', li_name: item.variant.name, currency: cart.currency)+ failure(item.variant, message) unless partial_success?++ warn(index, item, :currency_unavailable, message)+ next+ end++ apply_item(item, line_item)+ end+ end++ # Dispatches :validate for one item with that item's readers bound, and+ # converts a handler's rejection into a warning instead of failing the+ # batch. FailureSignal is what reject! raises; catching it here is the+ # deliberate difference between this workflow and every other one.+ def validated?(item, index)+ bind_current_item(item)+ run_hooks :validate+ true+ rescue Spree::Workflow::FailureSignal+ raise unless partial_success?++ rejection = errors+ @errors = nil+ warnings << Spree::Carts::ItemWarning.new(+ item_index: index,+ variant: item.variant,+ code: rejection.details.values.flatten.first&.dig(:error) || :rejected,+ message: rejection.full_messages.to_sentence+ )+ false+ ensure+ bind_current_item(nil)+ end++ def bind_current_item(item)+ @variant = item&.variant+ @quantity = item&.quantity+ @metadata = item&.metadata || {}+ end++ def apply_item(item, line_item)+ if line_item+ line_item.quantity = item.quantity+ line_item.metadata = line_item.metadata.merge(item.metadata) if item.metadata.present?+ else+ line_item = cart.line_items.new(+ quantity: item.quantity,+ variant: item.variant,+ options: { currency: cart.currency }+ )+ line_item.metadata = item.metadata if item.metadata.present?+ end++ created = line_item.new_record?+ failure(line_item) unless line_item.save++ line_item.reload.recalculate_price+ ::Spree.tax_provider.estimate(line_item.owner, [line_item]) if created+ end++ def handle_stock_reservations+ result = Spree::StockReservations::Reserve.call(cart: cart)+ failure(cart, result.error) if result.failure?+ end++ # Adds resolve through the store, so a variant belonging to another+ # tenant is a 404 rather than a cross-store add. Removals resolve+ # through the cart's own items instead: the line is already there, and+ # a product that has since been deleted or unpublished has left+ # store.variants — refusing to remove it would strand the customer+ # with a line they cannot get rid of.+ def resolve_variant(store, variant_id, removing: false)+ return nil if variant_id.blank?++ if removing+ cart.line_items.detect { |line_item| line_item.variant_id.to_s == variant_id.to_s }&.variant ||+ Spree::Variant.with_deleted.find_by_param(variant_id)+ else+ store.variants.find_by_param(variant_id) ||+ raise(ActiveRecord::RecordNotFound.new("Variant '#{variant_id}' not found in this store", 'Spree::Variant', 'id', variant_id))+ end+ end++ def warn(index, item, code, message)+ warnings << Spree::Carts::ItemWarning.new(item_index: index, variant: item.variant, code: code, message: message)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/orders/upsert_items.rb b/spree/core/app/workflows/spree/orders/upsert_items.rbnew file mode 100644index 0000000000..fc0f91357e--- /dev/null+++ b/spree/core/app/workflows/spree/orders/upsert_items.rb@@ -0,0 +1,28 @@+module Spree+ module Orders+ # Draft-order twin of the cart workflow — order: is the canonical keyword+ # on this side, and hooks dispatch under 'orders.upsert_items.*' so an+ # extension can hold admin edits to different rules than storefront ones.+ #+ # Totals are NOT recalculated here: Spree::Orders::Create and+ # Spree::Orders::Update run items, fulfillments and coupons as one+ # pipeline and recalculate once at the end of it.+ class UpsertItems < Spree::Carts::UpsertItems+ def perform(order:, **rest)+ super(cart: order, **rest)+ end++ private++ def recalculate?+ false+ end++ # A merchant's edit applies whole or not at all — a line silently+ # skipped is worse here than a failed request.+ def partial_success?+ false+ end+ end+ end+enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 100f5ce4b6..0eeec2e5b3 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -677,6 +677,7 @@ en:cart: Cartcart_already_updated: The cart has already been updated.cart_line_item:+ currency_unavailable: "%{li_name} is not available in %{currency}"delivery_unavailable: "%{li_name} cannot be delivered to the selected address"discontinued: "%{li_name} was removed because it was discontinued"out_of_stock: "%{li_name} was removed because it was sold out"diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 890784a3f1..e3784c467c 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -21,8 +21,6 @@ module Spreecart_recalculate_totals_workflow: 'Spree::Carts::RecalculateTotals',order_recalculate_totals_workflow: 'Spree::Orders::RecalculateTotals',cart_remove_item_service: 'Spree::Carts::RemoveItem',- cart_remove_line_item_service: 'Spree::Carts::RemoveLineItem',- cart_set_item_quantity_service: 'Spree::Carts::SetQuantity',# draft orders (admin item editing) — cart twins split so the two# sides can diverge; see Spree::Orders::AddItem@@ -39,7 +37,8 @@ module Spreecarts_complete_workflow: 'Spree::Carts::Complete',carts_create_service: 'Spree::Carts::Create',carts_update_service: 'Spree::Carts::Update',- carts_upsert_items_service: 'Spree::Carts::UpsertItems',+ cart_upsert_items_workflow: 'Spree::Carts::UpsertItems',+ order_upsert_items_workflow: 'Spree::Orders::UpsertItems',cart_merge_workflow: 'Spree::Carts::Merge',# checkout@@ -143,6 +142,9 @@ module Spreecart_recalculate_service: :cart_recalculate_workflow,cart_merge_strategy: :cart_merge_workflow,carts_complete_service: :carts_complete_workflow,+ carts_upsert_items_service: :cart_upsert_items_workflow,+ cart_set_item_quantity_service: :cart_upsert_items_workflow,+ cart_remove_line_item_service: :cart_upsert_items_workflow,payments_handle_webhook_service: :payments_handle_webhook_workflow,fulfillment_create_service: :fulfillment_create_workflow,order_cancel_service: :order_cancel_workflow,diff --git a/spree/core/spec/services/spree/returns/eligibility_validator_spec.rb b/spree/core/spec/services/spree/returns/eligibility_validator_spec.rbindex 034001413b..1d48db959d 100644--- a/spree/core/spec/services/spree/returns/eligibility_validator_spec.rb+++ b/spree/core/spec/services/spree/returns/eligibility_validator_spec.rb@@ -40,7 +40,8 @@ RSpec.describe Spree::Returns::EligibilityValidator doresult = open_returnexpect(result).to be_failure- expect(result.error.value).to include('30-day return window')+ expect(result.error.to_s).to include('30-day return window')+ expect(result.error.value.details[:base].first[:error]).to eq(:outside_return_window)expect(order.reload.returns).to be_emptyenddiff --git a/spree/core/spec/services/spree/carts/upsert_items_spec.rb b/spree/core/spec/workflows/spree/carts/upsert_items_spec.rbsimilarity index 69%rename from spree/core/spec/services/spree/carts/upsert_items_spec.rbrename to spree/core/spec/workflows/spree/carts/upsert_items_spec.rbindex cf7a21b918..ea9a8c5408 100644--- a/spree/core/spec/services/spree/carts/upsert_items_spec.rb+++ b/spree/core/spec/workflows/spree/carts/upsert_items_spec.rb@@ -149,9 +149,16 @@ module Spreelet(:cart) { create(:cart, customer: user, store: store, currency: 'GBP') }let(:items) { [{ variant_id: variant.prefixed_id, quantity: 1 }] }- it 'returns failure with message' do- expect(subject).to be_failure- expect(subject.error.to_s).to include('is not available in GBP')+ # Partial success: one unpriceable line must not cost the customer the+ # rest of the batch, so it comes back as a warning instead.+ it 'skips the item and reports it as a warning' do+ workflow = described_class.new+ result = workflow.call(cart: cart, items: items)++ expect(result).to be_success+ expect(cart.items.count).to eq(0)+ expect(workflow.warnings.first.code).to eq('currency_unavailable')+ expect(workflow.warnings.first.message).to include('is not available in GBP')endend@@ -253,5 +260,94 @@ module Spreeendendend++ describe 'the validate hook' do+ after { Spree.hooks.clear! }++ let(:items) do+ [+ { variant_id: variant.prefixed_id, quantity: 1 },+ { variant_id: variant2.prefixed_id, quantity: 99 }+ ]+ end++ it 'skips a rejected item and applies the rest' do+ Spree.hooks.register('carts.upsert_items.validate') do |flow|+ next if flow.quantity <= 10++ flow.errors.add(:quantity, :purchase_limit_exceeded, message: 'at most 10 per item')+ flow.reject!+ end++ workflow = described_class.new+ result = workflow.call(cart: cart, items: items)++ expect(result).to be_success+ expect(cart.items.map(&:variant)).to eq([variant])++ warning = workflow.warnings.sole+ expect(warning.item_index).to eq(1)+ expect(warning.variant).to eq(variant2)+ expect(warning.code).to eq('purchase_limit_exceeded')+ expect(warning.message).to eq('Quantity at most 10 per item')+ end++ # Each item is judged on its own — a rejection must not leak errors+ # into the next item's dispatch.+ it 'validates every item independently' do+ seen = []+ Spree.hooks.register('carts.upsert_items.validate') do |flow|+ seen << [flow.variant, flow.quantity]+ flow.reject!('nope') if flow.quantity == 99+ end++ described_class.call(cart: cart, items: items)++ expect(seen).to eq([[variant, 1], [variant2, 99]])+ end++ it 'exposes the whole batch for cross-item rules' do+ batch_size = nil+ Spree.hooks.register('carts.upsert_items.validate') { |flow| batch_size = flow.items.size }++ described_class.call(cart: cart, items: items)++ expect(batch_size).to eq(2)+ end+ end++ describe 'removals' do+ let!(:line_item) { create(:line_item, cart: cart, order: nil, variant: variant, quantity: 2) }++ it 'removes the line item when quantity is zero' do+ result = described_class.call(cart: cart, items: [{ variant_id: variant.prefixed_id, quantity: 0 }])++ expect(result).to be_success+ expect(cart.reload.items).to be_empty+ end++ it 'applies edits and removals in one pass' do+ result = described_class.call(cart: cart, items: [+ { variant_id: variant.prefixed_id, quantity: 0 },+ { variant_id: variant2.prefixed_id, quantity: 3 }+ ])++ expect(result).to be_success+ expect(cart.reload.items.map(&:variant)).to eq([variant2])+ expect(cart.items.sole.quantity).to eq(3)+ end+ end++ # The reason this is a batch workflow rather than a loop over AddItem:+ # the money math runs once no matter how many items arrive.+ it 'recalculates the cart once for the whole batch' do+ recalculate = Spree.cart_recalculate_workflow+ expect(recalculate).to receive(:new).once.and_call_original++ described_class.call(cart: cart, items: [+ { variant_id: variant.prefixed_id, quantity: 1 },+ { variant_id: variant2.prefixed_id, quantity: 2 }+ ])+ endendenddiff --git a/spree/core/spec/services/spree/orders/upsert_items_spec.rb b/spree/core/spec/workflows/spree/orders/upsert_items_spec.rbsimilarity index 100%rename from spree/core/spec/services/spree/orders/upsert_items_spec.rbrename to spree/core/spec/workflows/spree/orders/upsert_items_spec.rb