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
Merge pull request #15075 from spree/feat/orders-complete-validate-hook
Damian Legawiecb0e63e07e9d5
diff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdxindex 48ad9b9a98..e38481b298 100644--- a/docs/developer/customization/workflows.mdx+++ b/docs/developer/customization/workflows.mdx@@ -265,6 +265,7 @@ is reported through `Rails.error` so it's visible rather than mysterious.| `carts.recalculate_totals` | `set_tax_line_context` | context | Before tax is estimated || `orders.cancel` | `before_cancel` | validate | Before the cancellation is recorded || `orders.cancel` | `after_cancel` | lifecycle | With the cancellation, in transaction |+| `orders.complete` | `validate` | validate | Under the order's row lock, before payments are processed and a draft order is placed — admin and B2B drafts. Checkout does not run it (its payment is already taken by then; veto checkout in `carts.complete.validate`), nor do the orders a seller division places beside the first. Handlers hold the order's lock, so keep them to database reads || `fulfillments.create` | `validate` | validate | Before the order is locked || `fulfillments.create` | `get_provider_data` | context | Before the fulfillment is built || `fulfillments.create` | `after_create` | lifecycle | After the fulfillment is created and totals recalculated |diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex ce772d033e..193036b14e 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -829,7 +829,7 @@ module Spree# reaches it through +Spree.carts_complete_workflow+). Removed in 6.1.def finalize!Spree::Deprecation.warn('Spree::Order#finalize! is deprecated and will be removed in Spree 6.1. Completion runs through Spree.order_complete_workflow (Spree::Orders::Complete).')- Spree.order_complete_workflow.call(order: self, payment_pending: true)+ Spree.order_complete_workflow.call(order: self, payment_pending: true, validated: true)enddef fulfill!diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex e4dcb919ac..42b18b2205 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -560,7 +560,9 @@ module Spree# its children is the order this checkout carries on with. No child holds# the confirmation: the customer is confirmed from the group.def complete_orders- result = Spree.order_complete_workflow.call(order: order, payment_pending: payment_pending)+ # carts.complete.validate ran before the payment was taken; a veto now+ # would leave the customer charged for an order that never places.+ result = Spree.order_complete_workflow.call(order: order, payment_pending: payment_pending, validated: true)failure(cart, code: 'completion_failed', message: result.error) if result.failure?return unless result.value.is_a?(Spree::OrderGroup)diff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rbindex 5ad4612878..6a21b11583 100644--- a/spree/core/app/workflows/spree/orders/complete.rb+++ b/spree/core/app/workflows/spree/orders/complete.rb@@ -7,6 +7,8 @@ module Spree# may still need to process payments). Idempotent: an already-placed# order halts successfully, so interrupted completions replay safely.class Complete < Spree::Workflow+ hooks :validate+# Set only when the order divided between sellers.attr_reader :order_group@@ -18,9 +20,13 @@ module Spree# rollup work's call (docs/plans/6.0-b2b-wholesale-shipping.md phase 7)# @param notify_customer [Boolean, nil] admin drafts pass false to# complete silently; nil (checkout) leaves customer notification on+ # @param validated [Boolean] the caller already ran its own veto, so the+ # validate hook is skipped: checkout's finalize, whose+ # carts.complete.validate ran before the payment was taken, and the+ # orders a seller division places beside the one it came from# @return [Spree::ServiceModule::Result] value is the order, or the# Spree::OrderGroup when it divided between sellers- def perform(order:, payment_pending: false, notify_customer: nil)+ def perform(order:, payment_pending: false, notify_customer: nil, validated: false)superorder.notify_customer = notify_customer unless notify_customer.nil?@@ -37,20 +43,30 @@ module Spreestep :ensure_not_canceled- order.with_lock do- unless order.reload.placed?- step :process_payments unless payment_pending || !order.payment_required?- step :split_by_seller- step :finalize_fulfillments- step :place_order- step :freeze_tax_exemptions- step :use_coupon_codes- step :redeem_gift_card- step :fulfill_auto_fulfillments- step :ensure_digital_links- end+ placed_here = order.with_lock do+ # A completion running alongside this one placed it while this one+ # waited for the lock. Placed, not merely in that status: it may+ # have been canceled since.+ next false if order.reload.completed?++ step :validate_order unless validated+ step :process_payments unless payment_pending || !order.payment_required?+ step :split_by_seller+ step :finalize_fulfillments+ step :place_order+ step :freeze_tax_exemptions+ step :use_coupon_codes+ step :redeem_gift_card+ step :fulfill_auto_fulfillments+ step :ensure_digital_links+ trueend+ # The run that placed it announces it and finishes what follows; this+ # one answers as a replay would, so nothing after placement happens+ # twice.+ halt!(order.order_group || order) unless placed_here+step :ensure_placed_statusstep :release_stock_reservationsstep :cancel_unused_payment_sessions@@ -67,6 +83,14 @@ module Spreefailure(order, 'Order is canceled') if order.canceled?end+ # The extension veto, under the order's row lock: a handler sees the+ # order as it is placed, and anything else that takes the lock to change+ # it waits for the outcome. Rejecting rolls the lock back before any+ # payment is processed.+ def validate_order+ run_hooks :validate+ end+def process_paymentsorder.process_payments! unless payment_covered?@@ -276,7 +300,8 @@ module Spreeenddef place_sibling(sibling)- result = Spree.order_complete_workflow.call(order: sibling, payment_pending: true, notify_customer: false)+ result = Spree.order_complete_workflow.call(order: sibling, payment_pending: true, notify_customer: false,+ validated: true)failure(order, result.error) if result.failure?enddiff --git a/spree/core/lib/spree/agent_tools/default_catalog.rb b/spree/core/lib/spree/agent_tools/default_catalog.rbindex 3fabb53e4f..f1eef7ff69 100644--- a/spree/core/lib/spree/agent_tools/default_catalog.rb+++ b/spree/core/lib/spree/agent_tools/default_catalog.rb@@ -59,8 +59,10 @@ module Spree# Orders. `restock_items` is hidden: it is deprecated and ignored, so# offering it would invite a model to set something that does nothing.+ # `validated` is for callers that already ran their own veto; offered+ # to a model it would be a way around orders.complete.validate.order_cancel_workflow: { permission: 'write_orders', except: %i[restock_items] },- order_complete_workflow: 'write_orders',+ order_complete_workflow: { permission: 'write_orders', except: %i[validated] },# Fulfillmentfulfillment_create_workflow: 'write_fulfillments',diff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rbindex 506a82c8d5..6145ad9bbc 100644--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb@@ -2,6 +2,8 @@ require 'spec_helper'module Spreedescribe Orders::Complete do+ after { Spree.hooks.unregister('orders.complete.validate') }+let(:store) { @default_store }let(:order) { Spree::Order.create(email: '[email protected]') }@@ -129,6 +131,78 @@ module Spreeexpect(described_class.call(order: order)).to be_failureend+ describe 'the validate hook' do+ let(:order) { create(:order_with_line_items, store: store) }++ it 'lets a handler refuse the placement' do+ Spree.hooks.register('orders.complete.validate') { |workflow| workflow.reject!('quote changed') }++ result = described_class.call(order: order, payment_pending: true)++ expect(result).to be_failure+ expect(result.error.to_s).to eq('quote changed')+ expect(order.reload).to be_draft+ expect(order.completed_at).to be_nil+ end++ it 'is skipped when the caller already ran its own veto, as checkout does' do+ Spree.hooks.register('orders.complete.validate') { |workflow| workflow.reject!('never') }++ result = described_class.call(order: order, payment_pending: true, validated: true)++ expect(result).to be_success+ expect(order.reload).to be_placed+ end++ it 'runs under the order lock, before placement' do+ locked = false+ allow(order).to receive(:with_lock).and_wrap_original do |original, *args, &block|+ original.call(*args) do+ locked = true+ block.call+ end+ end+ seen = nil+ Spree.hooks.register('orders.complete.validate') { |workflow| seen = [locked, workflow.order.placed?] }++ described_class.call(order: order, payment_pending: true)++ expect(seen).to eq([true, false])+ end+ end++ # Two completions racing: the second waits on the lock while the first+ # places the order, then must not place it, or announce it, again.+ it 'neither places nor announces again an order another completion placed first' do+ order = create(:order_with_line_items, store: store)+ allow(order).to receive(:with_lock).and_wrap_original do |original, *args, &block|+ Spree::Order.where(id: order.id).update_all(status: 'placed', completed_at: Time.current)+ original.call(*args, &block)+ end+ handler_ran = false+ Spree.hooks.register('orders.complete.validate') { handler_ran = true }++ expect(order).not_to receive(:publish_event)+ result = described_class.call(order: order, payment_pending: true)++ expect(result).to be_success+ expect(result.value).to eq(order)+ expect(handler_ran).to be(false)+ end++ it 'does not place again an order another completion placed and someone canceled while it waited' do+ order = create(:order_with_line_items, store: store)+ allow(order).to receive(:with_lock).and_wrap_original do |original, *args, &block|+ Spree::Order.where(id: order.id).update_all(status: 'canceled', completed_at: Time.current, canceled_at: Time.current)+ original.call(*args, &block)+ end++ result = described_class.call(order: order, payment_pending: true)++ expect(result).to be_success+ expect(order.reload).to be_canceled+ end+it 'sets completed_at and places the order' doresult = described_class.call(order: order)@@ -327,6 +401,16 @@ module Spreeexpect(Spree::OrderGroup.count).to eq(0)end+ it 'validates the purchase once, not each order the division places' do+ draft = draft_for(seller, other_seller)+ validated = []+ Spree.hooks.register('orders.complete.validate') { |workflow| validated << workflow.order.id }++ described_class.call(order: draft, payment_pending: true)++ expect(validated).to eq([draft.id])+ end+it 'divides an order holding two sellers goods into one order each' dodraft = draft_for(seller, other_seller)@@ -427,6 +511,24 @@ module Spreeexpect(announced).to eq(1)end+ # The run that placed it announced it, with its own notify_customer; the+ # one that waited on the lock has nothing to add and no such flag.+ it 'does not announce the group again from a completion that lost the race', :events do+ draft = draft_for(seller, other_seller)+ waiting = Spree::Order.find(draft.id)+ described_class.call(order: draft, payment_pending: true, notify_customer: false)++ announced = 0+ allow_any_instance_of(Spree::OrderGroup).to receive(:publish_event) do |_, name, *|+ announced += 1 if name == 'order_group.completed'+ end++ result = described_class.call(order: waiting, payment_pending: true)++ expect(result.value).to be_a(Spree::OrderGroup)+ expect(announced).to eq(0)+ end+it 'divides once when the completion is replayed' dodraft = draft_for(seller, other_seller)described_class.call(order: draft, payment_pending: true)