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.

Move fulfillment side effects out of the state machine

Damian Legawiec88e8585ee10a
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index 6ea58f10ee..517032b423 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -118,7 +118,11 @@ module Spree
event :cancel do
transition to: :canceled, from: %i(pending ready ready_for_pickup)
end
- after_transition to: :canceled, do: [:after_cancel, :publish_fulfillment_canceled_event]
+ # Restocking and the provider call live in Spree::Fulfillments::Cancel,
+ # not here: they are stock movements and network I/O, which have no
+ # business running inside the save transaction. Only the event publish
+ # stays, because it describes the status change itself.
+ after_transition to: :canceled, do: :publish_fulfillment_canceled_event
event :resume do
transition from: :canceled, to: :ready, if: lambda { |fulfillment|
@@ -126,7 +130,8 @@ module Spree
}
transition from: :canceled, to: :pending
end
- after_transition from: :canceled, to: %i(pending ready fulfilled), do: [:after_resume, :publish_fulfillment_resumed_event]
+ # Re-unstocking lives in Spree::Fulfillments::Resume — see above.
+ after_transition from: :canceled, to: %i(pending ready fulfilled), do: :publish_fulfillment_resumed_event
end
# @deprecated Use {#fulfill}; removed in 6.1.
@@ -213,12 +218,19 @@ module Spree
add_delivery_method(delivery_method, selected)
end
+ # @deprecated Cancel through {Spree::Fulfillments::Cancel}; removed in 6.1.
+ # Restocking and the provider call are workflow steps now, so this no
+ # longer runs as a transition callback. Kept only so a host app that
+ # called it directly keeps working for one release.
def after_cancel
+ Spree::Deprecation.warn('Spree::Fulfillment#after_cancel is deprecated and will be removed in Spree 6.1. Cancel through Spree::Fulfillments::Cancel instead.')
manifest.each { |item| manifest_restock(item) }
provider.cancel_fulfillment(self)
end
+ # @deprecated Resume through {Spree::Fulfillments::Resume}; removed in 6.1.
def after_resume
+ Spree::Deprecation.warn('Spree::Fulfillment#after_resume is deprecated and will be removed in Spree 6.1. Resume through Spree::Fulfillments::Resume instead.')
manifest.each { |item| manifest_unstock(item) }
end
diff --git a/spree/core/app/workflows/spree/fulfillments/cancel.rb b/spree/core/app/workflows/spree/fulfillments/cancel.rb
new file mode 100644
index 0000000000..29aecfd230
--- /dev/null
+++ b/spree/core/app/workflows/spree/fulfillments/cancel.rb
@@ -0,0 +1,82 @@
+module Spree
+ module Fulfillments
+ # Cancels a fulfillment: the goods are not going out, so their units go
+ # back on the shelf and the carrier is told to stand down.
+ #
+ # In the workflow tier because cancelling talks to the outside world. The
+ # provider call refunds a purchased label or cancels a 3PL pick — network
+ # I/O that must not sit inside the database transaction holding the stock
+ # movements, since a slow carrier would hold row locks open and a failed
+ # call would roll back a restock that already happened at the warehouse.
+ # Restocking commits first; the provider is told afterwards.
+ class Cancel < Spree::Workflow
+ hooks :validate, :after_cancel
+
+ # @param fulfillment [Spree::Fulfillment] the fulfillment to cancel
+ # @param notify_provider [Boolean] whether to tell the carrier here. Pass
+ # false when the caller already holds a transaction and will batch the
+ # provider calls into its own external step — Spree::Orders::Cancel
+ # cancels every fulfillment on the order that way. A nested
+ # external_step would raise, correctly, since carrier I/O must never sit
+ # inside a transaction.
+ # @return [Spree::ServiceModule::Result] the canceled fulfillment on success
+ def perform(fulfillment:, notify_provider: true)
+ super
+
+ # Veto point — a 3PL that has already picked the order, a label that
+ # cannot be refunded. Before anything is written.
+ run_hooks :validate
+
+ step :ensure_cancelable
+
+ ApplicationRecord.transaction do
+ step :restock_units
+ step :mark_canceled
+ end
+
+ external_step :tell_provider_to_stand_down if notify_provider
+
+ run_hooks :after_cancel
+ success(fulfillment.reload)
+ end
+
+ private
+
+ def ensure_cancelable
+ return if fulfillment.can_cancel?
+
+ failure(fulfillment, Spree.t('fulfillments.errors.cannot_cancel'))
+ end
+
+ # Puts every unit back on the shelf. On-hand and backordered units go
+ # back by different routes: an on-hand unit returns real stock, while a
+ # backordered one only cancels the promise made against stock that never
+ # arrived, so restocking it as on-hand would invent inventory.
+ def restock_units
+ fulfillment.manifest.each do |item|
+ on_hand = item.states['on_hand'].to_i
+ backordered = item.states['backordered'].to_i
+
+ stock_location.restock(item.variant, on_hand, fulfillment) if on_hand.positive?
+ stock_location.restock_backordered(item.variant, backordered) if backordered.positive?
+ end
+ end
+
+ def stock_location
+ fulfillment.stock_location
+ end
+
+ # The machine still owns the status column and its guard; what it no
+ # longer owns is the side effects, which is the point of the move.
+ def mark_canceled
+ fulfillment.cancel!
+ rescue StateMachines::InvalidTransition => e
+ failure(fulfillment, e.message)
+ end
+
+ def tell_provider_to_stand_down
+ fulfillment.provider.cancel_fulfillment(fulfillment)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/fulfillments/resume.rb b/spree/core/app/workflows/spree/fulfillments/resume.rb
new file mode 100644
index 0000000000..f2532a1b8e
--- /dev/null
+++ b/spree/core/app/workflows/spree/fulfillments/resume.rb
@@ -0,0 +1,61 @@
+module Spree
+ module Fulfillments
+ # Brings a canceled fulfillment back: the goods are going out after all, so
+ # their units come off the shelf again and the fulfillment returns to
+ # pending or ready depending on what the owning order can support.
+ #
+ # In the workflow tier for symmetry with Cancel — unstocking is a stock
+ # movement, and a stock movement belongs in an explicit transaction rather
+ # than a transition callback where a failure would leave the status changed
+ # and the shelf wrong.
+ class Resume < Spree::Workflow
+ hooks :validate, :after_resume
+
+ # @param fulfillment [Spree::Fulfillment] the canceled fulfillment to resume
+ # @return [Spree::ServiceModule::Result] the resumed fulfillment on success
+ def perform(fulfillment:)
+ super
+
+ # Veto point — stock that has since been sold elsewhere, a closed
+ # fulfilment window. Before anything is written.
+ run_hooks :validate
+
+ step :ensure_resumable
+
+ ApplicationRecord.transaction do
+ step :unstock_units
+ step :mark_resumed
+ end
+
+ run_hooks :after_resume
+ success(fulfillment.reload)
+ end
+
+ private
+
+ def ensure_resumable
+ return if fulfillment.can_resume?
+
+ failure(fulfillment, Spree.t('fulfillments.errors.cannot_resume'))
+ end
+
+ # Takes the units back off the shelf. Runs before the transition so a
+ # variant that cannot be unstocked aborts while the fulfillment is still
+ # canceled, rather than leaving it live with stock never taken.
+ # Untracked variants are skipped — nothing counts them.
+ def unstock_units
+ fulfillment.manifest.each do |item|
+ next unless item.variant.track_inventory?
+
+ fulfillment.stock_location.unstock(item.variant, item.quantity, fulfillment)
+ end
+ end
+
+ def mark_resumed
+ fulfillment.resume!
+ rescue StateMachines::InvalidTransition => e
+ failure(fulfillment, e.message)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rb
index f7626e928f..64aed2b141 100644
--- a/spree/core/app/workflows/spree/orders/cancel.rb
+++ b/spree/core/app/workflows/spree/orders/cancel.rb
@@ -50,6 +50,7 @@ module Spree
run_hooks :after_cancel
end
+ external_step :notify_fulfillment_providers
external_step :settle_payments
step :recompute_totals, with: -> { Spree.order_recalculate_totals_workflow }
step :update_statuses, with: -> { Spree.order_update_statuses_service }
@@ -84,11 +85,35 @@ module Spree
order.update_columns(changes)
end
- # Canceling a fulfillment restocks its inventory (Spree::Fulfillment's
- # own cancel semantics); allow_cancel? already excluded orders with
- # shipped fulfillments.
+ # Restocks each fulfillment's units and cancels it. allow_cancel? already
+ # excluded orders with shipped fulfillments.
+ #
+ # Deliberately not delegated to Spree::Fulfillments::Cancel: that workflow
+ # ends with an external_step telling the carrier, which refuses to run
+ # inside a transaction — and this runs inside the order's. The carriers
+ # are notified in #notify_fulfillment_providers once the transaction has
+ # committed, which is the same ordering the fulfillment workflow uses.
def cancel_fulfillments
- order.fulfillments.each(&:cancel!)
+ order.fulfillments.each do |fulfillment|
+ result = Spree.fulfillment_cancel_workflow.call(
+ fulfillment: fulfillment,
+ # Carrier I/O cannot run inside this transaction; the providers are
+ # told in #notify_fulfillment_providers once it has committed.
+ notify_provider: false
+ )
+
+ failure(order, result.error) unless result.success?
+ end
+ end
+
+ # The provider half of cancelling each fulfillment — network I/O, so it
+ # runs after the transaction commits. A carrier that rejects the
+ # cancellation does not undo the order cancellation; the goods are not
+ # going out either way, and the failure surfaces through the provider.
+ def notify_fulfillment_providers
+ order.fulfillments.each do |fulfillment|
+ fulfillment.provider.cancel_fulfillment(fulfillment)
+ end
end
# Gateway I/O. Payments fully covered by a gift card are only voided,
diff --git a/spree/core/app/workflows/spree/orders/resume.rb b/spree/core/app/workflows/spree/orders/resume.rb
index 2bbefa05f0..e30a079419 100644
--- a/spree/core/app/workflows/spree/orders/resume.rb
+++ b/spree/core/app/workflows/spree/orders/resume.rb
@@ -39,8 +39,15 @@ module Spree
order.update_columns(status: 'placed')
end
+ # Takes the units back off the shelf and un-cancels each fulfillment.
+ # Resume has no external step, so it nests inside this transaction
+ # cleanly — unlike its cancel twin.
def resume_fulfillments
- order.fulfillments.each(&:resume!)
+ order.fulfillments.each do |fulfillment|
+ result = Spree.fulfillment_resume_workflow.call(fulfillment: fulfillment)
+
+ failure(order, result.error) unless result.success?
+ end
end
end
end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 327fe65d34..fdcf44f3de 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -72,6 +72,8 @@ module Spree
fulfillment_create_workflow: 'Spree::Fulfillments::Create',
fulfillment_update_workflow: 'Spree::Fulfillments::Update',
fulfillment_fulfill_workflow: 'Spree::Fulfillments::Fulfill',
+ fulfillment_cancel_workflow: 'Spree::Fulfillments::Cancel',
+ fulfillment_resume_workflow: 'Spree::Fulfillments::Resume',
# returns
return_create_workflow: 'Spree::Returns::Create',
diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rb
index b2861b8d5b..2de883dcd3 100644
--- a/spree/core/spec/models/spree/shipment_spec.rb
+++ b/spree/core/spec/models/spree/shipment_spec.rb
@@ -699,17 +699,23 @@ describe Spree::Shipment, type: :model do
describe '#cancel' do
let(:inventory_unit) { create(:inventory_unit, state: 'on_hand', line_item: line_item, variant: variant, quantity: 1) }
+ # Restocking is no longer a transition callback — it belongs to
+ # Spree::Fulfillments::Cancel, so the event only moves the status.
it 'cancels the shipment' do
allow(shipment.order).to receive(:recalculate_totals!)
shipment.state = 'pending'
- expect(shipment).to receive(:after_cancel)
+ expect(shipment).not_to receive(:after_cancel)
shipment.cancel!
expect(shipment.state).to eq 'canceled'
end
- it 'restocks the items' do
+ # Restocking belongs to Spree::Fulfillments::Cancel now; the deprecated
+ # shell is all that survives on the model. Covered by
+ # spec/workflows/spree/fulfillments/cancel_spec.rb.
+ it 'restocks the items through the deprecated shell' do
allow(shipment).to receive(:fulfillment_items).and_return([inventory_unit])
+ allow(shipment).to receive(:provider).and_return(instance_double(Spree::FulfillmentProvider::Manual, cancel_fulfillment: true))
shipment.stock_location = create(:stock_location)
expect(shipment.stock_location).to receive(:restock).with(variant, 1, shipment)
shipment.after_cancel
@@ -752,7 +758,7 @@ describe Spree::Shipment, type: :model do
shipment.state = 'canceled'
expect(shipment).to receive(:determine_state).and_return('ready')
- expect(shipment).to receive(:after_resume)
+ expect(shipment).not_to receive(:after_resume)
shipment.resume!
expect(shipment.state).to eq 'ready'
end
@@ -762,7 +768,7 @@ describe Spree::Shipment, type: :model do
shipment.state = 'canceled'
expect(shipment).to receive(:determine_state).and_return('pending')
- expect(shipment).to receive(:after_resume)
+ expect(shipment).not_to receive(:after_resume)
shipment.resume!
# Shipment is pending because order is already paid
expect(shipment.state).to eq 'pending'
@@ -797,9 +803,11 @@ describe Spree::Shipment, type: :model do
allow(shipment_with_inventory_units).to receive_messages(require_inventory: false, update_order: true)
end
- it 'unstocks them items' do
-
- expect(shipment_with_inventory_units.stock_location).to receive(:unstock)
+ # Taking the units back off the shelf moved to
+ # Spree::Fulfillments::Fulfill, so the bare transition no longer does it.
+ # See spec/workflows/spree/fulfillments/fulfill_spec.rb for the behavior.
+ it 'does not unstock on the bare transition' do
+ expect(shipment_with_inventory_units.stock_location).not_to receive(:unstock)
subject
end
end
@@ -1163,9 +1171,12 @@ describe Spree::Shipment, type: :model do
describe 'shipped state transition' do
before { shipment.update_column(:tracking, 'TRACK123') }
+ # The fulfilled event carries notify_customer metadata so an admin can
+ # suppress the shipment email for one dispatch.
it 'publishes shipment.shipped event' do
- expect(shipment).to receive(:publish_event).with('shipment.shipped')
- allow(shipment).to receive(:publish_event).with(anything)
+ expect(shipment).to receive(:publish_event).
+ with('shipment.shipped', nil, hash_including(notify_customer: true))
+ allow(shipment).to receive(:publish_event).with(any_args)
shipment.ship!
end
diff --git a/spree/core/spec/workflows/spree/fulfillments/cancel_spec.rb b/spree/core/spec/workflows/spree/fulfillments/cancel_spec.rb
new file mode 100644
index 0000000000..22df09422c
--- /dev/null
+++ b/spree/core/spec/workflows/spree/fulfillments/cancel_spec.rb
@@ -0,0 +1,89 @@
+require 'spec_helper'
+
+module Spree
+ describe Fulfillments::Cancel do
+ subject { described_class }
+
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store, line_items_count: 2) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ let(:execute) { subject.call(fulfillment: fulfillment) }
+
+ it 'cancels the fulfillment' do
+ expect(execute.success?).to eq(true)
+ expect(fulfillment.reload).to be_canceled
+ end
+
+ it 'puts the units back on the shelf' do
+ variant = fulfillment.fulfillment_items.first.variant
+ stock_item = fulfillment.stock_location.stock_item(variant)
+
+ expect { execute }.to change { stock_item.reload.count_on_hand }.by(
+ fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity)
+ )
+ end
+
+ # Fulfillment#provider builds a fresh Manual provider per call, so the
+ # double is injected rather than stubbed on an instance.
+ let(:provider) { instance_double(Spree::FulfillmentProvider::Manual, cancel_fulfillment: true) }
+
+ it 'tells the provider to stand down' do
+ allow(fulfillment).to receive(:provider).and_return(provider)
+ expect(provider).to receive(:cancel_fulfillment).with(fulfillment)
+
+ subject.call(fulfillment: fulfillment)
+ end
+
+ # The whole reason this moved out of the transition callback: a slow or
+ # failing carrier must not hold the stock movements' row locks, and must
+ # not roll back a restock that already happened.
+ it 'notifies the provider only after the restock has committed' do
+ open_transactions = nil
+ allow(fulfillment).to receive(:provider).and_return(provider)
+ allow(provider).to receive(:cancel_fulfillment) do
+ open_transactions = ApplicationRecord.connection.open_transactions
+ end
+
+ subject.call(fulfillment: fulfillment)
+
+ # The suite wraps each example in a transaction, so "committed" here
+ # means no transaction was opened beyond that outer one.
+ expect(open_transactions).to eq(ApplicationRecord.connection.open_transactions)
+ end
+
+ it 'refuses a fulfillment that cannot cancel' do
+ fulfillment.fulfill!
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.cannot_cancel'))
+ expect(fulfillment.reload).to be_fulfilled
+ end
+
+ describe 'hooks' do
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ it 'lets a validate handler veto before anything is written' do
+ Spree.hooks.register('fulfillments.cancel.validate') { |flow| flow.reject!('already picked') }
+
+ result = execute
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to eq('already picked')
+ expect(fulfillment.reload).not_to be_canceled
+ end
+
+ it 'runs after_cancel with the canceled fulfillment' do
+ seen = nil
+ Spree.hooks.register('fulfillments.cancel.after_cancel') { |flow| seen = flow.fulfillment }
+
+ execute
+
+ expect(seen).to eq(fulfillment)
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/fulfillments/resume_spec.rb b/spree/core/spec/workflows/spree/fulfillments/resume_spec.rb
new file mode 100644
index 0000000000..8068c774bc
--- /dev/null
+++ b/spree/core/spec/workflows/spree/fulfillments/resume_spec.rb
@@ -0,0 +1,62 @@
+require 'spec_helper'
+
+module Spree
+ describe Fulfillments::Resume do
+ subject { described_class }
+
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store, line_items_count: 2) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ let(:execute) { subject.call(fulfillment: fulfillment) }
+
+ before { fulfillment.cancel! }
+
+ it 'brings the fulfillment back' do
+ expect(execute.success?).to eq(true)
+ expect(fulfillment.reload).not_to be_canceled
+ end
+
+ it 'takes the units back off the shelf' do
+ variant = fulfillment.fulfillment_items.first.variant
+ stock_item = fulfillment.stock_location.stock_item(variant)
+
+ expect { execute }.to change { stock_item.reload.count_on_hand }.by(
+ -fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity)
+ )
+ end
+
+ it 'refuses a fulfillment that is not canceled' do
+ fulfillment.resume!
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.cannot_resume'))
+ end
+
+ describe 'hooks' do
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ it 'lets a validate handler veto before the stock moves' do
+ Spree.hooks.register('fulfillments.resume.validate') { |flow| flow.reject!('stock sold on') }
+
+ variant = fulfillment.fulfillment_items.first.variant
+ stock_item = fulfillment.stock_location.stock_item(variant)
+
+ expect { execute }.not_to change { stock_item.reload.count_on_hand }
+ expect(fulfillment.reload).to be_canceled
+ end
+
+ it 'runs after_resume with the resumed fulfillment' do
+ seen = nil
+ Spree.hooks.register('fulfillments.resume.after_resume') { |flow| seen = flow.fulfillment }
+
+ execute
+
+ expect(seen).to eq(fulfillment)
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/orders/cancel_spec.rb b/spree/core/spec/workflows/spree/orders/cancel_spec.rb
index 504c76efdb..a10d3799cf 100644
--- a/spree/core/spec/workflows/spree/orders/cancel_spec.rb
+++ b/spree/core/spec/workflows/spree/orders/cancel_spec.rb
@@ -9,6 +9,46 @@ module Spree
let(:result) { subject.call(order: order, canceler: user) }
+ # Cancelling the order cancels its fulfillments through the fulfillment
+ # workflow rather than reimplementing the restock, so extension hooks and
+ # guards registered there apply to an order cancellation too.
+ describe 'fulfillments' do
+ let(:order) { create(:order_ready_to_ship, line_items_count: 1) }
+
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ it 'cancels each fulfillment through Fulfillments::Cancel' do
+ seen = []
+ Spree.hooks.register('fulfillments.cancel.after_cancel') { |flow| seen << flow.fulfillment }
+
+ subject.call(order: order, canceler: user)
+
+ expect(seen).to eq(order.fulfillments.to_a)
+ expect(order.fulfillments.reload).to all(be_canceled)
+ end
+
+ it 'puts the units back on the shelf' do
+ fulfillment = order.fulfillments.first
+ variant = fulfillment.fulfillment_items.first.variant
+ stock_item = fulfillment.stock_location.stock_item(variant)
+
+ expect { subject.call(order: order, canceler: user) }.
+ to change { stock_item.reload.count_on_hand }.by(
+ fulfillment.fulfillment_items.where(variant_id: variant.id).sum(:quantity)
+ )
+ end
+
+ # The carrier calls are batched after the order transaction commits, so
+ # they must still happen — just not from inside the fulfillment workflow.
+ it 'tells each provider to stand down' do
+ expect_any_instance_of(Spree::FulfillmentProvider::Manual).
+ to receive(:cancel_fulfillment).at_least(:once)
+
+ subject.call(order: order, canceler: user)
+ end
+ end
+
shared_examples 'tries to cancel' do
context 'completed order' do
it { expect(result).to be_success }