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.

Feed EasyPost tracker updates into delivery tracking

Damian Legawiec2f916db5914c
diff --git a/docs/v6/developer/core-concepts/fulfillments.mdx b/docs/v6/developer/core-concepts/fulfillments.mdx
index 4bbfd3a0dc..8699fe412d 100644
--- a/docs/v6/developer/core-concepts/fulfillments.mdx
+++ b/docs/v6/developer/core-concepts/fulfillments.mdx
@@ -42,15 +42,39 @@ erDiagram
## Statuses
+A fulfillment's status says what **you** did with the parcel — nothing else.
+
| Value | Meaning |
|---|---|
-| `pending` | Not ready yet — awaiting payment, or items are on backorder |
-| `ready` | Everything in stock and paid for; the warehouse can pick it |
-| `backorder` | Waiting on stock |
-| `fulfilled` | It went out |
+| `unfulfilled` | Still with you. Nothing has left |
+| `fulfilled` | It went out — handed to the carrier, or waiting at the counter for a pickup order |
+| `delivered` | The customer has it |
| `canceled` | It won't be sent |
-One rule only ever moves one way: once something has gone out, it stays gone out. A later payment problem changes the order's [payment status](/v6/developer/core-concepts/orders#statuses) and leaves the fulfillment alone.
+Statuses only move forward: once something has gone out it stays gone out, and a later payment problem changes the order's [payment status](/v6/developer/core-concepts/orders#statuses) rather than the fulfillment.
+
+Whether a fulfillment *can* go out — the order is paid, nothing is on backorder — is checked when you fulfill it, and the answer comes back with a reason. It is not baked into the status, so a refund never moves a parcel backwards. Staff who need to ship against an invoice can pass `force`.
+
+### Where the parcel actually is
+
+Carrier reports live on a second field, `tracking_status`, and never change `status`:
+
+| Value | Meaning |
+|---|---|
+| `pre_transit` | Label made, carrier hasn't got it yet |
+| `in_transit` | On its way |
+| `out_for_delivery` | On the van |
+| `available_for_pickup` | Waiting at a carrier location |
+| `delivered` | Carrier says it arrived |
+| `return_to_sender` | Coming back to you |
+| `failure` | Delivery failed — a bad address, damage, a refused parcel |
+| `unknown` | The carrier said something we don't recognise |
+
+Keeping the two apart is the point. A parcel that bounces still shows `fulfilled`, because you did hand it over; the trouble shows up as `return_to_sender` and you decide what to do about it. The one report that crosses over is delivery, which also sets `delivered` and `delivered_at`.
+
+`delivered_at` is what return windows and the EU withdrawal period count from, so it records when the carrier says the parcel arrived rather than when you heard about it.
+
+Carriers set this through their provider's webhook. With no carrier integration, staff mark receipt by hand — `markDelivered` in the Admin SDK — which is also how pickup orders get closed out.
## Delivery types
@@ -124,7 +148,7 @@ curl 'https://api.mystore.com/api/v3/store/delivery_methods/dm_xxx/pickup_locati
<CodeGroup>
```typescript Admin SDK
-// What's ready to pick
+// What's still with you
const fulfillments = await adminClient.orders.fulfillments.list('or_xxx')
// Add tracking, then mark it sent
@@ -133,6 +157,9 @@ await adminClient.orders.fulfillments.update('or_xxx', 'ful_xxx', {
})
await adminClient.orders.fulfillments.fulfill('or_xxx', 'ful_xxx')
+// Record receipt yourself when no carrier reports it for you
+await adminClient.orders.fulfillments.markDelivered('or_xxx', 'ful_xxx')
+
// Split it when only part can go now
await adminClient.orders.fulfillments.split('or_xxx', 'ful_xxx', {
items: [{ fulfillment_item_id: 'fi_xxx', quantity: 1 }],
@@ -184,7 +211,7 @@ Methods can also carry conditions that decide when they're offered at all: free
## Events
-Fulfillments publish [events](/developer/core-concepts/events) — `fulfillment.created`, `fulfillment.fulfilled`, `fulfillment.canceled` — which also reach [webhooks](/developer/core-concepts/webhooks). Use them to notify a customer, push to a warehouse system, or send tracking emails.
+Fulfillments publish [events](/developer/core-concepts/events) — `fulfillment.created`, `fulfillment.fulfilled`, `fulfillment.delivered`, `fulfillment.canceled` — which also reach [webhooks](/developer/core-concepts/webhooks). Use them to notify a customer, push to a warehouse system, or send tracking emails.
## Related
diff --git a/docs/v6/developer/core-concepts/orders.mdx b/docs/v6/developer/core-concepts/orders.mdx
index 7c3f3155bd..d106ae7c2a 100644
--- a/docs/v6/developer/core-concepts/orders.mdx
+++ b/docs/v6/developer/core-concepts/orders.mdx
@@ -68,13 +68,15 @@ An order tracks payment and delivery separately, because they genuinely move at
| Value | Meaning |
|---|---|
-| `pending` | Not ready to send yet |
-| `ready` | Everything in stock and paid for |
+| `unfulfilled` | Nothing has gone out yet |
| `backorder` | Waiting on stock |
| `partial` | Some of it has gone out |
| `fulfilled` | Everything has gone out |
+| `delivered` | The customer has all of it |
| `canceled` | Nothing will be sent |
+A canceled parcel is ignored while others are still live, so an order whose second parcel was recalled is described by the first.
+
Both are worked out automatically from the order's payments, refunds and fulfillments. You change an order's status by acting on those — taking a payment, sending a parcel, issuing a refund — never by setting the status yourself.
## Reading an order
@@ -108,7 +110,7 @@ Back-office work happens through the Admin API.
```typescript Admin SDK
// Find orders needing attention
const orders = await adminClient.orders.list({
- filter: { payment_status_eq: 'paid', fulfillment_status_eq: 'ready' },
+ filter: { payment_status_eq: 'paid', fulfillment_status_eq: 'unfulfilled' },
})
// Cancel an order
diff --git a/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx b/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx
index 40412563df..4ba69abb40 100644
--- a/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx
+++ b/docs/v6/developer/how-to/custom-delivery-rate-provider.mdx
@@ -162,6 +162,36 @@ One delivery method is the carrier connection: every service your provider retur
Providers and calculators coexist freely. A store can price "Free shipping" with a flat-rate calculator, "Express" through your carrier, and "Local pickup" with neither.
+## Feeding carrier tracking back in
+
+Once a parcel is moving, most carriers will tell you where it is. Spree keeps
+that on a separate field from the fulfillment's own status, so a bounced parcel
+never un-ships itself — see [Fulfillments](/v6/developer/core-concepts/fulfillments#statuses).
+
+Translate the carrier's vocabulary into Spree's in your gem, then hand it over:
+
+```ruby
+Spree.fulfillment_update_tracking_workflow.call(
+ fulfillment: fulfillment,
+ tracking_status: 'out_for_delivery', # one of Spree::Fulfillment::TRACKING_STATUSES
+ estimated_delivery_at: Time.parse(payload['eta']),
+ details: payload.slice('status_detail', 'carrier')
+)
+```
+
+Two things it does for you: reporting `delivered` also confirms receipt on the
+fulfillment (setting `delivered_at`, which return windows count from), and an
+update that only carries a scan leaves an earlier estimate alone.
+
+Pass `delivered_at` from the carrier's delivering scan rather than letting it
+default to now — a webhook usually lands well after the parcel arrives, and the
+customer's return window starts at the doorstep.
+
+Do the translation in your gem, never in core: `unknown` keeps an unrecognised
+report visible instead of dropping it. A webhook endpoint should answer `200`
+even for parcels it does not recognise, or the carrier will retry a payload
+that can never succeed.
+
## Testing
Your provider is a plain object, so test it directly:
diff --git a/spree/providers/easypost/app/controllers/spree_easypost/webhooks_controller.rb b/spree/providers/easypost/app/controllers/spree_easypost/webhooks_controller.rb
new file mode 100644
index 0000000000..ee94798f55
--- /dev/null
+++ b/spree/providers/easypost/app/controllers/spree_easypost/webhooks_controller.rb
@@ -0,0 +1,44 @@
+module SpreeEasyPost
+ # Receives EasyPost's `tracker.updated` webhooks and hands them to
+ # {Spree::Fulfillments::UpdateTracking}.
+ #
+ # Always answers 200 once the payload has been read. A webhook endpoint that
+ # returns an error gets retried, and there is nothing to retry for a tracker
+ # we do not recognise — the parcel may belong to another system entirely.
+ # Genuine failures are reported rather than escalated to the carrier.
+ class WebhooksController < ActionController::Base
+ protect_from_forgery with: :null_session
+ skip_forgery_protection
+
+ def create
+ event = SpreeEasyPost::TrackerEvent.from_webhook(params)
+ return head(:ok) if event.nil?
+
+ fulfillment = find_fulfillment(event.tracking_code)
+ return head(:ok) if fulfillment.nil?
+
+ Spree.fulfillment_update_tracking_workflow.call(
+ fulfillment: fulfillment,
+ tracking_status: event.status,
+ estimated_delivery_at: event.estimated_delivery_at,
+ delivered_at: event.delivered_at,
+ details: event.details
+ )
+
+ head :ok
+ rescue StandardError => e
+ Rails.error.report(e, handled: true, context: { tracking_code: params.dig(:result, :tracking_code) })
+ head :ok
+ end
+
+ private
+
+ # Matched on tracking code alone: EasyPost's webhook says nothing about
+ # which store a parcel belongs to, and a tracking code is unique in
+ # practice. Scoped to fulfillments that actually shipped so a recycled code
+ # cannot reopen an old parcel's tracking.
+ def find_fulfillment(tracking_code)
+ Spree::Fulfillment.where(tracking: tracking_code).where.not(status: 'canceled').reverse_chronological.first
+ end
+ end
+end
diff --git a/spree/providers/easypost/app/models/spree_easypost/tracker_event.rb b/spree/providers/easypost/app/models/spree_easypost/tracker_event.rb
new file mode 100644
index 0000000000..f1b64cbb9b
--- /dev/null
+++ b/spree/providers/easypost/app/models/spree_easypost/tracker_event.rb
@@ -0,0 +1,73 @@
+module SpreeEasyPost
+ # One `tracker.updated` webhook, translated into the vocabulary
+ # Spree::Fulfillments::UpdateTracking speaks.
+ #
+ # Translating carrier status names is the provider's job precisely so core
+ # never learns any one carrier's spelling — EasyPost's own vocabulary happens
+ # to be close, but `unknown` and `error` are not the same thing to us, and a
+ # future provider's will not line up at all.
+ class TrackerEvent
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ # EasyPost status → Spree tracking status. Anything unlisted is recorded as
+ # `unknown` rather than dropped: a merchant looking at a parcel wants to
+ # see that something was reported, even if we cannot name it.
+ STATUS_MAP = {
+ 'pre_transit' => 'pre_transit',
+ 'in_transit' => 'in_transit',
+ 'out_for_delivery' => 'out_for_delivery',
+ 'available_for_pickup' => 'available_for_pickup',
+ 'delivered' => 'delivered',
+ 'return_to_sender' => 'return_to_sender',
+ 'failure' => 'failure',
+ 'cancelled' => 'failure',
+ 'error' => 'failure',
+ 'unknown' => 'unknown'
+ }.freeze
+
+ attribute :tracking_code, :string
+ attribute :status, :string
+ attribute :estimated_delivery_at, :datetime
+ attribute :delivered_at, :datetime
+ attr_accessor :details
+
+ # @param payload [Hash] the webhook body EasyPost posted
+ # @return [SpreeEasyPost::TrackerEvent, nil] nil when the payload is not a
+ # tracker update or carries no tracking code to match on
+ def self.from_webhook(payload)
+ # A webhook body is untrusted input we only ever read, so it is converted
+ # wholesale rather than declared field by field — permitting it would
+ # imply the values reach a model, and they do not.
+ payload = payload.respond_to?(:to_unsafe_h) ? payload.to_unsafe_h : payload
+ payload = payload.to_h.deep_stringify_keys
+ return unless payload['description'].to_s.start_with?('tracker.')
+
+ tracker = payload['result'] || {}
+ tracker = tracker.respond_to?(:to_unsafe_h) ? tracker.to_unsafe_h.deep_stringify_keys : tracker
+ tracking_code = tracker['tracking_code']
+ return if tracking_code.blank?
+
+ new(
+ tracking_code: tracking_code,
+ status: STATUS_MAP.fetch(tracker['status'].to_s, 'unknown'),
+ estimated_delivery_at: tracker['est_delivery_date'],
+ delivered_at: delivery_time(tracker),
+ details: tracker.slice('status', 'status_detail', 'carrier', 'est_delivery_date', 'public_url')
+ )
+ end
+
+ # The scan that actually recorded delivery, which is earlier than the
+ # webhook and is what a return window has to run from.
+ def self.delivery_time(tracker)
+ return unless tracker['status'].to_s == 'delivered'
+
+ delivering_scan = Array(tracker['tracking_details']).reverse.find do |detail|
+ detail.is_a?(Hash) && detail['status'].to_s == 'delivered'
+ end
+
+ delivering_scan&.dig('datetime')
+ end
+ private_class_method :delivery_time
+ end
+end
diff --git a/spree/providers/easypost/lib/spree_easypost/engine.rb b/spree/providers/easypost/lib/spree_easypost/engine.rb
index b290bad910..b5843c95a5 100644
--- a/spree/providers/easypost/lib/spree_easypost/engine.rb
+++ b/spree/providers/easypost/lib/spree_easypost/engine.rb
@@ -13,6 +13,19 @@ module SpreeEasyPost
end
end
+ # The gem ships one route (the tracker webhook), so it is appended rather
+ # than asking hosts to mount an engine for a single endpoint.
+ initializer 'spree_easypost.routes' do |app|
+ app.routes.append do
+ # Routed to the class rather than a 'spree_easypost/webhooks' string:
+ # Rails camelizes that to SpreeEasypost, which is not what the gem's
+ # module is called (see the inflection above).
+ post '/spree_easypost/webhooks',
+ to: SpreeEasyPost::WebhooksController.action(:create),
+ as: :spree_easypost_webhooks
+ end
+ end
+
config.after_initialize do
Spree.integrations << 'SpreeEasyPost::Integration'
Spree.delivery_rate_providers << SpreeEasyPost::DeliveryRateProvider
diff --git a/spree/providers/easypost/spec/models/spree_easypost/tracker_event_spec.rb b/spree/providers/easypost/spec/models/spree_easypost/tracker_event_spec.rb
new file mode 100644
index 0000000000..a8027461c2
--- /dev/null
+++ b/spree/providers/easypost/spec/models/spree_easypost/tracker_event_spec.rb
@@ -0,0 +1,95 @@
+require 'spec_helper'
+
+RSpec.describe SpreeEasyPost::TrackerEvent do
+ def webhook(status:, tracking_code: 'EZ1000000001', **extra)
+ {
+ 'description' => 'tracker.updated',
+ 'result' => {
+ 'object' => 'Tracker',
+ 'tracking_code' => tracking_code,
+ 'status' => status,
+ 'carrier' => 'USPS',
+ 'public_url' => 'https://track.easypost.com/EZ1000000001'
+ }.merge(extra)
+ }
+ end
+
+ describe '.from_webhook' do
+ it 'reads a carrier status into the Spree vocabulary' do
+ event = described_class.from_webhook(webhook(status: 'out_for_delivery'))
+
+ expect(event.tracking_code).to eq('EZ1000000001')
+ expect(event.status).to eq('out_for_delivery')
+ expect(Spree::Fulfillment::TRACKING_STATUSES).to include(event.status)
+ end
+
+ # EasyPost spells a few of its own states differently from ours; the point
+ # of the map is that core never has to know that.
+ it 'folds carrier-specific names onto the ones core knows' do
+ expect(described_class.from_webhook(webhook(status: 'cancelled')).status).to eq('failure')
+ expect(described_class.from_webhook(webhook(status: 'error')).status).to eq('failure')
+ end
+
+ it 'records an unrecognised status as unknown rather than dropping it' do
+ event = described_class.from_webhook(webhook(status: 'teleported'))
+
+ expect(event.status).to eq('unknown')
+ end
+
+ it 'ignores webhooks that are not tracker updates' do
+ expect(described_class.from_webhook('description' => 'batch.created', 'result' => {})).to be_nil
+ end
+
+ it 'ignores a tracker with no tracking code to match on' do
+ payload = webhook(status: 'in_transit')
+ payload['result']['tracking_code'] = nil
+
+ expect(described_class.from_webhook(payload)).to be_nil
+ end
+
+ it 'reads the carrier estimate' do
+ event = described_class.from_webhook(
+ webhook(status: 'in_transit', 'est_delivery_date' => '2026-08-14T00:00:00Z')
+ )
+
+ expect(event.estimated_delivery_at).to eq(Time.utc(2026, 8, 14))
+ end
+
+ describe 'delivery time' do
+ # The webhook usually lands after the parcel arrives, and a return window
+ # has to run from the scan rather than from when we heard about it.
+ it 'takes the time of the delivering scan' do
+ event = described_class.from_webhook(
+ webhook(
+ status: 'delivered',
+ 'tracking_details' => [
+ { 'status' => 'in_transit', 'datetime' => '2026-08-12T08:00:00Z' },
+ { 'status' => 'delivered', 'datetime' => '2026-08-13T14:20:00Z' }
+ ]
+ )
+ )
+
+ expect(event.delivered_at).to eq(Time.utc(2026, 8, 13, 14, 20))
+ end
+
+ it 'is blank while the parcel is still moving' do
+ event = described_class.from_webhook(
+ webhook(
+ status: 'in_transit',
+ 'tracking_details' => [{ 'status' => 'in_transit', 'datetime' => '2026-08-12T08:00:00Z' }]
+ )
+ )
+
+ expect(event.delivered_at).to be_nil
+ end
+ end
+
+ it 'keeps the carrier detail worth showing an admin' do
+ event = described_class.from_webhook(
+ webhook(status: 'failure', 'status_detail' => 'address_incorrect')
+ )
+
+ expect(event.details).to include('status_detail' => 'address_incorrect', 'carrier' => 'USPS')
+ end
+ end
+end
diff --git a/spree/providers/easypost/spec/requests/spree_easypost/webhooks_spec.rb b/spree/providers/easypost/spec/requests/spree_easypost/webhooks_spec.rb
new file mode 100644
index 0000000000..5c7bb9cc04
--- /dev/null
+++ b/spree/providers/easypost/spec/requests/spree_easypost/webhooks_spec.rb
@@ -0,0 +1,75 @@
+require 'spec_helper'
+
+# Exercises the whole path a carrier update travels: HTTP in, tracker parsed,
+# core workflow run, fulfillment updated. The pieces are unit-tested
+# separately; this is here because the wiring between them is what breaks.
+RSpec.describe 'EasyPost tracker webhooks', type: :request do
+ let(:store) { @default_store }
+ let(:order) { create(:order_ready_to_ship, store: store) }
+ let(:fulfillment) { order.fulfillments.first }
+
+ def post_tracker(status:, tracking_code:, **result)
+ post '/spree_easypost/webhooks', params: {
+ description: 'tracker.updated',
+ result: { object: 'Tracker', tracking_code: tracking_code, status: status, carrier: 'USPS' }.merge(result)
+ }, as: :json
+ end
+
+ before do
+ Spree.fulfillment_fulfill_workflow.call(fulfillment: fulfillment)
+ fulfillment.reload.update!(tracking: 'EZ1000000001')
+ end
+
+ it 'records the carrier update on the fulfillment' do
+ post_tracker(status: 'out_for_delivery', tracking_code: 'EZ1000000001')
+
+ expect(response).to have_http_status(:ok)
+ expect(fulfillment.reload.tracking_status).to eq('out_for_delivery')
+ end
+
+ it 'confirms receipt when the carrier reports delivery' do
+ post_tracker(
+ status: 'delivered',
+ tracking_code: 'EZ1000000001',
+ tracking_details: [{ status: 'delivered', datetime: '2026-08-13T14:20:00Z' }]
+ )
+
+ expect(fulfillment.reload).to be_delivered
+ expect(fulfillment.delivered_at).to eq(Time.utc(2026, 8, 13, 14, 20))
+ end
+
+ # The whole point of the second axis: a bounced parcel is still a parcel the
+ # merchant handed over.
+ it 'records a bounce without moving the fulfillment backwards' do
+ post_tracker(status: 'return_to_sender', tracking_code: 'EZ1000000001')
+
+ expect(fulfillment.reload.tracking_status).to eq('return_to_sender')
+ expect(fulfillment).to be_fulfilled
+ end
+
+ describe 'payloads it cannot act on' do
+ it 'accepts an unknown tracking code without changing anything' do
+ expect {
+ post_tracker(status: 'delivered', tracking_code: 'EZ_NOT_OURS')
+ }.not_to change { fulfillment.reload.status }
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it 'accepts a webhook that is not a tracker update' do
+ post '/spree_easypost/webhooks', params: { description: 'batch.created', result: {} }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ # Answering anything else would make EasyPost retry a payload that will
+ # never succeed.
+ it 'still answers 200 when the update itself fails' do
+ allow(Spree.fulfillment_update_tracking_workflow).to receive(:call).and_raise('boom')
+
+ post_tracker(status: 'in_transit', tracking_code: 'EZ1000000001')
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
+end