Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Re-quote delivery rates when a fulfillment changes origin
Damian Legawiec50a6c66707b1
diff --git a/docs/plans/6.0-service-workflows.md b/docs/plans/6.0-service-workflows.mdindex c0c9ad071d..2f88f5eee9 100644--- a/docs/plans/6.0-service-workflows.md+++ b/docs/plans/6.0-service-workflows.md@@ -405,6 +405,14 @@ that had already earned the tier (`Fulfillments::Create`, `Payments::Capture`,`Payments::Refund`, `Payments::HandleWebhook`, `Carts::Merge`). Returns,exchanges and claims then arrived with hooks from the start.+**`Fulfillments::Update` graduated on 2026-08-10**, once moving a fulfillment+between origins had to re-quote its delivery rates: the flow gained real+orchestration (assign → re-quote → reprice → roll up statuses) inside one+transaction, and moving a fulfillment to another warehouse is precisely the+decision a 3PL or per-location policy wants to veto. Seam+`fulfillment_update_workflow`, with `fulfillment_update_service` and+`shipment_update_service` aliased to it.+## Workflow and hook inventoryEvery workflow in `app/workflows/`, its Dependencies seam and its hooks.@@ -444,6 +452,7 @@ admin draft-order edits without touching storefront carts.| Workflow | Seam | Hooks | ||---|---|---|---|| `Fulfillments::Create` | `fulfillment_create_workflow` | `validate` (V), `get_provider_data` (C), `after_create` (L) | ✅ |+| `Fulfillments::Update` | `fulfillment_update_workflow` | `validate` (V), `after_update` (L) | ✅ |### Paymentdiff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rbindex 29f225d310..fc9c60c69b 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/fulfillments_controller.rb@@ -42,7 +42,7 @@ module Spree# PATCH /api/v3/admin/orders/:order_id/fulfillments/:iddef updatewith_order_lock do- result = Spree.fulfillment_update_service.call(+ result = Spree.fulfillment_update_workflow.call(fulfillment: @resource,fulfillment_attributes: permitted_params.to_h)diff --git a/spree/core/app/services/spree/fulfillments/update.rb b/spree/core/app/services/spree/fulfillments/update.rbdeleted file mode 100644index 83a702f738..0000000000--- a/spree/core/app/services/spree/fulfillments/update.rb+++ /dev/null@@ -1,48 +0,0 @@-# Update a Fulfillment and make sure the owning Order's totals and-# statuses follow the fulfillment changes-module Spree- module Fulfillments- class Update- prepend Spree::ServiceModule::Base-- def call(fulfillment: nil, fulfillment_attributes: nil, shipment: nil, shipment_attributes: nil)- if shipment || shipment_attributes- Spree::Deprecation.warn(- 'Calling Spree::Fulfillments::Update with shipment:/shipment_attributes: keywords is deprecated ' \- 'and will be removed in Spree 6.1. Use fulfillment:/fulfillment_attributes: instead.'- )- fulfillment ||= shipment- fulfillment_attributes ||= shipment_attributes- end- fulfillment_attributes ||= {}-- ActiveRecord::Base.transaction do- return failure(fulfillment) unless fulfillment.update(fulfillment_attributes)-- if fulfillment_attributes.key?(:selected_shipping_rate_id) || fulfillment_attributes.key?(:selected_delivery_rate_id)- order = fulfillment.order-- # Changing the selected Delivery Rate won't update the cost (for now)- # so we persist the Fulfillment#cost before calculating order delivery- # total and updating payment status (given a change in fulfillment cost- # might change the Order#payment_status)- fulfillment.update_amounts-- order.recalculate_totals!-- # Update fulfillment status only after order total is updated because it- # (via Order#paid?) affects the fulfillment status (YAY)- fulfillment.update_columns(- status: fulfillment.determine_state(order),- updated_at: Time.current- )-- # And then derive the order-level statuses from the new status- order.update_statuses!- end- end- success(fulfillment)- end- end- end-enddiff --git a/spree/core/app/workflows/spree/fulfillments/update.rb b/spree/core/app/workflows/spree/fulfillments/update.rbnew file mode 100644index 0000000000..90e0fa04fa--- /dev/null+++ b/spree/core/app/workflows/spree/fulfillments/update.rb@@ -0,0 +1,113 @@+module Spree+ module Fulfillments+ # Updates a fulfillment and keeps the owning order's money and statuses+ # in step with it.+ #+ # Two changes ripple beyond the row itself. Selecting a different delivery+ # rate re-prices the fulfillment, which can move the order total and with+ # it the payment status. Moving the fulfillment to another origin+ # invalidates its rates outright — they were quoted for the old location,+ # which may not even offer the same methods — so the flow re-quotes,+ # keeping the merchant's chosen method where the new origin still offers+ # it and falling back to the estimator's pick where it does not.+ #+ # In the workflow tier for its hooks and transaction discipline: moving a+ # fulfillment between warehouses is exactly the decision a 3PL or+ # per-location policy wants to veto, and the repricing that follows has to+ # roll back with it.+ class Update < Spree::Workflow+ hooks :validate, :after_update++ # @param fulfillment [Spree::Fulfillment] the fulfillment to update+ # @param fulfillment_attributes [Hash] attributes to assign; +stock_location_id++ # moves the fulfillment, +selected_delivery_rate_id+ changes its rate+ # @param shipment [Spree::Fulfillment, nil] @deprecated use +fulfillment++ # @param shipment_attributes [Hash, nil] @deprecated use +fulfillment_attributes++ # @return [Spree::ServiceModule::Result] the updated fulfillment on success+ def perform(fulfillment: nil, fulfillment_attributes: nil, shipment: nil, shipment_attributes: nil)+ super++ if shipment || shipment_attributes+ Spree::Deprecation.warn(+ 'Calling Spree::Fulfillments::Update with shipment:/shipment_attributes: keywords is deprecated ' \+ 'and will be removed in Spree 6.1. Use fulfillment:/fulfillment_attributes: instead.'+ )+ end++ @fulfillment = fulfillment || shipment+ @attributes = (fulfillment_attributes || shipment_attributes || {}).to_h+ @origin_changed = origin_change?++ # Veto point — per-location policy, 3PL capacity, cut-off windows.+ # Before the transaction: a rejection touches nothing.+ run_hooks :validate++ ApplicationRecord.transaction do+ step :assign_attributes+ step :requote_after_origin_change+ step :reprice_after_rate_change+ end++ run_hooks :after_update+ success(@fulfillment)+ end++ # The fulfillment being updated, readable by hook handlers.+ attr_reader :fulfillment++ # Whether this update moves the fulfillment to another origin.+ def origin_changed?+ @origin_changed+ end++ private++ def assign_attributes+ failure(@fulfillment) unless @fulfillment.update(@attributes)+ end++ def requote_after_origin_change+ return unless @origin_changed++ @fulfillment.refresh_rates(Spree::DeliveryMethod::BACKOFFICE)+ @fulfillment.update_amounts+ @fulfillment.owner&.recalculate_totals!+ end++ # Changing the selected rate does not update the cost on its own, so the+ # fulfillment cost is persisted before the order total is recalculated —+ # the new total is what decides the payment status, which in turn decides+ # the fulfillment status.+ def reprice_after_rate_change+ return unless rate_change?++ order = @fulfillment.order+ return if order.nil?++ @fulfillment.update_amounts+ order.recalculate_totals!++ @fulfillment.update_columns(+ status: @fulfillment.determine_state(order),+ updated_at: Time.current+ )++ order.update_statuses!+ end++ def rate_change?+ @attributes.key?(:selected_shipping_rate_id) || @attributes.key?('selected_shipping_rate_id') ||+ @attributes.key?(:selected_delivery_rate_id) || @attributes.key?('selected_delivery_rate_id')+ end++ # True only when the caller is actually moving the fulfillment, not+ # resubmitting the location it already has.+ def origin_change?+ requested = @attributes[:stock_location_id] || @attributes['stock_location_id']+ return false if requested.blank?++ requested.to_s != @fulfillment.stock_location_id.to_s+ end+ end+ end+enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 189e46419a..3e3208ad6c 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -70,7 +70,7 @@ module Spree# fulfillmentfulfillment_create_workflow: 'Spree::Fulfillments::Create',- fulfillment_update_service: 'Spree::Fulfillments::Update',+ fulfillment_update_workflow: 'Spree::Fulfillments::Update',# returnsreturn_create_workflow: 'Spree::Returns::Create',@@ -148,7 +148,8 @@ module Spree# warning), but a legacy override written against the old keywords is# not interchangeable with what the new call sites pass. Removed in 6.1.LEGACY_SERVICE_KEYS = {- shipment_update_service: :fulfillment_update_service+ shipment_update_service: :fulfillment_update_workflow,+ fulfillment_update_service: :fulfillment_update_workflow}.freezedef legacy_workflow_overridesdiff --git a/spree/core/spec/workflows/spree/fulfillments/update_spec.rb b/spree/core/spec/workflows/spree/fulfillments/update_spec.rbnew file mode 100644index 0000000000..239b485b52--- /dev/null+++ b/spree/core/spec/workflows/spree/fulfillments/update_spec.rb@@ -0,0 +1,87 @@+require 'spec_helper'++RSpec.describe Spree::Fulfillments::Update do+ let(:store) { @default_store }+ let!(:delivery_method) { create(:delivery_method, store: store) }+ let(:order) { create(:order_with_line_items, store: store) }+ let(:fulfillment) { order.fulfillments.first }++ describe 'moving the fulfillment to another origin' do+ let(:other_location) do+ create(:stock_location, store: store, name: "Warehouse #{SecureRandom.hex(3)}",+ propagate_all_variants: true, backorderable_default: true)+ end++ # Rates are quoted per origin, so leaving the old ones in place would offer+ # the customer a method the new warehouse may not even serve.+ it 're-quotes the delivery rates against the new location' do+ original_rate_ids = fulfillment.delivery_rates.map(&:id)++ result = described_class.call(+ fulfillment: fulfillment,+ fulfillment_attributes: { stock_location_id: other_location.id }+ )++ expect(result).to be_success+ expect(fulfillment.reload.stock_location_id).to eq(other_location.id)+ expect(fulfillment.delivery_rates.map(&:id)).not_to match_array(original_rate_ids)+ expect(fulfillment.selected_delivery_rate).to be_present+ end++ it 'leaves the rates alone when the location is merely resubmitted' do+ original_rate_ids = fulfillment.delivery_rates.map(&:id).sort++ described_class.call(+ fulfillment: fulfillment,+ fulfillment_attributes: { stock_location_id: fulfillment.stock_location_id }+ )++ expect(fulfillment.reload.delivery_rates.map(&:id).sort).to eq(original_rate_ids)+ end+ end++ describe 'hooks' do+ before { Spree.hooks.clear! }+ after { Spree.hooks.clear! }++ it 'lets a validate handler veto the move before anything is written' do+ original_location_id = fulfillment.stock_location_id+ other_location = create(:stock_location, store: store, name: "Blocked #{SecureRandom.hex(3)}")++ Spree.hooks.register('fulfillments.update.validate') do |flow|+ flow.reject!('this warehouse is at capacity') if flow.origin_changed?+ end++ result = described_class.call(+ fulfillment: fulfillment,+ fulfillment_attributes: { stock_location_id: other_location.id }+ )++ expect(result).to be_failure+ expect(fulfillment.reload.stock_location_id).to eq(original_location_id)+ end++ it 'notifies after_update handlers once the change is committed' do+ observed = nil+ Spree.hooks.register('fulfillments.update.after_update') { |flow| observed = flow.fulfillment.tracking }++ described_class.call(fulfillment: fulfillment, fulfillment_attributes: { tracking: 'XYZ789' })++ expect(observed).to eq('XYZ789')+ end+ end++ describe 'the deprecated shipment keywords' do+ it 'still updates through the old names, with a warning' do+ expect(Spree::Deprecation).to receive(:warn).at_least(:once)++ result = described_class.call(+ shipment: fulfillment,+ shipment_attributes: { tracking: 'ABC123' }+ )++ expect(result).to be_success+ expect(fulfillment.reload.tracking).to eq('ABC123')+ end+ end+end