Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Add validate and context hooks to the cart and order workflows

Damian Legawiecfbb532c2115b
diff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rb
index 9662c0cfd0..0bedfc3678 100644
--- a/spree/core/app/workflows/spree/carts/add_item.rb
+++ b/spree/core/app/workflows/spree/carts/add_item.rb
@@ -1,9 +1,10 @@
module Spree
module Carts
class AddItem < Spree::Workflow
- hooks :after_item_added
+ hooks :validate, :after_item_added
- # after_item_added handlers read these plus the argument readers.
+ # Hook handlers read these plus the argument readers. Both are nil
+ # when the :validate hook runs — it fires before the item is built.
attr_reader :line_item, :line_item_created
# @param cart [Spree::Cart, Spree::Order] draft orders ride the same pipeline
@@ -18,6 +19,11 @@ module Spree
super(cart: cart, variant: variant, quantity: quantity, metadata: metadata,
public_metadata: public_metadata, private_metadata: private_metadata, options: options)
+ # Veto point — purchase limits, B2B eligibility, per-group rules.
+ # Outside the transaction: nothing has been written yet, so a
+ # rejection costs no rollback.
+ run_hooks :validate
+
ApplicationRecord.transaction do
step :add_to_line_item
step :handle_stock_reservations if cart.in_checkout?
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index 141366d9a9..b6fb4dd586 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -18,9 +18,9 @@ module Spree
class Complete < Spree::Workflow
COMPLETING_TTL = 5.minutes
- hooks :before_finalize
+ hooks :validate, :before_finalize, :after_finalize
- # before_finalize handlers read this plus the argument readers.
+ # Hook handlers read this plus the argument readers.
attr_reader :order
# @param cart [Spree::Cart, Spree::Order] a draft order funnels into
@@ -52,6 +52,7 @@ module Spree
run_hooks :before_finalize
step :finalize_completion
+ run_hooks :after_finalize
success(order)
rescue ActiveRecord::RecordNotUnique
# Concurrent completion lost the unique orders.cart_id race —
@@ -104,9 +105,14 @@ module Spree
end
end
+ # Core's own checkout requirements first, then the extension veto —
+ # a handler that rejects here does so before any money moves and
+ # before the draft order exists, so the lock's rollback is the undo.
def validate_cart
validation = Spree::Checkout::Requirements.new(cart).call(completion: true)
failure(cart, code: 'validation_failed', errors: validation) if validation.any?
+
+ run_hooks :validate
end
def mark_completing
diff --git a/spree/core/app/workflows/spree/carts/recalculate.rb b/spree/core/app/workflows/spree/carts/recalculate.rb
index bd09f8493c..013dc66c4e 100644
--- a/spree/core/app/workflows/spree/carts/recalculate.rb
+++ b/spree/core/app/workflows/spree/carts/recalculate.rb
@@ -1,6 +1,12 @@
module Spree
module Carts
class Recalculate < Spree::Workflow
+ hooks :set_promotion_context, :after_recalculate
+
+ # Promotion context contributed by set_promotion_context handlers,
+ # readable by later hooks.
+ attr_reader :promotion_context
+
# @param cart [Spree::Cart, Spree::Order] draft orders ride the same pipeline
# @param line_item [Spree::LineItem, nil] the item whose change triggered this
def perform(cart: nil, order: nil, line_item: nil, line_item_created: false, options: {})
@@ -19,6 +25,7 @@ module Spree
# Typed rows (discounts + tax) are rebuilt by the full recalculation.
step :final_recalculation, with: -> { Spree.cart_recalculate_totals_workflow }
+ run_hooks :after_recalculate
success(line_item)
end
@@ -33,7 +40,13 @@ module Spree
cart.ensure_updated_fulfillments
end
+ # Extensions contribute eligibility data (customer segment, campaign
+ # attribution) before promotions are evaluated. Core's handler reads
+ # the cart directly; the context is exposed for handlers and for a
+ # promotion handler swapped in via Spree::Dependencies.
def activate_promotions
+ @promotion_context = run_hooks :set_promotion_context
+
::Spree::PromotionHandler::Cart.new(cart, line_item).activate
end
end
diff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
index 95da840ef6..95bfab8b2b 100644
--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb
+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
@@ -14,6 +14,13 @@ module Spree
# tax_lines/discounts/fees endpoints write rows directly, then run
# this).
class RecalculateTotals < Spree::Workflow
+ hooks :set_tax_line_context
+
+ # Tax context contributed by set_tax_line_context handlers (exemption
+ # certificates, customer tax IDs) — read by tax providers that support
+ # it. Nil until the typed rows are regenerated.
+ attr_reader :tax_line_context
+
# @param cart [Spree::Cart, Spree::Order]
def perform(cart:)
super
@@ -49,6 +56,7 @@ module Spree
def regenerate_typed_rows
Spree.adjusters.each { |adjuster| adjuster.adjust(cart) }
refresh_discount_and_fee_columns
+ @tax_line_context = run_hooks :set_tax_line_context
Spree.tax_provider.estimate(cart)
end
diff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rb
index 4bda0a8e85..f7626e928f 100644
--- a/spree/core/app/workflows/spree/orders/cancel.rb
+++ b/spree/core/app/workflows/spree/orders/cancel.rb
@@ -10,9 +10,10 @@ module Spree
class Cancel < Spree::Workflow
DEFAULT_REASON = 'other'.freeze
- hooks :after_cancel
+ hooks :before_cancel, :after_cancel
- # after_cancel handlers read this plus the argument readers.
+ # Hook handlers read this plus the argument readers. Nil when
+ # before_cancel runs — the record does not exist yet.
attr_reader :cancellation
# @param order [Spree::Order]
@@ -33,6 +34,11 @@ module Spree
step :ensure_cancellable
+ # Veto point — vendor policy, already-dispatched guards. Before the
+ # transaction: nothing is written yet, and payment settlement has
+ # not run.
+ run_hooks :before_cancel
+
@decided_at = canceled_at || Time.current
@amount_to_refund = refund_amount
@amount_to_refund ||= order.payment_total if refund_payments
diff --git a/spree/core/app/workflows/spree/orders/resume.rb b/spree/core/app/workflows/spree/orders/resume.rb
index f57f6a9e04..2bbefa05f0 100644
--- a/spree/core/app/workflows/spree/orders/resume.rb
+++ b/spree/core/app/workflows/spree/orders/resume.rb
@@ -6,13 +6,14 @@ module Spree
# inside the transaction), then risk reassessment, status recomputation
# and the order.resumed event.
class Resume < Spree::Workflow
- hooks :after_resume
+ hooks :before_resume, :after_resume
# @param order [Spree::Order]
def perform(order:)
super
step :ensure_resumable
+ run_hooks :before_resume
ApplicationRecord.transaction do
step :mark_placed
diff --git a/spree/core/lib/spree/hooks.rb b/spree/core/lib/spree/hooks.rb
index 0eb30da3b3..f9ad850f05 100644
--- a/spree/core/lib/spree/hooks.rb
+++ b/spree/core/lib/spree/hooks.rb
@@ -8,6 +8,9 @@ module Spree
class Hooks
class UnknownHookError < StandardError; end
+ # Reported (never raised) when two context-hook handlers set the same key.
+ class ContextCollision < StandardError; end
+
def initialize
@handlers = Hash.new { |hash, key| hash[key] = [] }
# workflow key => workflow class name; populated by Spree::Workflow
@@ -41,8 +44,21 @@ module Spree
@handlers[key.to_s].map { |entry| entry.is_a?(Proc) ? entry : entry.constantize.new }
end
+ # Calls every handler registered for the key and deep-merges the hashes
+ # they return, so context hooks (set_pricing_context, get_provider_data)
+ # can feed data into a calculation without sharing mutable state.
+ # Handlers returning anything other than a Hash contribute nothing —
+ # lifecycle handlers routinely return whatever their last expression was.
+ #
+ # @return [Hash] merged contributions; empty when no handler contributed
def dispatch(key, context)
- self.for(key).each { |handler| handler.call(context) }
+ self.for(key).each_with_object({}) do |handler, merged|
+ contribution = handler.call(context)
+ next unless contribution.is_a?(Hash)
+
+ report_collisions(key, merged, contribution)
+ merged.deep_merge!(contribution)
+ end
end
# Registered by Spree::Workflow at class-definition time.
@@ -94,6 +110,23 @@ module Spree
private
+ # Last writer wins on a collision, which is only defensible if it's
+ # visible — two extensions silently fighting over one key is the failure
+ # mode this whole contract exists to avoid.
+ def report_collisions(key, merged, contribution)
+ collisions = merged.keys & contribution.keys
+ return if collisions.empty?
+
+ Rails.error.report(
+ Spree::Hooks::ContextCollision.new(
+ "Hook '#{key}' handlers both set: #{collisions.join(', ')} — last registered handler wins"
+ ),
+ context: { hook: key, keys: collisions },
+ source: 'spree.hooks',
+ handled: true
+ )
+ end
+
def split_key(key)
parts = key.to_s.split('.')
[parts[0..-2].join('.'), parts[-1]]
diff --git a/spree/core/lib/spree/workflow.rb b/spree/core/lib/spree/workflow.rb
index af75fa05ce..fb6f1ecef3 100644
--- a/spree/core/lib/spree/workflow.rb
+++ b/spree/core/lib/spree/workflow.rb
@@ -154,6 +154,18 @@ module Spree
raise Halted.new(value)
end
+ # Vetoes the flow from a hook handler — the extension-facing twin of
+ # failure(...). Same mechanics (raises, unwinds the undo stack, rolls
+ # back an open transaction); the distinct name keeps "an extension
+ # rejected this" legible against "this step failed" at the call site.
+ # Public because handlers call it on the dispatched instance.
+ #
+ # @param message [String, Symbol] surfaced as the failure Result's error
+ # @param value [Object, nil] subject of the failure Result
+ def reject!(message, value = nil)
+ failure(value, message)
+ end
+
private
def step(name, with: nil, on_flow_failure: nil)
@@ -181,6 +193,10 @@ module Spree
# Dispatches every handler registered for this extension point with
# the workflow instance — argument readers plus whatever the workflow
# exposes via attr_reader are the handler's contract.
+ #
+ # @return [Hash] the deep-merged hashes handlers returned. Context hooks
+ # consume it (`context = run_hooks(:set_pricing_context)`); lifecycle
+ # hooks ignore it and validate handlers abort via #reject! instead.
def run_hooks(name)
unless self.class.declared_hooks&.include?(name.to_sym)
raise ContractError, "#{self.class.name} does not declare hook :#{name} — add `hooks :#{name}` to the class"
diff --git a/spree/core/spec/lib/spree/workflow_spec.rb b/spree/core/spec/lib/spree/workflow_spec.rb
index 1949eb7989..15798cc21d 100644
--- a/spree/core/spec/lib/spree/workflow_spec.rb
+++ b/spree/core/spec/lib/spree/workflow_spec.rb
@@ -264,6 +264,59 @@ RSpec.describe Spree::Workflow do
expect { Spree.hooks.validate! }.to raise_error(Spree::Hooks::UnknownHookError, /declares no hook 'typo_hook'/)
end
+ it 'merges the hashes context handlers return and ignores non-hash returns' do
+ workflow = build_workflow do
+ hooks :set_pricing_context
+ attr_reader :collected
+
+ def perform(subject:)
+ super
+ @collected = run_hooks :set_pricing_context
+ success(collected)
+ end
+ end
+
+ Spree.hooks.register('testing.sample_workflow.set_pricing_context') { |_flow| { tier: 'gold' } }
+ Spree.hooks.register('testing.sample_workflow.set_pricing_context') { |flow| { subject: flow.subject } }
+ # Lifecycle-style handler: returns whatever its last expression was.
+ Spree.hooks.register('testing.sample_workflow.set_pricing_context') { |_flow| 'not a hash' }
+
+ expect(workflow.call(subject: 7).value).to eq(tier: 'gold', subject: 7)
+ end
+
+ it 'returns an empty hash when no handler contributes' do
+ workflow = build_workflow do
+ hooks :set_pricing_context
+
+ def perform(subject:)
+ super
+ success(run_hooks(:set_pricing_context))
+ end
+ end
+
+ expect(workflow.call(subject: 1).value).to eq({})
+ end
+
+ it 'lets the last registered handler win a key collision and reports it' do
+ workflow = build_workflow do
+ hooks :set_pricing_context
+
+ def perform(subject:)
+ super
+ success(run_hooks(:set_pricing_context))
+ end
+ end
+
+ Spree.hooks.register('testing.sample_workflow.set_pricing_context') { |_flow| { tier: 'silver' } }
+ Spree.hooks.register('testing.sample_workflow.set_pricing_context') { |_flow| { tier: 'gold' } }
+
+ expect(Rails.error).to receive(:report).with(
+ an_instance_of(Spree::Hooks::ContextCollision), hash_including(source: 'spree.hooks')
+ )
+
+ expect(workflow.call(subject: 1).value).to eq(tier: 'gold')
+ end
+
it 'raises when dispatching a hook the class does not declare' do
workflow = build_workflow do
def perform(subject:)
@@ -276,6 +329,58 @@ RSpec.describe Spree::Workflow do
expect { workflow.call(subject: 1) }
.to raise_error(Spree::Workflow::ContractError, /does not declare hook :never_declared/)
end
+
+ describe 'reject!' do
+ it 'aborts the flow with a failure result the caller can inspect' do
+ workflow = build_workflow do
+ hooks :validate
+
+ def perform(subject:)
+ super
+ run_hooks :validate
+ step :never_runs
+ success(subject)
+ end
+
+ private
+
+ def never_runs = raise('should not be reached')
+ end
+
+ Spree.hooks.register('testing.sample_workflow.validate') do |flow|
+ flow.reject!('outside the return window')
+ end
+
+ result = workflow.call(subject: 1)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq('outside the return window')
+ end
+
+ it 'rolls back work committed by earlier steps in the same transaction' do
+ workflow = build_workflow do
+ hooks :validate
+
+ def perform(subject:)
+ super
+ ApplicationRecord.transaction do
+ step :create_store
+ run_hooks :validate
+ end
+ success(subject)
+ end
+
+ private
+
+ def create_store = Spree::Store.create!(name: 'Rejected', code: 'rejected-hook', url: 'rejected.test', mail_from_address: '[email protected]')
+ end
+
+ Spree.hooks.register('testing.sample_workflow.validate') { |flow| flow.reject!(:vetoed) }
+
+ expect { workflow.call(subject: 1) }.not_to change(Spree::Store, :count)
+ expect(workflow.call(subject: 1)).to be_failure
+ end
+ end
end
describe 'with: collaborators' do