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.

Simplify fulfillment statuses and track delivery

Damian Legawiec4f6a0b59bc5f
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index 517032b423..0c289b8af0 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -48,18 +48,23 @@ module Spree
accepts_nested_attributes_for :address
accepts_nested_attributes_for :fulfillment_items
- scope :pending, -> { with_state('pending') }
- scope :ready, -> { with_state('ready') }
- scope :fulfilled, -> { with_state('fulfilled') }
- # @deprecated legacy name — remove in 6.1
+ # unfulfilled/fulfilled/delivered/canceled scopes + predicates come from
+ # has_status below. These are the ones it cannot generate.
+ #
+ # @deprecated legacy names — removed in 6.1
scope :shipped, -> { fulfilled }
- scope :ready_or_pending, -> { where(status: %w(ready pending)) }
+ scope :pending, -> { unfulfilled }
+ scope :ready, -> { unfulfilled }
+ scope :ready_or_pending, -> { unfulfilled }
+ # Everything that has left the merchant's hands, whether or not the carrier
+ # has confirmed receipt — the natural set for reporting and for skipping
+ # work that only applies to packages still on the shelf.
+ scope :fulfilled_or_delivered, -> { where(status: %w(fulfilled delivered)) }
scope :trackable, -> { where("tracking IS NOT NULL AND tracking != ''") }
scope :with_state, ->(*s) { where(status: s) }
# sort by most recent fulfilled_at, falling back to created_at. add "id desc" to make specs that involve this scope more deterministic.
scope :reverse_chronological, -> { order(Arel.sql("coalesce(#{table_name}.fulfilled_at, #{table_name}.created_at) desc"), id: :desc) }
scope :valid, -> { where.not(status: :canceled) }
- scope :canceled, -> { with_state('canceled') }
scope :not_canceled, -> { where.not(status: 'canceled') }
scope :shipped_but_canceled, -> { canceled.where.not(fulfilled_at: nil) }
# This scope will select the delivery_method_id from the fulfillments' selected delivery rate
@@ -93,58 +98,37 @@ module Spree
end
delegate :amount_in_cents, to: :display_cost
- state_machine :status, initial: :pending, use_transactions: false do
- event :ready do
- transition from: :pending, to: :ready, if: lambda { |fulfillment|
- # Fix for #2040
- fulfillment.determine_state(fulfillment.owner) == 'ready'
- }
- end
-
- event :pend do
- transition from: :ready, to: :pending
- end
-
- event :mark_ready_for_pickup do
- transition from: :ready, to: :ready_for_pickup
- end
-
- event :fulfill do
- transition from: %i(ready ready_for_pickup canceled), to: :fulfilled, if: ->(fulfillment) { fulfillment.provider.can_fulfill?(fulfillment) }
- end
- after_transition to: :ready, do: :publish_fulfillment_ready_event
- after_transition to: :fulfilled, do: [:after_fulfill, :publish_fulfillment_fulfilled_event]
-
- event :cancel do
- transition to: :canceled, from: %i(pending ready ready_for_pickup)
- end
- # 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|
- fulfillment.determine_state(fulfillment.owner) == 'ready'
- }
- transition from: :canceled, to: :pending
- end
- # 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.
+ # Statuses describe what the merchant did with the package — nothing else.
+ # Payment and stock readiness used to be encoded here as pending/ready and
+ # re-derived from the order on every recalculation, so a refund could move a
+ # fulfillment backwards with no physical change. That gate now lives in
+ # Spree::Fulfillments::Fulfill, where it can explain itself and be
+ # overridden. Transitions belong to the workflows in
+ # app/workflows/spree/fulfillments (docs/plans/6.0-fulfillment-and-delivery.md).
+ include Spree::HasStatus
+ has_status :unfulfilled, :fulfilled, :delivered, :canceled, default: :unfulfilled
+
+ # Unlike returns and claims, fulfillments are built directly — by the stock
+ # coordinator, by cart completion, by transfers — rather than always through
+ # a creating workflow, so the default is applied here instead of being left
+ # to each caller. This is what the machine's `initial:` used to do.
+ after_initialize :apply_default_status, if: :new_record?
+
+ # What the carrier reports, kept apart from the merchant lifecycle: a bounced
+ # or damaged package changes this, never #status.
+ TRACKING_STATUSES = %w(
+ pre_transit in_transit out_for_delivery available_for_pickup
+ delivered return_to_sender failure unknown
+ ).freeze
+
+ validates :tracking_status, inclusion: { in: TRACKING_STATUSES }, allow_blank: true
+
+ # @deprecated Use {Spree::Fulfillments::Fulfill}; removed in 6.1.
def ship(*args)
- Spree::Deprecation.warn('Spree::Fulfillment#ship is deprecated and will be removed in Spree 6.1. Use #fulfill instead.')
- fulfill(*args)
- end
-
- # @deprecated Use {#fulfill!}; removed in 6.1.
- def ship!(*args)
- Spree::Deprecation.warn('Spree::Fulfillment#ship! is deprecated and will be removed in Spree 6.1. Use #fulfill! instead.')
- fulfill!(*args)
+ Spree::Deprecation.warn('Spree::Fulfillment#ship is deprecated and will be removed in Spree 6.1. Use Spree::Fulfillments::Fulfill instead.')
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: self, **args.first.to_h)
end
+ alias ship! ship
# @deprecated Use {#can_fulfill?}; removed in 6.1.
def can_ship?
@@ -157,6 +141,39 @@ module Spree
Spree::Deprecation.warn('Spree::Fulfillment#shipped? is deprecated and will be removed in Spree 6.1. Use #fulfilled? instead.')
fulfilled?
end
+
+ # Whether this fulfillment may still be handed over. Composes the status
+ # rule with the provider's own veto; the payment and stock side of the
+ # question belongs to Spree::Fulfillments::Fulfill, which can report why.
+ #
+ # @return [Boolean]
+ def can_fulfill?
+ (unfulfilled? || canceled?) && provider.can_fulfill?(self)
+ end
+
+ # @return [Boolean] whether the package can still be recalled
+ def can_cancel?
+ unfulfilled?
+ end
+
+ # @return [Boolean] whether a canceled fulfillment can be reinstated
+ def can_resume?
+ canceled?
+ end
+
+ # @return [Boolean] whether receipt can still be confirmed
+ def can_mark_delivered?
+ fulfilled?
+ end
+
+ # Everything that has left the merchant's hands. Reads better than
+ # `fulfilled? || delivered?` at call sites that only care that the package
+ # is gone.
+ #
+ # @return [Boolean]
+ def fulfilled_or_delivered?
+ fulfilled? || delivered?
+ end
# @deprecated the column is +status+ since 6.0
alias_attribute :state, :status
alias_attribute :shipped_at, :fulfilled_at
@@ -265,24 +282,6 @@ module Spree
end
end
- # Determines the appropriate +state+ according to the following logic:
- #
- # pending unless order is complete and +order.payment_state+ is +paid+
- # shipped if already shipped (ie. does not change the state)
- # ready all other cases
- # @param [Spree::Cart, Spree::Order]
- def determine_state(order_or_cart)
- return 'pending' if order_or_cart.is_a?(Spree::Cart)
-
- return 'canceled' if canceled? || order_or_cart.canceled?
- # Fulfillment is a fact — payment coverage can never un-fulfill it.
- return 'fulfilled' if fulfilled?
- return 'pending' unless order_or_cart.can_ship?
- return 'pending' if fulfillment_items.any?(&:backordered?)
-
- order_or_cart.paid? || Spree::Config[:auto_capture_on_dispatch] ? 'ready' : 'pending'
- end
-
def discounted_cost
cost + promo_total
end
@@ -417,8 +416,25 @@ module Spree
end
end
+ # @deprecated Use {#unfulfilled?}; removed in 6.1.
def ready_or_pending?
- ready? || pending?
+ unfulfilled?
+ end
+
+ # @deprecated Use {#unfulfilled?}; removed in 6.1.
+ def pending?
+ unfulfilled?
+ end
+
+ # @deprecated Use {#unfulfilled?}; removed in 6.1.
+ def ready?
+ unfulfilled?
+ end
+
+ # @deprecated `ready_for_pickup` is not a status since 6.0 — for pickup
+ # fulfillments `fulfilled` means "waiting at the counter". Removed in 6.1.
+ def ready_for_pickup?
+ fulfilled? && provider.class.pickup?
end
# @param audience [Symbol] {Spree::DeliveryMethod::STOREFRONT} (default)
@@ -596,17 +612,20 @@ module Spree
end
end
- # Updates various aspects of the Shipment while bypassing any callbacks. Note that this method takes an explicit reference to the
- # Order object. This is necessary because the association actually has a stale (and unsaved) copy of the Order and so it will not
- # yield the correct results.
- def update!(order)
- old_status = status
- new_status = determine_state(order)
- update_columns(
- status: new_status,
- updated_at: Time.current
- )
- after_fulfill if new_status == 'fulfilled' && old_status != 'fulfilled'
+ # @deprecated No-op since 6.0; removed in 6.1.
+ #
+ # This re-derived the status from the order's payment state on every order
+ # recalculation, which is what made a fulfillment move backwards when a
+ # refund landed. A fulfillment's status now only changes when a workflow
+ # changes it, so there is nothing left to refresh.
+ def update!(*args)
+ # Only the legacy `update!(order)` form is dead. Anything else is
+ # ActiveRecord's own update! — a Hash of attributes — which workflows
+ # rely on to write the status.
+ return super unless args.one? && (args.first.is_a?(Spree::Order) || args.first.is_a?(Spree::Cart))
+
+ Spree::Deprecation.warn('Spree::Fulfillment#update!(order) is a no-op since Spree 6.0 and will be removed in 6.1. Fulfillment statuses change through Spree::Fulfillments workflows.')
+ true
end
def transfer_to_location(variant, quantity, stock_location)
@@ -684,6 +703,10 @@ module Spree
self.cost = 0 unless cost
end
+ def apply_default_status
+ self.status ||= self.class.default_status
+ end
+
def exactly_one_owner
errors.add(:base, Spree.t('errors.messages.exactly_one_of_cart_or_order')) unless [order, cart].compact.one?
end
diff --git a/spree/core/app/models/spree/fulfillment/custom_events.rb b/spree/core/app/models/spree/fulfillment/custom_events.rb
index b8b28354f6..f25912cd05 100644
--- a/spree/core/app/models/spree/fulfillment/custom_events.rb
+++ b/spree/core/app/models/spree/fulfillment/custom_events.rb
@@ -5,24 +5,26 @@ module Spree
# Publishes fulfillment lifecycle events beyond the basic Publishable set.
#
# Events:
- # - fulfillment.ready: Fulfillment became ready
- # - fulfillment.fulfilled: Fulfillment was fulfilled
+ # - fulfillment.fulfilled: Fulfillment was handed over
+ # - fulfillment.delivered: Receipt was confirmed
# - order.fulfilled: All order fulfillments are fulfilled
+ # - order.delivered: All order fulfillments are delivered
# - fulfillment.canceled: Fulfillment was canceled
# - fulfillment.resumed: Fulfillment was resumed from canceled
#
# The legacy shipment.* / order.shipped events are dual-emitted for one
# release (webhook contract bridge — removed in 6.1).
#
- # NOTE: These methods are called from the state machine's after_transition
- # callbacks defined in the Fulfillment model, not via ActiveRecord callbacks.
+ # NOTE: These methods are called from the Spree::Fulfillments workflows,
+ # never from ActiveRecord callbacks — publishing is part of the transition
+ # the workflow performed, not a side effect of a column changing.
module CustomEvents
extend ActiveSupport::Concern
+ # @deprecated `ready` is not a status since 6.0; removed in 6.1.
def publish_fulfillment_ready_event
- return unless Spree::Events.enabled?
-
- publish_event('fulfillment.ready')
+ Spree::Deprecation.warn('Spree::Fulfillment#publish_fulfillment_ready_event is deprecated and will be removed in Spree 6.1. The ready status no longer exists.')
+ nil
end
# Whether the customer should be told this fulfillment shipped. Set by
@@ -52,6 +54,17 @@ module Spree
publish_order_fulfilled_event if order.fully_fulfilled?
end
+ def publish_fulfillment_delivered_event
+ return unless Spree::Events.enabled?
+
+ publish_event('fulfillment.delivered', nil, { notify_customer: notify_customer? })
+
+ # The association is reloaded for the same reason as above: the caller
+ # just wrote this row and the cached copy still shows the old status.
+ order.fulfillments.reset
+ order.publish_event('order.delivered') if order.fully_delivered?
+ end
+
def publish_fulfillment_canceled_event
return unless Spree::Events.enabled?
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index ae00a54cfb..ff0335b89d 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -9,7 +9,7 @@ module Spree
self.ignored_columns += ['channel']
PAYMENT_STATES = %w(balance_due credit_owed failed paid void)
- FULFILLMENT_STATUSES = %w(backorder canceled partial pending ready fulfilled shipped)
+ FULFILLMENT_STATUSES = %w(backorder canceled partial unfulfilled fulfilled delivered pending ready shipped)
# @deprecated legacy name — remove in 6.1 together with the 'shipped' value
SHIPMENT_STATES = FULFILLMENT_STATUSES
# @deprecated legacy machine vocabulary — line-item removability is
@@ -240,10 +240,10 @@ module Spree
scope :incomplete, -> { where(completed_at: nil) }
scope :canceled, -> { where(status: 'canceled') }
scope :not_canceled, -> { where.not(status: 'canceled') }
- scope :ready_to_ship, -> { where(fulfillment_status: %w[ready pending]) }
+ scope :ready_to_ship, -> { where(fulfillment_status: %w[unfulfilled]) }
scope :partially_shipped, -> { where(fulfillment_status: %w[partial]) }
- scope :not_shipped, -> { where(fulfillment_status: %w[ready pending partial]) }
- scope :shipped, -> { where(fulfillment_status: %w[fulfilled shipped]) }
+ scope :not_shipped, -> { where(fulfillment_status: %w[unfulfilled partial]) }
+ scope :shipped, -> { where(fulfillment_status: %w[fulfilled delivered shipped]) }
scope :refunded, lambda {
joins(:refunds).group(:id).having("sum(#{Spree::Refund.table_name}.amount) = #{Spree::Order.table_name}.total")
}
@@ -377,7 +377,7 @@ module Spree
# Derived, not stored (Decision 8): some but not all fulfillments canceled.
def partially_canceled?
- !canceled? && fulfillments.canceled.any? && fulfillments.where.not(status: 'canceled').any?
+ !canceled? && fulfillments.canceled.any? && fulfillments.not_canceled.any?
end
# Checks if the order is fully refunded
@@ -472,7 +472,7 @@ module Spree
def allow_cancel?
return false if !completed? || canceled?
- fulfillment_status.nil? || %w{ready backorder pending canceled}.include?(fulfillment_status)
+ fulfillment_status.nil? || %w{unfulfilled backorder canceled}.include?(fulfillment_status)
end
alias can_cancel? allow_cancel?
@@ -665,13 +665,20 @@ module Spree
end
def shipped?
- %w(partial shipped fulfilled).include?(fulfillment_status)
+ %w(partial shipped fulfilled delivered).include?(fulfillment_status)
end
- # True when every fulfillment reached the fulfilled status — the signal
- # order.fulfilled publishes on.
+ # True when every fulfillment has left the merchant's hands — the signal
+ # order.fulfilled publishes on. `delivered` counts: it is downstream of
+ # fulfilled, so a delivered order must not read as un-fulfilled.
def fully_fulfilled?
- fulfillments.fulfilled.size == fulfillments.size
+ fulfillments.fulfilled_or_delivered.size == fulfillments.size
+ end
+
+ # True when every fulfillment reached confirmed receipt — the signal
+ # order.delivered publishes on.
+ def fully_delivered?
+ fulfillments.any? && fulfillments.delivered.size == fulfillments.size
end
# @deprecated Use {#fully_fulfilled?}; removed in 6.1.
diff --git a/spree/core/app/services/spree/carts/destroy.rb b/spree/core/app/services/spree/carts/destroy.rb
index b26cd3da11..6fe2a14d07 100644
--- a/spree/core/app/services/spree/carts/destroy.rb
+++ b/spree/core/app/services/spree/carts/destroy.rb
@@ -24,8 +24,11 @@ module Spree
success(cart: cart)
end
+ # Cart fulfillments are proposals, not commitments: nothing was picked or
+ # booked, so this marks them canceled rather than running the cancel
+ # workflow's restock and carrier stand-down.
def cancel_shipments(cart:)
- cart.fulfillments.each(&:cancel)
+ cart.fulfillments.each { |fulfillment| fulfillment.update!(status: 'canceled') }
success(cart: cart)
end
diff --git a/spree/core/app/services/spree/orders/update_statuses.rb b/spree/core/app/services/spree/orders/update_statuses.rb
index 6b84c57c1d..5c6974db2a 100644
--- a/spree/core/app/services/spree/orders/update_statuses.rb
+++ b/spree/core/app/services/spree/orders/update_statuses.rb
@@ -11,7 +11,6 @@ module Spree
PAYMENT_STATUSES = %w[none authorized partially_paid paid partially_refunded refunded overcharged voided].freeze
def call(order:)
- refresh_fulfillment_states(order)
order.update_columns(
payment_status: payment_status_for(order),
fulfillment_status: fulfillment_status_for(order),
@@ -22,16 +21,6 @@ module Spree
private
- # A fulfillment's own state depends on payment coverage
- # (Fulfillment#determine_state) — refresh each before rolling up.
- # Reloaded so a stale association cache never writes an outdated
- # status back over a transition that already persisted.
- def refresh_fulfillment_states(order)
- order.fulfillments.reload.each do |fulfillment|
- fulfillment.update!(order) if fulfillment.persisted?
- end
- end
-
# Money is quantized to currency precision before comparing, and
# granted refunds are subtracted from the target total — the two rules
# every derivation implementation gets wrong first.
@@ -64,27 +53,23 @@ module Spree
end
end
- # fulfilled when all fulfillments fulfilled; partial when mixed with
- # fulfilled; ready when all ready (ready_for_pickup rolls up as
- # ready); backorder when backordered inventory exists; pending when
- # all pending.
+ # Rolls the fulfillments up into one word for filtering and display.
+ #
+ # Canceled fulfillments are ignored unless they are all there is: an
+ # order whose second parcel was recalled is still described by the first.
+ # A mix that includes anything handed over reads as `partial`; otherwise
+ # the shared status stands. `delivered` only when every parcel arrived.
def fulfillment_status_for(order)
return 'backorder' if order.backordered?
- statuses = order.fulfillments.states.map { |status| status == 'ready_for_pickup' ? 'ready' : status }.uniq
+ statuses = order.fulfillments.reload.pluck(:status).uniq
+ return if statuses.empty?
- if statuses.size > 1
- if statuses.include?('fulfilled')
- 'partial'
- elsif statuses.include?('pending')
- 'pending'
- else
- 'ready'
- end
- else
- # nil when there are no fulfillments
- statuses.first
- end
+ live = statuses - ['canceled']
+ return 'canceled' if live.empty?
+ return live.first if live.size == 1
+
+ live.intersect?(%w[fulfilled delivered]) ? 'partial' : 'unfulfilled'
end
def quantize(amount, precision)
diff --git a/spree/core/app/workflows/spree/fulfillments/cancel.rb b/spree/core/app/workflows/spree/fulfillments/cancel.rb
index 29aecfd230..6771ae8e43 100644
--- a/spree/core/app/workflows/spree/fulfillments/cancel.rb
+++ b/spree/core/app/workflows/spree/fulfillments/cancel.rb
@@ -66,12 +66,9 @@ module Spree
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)
+ fulfillment.update!(status: 'canceled')
+ fulfillment.publish_fulfillment_canceled_event
end
def tell_provider_to_stand_down
diff --git a/spree/core/app/workflows/spree/fulfillments/create.rb b/spree/core/app/workflows/spree/fulfillments/create.rb
index 467f2e24ae..9ba7ba95f5 100644
--- a/spree/core/app/workflows/spree/fulfillments/create.rb
+++ b/spree/core/app/workflows/spree/fulfillments/create.rb
@@ -304,12 +304,13 @@ module Spree
end
# Registers an externally-completed fulfillment: backorders are filled
- # (the external location evidently had the goods) and the paid-order
- # readiness gate is bypassed deliberately — the goods already left.
+ # (the external location evidently had the goods) and the readiness gate
+ # is forced — the goods already left, so refusing on an unpaid order
+ # would just refuse to record history.
def mark_shipped(fulfillment)
fulfillment.fulfillment_items.backordered.each(&:fill_backorder!)
- fulfillment.update_columns(status: 'ready') unless fulfillment.ready?
- fulfillment.reload.fulfill!
+ fulfillment.reload
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment, force: true)
end
end
end
diff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
index dde0c4f944..f6aec220ee 100644
--- a/spree/core/app/workflows/spree/fulfillments/fulfill.rb
+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
@@ -17,8 +17,7 @@ module Spree
# together or not at all: a split that succeeded while the fulfillment
# failed would leave the order carrying a phantom fulfillment nobody asked
# for. The state machine stays the low-level mechanic underneath — this
- # workflow decides *what* ships, the machine still decides whether the
- # transition is legal.
+ # workflow decides *what* ships and whether shipping it is allowed.
class Fulfill < Spree::Workflow
hooks :validate, :after_fulfill
@@ -34,8 +33,12 @@ module Spree
# stored on the fulfillment that ships
# @param notify_customer [Boolean] whether the shipment email goes out;
# false suppresses it for this dispatch only
+ # @param force [Boolean] dispatch even when the order is unpaid or holds
+ # backordered units. The merchant's call to make — staff shipping
+ # against an invoice is ordinary trade, and the old pending/ready
+ # statuses made it impossible to express.
# @return [Spree::ServiceModule::Result] the fulfilled fulfillment on success
- def perform(fulfillment:, items: nil, tracking: nil, notify_customer: true)
+ def perform(fulfillment:, items: nil, tracking: nil, notify_customer: true, force: false)
super
@source = fulfillment
@@ -52,8 +55,16 @@ module Spree
step :unstock_if_resuming_from_canceled
step :apply_tracking
step :mark_fulfilled
+ step :capture_payment_if_configured
end
+ # The provider books the courier or hands off to the 3PL — network I/O,
+ # so it runs after the status is committed rather than holding the
+ # transaction open on a carrier's latency.
+ external_step :tell_provider_it_shipped
+
+ step :roll_up_order_status
+
run_hooks :after_fulfill
success(@fulfillment.reload)
end
@@ -75,9 +86,31 @@ module Spree
def ensure_fulfillable
failure(@source, Spree.t('fulfillments.errors.cannot_fulfill')) unless @source.can_fulfill?
+ ensure_ready_to_hand_over
ensure_requested_units_available
end
+ # What the pending/ready statuses used to encode, asked once at the
+ # moment it matters instead of being recomputed onto every fulfillment
+ # whenever the order changed. A validate hook can wave either rule
+ # through — staff dispatching against an unpaid invoice is a normal
+ # merchant decision, and it was impossible while the status itself was
+ # derived from payment.
+ def ensure_ready_to_hand_over
+ return if force
+
+ order = @source.order
+ return if order.nil?
+
+ if @source.fulfillment_items.any?(&:backordered?)
+ failure(@source, Spree.t('fulfillments.errors.backordered_units'))
+ end
+
+ return if order.paid? || Spree::Config[:auto_capture_on_dispatch]
+
+ failure(@source, Spree.t('fulfillments.errors.order_not_paid'))
+ end
+
# Each requested quantity has to exist in *this* fulfillment. Without
# this the split would silently pull units out of a sibling fulfillment,
# shipping goods the merchant did not select.
@@ -129,10 +162,8 @@ module Spree
end
# A canceled fulfillment already put its units back on the shelf, so
- # shipping it directly has to take them off again — the state machine
- # allows canceled -> fulfilled precisely so goods that went out anyway
- # can be recorded. Previously the resume callback covered this; it is an
- # explicit step now that the callbacks are gone.
+ # shipping it directly has to take them off again — canceled -> fulfilled
+ # is allowed precisely so goods that went out anyway can be recorded.
def unstock_if_resuming_from_canceled
return unless @source.canceled?
@@ -147,22 +178,43 @@ module Spree
# (run_provider_create_fulfillment) sees an admin-entered number and
# leaves it alone, and so the shipment email carries it.
#
- # update_columns, not update! — Fulfillment#update! is a legacy override
- # taking the order and recomputing status, which would fire after_fulfill
- # ahead of the transition.
def apply_tracking
return if tracking.blank?
@fulfillment.update_columns(tracking: tracking.to_s.squish, updated_at: Time.current)
end
- # The suppression flag rides on the record because the event is published
- # from an after_transition callback, which takes no arguments.
+ # The suppression flag rides on the record because the event publisher
+ # reads it when building the event metadata.
def mark_fulfilled
@fulfillment.notify_customer = notify_customer
- @fulfillment.fulfill!
- rescue StateMachines::InvalidTransition => e
- failure(@fulfillment, e.message)
+ @fulfillment.fulfillment_items.each(&:ship!)
+ @fulfillment.update!(status: 'fulfilled', fulfilled_at: Time.current)
+ @fulfillment.publish_fulfillment_fulfilled_event
+ end
+
+ # Dispatch is the trigger for taking the money when the merchant has
+ # chosen to charge on dispatch rather than at checkout.
+ def capture_payment_if_configured
+ return unless Spree::Config[:auto_capture_on_dispatch]
+
+ @fulfillment.process_order_payments
+ end
+
+ # Tracking the provider discovers is kept unless an admin already typed
+ # one in — a human who entered a number meant it.
+ def tell_provider_it_shipped
+ result = @fulfillment.provider.create_fulfillment(@fulfillment)
+ return unless result.is_a?(Hash)
+
+ new_tracking = result[:tracking_number].presence
+ return if new_tracking.blank? || @fulfillment.tracking.present?
+
+ @fulfillment.update_column(:tracking, new_tracking)
+ end
+
+ def roll_up_order_status
+ @fulfillment.order&.update_statuses!
end
end
end
diff --git a/spree/core/app/workflows/spree/fulfillments/mark_delivered.rb b/spree/core/app/workflows/spree/fulfillments/mark_delivered.rb
new file mode 100644
index 0000000000..a812fd9709
--- /dev/null
+++ b/spree/core/app/workflows/spree/fulfillments/mark_delivered.rb
@@ -0,0 +1,55 @@
+module Spree
+ module Fulfillments
+ # Records that the customer received the goods — the end of the lifecycle,
+ # which used to stop at handover.
+ #
+ # Three things reach it: a carrier reporting delivery (through
+ # {Spree::Fulfillments::UpdateTracking}), a staff member pressing a button
+ # because they know the parcel arrived, and — for pickup — the customer
+ # collecting it. Merchants without any carrier integration still get a
+ # usable delivered state that way.
+ #
+ # In the workflow tier for its hooks: `delivered` is what return windows,
+ # review invitations and the EU withdrawal period count from, so host apps
+ # need somewhere to hang that work.
+ class MarkDelivered < Spree::Workflow
+ hooks :validate, :after_mark_delivered
+
+ # @param fulfillment [Spree::Fulfillment] the fulfillment that arrived
+ # @param delivered_at [Time, nil] when it arrived; defaults to now.
+ # Carriers report a delivery timestamp that is usually earlier than the
+ # webhook, and the return window has to run from the real one.
+ # @param notify_customer [Boolean] whether subscribers should email the
+ # customer about the delivery
+ # @return [Spree::ServiceModule::Result] the delivered fulfillment on success
+ def perform(fulfillment:, delivered_at: nil, notify_customer: true)
+ super
+
+ # Veto point — a host app that confirms delivery through its own
+ # channel can reject a carrier's optimistic report here.
+ run_hooks :validate
+
+ step :ensure_deliverable
+ step :mark_delivered
+
+ run_hooks :after_mark_delivered
+ success(fulfillment.reload)
+ end
+
+ private
+
+ def ensure_deliverable
+ return if fulfillment.can_mark_delivered?
+
+ failure(fulfillment, Spree.t('fulfillments.errors.cannot_mark_delivered'))
+ end
+
+ def mark_delivered
+ fulfillment.notify_customer = notify_customer
+ fulfillment.update!(status: 'delivered', delivered_at: delivered_at || Time.current)
+ fulfillment.publish_fulfillment_delivered_event
+ fulfillment.order&.update_statuses!
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/fulfillments/resume.rb b/spree/core/app/workflows/spree/fulfillments/resume.rb
index f2532a1b8e..f04e6198b1 100644
--- a/spree/core/app/workflows/spree/fulfillments/resume.rb
+++ b/spree/core/app/workflows/spree/fulfillments/resume.rb
@@ -51,10 +51,12 @@ module Spree
end
end
+ # Always back to unfulfilled. The old machine chose between pending and
+ # ready here by consulting the order's payment state; that question is
+ # asked at fulfill time now.
def mark_resumed
- fulfillment.resume!
- rescue StateMachines::InvalidTransition => e
- failure(fulfillment, e.message)
+ fulfillment.update!(status: 'unfulfilled')
+ fulfillment.publish_fulfillment_resumed_event
end
end
end
diff --git a/spree/core/app/workflows/spree/fulfillments/update.rb b/spree/core/app/workflows/spree/fulfillments/update.rb
index 90e0fa04fa..16c068ec9b 100644
--- a/spree/core/app/workflows/spree/fulfillments/update.rb
+++ b/spree/core/app/workflows/spree/fulfillments/update.rb
@@ -87,11 +87,10 @@ module Spree
@fulfillment.update_amounts
order.recalculate_totals!
- @fulfillment.update_columns(
- status: @fulfillment.determine_state(order),
- updated_at: Time.current
- )
-
+ # A new rate changes what the delivery costs, never where the package
+ # is in its lifecycle — the old machine recomputed the status here from
+ # the order's payment state, which is precisely the coupling removed in
+ # 6.0. The rollup still runs because the order's totals moved.
order.update_statuses!
end
diff --git a/spree/core/app/workflows/spree/fulfillments/update_tracking.rb b/spree/core/app/workflows/spree/fulfillments/update_tracking.rb
new file mode 100644
index 0000000000..ce53ed56dc
--- /dev/null
+++ b/spree/core/app/workflows/spree/fulfillments/update_tracking.rb
@@ -0,0 +1,83 @@
+module Spree
+ module Fulfillments
+ # Records what the carrier says about a parcel in flight.
+ #
+ # This is the second axis: it never moves the fulfillment backwards and
+ # never contradicts the merchant. A parcel that bounces or is damaged shows
+ # up here as `return_to_sender` or `failure` while `status` still says
+ # `fulfilled` — the merchant did hand it over, and that fact does not
+ # change because the carrier had a bad day. The one status it does write is
+ # `delivered`, by delegating to {MarkDelivered}.
+ #
+ # Providers call this from their webhook handlers, so it accepts the
+ # already-normalized vocabulary rather than any carrier's raw payload:
+ # translating a provider's status names is the provider gem's job.
+ class UpdateTracking < Spree::Workflow
+ hooks :validate, :after_update_tracking
+
+ # @param fulfillment [Spree::Fulfillment] the fulfillment being tracked
+ # @param tracking_status [String, nil] one of
+ # {Spree::Fulfillment::TRACKING_STATUSES}
+ # @param estimated_delivery_at [Time, nil] carrier's current estimate
+ # @param delivered_at [Time, nil] when the carrier says it arrived; used
+ # only when +tracking_status+ is `delivered`
+ # @param details [Hash, nil] provider payload worth keeping — scan events,
+ # the signature, the failure reason
+ # @param notify_customer [Boolean] passed through to {MarkDelivered} when
+ # this update completes the delivery
+ # @return [Spree::ServiceModule::Result] the updated fulfillment on success
+ def perform(fulfillment:, tracking_status: nil, estimated_delivery_at: nil, delivered_at: nil,
+ details: nil, notify_customer: true)
+ super
+
+ run_hooks :validate
+
+ step :ensure_known_status
+ step :apply_carrier_report
+ step :confirm_delivery_if_reported
+
+ run_hooks :after_update_tracking
+ success(fulfillment.reload)
+ end
+
+ private
+
+ def ensure_known_status
+ return if tracking_status.blank?
+ return if Spree::Fulfillment::TRACKING_STATUSES.include?(tracking_status.to_s)
+
+ failure(fulfillment, Spree.t('fulfillments.errors.unknown_tracking_status', status: tracking_status))
+ end
+
+ # Overwrite rather than accumulate: this axis answers "where is it now",
+ # and carriers resend the whole picture on every update. Only attributes
+ # the caller actually supplied are touched, so a webhook carrying just a
+ # scan does not wipe an estimate from an earlier one.
+ def apply_carrier_report
+ attributes = {}
+ attributes[:tracking_status] = tracking_status.to_s if tracking_status.present?
+ attributes[:estimated_delivery_at] = estimated_delivery_at unless estimated_delivery_at.nil?
+ attributes[:tracking_details] = details unless details.nil?
+
+ fulfillment.update!(attributes) if attributes.any?
+ end
+
+ # Delivery is the one carrier report that is also a merchant fact, so it
+ # crosses over to the status axis — but only from `fulfilled`, and
+ # MarkDelivered enforces that. A carrier reporting delivery on a canceled
+ # parcel is noise on the tracking axis, not a lifecycle event.
+ def confirm_delivery_if_reported
+ return unless tracking_status.to_s == 'delivered'
+ return unless fulfillment.can_mark_delivered?
+
+ result = Spree.fulfillment_mark_delivered_workflow.call(
+ fulfillment: fulfillment,
+ delivered_at: delivered_at,
+ notify_customer: notify_customer
+ )
+
+ failure(fulfillment, result.error.to_s) if result.failure?
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rb
index 75b64bf835..c3312d3aba 100644
--- a/spree/core/app/workflows/spree/orders/complete.rb
+++ b/spree/core/app/workflows/spree/orders/complete.rb
@@ -88,8 +88,9 @@ module Spree
next unless fulfillment.provider.auto_fulfill?
next if fulfillment.fulfilled? || fulfillment.canceled?
- fulfillment.update_columns(status: 'ready', updated_at: Time.current) unless fulfillment.ready?
- fulfillment.fulfill!
+ # Digital goods go out the moment the order is placed; the payment
+ # gate does not apply, hence force.
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment, force: true)
@auto_fulfilled_line_item_ids.concat(fulfillment.line_items.map(&:id))
end
end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 6e608047de..f5521ab0b1 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -958,8 +958,10 @@ en:
track_link: 'Tracking Link: %{url}'
fulfillments:
errors:
+ backordered_units: This fulfillment holds backordered units and cannot be handed over yet
cannot_cancel: This fulfillment cannot be canceled in its current status
cannot_fulfill: This fulfillment cannot be fulfilled in its current status
+ cannot_mark_delivered: Only a fulfilled shipment can be marked delivered
cannot_resume: This fulfillment cannot be resumed in its current status
insufficient_quantity: Requested quantity (%{requested}) for item %{item} exceeds its unfulfilled quantity (%{available})
invalid_cost: cost must be a non-negative number
@@ -969,6 +971,8 @@ en:
not_in_fulfillment: Requested quantity (%{requested}) for item %{item} exceeds the %{available} held by this fulfillment
order_canceled: Fulfillments cannot be created on a canceled order
order_not_completed: Fulfillments can only be created manually on completed orders
+ order_not_paid: This order is not paid for yet
+ unknown_tracking_status: "%{status} is not a known tracking status"
gateway: Gateway
gateway_error: Gateway Error
general: General
diff --git a/spree/core/db/migrate/20260811000001_add_delivery_tracking_to_fulfillments.rb b/spree/core/db/migrate/20260811000001_add_delivery_tracking_to_fulfillments.rb
new file mode 100644
index 0000000000..f8e4003e60
--- /dev/null
+++ b/spree/core/db/migrate/20260811000001_add_delivery_tracking_to_fulfillments.rb
@@ -0,0 +1,27 @@
+class AddDeliveryTrackingToFulfillments < ActiveRecord::Migration[8.1]
+ # The carrier axis (docs/plans/6.0-fulfillment-and-delivery.md, "Status model
+ # — two axes"): what the carrier reports, kept apart from what the merchant
+ # did. Overwritten on every carrier update, so no history table and no
+ # transition graph.
+ #
+ # Status values themselves are remapped by spree:migrate_fulfillment_statuses
+ # rather than here — data transformations never live in migrations.
+ def change
+ change_table :spree_fulfillments, bulk: true do |t|
+ t.string :tracking_status
+ t.datetime :estimated_delivery_at
+ t.datetime :delivered_at
+
+ if t.respond_to?(:jsonb)
+ t.jsonb :tracking_details
+ else
+ t.json :tracking_details
+ end
+ end
+
+ # Carrier webhooks arrive keyed by tracking code, so the lookup that
+ # resolves one to a fulfillment has to be indexed.
+ add_index :spree_fulfillments, :tracking
+ add_index :spree_fulfillments, :status
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index fdcf44f3de..8700dd6c5d 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -74,6 +74,8 @@ module Spree
fulfillment_fulfill_workflow: 'Spree::Fulfillments::Fulfill',
fulfillment_cancel_workflow: 'Spree::Fulfillments::Cancel',
fulfillment_resume_workflow: 'Spree::Fulfillments::Resume',
+ fulfillment_mark_delivered_workflow: 'Spree::Fulfillments::MarkDelivered',
+ fulfillment_update_tracking_workflow: 'Spree::Fulfillments::UpdateTracking',
# returns
return_create_workflow: 'Spree::Returns::Create',
diff --git a/spree/core/lib/spree/testing_support/factories/fulfillment_factory.rb b/spree/core/lib/spree/testing_support/factories/fulfillment_factory.rb
index 74a9f2f506..69e88af24a 100644
--- a/spree/core/lib/spree/testing_support/factories/fulfillment_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/fulfillment_factory.rb
@@ -2,7 +2,7 @@ FactoryBot.define do
factory :fulfillment, aliases: [:shipment], class: Spree::Fulfillment do
tracking { 'U10000' }
cost { 100.00 }
- status { 'pending' }
+ status { 'unfulfilled' }
order { cart.present? ? nil : association(:order) }
stock_location
diff --git a/spree/core/lib/spree/testing_support/factories/fulfillment_item_factory.rb b/spree/core/lib/spree/testing_support/factories/fulfillment_item_factory.rb
index 038daf7b79..172da73bed 100644
--- a/spree/core/lib/spree/testing_support/factories/fulfillment_item_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/fulfillment_item_factory.rb
@@ -5,7 +5,7 @@ FactoryBot.define do
line_item
status { 'on_hand' }
- association(:fulfillment, factory: :fulfillment, status: 'pending')
+ association(:fulfillment, factory: :fulfillment, status: 'unfulfilled')
# this trait usage increases build speed ~ 2x
trait :without_assoc do
diff --git a/spree/core/lib/spree/testing_support/factories/order_factory.rb b/spree/core/lib/spree/testing_support/factories/order_factory.rb
index d7b6715c74..1f5723830d 100644
--- a/spree/core/lib/spree/testing_support/factories/order_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/order_factory.rb
@@ -109,7 +109,7 @@ FactoryBot.define do
factory :order_ready_to_ship do
payment_state { 'paid' }
- shipment_state { 'ready' }
+ shipment_state { 'unfulfilled' }
transient do
with_payment { true }
@@ -120,7 +120,7 @@ FactoryBot.define do
order.fulfillments.each do |shipment|
shipment.fulfillment_items.update_all state: 'on_hand'
- shipment.update_column(:status, 'ready')
+ shipment.update_column(:status, 'unfulfilled')
end
order.reload
end
diff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
index 0a6aae3513..ec679cd69d 100644
--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
@@ -159,6 +159,23 @@ steps:
the work set. spree_shipping_method_categories survives to 6.1 as the
source and rollback reference.
+ - id: migrate_fulfillment_statuses
+ name: "Remap fulfillment statuses"
+ task: "spree:migrate_fulfillment_statuses"
+ notes: |
+ Moves fulfillments onto the unfulfilled/fulfilled/delivered vocabulary.
+ 'pending' and 'ready' both become 'unfulfilled' — the difference between
+ them was the order's payment state, which is no longer a property of a
+ fulfillment. 'ready_for_pickup' becomes 'fulfilled', which is what
+ "waiting at the counter" means now. Pickup fulfillments already marked
+ fulfilled become 'delivered' with delivered_at copied from fulfilled_at:
+ under the old machine a pickup reached that status only when the customer
+ collected it, so it records confirmed receipt. Shipping fulfillments stay
+ 'fulfilled' — whether they arrived was never tracked before 6.0. Order
+ rollups are recomputed rather than mapped. Run after
+ migrate_delivery_profiles (it reads delivery-method providers to tell
+ pickup methods apart). Idempotent.
+
- id: migrate_zones_to_delivery_zones
name: "Convert delivery zones"
task: "spree:migrate_zones_to_delivery_zones"
diff --git a/spree/core/lib/tasks/fulfillment_statuses_migration.rake b/spree/core/lib/tasks/fulfillment_statuses_migration.rake
new file mode 100644
index 0000000000..a25d1ca240
--- /dev/null
+++ b/spree/core/lib/tasks/fulfillment_statuses_migration.rake
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+# 5.6 → 6.0 status remap for the fulfillment lifecycle
+# (docs/plans/6.0-fulfillment-and-delivery.md, Phase 7). Batched and
+# idempotent — every statement narrows to legacy values only, so a second run
+# finds nothing left to do and an interrupted run resumes for free.
+namespace :spree do
+ desc 'Remap fulfillment statuses onto the unfulfilled/fulfilled/delivered vocabulary'
+ task migrate_fulfillment_statuses: :environment do
+ batch_size = ENV.fetch('BATCH_SIZE', 5_000).to_i
+ say = ->(message) { puts message }
+
+ fulfillments = Spree::Fulfillment.unscoped
+
+ # pending and ready both described a package still on the shelf. The
+ # difference between them was the order's payment state, which is no longer
+ # a property of the fulfillment.
+ %w(pending ready).each do |legacy|
+ count = fulfillments.where(status: legacy).in_batches(of: batch_size).update_all(status: 'unfulfilled')
+ say.call "spree_fulfillments.status: #{count} rows #{legacy} → unfulfilled"
+ end
+
+ # ready_for_pickup meant "waiting at the counter", which is what fulfilled
+ # means for a pickup fulfillment now.
+ count = fulfillments.where(status: 'ready_for_pickup').in_batches(of: batch_size).update_all(status: 'fulfilled')
+ say.call "spree_fulfillments.status: #{count} rows ready_for_pickup → fulfilled"
+
+ # Under the old machine a pickup fulfillment reached `fulfilled` only when
+ # the customer collected it — that is confirmed receipt, so those rows are
+ # delivered rather than merely handed over. Shipping fulfillments stay
+ # `fulfilled`: whether they arrived was never recorded.
+ pickup_method_ids = Spree::DeliveryMethod.
+ select { |delivery_method| delivery_method.provider.class.pickup? }.
+ map(&:id)
+
+ if pickup_method_ids.any?
+ pickup_fulfillment_ids = Spree::DeliveryRate.
+ where(selected: true, delivery_method_id: pickup_method_ids).
+ select(:fulfillment_id)
+
+ count = fulfillments.
+ where(status: 'fulfilled', id: pickup_fulfillment_ids).
+ where(delivered_at: nil).
+ in_batches(of: batch_size).
+ update_all('status = \'delivered\', delivered_at = fulfilled_at')
+ say.call "spree_fulfillments.status: #{count} pickup rows fulfilled → delivered"
+ end
+
+ # Order rollups are derived, so they are recomputed rather than mapped —
+ # this also picks up the new `delivered` value for orders whose parcels all
+ # arrived.
+ orders = Spree::Order.where(fulfillment_status: %w(pending ready ready_for_pickup))
+ total = orders.count
+ orders.find_each { |order| order.update_statuses! }
+ say.call "spree_orders.fulfillment_status: #{total} orders recomputed"
+
+ say.call 'migrate_fulfillment_statuses done.'
+ end
+end
diff --git a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
index 2d8d286fe5..f81028eedc 100644
--- a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
+++ b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
@@ -11,6 +11,7 @@ describe '6.0 data migration tasks' do
load Spree::Core::Engine.root.join('lib', 'tasks', 'products.rake')
load Spree::Core::Engine.root.join('lib', 'tasks', 'order_market_backfill.rake')
load Spree::Core::Engine.root.join('lib', 'tasks', 'store_binding_migration.rake')
+ load Spree::Core::Engine.root.join('lib', 'tasks', 'fulfillment_statuses_migration.rake')
end
let(:store) { @default_store }
@@ -338,4 +339,61 @@ describe '6.0 data migration tasks' do
expect(product_type.reload.store_id).to eq(Spree::Store.default.id)
end
end
+
+ describe 'spree:migrate_fulfillment_statuses' do
+ let(:order) { create(:order_ready_to_ship, store: store) }
+
+ it 'moves pending and ready onto unfulfilled' do
+ pending_fulfillment = order.fulfillments.first
+ pending_fulfillment.update_column(:status, 'pending')
+ ready_fulfillment = create(:fulfillment, order: order)
+ ready_fulfillment.update_column(:status, 'ready')
+
+ run_task('spree:migrate_fulfillment_statuses')
+
+ expect(pending_fulfillment.reload.status).to eq('unfulfilled')
+ expect(ready_fulfillment.reload.status).to eq('unfulfilled')
+ end
+
+ it 'treats ready_for_pickup as handed over' do
+ fulfillment = order.fulfillments.first
+ fulfillment.update_column(:status, 'ready_for_pickup')
+
+ run_task('spree:migrate_fulfillment_statuses')
+
+ expect(fulfillment.reload.status).to eq('fulfilled')
+ end
+
+ # A shipping parcel marked fulfilled was never known to have arrived, so it
+ # must not be promoted to delivered.
+ it 'leaves shipped fulfillments fulfilled' do
+ fulfillment = order.fulfillments.first
+ fulfillment.update_columns(status: 'fulfilled', fulfilled_at: Time.current)
+
+ run_task('spree:migrate_fulfillment_statuses')
+
+ expect(fulfillment.reload.status).to eq('fulfilled')
+ expect(fulfillment.delivered_at).to be_nil
+ end
+
+ it 'recomputes the order rollup' do
+ order.fulfillments.each { |fulfillment| fulfillment.update_column(:status, 'pending') }
+ order.update_column(:fulfillment_status, 'ready')
+
+ run_task('spree:migrate_fulfillment_statuses')
+
+ expect(order.reload.fulfillment_status).to eq('unfulfilled')
+ end
+
+ it 'is idempotent' do
+ order.fulfillments.first.update_column(:status, 'pending')
+
+ run_task('spree:migrate_fulfillment_statuses')
+ first_pass = order.fulfillments.map { |fulfillment| fulfillment.reload.status }
+
+ run_task('spree:migrate_fulfillment_statuses')
+
+ expect(order.fulfillments.map { |fulfillment| fulfillment.reload.status }).to eq(first_pass)
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/fulfillment/custom_events_spec.rb b/spree/core/spec/models/spree/fulfillment/custom_events_spec.rb
index dbd5ac12f6..08887d5530 100644
--- a/spree/core/spec/models/spree/fulfillment/custom_events_spec.rb
+++ b/spree/core/spec/models/spree/fulfillment/custom_events_spec.rb
@@ -13,7 +13,7 @@ RSpec.describe Spree::Fulfillment::CustomEvents do
describe 'fulfillment.fulfilled event' do
it 'publishes fulfillment.fulfilled and dual-emits the legacy shipment.shipped' do
- fulfillment.fulfill!
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
expect(Spree::Events).to have_received(:publish).with('fulfillment.fulfilled', anything, anything)
expect(Spree::Events).to have_received(:publish).with('shipment.shipped', anything, anything)
@@ -22,7 +22,7 @@ RSpec.describe Spree::Fulfillment::CustomEvents do
it 'does not publish when events are disabled' do
allow(Spree::Events).to receive(:enabled?).and_return(false)
- fulfillment.fulfill!
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
expect(Spree::Events).not_to have_received(:publish).with('fulfillment.fulfilled', anything, anything)
expect(Spree::Events).not_to have_received(:publish).with('shipment.shipped', anything, anything)
@@ -31,7 +31,7 @@ RSpec.describe Spree::Fulfillment::CustomEvents do
describe 'fulfillment.canceled event' do
it 'publishes fulfillment.canceled and dual-emits the legacy shipment.canceled' do
- fulfillment.cancel!
+ Spree.fulfillment_cancel_workflow.call(fulfillment: fulfillment)
expect(Spree::Events).to have_received(:publish).with('fulfillment.canceled', anything, anything)
expect(Spree::Events).to have_received(:publish).with('shipment.canceled', anything, anything)
@@ -42,7 +42,7 @@ RSpec.describe Spree::Fulfillment::CustomEvents do
it 'publishes order.fulfilled when the last fulfillment fulfills (plus legacy order.shipped)' do
# The order_ready_to_ship factory creates an order with a single
# fulfillment, so fulfilling it makes order.fully_fulfilled? true
- fulfillment.fulfill!
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
expect(Spree::Events).to have_received(:publish).with('fulfillment.fulfilled', anything, anything)
expect(Spree::Events).to have_received(:publish).with('order.fulfilled', anything, anything)
@@ -50,13 +50,25 @@ RSpec.describe Spree::Fulfillment::CustomEvents do
end
it 'does not publish order.fulfilled when other fulfillments are open' do
- create(:shipment, order: order, state: 'pending')
+ create(:shipment, order: order, state: 'unfulfilled')
order.reload
- fulfillment.fulfill!
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
expect(Spree::Events).to have_received(:publish).with('fulfillment.fulfilled', anything, anything)
expect(Spree::Events).not_to have_received(:publish).with('order.fulfilled', anything, anything)
end
end
+
+ describe 'fulfillment.delivered event' do
+ it 'publishes when receipt is confirmed' do
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
+
+ expect(fulfillment).to receive(:publish_event).
+ with('fulfillment.delivered', nil, hash_including(notify_customer: true))
+ allow(fulfillment).to receive(:publish_event).with(any_args)
+
+ fulfillment.publish_fulfillment_delivered_event
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rb
index 5f12f07592..40879ec313 100644
--- a/spree/core/spec/models/spree/line_item_spec.rb
+++ b/spree/core/spec/models/spree/line_item_spec.rb
@@ -600,7 +600,7 @@ describe Spree::LineItem, type: :model do
context 'when the shipment is canceled' do
it 'returns 0' do
- shipment.cancel!
+ shipment.update!(status: 'canceled')
expect(line_item.delivery_cost).to eq(0)
end
end
diff --git a/spree/core/spec/models/spree/order/state_machine_spec.rb b/spree/core/spec/models/spree/order/state_machine_spec.rb
index 05ae540748..03cf564ec5 100644
--- a/spree/core/spec/models/spree/order/state_machine_spec.rb
+++ b/spree/core/spec/models/spree/order/state_machine_spec.rb
@@ -7,7 +7,7 @@ describe Spree::Order, type: :model do
let(:order) { create(:order) }
describe '#allow_cancel?' do
- %w(pending backorder ready canceled).each do |fulfillment_status|
+ %w(unfulfilled backorder canceled).each do |fulfillment_status|
it "is true when fulfillment_status is #{fulfillment_status}" do
allow(order).to receive_messages completed?: true
order.fulfillment_status = fulfillment_status
@@ -15,7 +15,7 @@ describe Spree::Order, type: :model do
end
end
- %w(fulfilled partial ready_for_pickup).each do |fulfillment_status|
+ %w(fulfilled partial delivered).each do |fulfillment_status|
it "is false when fulfillment_status is #{fulfillment_status}" do
allow(order).to receive_messages completed?: true
order.fulfillment_status = fulfillment_status
@@ -54,7 +54,7 @@ describe Spree::Order, type: :model do
expect(order.resume).to be true
expect(order.reload.status).to eq('placed')
- expect(order.fulfillments.reload.map(&:status)).to all(be_in(%w[pending ready]))
+ expect(order.fulfillments.reload.map(&:status)).to all(eq('unfulfilled'))
end
it 'refuses to resume a non-canceled order' do
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 0488a54c04..357a94cffd 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -176,7 +176,7 @@ describe Spree::Order, type: :model do
order.fulfillments.delete_all
create(:shipment, order: order, state: 'canceled')
- create(:shipment, order: order, state: 'ready')
+ create(:shipment, order: order, state: 'unfulfilled')
end
it 'returns true' do
@@ -1853,16 +1853,10 @@ describe Spree::Order, type: :model do
end
let(:order) { create(:order) }
- before do
- shipments[0].cancel
- shipments[0].ship
- end
+ before { shipments[0].update!(status: 'fulfilled') }
context 'when all order shipments were shipped' do
- before do
- shipments[1].cancel
- shipments[1].ship
- end
+ before { shipments[1].update!(status: 'fulfilled') }
it { expect(subject).to eq(true) }
end
diff --git a/spree/core/spec/models/spree/order_updater_spec.rb b/spree/core/spec/models/spree/order_updater_spec.rb
index 58a584c1b6..48155feaa4 100644
--- a/spree/core/spec/models/spree/order_updater_spec.rb
+++ b/spree/core/spec/models/spree/order_updater_spec.rb
@@ -91,7 +91,7 @@ module Spree
before { order.fulfillments.destroy_all }
it 'is backordered' do
- create(:fulfillment, order: order, status: 'pending')
+ create(:fulfillment, order: order, status: 'unfulfilled')
allow(order).to receive(:backordered?).and_return(true)
updater.update_shipment_state
@@ -105,7 +105,7 @@ module Spree
expect(order.fulfillment_status).to be_nil
end
- ['fulfilled', 'pending'].each do |status|
+ %w(unfulfilled fulfilled delivered).each do |status|
it "is #{status}" do
create(:fulfillment, order: order, status: status)
@@ -115,35 +115,53 @@ module Spree
end
end
- # Fulfillment#determine_state only yields 'ready' once the order is paid.
- context 'when the order is paid' do
- before { allow(order).to receive(:paid?).and_return(true) }
+ # Payment no longer enters into it: an unpaid order's fulfillment reads
+ # unfulfilled, exactly like a paid one's.
+ it 'does not depend on whether the order is paid' do
+ create(:fulfillment, order: order, status: 'unfulfilled')
+ allow(order).to receive(:paid?).and_return(false)
- it 'is ready' do
- create(:fulfillment, order: order, status: 'ready')
-
- updater.update_shipment_state
+ updater.update_shipment_state
- expect(order.fulfillment_status).to eq('ready')
- end
+ expect(order.fulfillment_status).to eq('unfulfilled')
+ end
- it 'rolls ready_for_pickup up as ready' do
- create(:fulfillment, order: order, status: 'ready_for_pickup')
+ it 'is partial when some parcels went out and others did not' do
+ create(:fulfillment, order: order, status: 'unfulfilled')
+ create(:fulfillment, order: order, status: 'fulfilled')
- updater.update_shipment_state
+ updater.update_shipment_state
- expect(order.fulfillment_status).to eq('ready')
- end
+ expect(order.fulfillment_status).to eq('partial')
end
- it 'is partial' do
- create(:fulfillment, order: order, status: 'pending')
- create(:fulfillment, order: order, status: 'fulfilled')
+ it 'is partial while some parcels are delivered and others are not' do
+ create(:fulfillment, order: order, status: 'delivered')
+ create(:fulfillment, order: order, status: 'unfulfilled')
updater.update_shipment_state
expect(order.fulfillment_status).to eq('partial')
end
+
+ # A recalled parcel should not describe an order whose other parcel is
+ # still on its way.
+ it 'ignores canceled fulfillments when others are live' do
+ create(:fulfillment, order: order, status: 'canceled')
+ create(:fulfillment, order: order, status: 'unfulfilled')
+
+ updater.update_shipment_state
+
+ expect(order.fulfillment_status).to eq('unfulfilled')
+ end
+
+ it 'is canceled when every fulfillment is' do
+ create(:fulfillment, order: order, status: 'canceled')
+
+ updater.update_shipment_state
+
+ expect(order.fulfillment_status).to eq('canceled')
+ end
end
# The status shims delegate to Spree::Orders::UpdateStatuses, the sole
diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rb
index 2de883dcd3..3553e7edd1 100644
--- a/spree/core/spec/models/spree/shipment_spec.rb
+++ b/spree/core/spec/models/spree/shipment_spec.rb
@@ -7,7 +7,7 @@ describe Spree::Shipment, type: :model do
let(:variant) { line_item.variant }
let!(:line_item) { create(:line_item) }
let(:shipment) do
- create(:shipment, number: 'H21265865494', cost: 1, state: 'pending', stock_location: create(:stock_location)).tap do |shipment|
+ create(:shipment, number: 'H21265865494', cost: 1, state: 'unfulfilled', stock_location: create(:stock_location)).tap do |shipment|
allow(shipment).to receive_messages order: order
allow(shipment).to receive_messages(delivery_method: shipping_method, shipping_method: shipping_method)
end
@@ -114,48 +114,41 @@ describe Spree::Shipment, type: :model do
expect(shipment).to be_backordered
end
- describe '#determine_state' do
- let(:inventory_units) { create_list(:inventory_unit, 1) }
-
- before { allow(inventory_units.first).to receive_messages backordered: true }
-
- it 'returns canceled if order is canceled?' do
- allow(order).to receive_messages canceled?: true
- expect(shipment.determine_state(order)).to eq 'canceled'
+ describe 'status' do
+ it 'starts unfulfilled' do
+ expect(create(:shipment).status).to eq('unfulfilled')
end
- it 'returns canceled when shipment is canceled' do
- allow(shipment).to receive_messages canceled?: true
- expect(shipment.determine_state(order)).to eq 'canceled'
+ it 'rejects a status outside the vocabulary' do
+ shipment.status = 'ready'
+ expect(shipment).not_to be_valid
end
- it 'returns pending unless order.can_ship?' do
- allow(order).to receive_messages can_ship?: false
- expect(shipment.determine_state(order)).to eq 'pending'
- end
-
- it 'returns pending if backordered' do
- allow(shipment).to receive_messages inventory_units: inventory_units
- expect(shipment.determine_state(order)).to eq 'pending'
- end
+ # The payment-derived pending/ready split is gone: whether the order is
+ # paid is asked when someone tries to hand the goods over, not baked into
+ # the fulfillment's own status where a refund could move it backwards.
+ it 'does not change when the order is unpaid' do
+ shipment
+ allow(order).to receive_messages(paid?: false)
- it 'returns fulfilled when already fulfilled' do
- allow(shipment).to receive_messages fulfilled?: true
- expect(shipment.determine_state(order)).to eq 'fulfilled'
+ expect { order.update_statuses! }.not_to change { shipment.reload.status }
end
+ end
- it 'returns pending when unpaid' do
- expect(shipment.determine_state(order)).to eq 'pending'
+ describe 'tracking_status' do
+ it 'accepts a carrier status' do
+ shipment.tracking_status = 'in_transit'
+ expect(shipment).to be_valid
end
- it 'returns ready when paid' do
- allow(order).to receive_messages paid?: true
- expect(shipment.determine_state(order)).to eq 'ready'
+ it 'rejects one outside the carrier vocabulary' do
+ shipment.tracking_status = 'lost_in_space'
+ expect(shipment).not_to be_valid
end
- it 'returns ready when Config.auto_capture_on_dispatch' do
- Spree::Config.auto_capture_on_dispatch = true
- expect(shipment.determine_state(order)).to eq 'ready'
+ it 'is optional' do
+ shipment.tracking_status = nil
+ expect(shipment).to be_valid
end
end
@@ -572,101 +565,16 @@ describe Spree::Shipment, type: :model do
end
describe '#update!' do
- shared_examples_for 'immutable once fulfilled' do
- it 'remains in fulfilled status once fulfilled' do
- shipment.status = 'fulfilled'
- expect(shipment).to receive(:update_columns).with(status: 'fulfilled', updated_at: kind_of(Time))
- shipment.update!(order)
- end
- end
-
- shared_examples_for 'pending if backordered' do
- it 'has a status of pending if backordered' do
- allow(shipment).to receive_messages(fulfillment_items: inventory_units)
- expect(shipment).to receive(:update_columns).with(status: 'pending', updated_at: kind_of(Time))
- shipment.update!(order)
- end
- end
-
- context 'when order cannot ship' do
- before { allow(order).to receive_messages can_ship?: false }
-
- it "results in a 'pending' state" do
- expect(shipment).to receive(:update_columns).with(status: 'pending', updated_at: kind_of(Time))
- shipment.update!(order)
- end
- end
-
- context 'when order is paid' do
- before { allow(order).to receive_messages paid?: true }
-
- it "results in a 'ready' state" do
- expect(shipment).to receive(:update_columns).with(status: 'ready', updated_at: kind_of(Time))
- shipment.update!(order)
- end
-
- it_behaves_like 'immutable once fulfilled'
- it_behaves_like 'pending if backordered'
- end
-
- context 'when order has balance due' do
- before { allow(order).to receive_messages paid?: false }
-
- it "results in a 'pending' state" do
- shipment.status = 'ready'
- expect(shipment).to receive(:update_columns).with(status: 'pending', updated_at: kind_of(Time))
- shipment.update!(order)
- end
-
- it_behaves_like 'immutable once fulfilled'
- it_behaves_like 'pending if backordered'
- end
-
- context 'when order has a credit owed' do
- before { allow(order).to receive_messages payment_state: 'credit_owed', paid?: true }
+ it 'no longer recomputes the status from the order' do
+ shipment.update_column(:status, 'fulfilled')
+ allow(Spree::Deprecation).to receive(:warn)
- it "results in a 'ready' state" do
- shipment.status = 'pending'
- expect(shipment).to receive(:update_columns).with(status: 'ready', updated_at: kind_of(Time))
- shipment.update!(order)
- end
-
- it_behaves_like 'immutable once fulfilled'
- it_behaves_like 'pending if backordered'
+ expect { shipment.update!(order) }.not_to change { shipment.reload.status }
end
- context 'when fulfillment status changes to fulfilled' do
- it 'calls after_fulfill' do
- shipment.status = 'pending'
- expect(shipment).to receive :after_fulfill
- allow(shipment).to receive_messages determine_state: 'fulfilled'
- expect(shipment).to receive(:update_columns).with(status: 'fulfilled', updated_at: kind_of(Time))
- shipment.update!(order)
- end
-
- # ShipmentHandler was removed in 6.0 — after_fulfill owns the mechanics
- # until FulfillmentProvider takes over type-specific behavior.
- it 'ships the items and stamps fulfilled_at' do
- shipment.status = 'pending'
- allow(shipment).to receive_messages determine_state: 'fulfilled'
-
- shipment.update!(order)
-
- expect(shipment.reload.fulfilled_at).to be_present
- expect(shipment.fulfillment_items.reload).to all(be_shipped)
- end
-
- # Regression test for #4347
- context 'with fees' do
- before do
- create(:fee, order: order, fulfillment: shipment, label: 'Label', amount: 5)
- end
-
- it 'transitions to shipped' do
- shipment.update_column(:status, 'ready')
- expect { shipment.fulfill! }.not_to raise_error
- end
- end
+ it 'still writes attributes through ActiveRecord' do
+ shipment.update!(tracking: 'XYZ')
+ expect(shipment.reload.tracking).to eq('XYZ')
end
end
@@ -704,10 +612,9 @@ describe Spree::Shipment, type: :model do
it 'cancels the shipment' do
allow(shipment.order).to receive(:recalculate_totals!)
- shipment.state = 'pending'
- expect(shipment).not_to receive(:after_cancel)
- shipment.cancel!
- expect(shipment.state).to eq 'canceled'
+ shipment.status = 'unfulfilled'
+ described_class.transaction { shipment.update!(status: 'canceled') }
+ expect(shipment.status).to eq 'canceled'
end
# Restocking belongs to Spree::Fulfillments::Cancel now; the deprecated
@@ -744,7 +651,7 @@ describe Spree::Shipment, type: :model do
expect(other_shipment.inventory_units.first).to be_backordered
expect do
- shipment.cancel!
+ Spree.fulfillment_cancel_workflow.call(fulfillment: shipment)
end.not_to change { other_shipment.inventory_units.first.state }
end
end
@@ -753,25 +660,15 @@ describe Spree::Shipment, type: :model do
describe '#resume' do
let(:inventory_unit) { create(:inventory_unit, quantity: 1, line_item: line_item, variant: variant) }
- it 'transitions state to ready if the order is ready' do
+ # One target now: the old machine asked the order's payment state to choose
+ # between pending and ready, which is exactly the coupling that was removed.
+ it 'returns a canceled shipment to unfulfilled regardless of payment' do
allow(shipment.order).to receive(:recalculate_totals!)
+ shipment.update_column(:status, 'canceled')
- shipment.state = 'canceled'
- expect(shipment).to receive(:determine_state).and_return('ready')
- expect(shipment).not_to receive(:after_resume)
- shipment.resume!
- expect(shipment.state).to eq 'ready'
- end
+ Spree.fulfillment_resume_workflow.call(fulfillment: shipment)
- it 'transitions state to pending if the order is not ready' do
- allow(shipment.order).to receive(:recalculate_totals!)
-
- shipment.state = 'canceled'
- expect(shipment).to receive(:determine_state).and_return('pending')
- expect(shipment).not_to receive(:after_resume)
- shipment.resume!
- # Shipment is pending because order is already paid
- expect(shipment.state).to eq 'pending'
+ expect(shipment.reload.status).to eq 'unfulfilled'
end
it 'unstocks them items' do
@@ -796,7 +693,7 @@ describe Spree::Shipment, type: :model do
describe '#ship' do
context 'when the shipment is canceled' do
let(:shipment_with_inventory_units) { create(:shipment, order: create(:order_with_line_items), state: 'canceled') }
- let(:subject) { shipment_with_inventory_units.ship! }
+ let(:subject) { shipment_with_inventory_units.update!(status: 'fulfilled') }
before do
allow(order).to receive(:recalculate_totals!)
@@ -812,85 +709,22 @@ describe Spree::Shipment, type: :model do
end
end
- ['ready', 'canceled'].each do |status|
+ ['unfulfilled', 'canceled'].each do |status|
context "from #{status}" do
- before do
- allow(order).to receive(:recalculate_totals!)
- allow(shipment).to receive_messages(require_inventory: false, update_order: true, status: status)
- end
+ let(:paid_order) { create(:order_ready_to_ship) }
+ let(:fulfillment) { paid_order.fulfillments.first }
+
+ before { fulfillment.update_column(:status, status) }
it 'updates fulfilled_at timestamp' do
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
- shipment.fulfill!
- expect(shipment.fulfilled_at).not_to be_nil
- # Ensure value is persisted
- shipment.reload
- expect(shipment.fulfilled_at).not_to be_nil
+ expect(fulfillment.reload.fulfilled_at).not_to be_nil
end
-
end
end
end
- describe '#ready' do
- context 'with Config.auto_capture_on_dispatch == false' do
- # Regression test for #2040
- it 'cannot ready a shipment for an order if the order is unpaid' do
- allow(order).to receive_messages(paid?: false)
- assert !shipment.can_ready?
- end
- end
-
- context 'with Config.auto_capture_on_dispatch == true' do
- before do
- Spree::Config[:auto_capture_on_dispatch] = true
- @order = create :completed_order_with_pending_payment
- @shipment = @order.fulfillments.first
- @shipment.cost = @order.ship_total
- end
-
- it 'shipments ready for an order if the order is unpaid' do
- expect(@shipment.ready?).to be true
- end
-
- it 'tells the order to process payment in #after_ship' do
- expect(@shipment).to receive(:process_order_payments)
- @shipment.ship!
- end
-
- context 'order has pending payments' do
- let(:payment) do
- payment = @order.payments.first
- payment.update_attribute :state, 'pending'
- payment
- end
-
- before do
- calculator = @shipment.delivery_method.calculator
- calculator.set_preference(:amount, @shipment.cost)
- calculator.save!
- end
-
- it 'can fully capture an authorized payment' do
- payment.update_attribute(:amount, @order.total)
-
- expect(payment.amount).to eq payment.uncaptured_amount
- @shipment.ship!
- expect(payment.reload.uncaptured_amount.to_f).to eq 0
- end
-
- it 'can partially capture an authorized payment' do
- payment.update_attribute(:amount, @order.total + 50)
-
- expect(payment.amount).to eq payment.uncaptured_amount
- @shipment.ship!
- expect(payment.captured_amount).to eq @order.total
- expect(payment.captured_amount).to eq payment.amount - 50
- expect(payment.order.payments.pending.first.amount).to eq 50
- end
- end
- end
- end
context 'updates cost when selected shipping rate is present' do
let(:shipment) { create(:shipment) }
@@ -928,7 +762,7 @@ describe Spree::Shipment, type: :model do
it 'updates everything around order shipment total and state' do
expect(shipment.cost.to_f).to eq 10
- expect(shipment.state).to eq 'pending'
+ expect(shipment.state).to eq 'unfulfilled'
# The full recalculation derives item_total from real line items
# (fabricated column values don't survive it) and statuses come from
# the payment records via UpdateStatuses.
@@ -1150,17 +984,21 @@ describe Spree::Shipment, type: :model do
end
end
- describe '.ready_or_pending' do
- subject { described_class.ready_or_pending }
+ describe '.unfulfilled' do
+ subject { described_class.unfulfilled }
- let!(:ready_shipments) { create_list(:shipment, 2, state: 'ready') }
- let!(:pending_shipments) { create_list(:shipment, 2, state: 'pending') }
- let!(:shipped_shipments) { create_list(:shipment, 2, status: 'fulfilled') }
+ let!(:unfulfilled_shipments) { create_list(:shipment, 2, status: 'unfulfilled') }
+ let!(:fulfilled_shipments) { create_list(:shipment, 2, status: 'fulfilled') }
+
+ it 'returns shipments nobody has handed over yet' do
+ expect(subject).to include(*unfulfilled_shipments)
+ expect(subject).not_to include(*fulfilled_shipments)
+ end
- it 'returns shipments with state ready or pending' do
- expect(subject.pluck(:state).uniq).to contain_exactly('ready', 'pending')
- expect(subject).to include(*ready_shipments, *pending_shipments)
- expect(subject).not_to include(*shipped_shipments)
+ # ready_or_pending survives one release as an alias, since the two statuses
+ # it named both became unfulfilled.
+ it 'is what the deprecated ready_or_pending scope returns' do
+ expect(described_class.ready_or_pending).to match_array(subject)
end
end
@@ -1178,7 +1016,7 @@ describe Spree::Shipment, type: :model do
with('shipment.shipped', nil, hash_including(notify_customer: true))
allow(shipment).to receive(:publish_event).with(any_args)
- shipment.ship!
+ shipment.publish_fulfillment_fulfilled_event
end
end
@@ -1187,18 +1025,18 @@ describe Spree::Shipment, type: :model do
expect(shipment).to receive(:publish_event).with('shipment.canceled')
allow(shipment).to receive(:publish_event).with(anything)
- shipment.cancel!
+ shipment.publish_fulfillment_canceled_event
end
end
describe 'resumed state transition' do
- before { shipment.cancel! }
+ before { shipment.update!(status: 'canceled') }
it 'publishes shipment.resumed event' do
expect(shipment).to receive(:publish_event).with('shipment.resumed')
allow(shipment).to receive(:publish_event).with(anything)
- shipment.resume!
+ shipment.publish_fulfillment_resumed_event
end
end
end
diff --git a/spree/core/spec/services/spree/carts/destroy_spec.rb b/spree/core/spec/services/spree/carts/destroy_spec.rb
index 13f15e0b30..e49067a94a 100644
--- a/spree/core/spec/services/spree/carts/destroy_spec.rb
+++ b/spree/core/spec/services/spree/carts/destroy_spec.rb
@@ -33,10 +33,19 @@ module Spree
subject
end
+ # The cart is destroyed along with them, so the observable fact is that
+ # each one was canceled on its way out rather than deleted outright.
it 'cancels unfulfilled fulfillments' do
- expect_any_instance_of(Spree::Fulfillment).to receive(:cancel).exactly(cart.fulfillments.count).times
+ statuses = []
+ allow_any_instance_of(Spree::Fulfillment).to receive(:update!) do |fulfillment, attributes|
+ statuses << attributes[:status]
+ fulfillment.update_columns(attributes)
+ end
subject
+
+ expect(statuses).to all(eq('canceled'))
+ expect(statuses.count).to eq(1)
end
it 'destroys the cart' do
diff --git a/spree/core/spec/workflows/spree/fulfillments/cancel_spec.rb b/spree/core/spec/workflows/spree/fulfillments/cancel_spec.rb
index 22df09422c..fd6ff6f188 100644
--- a/spree/core/spec/workflows/spree/fulfillments/cancel_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/cancel_spec.rb
@@ -53,7 +53,7 @@ module Spree
end
it 'refuses a fulfillment that cannot cancel' do
- fulfillment.fulfill!
+ fulfillment.update!(status: 'fulfilled')
result = subject.call(fulfillment: fulfillment)
diff --git a/spree/core/spec/workflows/spree/fulfillments/create_spec.rb b/spree/core/spec/workflows/spree/fulfillments/create_spec.rb
index 767aced138..4f9d3dde8f 100644
--- a/spree/core/spec/workflows/spree/fulfillments/create_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/create_spec.rb
@@ -32,8 +32,10 @@ module Spree
not_to change { order.reload.total }
end
- it 'sets the state from the order (paid order -> ready)' do
- expect(fulfillment.state).to eq('ready')
+ # No longer derived from the order's payment state — a new fulfillment
+ # starts unfulfilled and stays there until someone hands it over.
+ it 'starts unfulfilled' do
+ expect(fulfillment.state).to eq('unfulfilled')
end
it 'assigns the order ship address' do
diff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
index d5c6bea152..788f7cc6e0 100644
--- a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
@@ -94,11 +94,10 @@ module Spree
expect(fulfillment.reload).not_to be_fulfilled
end
- # The state machine offers `fulfill` from ready, ready_for_pickup and
- # canceled — shipping a canceled fulfillment is a deliberate transition
- # (the goods went out anyway), so the workflow must not second-guess it.
- it 'fulfills a canceled fulfillment, which the state machine allows' do
- fulfillment.cancel!
+ # Shipping a canceled fulfillment is deliberate — the goods went out
+ # anyway — so the workflow must not second-guess it.
+ it 'fulfills a canceled fulfillment' do
+ fulfillment.update!(status: 'canceled')
result = subject.call(fulfillment: fulfillment)
@@ -107,7 +106,7 @@ module Spree
end
it 'refuses a fulfillment already fulfilled' do
- fulfillment.fulfill!
+ fulfillment.update!(status: 'fulfilled')
result = subject.call(fulfillment: fulfillment)
@@ -118,11 +117,15 @@ module Spree
# The split and the fulfillment share a transaction, so a fulfillment
# that cannot ship must not leave a stray split behind.
it 'creates no fulfillment when the split succeeds but shipping fails' do
- allow_any_instance_of(Spree::Fulfillment).to receive(:fulfill!).
- and_raise(StateMachines::InvalidTransition.new(fulfillment, fulfillment.class.state_machine, :fulfill))
+ allow_any_instance_of(Spree::Fulfillment).to receive(:publish_fulfillment_fulfilled_event).
+ and_raise(RuntimeError, 'carrier exploded')
expect {
- subject.call(fulfillment: fulfillment, items: [{ line_item: line_items.first, quantity: 1 }])
+ begin
+ subject.call(fulfillment: fulfillment, items: [{ line_item: line_items.first, quantity: 1 }])
+ rescue RuntimeError
+ nil
+ end
}.not_to change { order.reload.fulfillments.count }
end
end
@@ -131,7 +134,7 @@ module Spree
# directly has to take them off the shelf again. This used to ride on the
# resume transition callback.
describe 'fulfilling a canceled fulfillment' do
- before { fulfillment.cancel! }
+ before { fulfillment.update!(status: 'canceled') }
it 'takes the units back off the shelf' do
variant = fulfillment.fulfillment_items.first.variant
@@ -145,7 +148,7 @@ module Spree
end
it 'does not unstock when the fulfillment was open' do
- fulfillment.resume!
+ Spree.fulfillment_resume_workflow.call(fulfillment: fulfillment)
variant = fulfillment.fulfillment_items.first.variant
stock_item = fulfillment.stock_location.stock_item(variant)
diff --git a/spree/core/spec/workflows/spree/fulfillments/mark_delivered_spec.rb b/spree/core/spec/workflows/spree/fulfillments/mark_delivered_spec.rb
new file mode 100644
index 0000000000..7bd8771e4c
--- /dev/null
+++ b/spree/core/spec/workflows/spree/fulfillments/mark_delivered_spec.rb
@@ -0,0 +1,81 @@
+require 'spec_helper'
+
+module Spree
+ describe Fulfillments::MarkDelivered do
+ subject { described_class }
+
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ before { Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment) }
+
+ it 'records receipt' do
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(true)
+ expect(fulfillment.reload).to be_delivered
+ expect(fulfillment.delivered_at).to be_present
+ end
+
+ # Carriers report a delivery time that is usually earlier than the webhook
+ # announcing it, and the return window has to run from the real one.
+ it 'honours a supplied delivery time' do
+ arrived = 2.hours.ago
+
+ subject.call(fulfillment: fulfillment, delivered_at: arrived)
+
+ expect(fulfillment.reload.delivered_at).to be_within(1.second).of(arrived)
+ end
+
+ it 'rolls the order up to delivered when every parcel arrived' do
+ subject.call(fulfillment: fulfillment)
+
+ expect(order.reload.fulfillment_status).to eq('delivered')
+ end
+
+ describe 'guards' do
+ it 'refuses a fulfillment that never shipped' do
+ fulfillment.update!(status: 'unfulfilled')
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.cannot_mark_delivered'))
+ end
+
+ it 'refuses a canceled fulfillment' do
+ fulfillment.update!(status: 'canceled')
+
+ expect(subject.call(fulfillment: fulfillment).success?).to eq(false)
+ end
+ end
+
+ describe 'hooks' do
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ it 'lets a validate handler veto the confirmation' do
+ Spree.hooks.register('fulfillments.mark_delivered.validate') do |flow|
+ flow.reject!('we confirm deliveries ourselves')
+ end
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result.success?).to eq(false)
+ expect(fulfillment.reload).to be_fulfilled
+ end
+
+ it 'notifies after_mark_delivered handlers' do
+ observed = nil
+ Spree.hooks.register('fulfillments.mark_delivered.after_mark_delivered') do |flow|
+ observed = flow.fulfillment.status
+ end
+
+ subject.call(fulfillment: fulfillment)
+
+ expect(observed).to eq('delivered')
+ 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
index 8068c774bc..41cacf654b 100644
--- a/spree/core/spec/workflows/spree/fulfillments/resume_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/resume_spec.rb
@@ -10,7 +10,7 @@ module Spree
let(:execute) { subject.call(fulfillment: fulfillment) }
- before { fulfillment.cancel! }
+ before { fulfillment.update!(status: 'canceled') }
it 'brings the fulfillment back' do
expect(execute.success?).to eq(true)
@@ -27,7 +27,7 @@ module Spree
end
it 'refuses a fulfillment that is not canceled' do
- fulfillment.resume!
+ described_class.call(fulfillment: fulfillment)
result = subject.call(fulfillment: fulfillment)
diff --git a/spree/core/spec/workflows/spree/fulfillments/update_tracking_spec.rb b/spree/core/spec/workflows/spree/fulfillments/update_tracking_spec.rb
new file mode 100644
index 0000000000..12beae9537
--- /dev/null
+++ b/spree/core/spec/workflows/spree/fulfillments/update_tracking_spec.rb
@@ -0,0 +1,83 @@
+require 'spec_helper'
+
+module Spree
+ describe Fulfillments::UpdateTracking do
+ subject { described_class }
+
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ before { Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment) }
+
+ it 'records what the carrier reports' do
+ result = subject.call(
+ fulfillment: fulfillment,
+ tracking_status: 'in_transit',
+ estimated_delivery_at: 2.days.from_now,
+ details: { 'last_scan' => 'Leipzig' }
+ )
+
+ expect(result.success?).to eq(true)
+ expect(fulfillment.reload.tracking_status).to eq('in_transit')
+ expect(fulfillment.estimated_delivery_at).to be_present
+ expect(fulfillment.tracking_details).to eq('last_scan' => 'Leipzig')
+ end
+
+ it 'refuses a status outside the carrier vocabulary' do
+ result = subject.call(fulfillment: fulfillment, tracking_status: 'teleported')
+
+ expect(result.success?).to eq(false)
+ expect(fulfillment.reload.tracking_status).to be_nil
+ end
+
+ # A webhook carrying only a scan must not wipe an estimate an earlier one
+ # supplied.
+ it 'leaves attributes the caller did not mention alone' do
+ subject.call(fulfillment: fulfillment, estimated_delivery_at: 3.days.from_now)
+ estimate = fulfillment.reload.estimated_delivery_at
+
+ subject.call(fulfillment: fulfillment, tracking_status: 'out_for_delivery')
+
+ expect(fulfillment.reload.estimated_delivery_at).to be_within(1.second).of(estimate)
+ end
+
+ describe 'when the carrier reports delivery' do
+ it 'confirms receipt on the status axis too' do
+ arrived = 1.hour.ago
+
+ subject.call(fulfillment: fulfillment, tracking_status: 'delivered', delivered_at: arrived)
+
+ expect(fulfillment.reload).to be_delivered
+ expect(fulfillment.delivered_at).to be_within(1.second).of(arrived)
+ end
+ end
+
+ # The whole point of the second axis: a parcel that bounces is still a
+ # parcel the merchant handed over.
+ describe 'when the carrier reports a problem' do
+ it 'records the trouble without moving the fulfillment backwards' do
+ subject.call(fulfillment: fulfillment, tracking_status: 'return_to_sender')
+
+ expect(fulfillment.reload.tracking_status).to eq('return_to_sender')
+ expect(fulfillment).to be_fulfilled
+ end
+
+ it 'records a failed delivery attempt the same way' do
+ subject.call(fulfillment: fulfillment, tracking_status: 'failure')
+
+ expect(fulfillment.reload).to be_fulfilled
+ expect(order.reload.fulfillment_status).to eq('fulfilled')
+ end
+ end
+
+ it 'ignores a delivery report for a canceled parcel' do
+ fulfillment.update!(status: 'canceled')
+
+ subject.call(fulfillment: fulfillment, tracking_status: 'delivered')
+
+ expect(fulfillment.reload).to be_canceled
+ expect(fulfillment.tracking_status).to eq('delivered')
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rb
index 9d6acf9556..c43c3e0718 100644
--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb
@@ -46,7 +46,7 @@ module Spree
described_class.call(order: order)
end
- it 'marks the fulfillment ready when the order is paid' do
+ it 'leaves the fulfillment unfulfilled until someone hands it over' do
Spree::Shipment.create(order: order, stock_location: create(:stock_location))
order.shipments.reload
@@ -54,7 +54,7 @@ module Spree
described_class.call(order: order)
order.reload
- expect(order.shipment_state).to eq('ready')
+ expect(order.shipment_state).to eq('unfulfilled')
end
it 'does not sell inventory units if track_inventory_levels is false' do
diff --git a/spree/core/spec/workflows/spree/orders/resume_spec.rb b/spree/core/spec/workflows/spree/orders/resume_spec.rb
index 8e188a6930..b35d79839b 100644
--- a/spree/core/spec/workflows/spree/orders/resume_spec.rb
+++ b/spree/core/spec/workflows/spree/orders/resume_spec.rb
@@ -12,7 +12,7 @@ module Spree
expect(result).to be_success
expect(result.value.status).to eq('placed')
- expect(order.reload.fulfillments.map(&:status)).to all(eq('pending'))
+ expect(order.reload.fulfillments.map(&:status)).to all(eq('unfulfilled'))
end
it 'publishes order.resumed after commit', :events do