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
Added cart copiers and a merge hook for carrying extension records onto orders (#15078)
Damian Legawiecea3f6073ed81
diff --git a/docs/developer/customization/checkout.mdx b/docs/developer/customization/checkout.mdxindex fbd1aceda8..165f9b430d 100644--- a/docs/developer/customization/checkout.mdx+++ b/docs/developer/customization/checkout.mdx@@ -1,6 +1,6 @@---title: Customizing Checkout-description: Add your own checkout step or requirement, and reorder or remove the built-in ones.+description: Add your own checkout step or requirement, reorder or remove the built-in ones, and carry your own records onto the order.---Spree does not run your checkout — your storefront does. What Spree owns is the list@@ -119,6 +119,63 @@ For anything a customer has to fix, a requirement is better: it is reported on ecart read, so the storefront can show it while they can still act, rather than failingat the last step with an error they have to interpret.+## Carrying your own records onto the order++A cart's `metadata` is copied onto the order for you. Records your extension keeps in+its own tables against a cart or its line items are not. Register a cart copier to+bring them across:++```ruby config/initializers/engravings.rb+Spree.cart_copiers << MyApp::CopyEngravings+```++```ruby app/services/my_app/copy_engravings.rb+module MyApp+ class CopyEngravings+ def self.call(cart:, order:, line_item_map:)+ MyApp::Engraving.where(line_item: line_item_map.keys).find_each do |engraving|+ engraving.dup.update!(line_item: line_item_map.fetch(engraving.line_item))+ end+ end+ end+end+```++`line_item_map` pairs each cart line item with its copy on the order. Copiers run+whenever a cart becomes an order: at checkout, and when a draft order is created from a+cart (`Spree::Orders::CreateFromCart`, which quoting extensions use). They run inside+that copy's transaction once the order's line items exist, so a copier that raises rolls+the whole copy back, and the cart is left as it was.++The copy commits before the payment is taken. If the payment fails before anything was+captured, the order is deleted rather than rolled back, and the customer's next attempt+runs your copier again on a new order. Once a payment has been captured the order is+kept, and completing it resumes that order without copying again. Tie the copied records+to the order's line items with a dependent or cascading delete, so they go with a deleted+order.++When a checkout spans several sellers, the order is divided after the copy. Line items+keep their ids as they move to each seller's order, so key your records by line item+rather than by order.++### When a guest signs in++A guest's cart is folded into the customer's cart when they sign in, and the guest cart+is then deleted. That is a move, not a copy, so it has its own hook rather than a cart+copier. A guest item the customer's cart did not have moves across with its id; one it+already had is added to the matching item and deleted. `carts.merge.after_items_moved`+runs before those deletions, inside the merge's transaction:++```ruby config/initializers/engravings.rb+Spree.hooks.register('carts.merge.after_items_moved') do |merge|+ merge.line_item_map.each do |guest_line_item, line_item|+ next if guest_line_item == line_item++ MyApp::Engraving.where(line_item: guest_line_item).update_all(line_item_id: line_item.id)+ end+end+```+## Related- [Carts](/developer/core-concepts/carts) — reading requirements and completing a cartdiff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdxindex e38481b298..dbe2e4bf4c 100644--- a/docs/developer/customization/workflows.mdx+++ b/docs/developer/customization/workflows.mdx@@ -259,6 +259,7 @@ is reported through `Rails.error` so it's visible rather than mysterious.| `carts.complete` | `before_finalize` | lifecycle | After payment, before the order is placed || `carts.complete` | `after_finalize` | lifecycle | After the order is placed || `carts.merge` | `validate` | validate | Before any items move between carts |+| `carts.merge` | `after_items_moved` | lifecycle | Inside the merge's transaction, once the guest cart's items have moved or been added to matching ones, and before those absorbed items are deleted. `workflow.line_item_map` pairs each guest item with the item now holding it || `carts.merge` | `after_merge` | lifecycle | After the carts are folded together || `carts.recalculate` | `set_promotion_context` | context | Before promotions are evaluated || `carts.recalculate` | `after_recalculate` | lifecycle | After the cart is fully repriced |diff --git a/spree/core/app/services/spree/orders/create_from_cart.rb b/spree/core/app/services/spree/orders/create_from_cart.rbindex 1a7e6cb5ce..329089ab4b 100644--- a/spree/core/app/services/spree/orders/create_from_cart.rb+++ b/spree/core/app/services/spree/orders/create_from_cart.rb@@ -25,7 +25,8 @@ module Spreeorder = build_order(cart, customer: customer, created_by: created_by)order.save!- copy_line_items(cart, order)+ line_item_map = copy_line_items(cart, order)+ Spree.cart_copiers.each { |copier| copier.call(cart: cart, order: order, line_item_map: line_item_map) }estimate_taxes(order)build_fulfillments(order)order.recalculate_totals!@@ -60,12 +61,15 @@ module Spree)end+ # @return [Hash{Spree::LineItem => Spree::LineItem}] cart line item → its+ # copy on the order, the map {Spree.cart_copiers} receivedef copy_line_items(cart, order)- cart.line_items.each do |cart_line_item|+ cart.line_items.to_a.index_with do |cart_line_item|line_item = order.line_items.new(cart_line_item.attributes.slice(*LINE_ITEM_COPIED_ATTRIBUTES))# Estimated once for the batch below, not once per line.line_item.skip_tax_estimation = trueline_item.save!+ line_itemendenddiff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex 42b18b2205..fe6e492296 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -292,6 +292,7 @@ module Spreecopy_tax_exemptions!(cart, order, line_item_map, fulfillment_map, fee_map)copy_po_document!(cart, order)repoint_money_records!(cart, order)+ Spree.cart_copiers.each { |copier| copier.call(cart: cart, order: order, line_item_map: line_item_map) }order.update_columns(item_total: cart.item_total,diff --git a/spree/core/app/workflows/spree/carts/merge.rb b/spree/core/app/workflows/spree/carts/merge.rbindex 4ba2904cd1..984d3b0706 100644--- a/spree/core/app/workflows/spree/carts/merge.rb+++ b/spree/core/app/workflows/spree/carts/merge.rb@@ -10,7 +10,14 @@ module Spree# cap the merged quantity) and previously required replacing the whole# strategy class.class Merge < Spree::Workflow- hooks :validate, :after_merge+ hooks :validate, :after_items_moved, :after_merge++ # Every line item of the folded-in cart → the line item now holding its+ # quantity: itself when it moved across, or the surviving cart's line it+ # was added to. Set before +after_items_moved+ runs.+ #+ # @return [Hash{Spree::LineItem => Spree::LineItem}]+ attr_reader :line_item_map# @param cart [Spree::Cart] the surviving cart# @param other_cart [Spree::Cart, nil] the cart folded in and destroyed@@ -28,6 +35,10 @@ module SpreeApplicationRecord.transaction dostep :move_line_items+ # Inside the transaction and before the absorbed lines are deleted,+ # so an extension can move what it keeps against them.+ run_hooks :after_items_moved+ step :destroy_absorbed_line_itemsstep :associate_customerstep :destroy_drained_cartend@@ -46,19 +57,29 @@ module Spreeend# A matching item absorbs the quantity; everything else is re-pointed- # at the surviving cart.+ # at the surviving cart. Absorbed items are deleted only after the+ # +after_items_moved+ hook.def move_line_items- other_cart.line_items.reload.each do |other_line_item|+ @line_item_map = other_cart.line_items.reload.to_a.index_with do |other_line_item|existing = matching_line_item(other_line_item)if existingexisting.quantity += other_line_item.quantityexisting.save!- other_line_item.destroy!+ existingelseother_line_item.update!(cart: cart, order: nil)+ other_line_itemendend+ # Matching loaded the surviving cart's items before any moved in.+ cart.line_items.reset+ end++ def destroy_absorbed_line_items+ line_item_map.each do |other_line_item, line_item|+ other_line_item.destroy! unless other_line_item == line_item+ endend# Options-aware comparison (personalization, gift wrapping) with adiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 1b951e393e..dbcff314ac 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -323,6 +323,22 @@ module Spree# @return [Array<Class>]singleton_class.delegate :tax_providers, :tax_providers=, to: :spree_config+ # Extensions that copy their own cart data onto the order a cart becomes.+ # Each entry is a class with a class-level +call(cart:, order:,+ # line_item_map:)+ (a class, so it is re-resolved when code reloads in+ # development; see {.refresh_provider_registries!}), where the map+ # pairs each cart line item with its copy on the order. Both copies run them+ # — checkout ({Spree::Carts::Complete}) and the draft-order copy+ # ({Spree::Orders::CreateFromCart}) — inside their transaction, once the+ # order's line items exist, so an entry that raises rolls the order back.+ #+ # Append, never assign, so an extension does not drop what another added:+ #+ # Spree.cart_copiers << MyApp::CopyEngravings+ #+ # @return [Array<Class>]+ singleton_class.delegate :cart_copiers, :cart_copiers=, to: :spree_config+# Pricing engines a store can be pointed at. Connector gems append their own,# so a merchant picks from what is actually installed.#@@ -400,7 +416,8 @@ module Spreedef self.refresh_provider_registries![Rails.application.config.spree.delivery_rate_providers,Rails.application.config.spree.fulfillment_providers,- Rails.application.config.spree.pickup_point_providers].compact.each do |registry|+ Rails.application.config.spree.pickup_point_providers,+ Rails.application.config.spree.cart_copiers].compact.each do |registry|registry.map! { |entry| entry.is_a?(Module) && entry.name ? entry.name.constantize : entry }endenddiff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex c3eb88a33b..1d5be8503c 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -10,6 +10,7 @@ module Spree:dependencies,:payment_methods,:adjusters,+ :cart_copiers,:media_viewable_types,:default_tax_provider,:tax_providers,@@ -79,7 +80,7 @@ module Spree%i[subscribers actor_classes commission_rules delivery_method_rules seller_requirementsdelivery_rate_providers tax_providers pricing_providers inventory_providerspayout_providers digital_asset_providers delivery_profile_types pickup_point_providers- maintenance_tasks].each do |registry|+ maintenance_tasks cart_copiers].each do |registry|app.config.spree[registry] = []endapp.config.spree.line_item_comparison_hooks = Set.newdiff --git a/spree/core/spec/lib/spree/core_spec.rb b/spree/core/spec/lib/spree/core_spec.rbindex 1f51e88d86..41b0ad76e8 100644--- a/spree/core/spec/lib/spree/core_spec.rb+++ b/spree/core/spec/lib/spree/core_spec.rb@@ -170,5 +170,18 @@ describe Spree doexpect(registry).not_to include(stale)expect(registry).to include(anonymous)end++ it 'refreshes cart copiers, which are called on every checkout' do+ stale_copier = Class.new.tap { |klass| klass.define_singleton_method(:name) { 'Spree::Orders::CreateFromCart' } }+ original = Spree.cart_copiers.dup+ Spree.cart_copiers << stale_copier++ Spree.refresh_provider_registries!++ expect(Spree.cart_copiers).to include(Spree::Orders::CreateFromCart)+ expect(Spree.cart_copiers).not_to include(stale_copier)+ ensure+ Spree.cart_copiers.replace(original)+ endendenddiff --git a/spree/core/spec/services/spree/orders/create_from_cart_spec.rb b/spree/core/spec/services/spree/orders/create_from_cart_spec.rbindex 7fc0548c55..a71dab6d73 100644--- a/spree/core/spec/services/spree/orders/create_from_cart_spec.rb+++ b/spree/core/spec/services/spree/orders/create_from_cart_spec.rb@@ -90,5 +90,35 @@ module Spreeexpect(result.value).to eq(:cart_is_required)endend++ describe 'cart copiers' do+ let(:received) { [] }+ let(:copier) { ->(**args) { received << args } }++ before { allow(Spree).to receive(:cart_copiers).and_return([copier]) }++ # Extensions keep their own records against cart lines; the map is how+ # they find each line's copy on the draft.+ it 'hands each copier the cart, the draft and every cart line paired with its copy' do+ order = described_class.call(cart: cart).value++ expect(received.size).to eq(1)+ expect(received.first[:cart]).to eq(cart)+ expect(received.first[:order]).to eq(order)++ line_item_map = received.first[:line_item_map]+ expect(line_item_map.keys).to match_array(cart.line_items.to_a)+ line_item_map.each do |cart_line_item, order_line_item|+ expect(order_line_item.order_id).to eq(order.id)+ expect(order_line_item.variant_id).to eq(cart_line_item.variant_id)+ end+ end++ it 'leaves no draft behind when a copier raises' do+ allow(Spree).to receive(:cart_copiers).and_return([->(**) { raise ActiveRecord::RecordInvalid, Spree::Order.new }])++ expect { described_class.call(cart: cart) }.not_to change(Spree::Order, :count)+ end+ endendenddiff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rbindex a78436ab8f..750ff5cb4a 100644--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb@@ -618,6 +618,36 @@ module Spreeendend+ describe 'cart copiers' do+ let(:received) { [] }+ let(:copier) { ->(**args) { received << args } }++ before { allow(Spree).to receive(:cart_copiers).and_return([copier]) }++ it 'hands each copier the cart, the order and every cart line paired with its copy' do+ order = described_class.call(cart: ready_cart).value++ expect(received.size).to eq(1)+ expect(received.first[:cart]).to eq(ready_cart)+ expect(received.first[:order]).to eq(order)++ line_item_map = received.first[:line_item_map]+ expect(line_item_map.keys).to match_array(ready_cart.line_items.to_a)+ expect(line_item_map.values.map(&:id)).to match_array(order.line_items.ids)+ end++ # The copy runs in the same transaction as the order, so a copier that+ # cannot finish leaves the cart as it was rather than an order missing+ # what the extension kept against it.+ it 'rolls the completion back when a copier raises' do+ allow(Spree).to receive(:cart_copiers).and_return([->(**) { raise ActiveRecord::RecordInvalid, Spree::Order.new }])++ expect { described_class.call(cart: ready_cart) }.to raise_error(ActiveRecord::RecordInvalid)+ expect(Spree::Order.where(cart_id: ready_cart.id)).to be_empty+ expect(ready_cart.reload.completing_at).to be_nil+ end+ end+describe 'guest checkout policy' doit 'fails when the channel forbids guest checkout and the cart has no customer' doallow_any_instance_of(Spree::Cart).to receive(:guest_checkout_disallowed?).and_return(true)diff --git a/spree/core/spec/workflows/spree/carts/merge_spec.rb b/spree/core/spec/workflows/spree/carts/merge_spec.rbindex cf94166b50..a9e24b109a 100644--- a/spree/core/spec/workflows/spree/carts/merge_spec.rb+++ b/spree/core/spec/workflows/spree/carts/merge_spec.rb@@ -72,5 +72,38 @@ RSpec.describe Spree::Carts::Merge doexpect(merged_count).to eq(1)end++ # Extensions keep records against the guest cart's lines; the map tells+ # them where each line went while the folded-in lines still exist.+ describe 'after_items_moved' do+ let(:other_variant) { create(:variant) }+ let!(:existing) { cart.line_items.create!(variant: variant, quantity: 1, currency: cart.currency) }+ let!(:absorbed) { other_cart.line_items.create!(variant: variant, quantity: 2, currency: other_cart.currency) }+ let!(:moved) { other_cart.line_items.create!(variant: other_variant, quantity: 1, currency: other_cart.currency) }++ it 'maps each guest line to the line now holding it, before the absorbed ones are deleted' do+ seen = nil+ seen_cart_lines = nil+ Spree.hooks.register('carts.merge.after_items_moved') do |flow|+ seen = flow.line_item_map.to_h { |from, to| [from.id, [to.id, Spree::LineItem.exists?(from.id)]] }+ seen_cart_lines = flow.cart.line_items.to_a+ end++ described_class.call(cart: cart, other_cart: other_cart)++ expect(seen).to eq(absorbed.id => [existing.id, true], moved.id => [moved.id, true])+ expect(seen_cart_lines).to contain_exactly(existing, moved)+ expect(Spree::LineItem.exists?(absorbed.id)).to be(false)+ expect(cart.reload.line_items).to contain_exactly(existing, moved)+ end++ it 'rolls the merge back when a handler raises' do+ Spree.hooks.register('carts.merge.after_items_moved') { |_flow| raise ActiveRecord::RecordInvalid, Spree::Cart.new }++ expect { described_class.call(cart: cart, other_cart: other_cart) }.to raise_error(ActiveRecord::RecordInvalid)+ expect(other_cart.reload.line_items).to contain_exactly(absorbed, moved)+ expect(existing.reload.quantity).to eq(1)+ end+ endendend