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.

Buy the label before declaring the parcel fulfilled

Damian Legawiec2f5dbdef034a
diff --git a/spree/core/app/models/spree/fulfillment_provider/base.rb b/spree/core/app/models/spree/fulfillment_provider/base.rb
index 72c9ec4a23..3aa9b4b218 100644
--- a/spree/core/app/models/spree/fulfillment_provider/base.rb
+++ b/spree/core/app/models/spree/fulfillment_provider/base.rb
@@ -21,6 +21,12 @@ module Spree
false
end
+ # Whether this provider produces shipping labels (and so supports the
+ # explicit buy-label step before fulfilling). Carrier gems override.
+ def generates_labels?
+ false
+ end
+
# Human-readable name for admin UIs. Provider gems follow the
# `SpreeEasyPost::DeliveryRateProvider` convention, where demodulizing
# yields the useless class name ("Delivery Rate Provider") — so those
diff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
index b8390b9c0e..93e3f8af71 100644
--- a/spree/core/app/workflows/spree/fulfillments/fulfill.rb
+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
@@ -52,19 +52,32 @@ module Spree
step :ensure_fulfillable
+ # The split has to land before the provider is involved: the label is
+ # for the actual parcel, and a partial shipment's parcel only exists
+ # after the split.
ApplicationRecord.transaction do
step :split_off_requested_units
- 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.
+ # The label is bought BEFORE the fulfillment is declared fulfilled —
+ # the physical order of a warehouse (print the label, stick it on the
+ # box, hand it over), and the ordering that lets the shipped email
+ # carry the tracking number the provider discovered instead of racing
+ # it. No-op when a label was already bought through
+ # Spree::Fulfillments::PurchaseLabel (the flow where a failure is
+ # loud), or when the provider has no dispatch mechanics (Manual). A
+ # failure here still degrades to "no label yet" — a carrier outage
+ # must never stop a merchant recording a parcel that physically left.
+ # Network I/O, so never in a transaction.
external_step :tell_provider_it_shipped
+ ApplicationRecord.transaction do
+ step :unstock_if_resuming_from_canceled
+ step :mark_fulfilled
+ step :capture_payment_if_configured
+ end
+
step :roll_up_order_status
run_hooks :after_fulfill
diff --git a/spree/core/app/workflows/spree/fulfillments/purchase_label.rb b/spree/core/app/workflows/spree/fulfillments/purchase_label.rb
new file mode 100644
index 0000000000..5c20367dde
--- /dev/null
+++ b/spree/core/app/workflows/spree/fulfillments/purchase_label.rb
@@ -0,0 +1,62 @@
+module Spree
+ module Fulfillments
+ # Buys the shipping label for a parcel that has not shipped yet — the step
+ # a warehouse performs BEFORE anything is handed over: print the label,
+ # stick it on the box, then mark the fulfillment fulfilled.
+ #
+ # This is where a purchase failure is loud. The one-click fulfill path
+ # degrades a label failure to "no label yet" because a carrier outage must
+ # never stop a merchant recording a parcel that physically left; here
+ # nothing has left, so a failed purchase simply fails and the merchant
+ # retries.
+ class PurchaseLabel < Spree::Workflow
+ hooks :validate, :after_purchase_label
+
+ # @param fulfillment [Spree::Fulfillment] the parcel to buy a label for
+ # @return [Spree::ServiceModule::Result] the fulfillment with tracking
+ # and label attached on success
+ def perform(fulfillment:)
+ super
+
+ run_hooks :validate
+
+ step :ensure_purchasable
+
+ # Carrier I/O — never inside a transaction.
+ external_step :purchase
+
+ run_hooks :after_purchase_label
+ success(fulfillment.reload)
+ end
+
+ private
+
+ def ensure_purchasable
+ unless fulfillment.provider.class.generates_labels?
+ failure(fulfillment, Spree.t('fulfillments.errors.provider_has_no_labels'))
+ end
+
+ unless fulfillment.unfulfilled?
+ failure(fulfillment, Spree.t('fulfillments.errors.cannot_purchase_label'))
+ end
+
+ failure(fulfillment, Spree.t('fulfillments.errors.order_draft')) if fulfillment.order&.draft?
+ end
+
+ # The provider is idempotent about an already-bought label (it returns
+ # the stored purchase), so re-running after a partial failure is safe.
+ def purchase
+ result = fulfillment.provider.create_fulfillment(fulfillment)
+
+ unless result.is_a?(Hash) && result[:tracking_number].present?
+ failure(fulfillment, Spree.t('fulfillments.errors.label_purchase_failed'))
+ end
+
+ return if fulfillment.tracking.present?
+
+ # update! so carrier detection pins the badge and tracking URL.
+ fulfillment.update!(tracking: result[:tracking_number])
+ end
+ end
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 3e62cb8993..d3c28e3897 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -962,6 +962,8 @@ en:
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_purchase_label: Labels can only be bought before the fulfillment ships
+ label_purchase_failed: The label could not be purchased — check the carrier connection and try again
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
@@ -973,6 +975,7 @@ en:
order_draft: Draft orders cannot be fulfilled — complete the order first
order_not_completed: Fulfillments can only be created manually on completed orders
order_not_paid: This order is not paid for yet
+ provider_has_no_labels: This delivery method's provider does not produce labels
unknown_tracking_status: "%{status} is not a known tracking status"
gateway: Gateway
gateway_error: Gateway Error
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 8700dd6c5d..4820c9503e 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -75,6 +75,7 @@ module Spree
fulfillment_cancel_workflow: 'Spree::Fulfillments::Cancel',
fulfillment_resume_workflow: 'Spree::Fulfillments::Resume',
fulfillment_mark_delivered_workflow: 'Spree::Fulfillments::MarkDelivered',
+ fulfillment_purchase_label_workflow: 'Spree::Fulfillments::PurchaseLabel',
fulfillment_update_tracking_workflow: 'Spree::Fulfillments::UpdateTracking',
# returns
diff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
index 50f4f85b86..239fa96b56 100644
--- a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
@@ -126,9 +126,12 @@ module Spree
expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.cannot_fulfill'))
end
- # 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
+ # Deliberately NOT rolled back: the label step sits between the split
+ # and the fulfilled write, so by the time fulfilling fails a label may
+ # already be bought for the split parcel — rolling the parcel away
+ # would orphan a paid label. The split survives, unfulfilled, and a
+ # retry picks it up.
+ it 'keeps the split parcel unfulfilled when fulfilling it fails' do
allow_any_instance_of(Spree::Fulfillment).to receive(:publish_fulfillment_fulfilled_event).
and_raise(RuntimeError, 'carrier exploded')
@@ -138,7 +141,9 @@ module Spree
rescue RuntimeError
nil
end
- }.not_to change { order.reload.fulfillments.count }
+ }.to change { order.reload.fulfillments.count }.by(1)
+
+ expect(order.fulfillments.reload.map(&:status)).to all(eq('unfulfilled'))
end
end
@@ -228,6 +233,46 @@ module Spree
end
end
+ describe 'label-before-fulfilled ordering' do
+ let(:label_provider) do
+ Class.new(Spree::FulfillmentProvider::Base) do
+ def create_fulfillment(_fulfillment)
+ { tracking_number: 'CARRIER-XYZ' }
+ end
+ end.new
+ end
+
+ # The shipped email renders from the fulfilled event — it used to race
+ # the label purchase for the tracking number and sometimes lose.
+ it 'publishes the fulfilled event only after provider tracking is persisted' do
+ fulfillment.update_column(:tracking, nil)
+ allow_any_instance_of(Spree::Fulfillment).to receive(:provider).and_return(label_provider)
+
+ tracking_at_publish = :never_published
+ allow_any_instance_of(Spree::Fulfillment).to receive(:publish_fulfillment_fulfilled_event) do |record|
+ tracking_at_publish = record.reload.tracking
+ end
+
+ subject.call(fulfillment: fulfillment)
+
+ expect(tracking_at_publish).to eq('CARRIER-XYZ')
+ end
+
+ it 'still fulfills when the provider degrades to no label' do
+ broken = Class.new(Spree::FulfillmentProvider::Base) do
+ def create_fulfillment(_fulfillment)
+ {}
+ end
+ end.new
+ allow_any_instance_of(Spree::Fulfillment).to receive(:provider).and_return(broken)
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result).to be_success
+ expect(fulfillment.reload).to be_fulfilled
+ end
+ end
+
describe 'tracking carrier' do
it 'stores an explicit carrier beside the number' do
subject.call(fulfillment: fulfillment, tracking: '421432', tracking_carrier: 'inpost')
diff --git a/spree/core/spec/workflows/spree/fulfillments/purchase_label_spec.rb b/spree/core/spec/workflows/spree/fulfillments/purchase_label_spec.rb
new file mode 100644
index 0000000000..c36063af4d
--- /dev/null
+++ b/spree/core/spec/workflows/spree/fulfillments/purchase_label_spec.rb
@@ -0,0 +1,87 @@
+require 'spec_helper'
+
+module Spree
+ describe Fulfillments::PurchaseLabel do
+ subject { described_class }
+
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ let(:label_provider_class) do
+ Class.new(Spree::FulfillmentProvider::Base) do
+ def self.generates_labels?
+ true
+ end
+
+ def create_fulfillment(_fulfillment)
+ { tracking_number: '1Z879E930346834440', tracking_url: 'https://carrier.example/t/1' }
+ end
+ end
+ end
+
+ before do
+ allow(fulfillment).to receive(:provider).and_return(label_provider_class.new)
+ # The factory seeds a tracking number; a parcel awaiting its label has none.
+ fulfillment.update_column(:tracking, nil)
+ end
+
+ it 'buys the label and attaches tracking without fulfilling' do
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result).to be_success
+ expect(fulfillment.reload.tracking).to eq('1Z879E930346834440')
+ expect(fulfillment).to be_unfulfilled
+ end
+
+ it 'pins the carrier detected from the purchased number' do
+ subject.call(fulfillment: fulfillment)
+
+ expect(fulfillment.reload.tracking_carrier).to eq('ups')
+ end
+
+ # The one-click fulfill degrades a label failure; here nothing has left
+ # the building, so failing loudly is the point.
+ it 'fails when the provider cannot produce a label' do
+ allow(fulfillment.provider).to receive(:create_fulfillment).and_return({})
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.label_purchase_failed'))
+ expect(fulfillment.reload).to be_unfulfilled
+ end
+
+ it 'refuses a provider without labels' do
+ allow(fulfillment).to receive(:provider).and_return(Spree::FulfillmentProvider::Manual.new)
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.provider_has_no_labels'))
+ end
+
+ it 'refuses a fulfillment that already shipped' do
+ fulfillment.update!(status: 'fulfilled')
+
+ expect(subject.call(fulfillment: fulfillment)).to be_failure
+ end
+
+ it 'refuses a draft order' do
+ order.update_columns(status: 'draft', completed_at: nil)
+
+ result = subject.call(fulfillment: fulfillment)
+
+ expect(result).to be_failure
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.order_draft'))
+ end
+
+ it 'keeps a merchant-entered tracking number' do
+ fulfillment.update!(tracking: 'MERCHANT-123')
+
+ subject.call(fulfillment: fulfillment)
+
+ expect(fulfillment.reload.tracking).to eq('MERCHANT-123')
+ end
+ end
+end
diff --git a/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb b/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb
index 60b4c47ea5..708887802d 100644
--- a/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb
+++ b/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb
@@ -13,12 +13,25 @@ module SpreeEasyPost
SpreeEasyPost::PROVIDER_NAME
end
+ def self.generates_labels?
+ true
+ end
+
# Buys the rate quoted at checkout when it is still valid; EasyPost
# quotes expire, so a stale or missing quote is re-quoted from the
# actual fulfillment and bought only when a rate for the exact
# carrier/service the customer selected comes back — silently shipping a
# different service than the customer paid for is worse than no label.
def create_fulfillment(fulfillment)
+ # Idempotent: a label bought through the explicit buy-label step must
+ # not be bought again when the fulfillment is later marked fulfilled.
+ if fulfillment.metadata['easypost_purchased_shipment_id'].present?
+ return {
+ tracking_number: fulfillment.tracking,
+ tracking_url: fulfillment.metadata['easypost_tracker_url']
+ }
+ end
+
integration = integration_for(fulfillment)
return {} if integration.nil?
diff --git a/spree/providers/easypost/spec/models/spree_easypost/fulfillment_provider_spec.rb b/spree/providers/easypost/spec/models/spree_easypost/fulfillment_provider_spec.rb
index 2d0e40d6ca..94083df4e2 100644
--- a/spree/providers/easypost/spec/models/spree_easypost/fulfillment_provider_spec.rb
+++ b/spree/providers/easypost/spec/models/spree_easypost/fulfillment_provider_spec.rb
@@ -44,6 +44,23 @@ RSpec.describe SpreeEasyPost::FulfillmentProvider do
end
describe '#create_fulfillment' do
+ it 'does not buy twice — an already-purchased label is returned as-is' do
+ fulfillment.update_columns(
+ tracking: 'EXISTING-123',
+ metadata: fulfillment.metadata.merge(
+ 'easypost_purchased_shipment_id' => 'shp_bought',
+ 'easypost_tracker_url' => 'https://track.example/t/1'
+ )
+ )
+
+ expect(client).not_to receive(:shipment)
+
+ result = provider.create_fulfillment(fulfillment)
+
+ expect(result[:tracking_number]).to eq('EXISTING-123')
+ expect(result[:tracking_url]).to eq('https://track.example/t/1')
+ end
+
let(:purchased_shipment) do
double(
id: 'shp_recorded1',