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
Route every delivery write through one path and stop blocking on the label file
Damian Legawiecfe609a4b120c
diff --git a/packages/admin-sdk/src/types/generated/ShippingLabel.ts b/packages/admin-sdk/src/types/generated/ShippingLabel.tsindex c05ad8d1dc..77d1453116 100644--- a/packages/admin-sdk/src/types/generated/ShippingLabel.ts+++ b/packages/admin-sdk/src/types/generated/ShippingLabel.ts@@ -1,4 +1,4 @@-// Typelizer digest 40290dc0266f99196b6506a1da1e5b1a+// Typelizer digest d63687d58e3a60dfcb71df3de4786fd2//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -7,6 +7,7 @@ interface ShippingLabel {source: string;status: string;carrier: string | null;+ carrier_name: string | null;service: string | null;tracking_number: string | null;currency: string | null;@@ -18,7 +19,6 @@ interface ShippingLabel {updated_at: string;owner_id: string;owner_type: string;- carrier_name: string | null;cost: string;display_cost: string;integration_id: string | null;diff --git a/packages/dashboard/src/components/spree/orders/fulfillment-delivery-dialog.tsx b/packages/dashboard/src/components/spree/orders/fulfillment-delivery-dialog.tsxindex 85660a6a67..edc9947c12 100644--- a/packages/dashboard/src/components/spree/orders/fulfillment-delivery-dialog.tsx+++ b/packages/dashboard/src/components/spree/orders/fulfillment-delivery-dialog.tsx@@ -53,8 +53,11 @@ export function FulfillmentDeliveryDialog({const { createDelivery, updateDelivery } = useFulfillmentActions(orderId)const { data: carriersData } = useTrackingCarriers(open)+ // The datalist suggests display names, but what is stored and submitted is+ // the registry key — seeding the field with the name would rewrite a known+ // carrier to its own label on the next save.const carrierOptions = (carriersData?.data ?? []).map((carrier) => ({- value: carrier.name,+ value: carrier.id,label: carrier.name,}))@@ -62,7 +65,7 @@ export function FulfillmentDeliveryDialog({resolver: zodResolver(deliverySchema),defaultValues: {tracking_number: delivery?.tracking_number ?? '',- carrier: delivery?.carrier_name ?? '',+ carrier: delivery?.carrier ?? '',tracking_url: delivery?.tracking_url ?? '',},})@@ -139,7 +142,7 @@ export function FulfillmentDeliveryDialog({/><datalist id="delivery-carrier-options">{carrierOptions.map((option) => (- <option key={option.value} value={option.value} />+ <option key={option.value} value={option.value} label={option.label} />))}</datalist></Field>diff --git a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsxindex 8dc7d3f065..cc0b2afbad 100644--- a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx+++ b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx@@ -431,8 +431,7 @@ function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: Fulconst canBuyLabel = shippable && fulfillment.provider_generates_labels && !activeLabel// Merchants without a carrier account buy postage elsewhere and still need// the file and the cost on the parcel.- const canUploadLabel =- !activeLabel && !CAN_MARK_DELIVERED.includes(fulfillment.status) ? shippable : false+ const canUploadLabel = shippable && !activeLabelreturn (<FulfillmentPaneldiff --git a/packages/sdk/src/types/generated/ShippingLabelEvent.ts b/packages/sdk/src/types/generated/ShippingLabelEvent.tsindex 5b97d5f0e1..250436eabd 100644--- a/packages/sdk/src/types/generated/ShippingLabelEvent.ts+++ b/packages/sdk/src/types/generated/ShippingLabelEvent.ts@@ -1,4 +1,4 @@-// Typelizer digest 28ef8030836c61f77a9912e2c3146c0f+// Typelizer digest 015b6583b443064c2f962b9b2406676d//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -7,6 +7,7 @@ interface ShippingLabelEvent {source: string;status: string;carrier: string | null;+ carrier_name: string | null;service: string | null;tracking_number: string | null;currency: string | null;@@ -18,7 +19,6 @@ interface ShippingLabelEvent {updated_at: string;owner_id: string;owner_type: string;- carrier_name: string | null;cost: string;display_cost: string;integration_id: string | null;diff --git a/packages/sdk/src/zod/generated/ShippingLabelEvent.ts b/packages/sdk/src/zod/generated/ShippingLabelEvent.tsindex 361be91b81..038af26356 100644--- a/packages/sdk/src/zod/generated/ShippingLabelEvent.ts+++ b/packages/sdk/src/zod/generated/ShippingLabelEvent.ts@@ -6,6 +6,7 @@ export const ShippingLabelEventSchema = z.object({source: z.string(),status: z.string(),carrier: z.string().nullable(),+ carrier_name: z.string().nullable(),service: z.string().nullable(),tracking_number: z.string().nullable(),currency: z.string().nullable(),@@ -17,7 +18,6 @@ export const ShippingLabelEventSchema = z.object({updated_at: z.string(),owner_id: z.string(),owner_type: z.string(),- carrier_name: z.string().nullable(),cost: z.string(),display_cost: z.string(),integration_id: z.string().nullable(),diff --git a/packages/seller-sdk/src/types/generated/Delivery.ts b/packages/seller-sdk/src/types/generated/Delivery.tsindex c5224b378a..45fc7a1488 100644--- a/packages/seller-sdk/src/types/generated/Delivery.ts+++ b/packages/seller-sdk/src/types/generated/Delivery.ts@@ -1,15 +1,15 @@-// Typelizer digest 419b9251277a1f6b303a310472c8629c+// Typelizer digest 533d941764285691eac20d99c3b59e76//// DO NOT MODIFY: This file was automatically generated by Typelizer.type Delivery = {id: string;tracking_number: string;- tracking_url: string | null;carrier: string | null;carrier_name: string | null;service: string | null;status: string;+ tracking_url: string | null;estimated_delivery_at: string | null;delivered_at: string | null;created_at: string;diff --git a/spree/api/app/controllers/concerns/spree/api/v3/streams_shipping_label.rb b/spree/api/app/controllers/concerns/spree/api/v3/streams_shipping_label.rbnew file mode 100644index 0000000000..fdaf8f10f9--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/streams_shipping_label.rb@@ -0,0 +1,37 @@+module Spree+ module Api+ module V3+ # Serving a label file, shared by every surface that offers one — the+ # operator's, the seller's and the customer's return download.+ #+ # The bytes are streamed rather than redirected to storage, so the+ # credentials that reached the action are what protects the file. The+ # one exception is a label whose file is still being fetched from the+ # carrier: until it lands, the carrier's own copy stands in.+ #+ # Deliberately carries no scope of its own — the caller has already+ # fetched and authorized the label.+ module StreamsShippingLabel+ extend ActiveSupport::Concern++ # @param shipping_label [Spree::ShippingLabel]+ # @yield when there is nothing to serve, so each surface answers in+ # its own vocabulary (a 404 for a customer, a 422 for staff)+ def stream_shipping_label(shipping_label, &on_missing)+ if shipping_label.file.attached?+ send_data(+ shipping_label.file.download,+ filename: shipping_label.download_filename,+ type: shipping_label.file.content_type || 'application/octet-stream',+ disposition: 'attachment'+ )+ elsif shipping_label.file_pending?+ redirect_to shipping_label.file_url, allow_other_host: true+ else+ on_missing.call+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rbindex f1c5e68279..3a4d9b7b19 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/deliveries_controller.rb@@ -35,12 +35,7 @@ module Spree# journey starts over.def updatewith_order_lock do- attributes = update_params.to_h- if attributes[:tracking_number].present? && attributes[:tracking_number].squish != @resource.tracking_number- attributes[:status] = 'pending'- end-- if @resource.update(attributes)+ if @resource.update(corrected_attributes(update_params.to_h, @resource))render json: serialize_resource(@resource.reload)elserender_validation_error(@resource.errors)@@ -83,6 +78,15 @@ module Spreeprotected+ # A corrected number is a different parcel as far as the carrier is+ # concerned, so its journey starts over.+ def corrected_attributes(attributes, delivery)+ number = attributes[:tracking_number]+ return attributes if number.blank? || number.squish == delivery.tracking_number++ attributes.merge(status: 'pending')+ end+def model_classSpree::Deliveryenddiff --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 df864baa8f..8fce128464 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@@ -171,6 +171,12 @@ module Spree:shipmentsend+ # The serializer embeds both, and the tracking summary reads the+ # first consignment.+ def collection_includes+ [:deliveries, { shipping_labels: { file_attachment: :blob } }]+ end+# State changes go through the dedicated `fulfill`/`cancel` member# actions, not mass assignment. `tracking` and `tracking_carrier`# are the one-parcel shortcut onto the primary delivery.diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rbindex bb9dadf7a7..9eeaf6ce26 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/labels_controller.rb@@ -15,6 +15,7 @@ module Spree# nothing to refund.class LabelsController < BaseControllerinclude ActiveStorage::SetCurrent+ include Spree::Api::V3::StreamsShippingLabelbefore_action :set_resource, only: [:show, :download, :refund, :destroy]@@ -44,16 +45,7 @@ module Spree# the label is never reachable without admin credentials. The# carrier's copy is proxied only while the fetch is still pending.def download- if @resource.file.attached?- send_data(- @resource.file.download,- filename: @resource.download_filename,- type: @resource.file.content_type || 'application/octet-stream',- disposition: 'attachment'- )- elsif @resource.file_pending?- redirect_to @resource.file_url, allow_other_host: true- else+ stream_shipping_label(@resource) dorender_error(code: ERROR_CODES[:validation_error],message: Spree.t('shipping_labels.errors.no_file_url'),diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rbindex f79cc21a72..8013f686fa 100644--- a/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/deliveries_controller.rb@@ -48,12 +48,7 @@ module Spreeauthorize! :update, @fulfillmentwith_order_lock do- attributes = delivery_params.to_h- if attributes[:tracking_number].present? && attributes[:tracking_number].squish != @delivery.tracking_number- attributes[:status] = 'pending'- end-- if @delivery.update(attributes)+ if @delivery.update(corrected_attributes(delivery_params.to_h, @delivery))render json: serialize(@delivery.reload)elserender_validation_error(@delivery.errors)@@ -84,6 +79,15 @@ module Spreeprivate+ # A corrected number is a different parcel as far as the carrier is+ # concerned, so its journey starts over.+ def corrected_attributes(attributes, delivery)+ number = attributes[:tracking_number]+ return attributes if number.blank? || number.squish == delivery.tracking_number++ attributes.merge(status: 'pending')+ end+def set_fulfillment@order = current_seller_orders.find_by_prefix_id!(params[:order_id])authorize! :show, @orderdiff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rbindex 1345f8128c..14bfd8448b 100644--- a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb@@ -22,9 +22,15 @@ module Spreebefore_action :set_fulfillment, only: [:show, :fulfill]def index- render json: {- data: @order.fulfillments.map { |fulfillment| serialize(fulfillment) }- }+ # This action builds its own collection rather than going through+ # the base controller, so it preloads what the serializer reads —+ # otherwise every parcel costs a query for its consignments and+ # another for its labels.+ fulfillments = @order.fulfillments.+ includes(:deliveries, :shipping_labels, :fulfillment_items).+ preload_associations_lazily++ render json: { data: fulfillments.map { |fulfillment| serialize(fulfillment) } }enddef showdiff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rbindex eb648ff453..ab310a40c3 100644--- a/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/labels_controller.rb@@ -10,6 +10,7 @@ module Spreeclass LabelsController < Seller::BaseControllerinclude Spree::Api::V3::OrderLockinclude ActiveStorage::SetCurrent+ include Spree::Api::V3::StreamsShippingLabelscoped_resource :fulfillments@@ -64,16 +65,7 @@ module Spree# GET .../labels/:id/downloaddef download- if @label.file.attached?- send_data(- @label.file.download,- filename: @label.download_filename,- type: @label.file.content_type || 'application/octet-stream',- disposition: 'attachment'- )- elsif @label.file_pending?- redirect_to @label.file_url, allow_other_host: true- else+ stream_shipping_label(@label) dorender_error(code: ERROR_CODES[:validation_error],message: Spree.t('shipping_labels.errors.no_file_url'),diff --git a/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb b/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rbindex eb8226bd4a..a94cedfd46 100644--- a/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb@@ -11,6 +11,8 @@ module Spree# Whether a customer may open a return at all is store policy, and# belongs in a `returns.create.validate` hook rather than here.class ReturnsController < Store::ResourceController+ include Spree::Api::V3::StreamsShippingLabel+# Re-declaring the filter replaces the inherited options, so the# standard actions are listed alongside the label download.before_action :set_resource, only: [:show, :update, :destroy, :label]@@ -24,18 +26,7 @@ module Spreeshipping_label = @resource.active_shipping_labelreturn head :not_found if shipping_label.nil?- if shipping_label.file.attached?- send_data(- shipping_label.file.download,- filename: shipping_label.download_filename,- type: shipping_label.file.content_type || 'application/octet-stream',- disposition: 'attachment'- )- elsif shipping_label.file_pending?- redirect_to shipping_label.file_url, allow_other_host: true- else- head :not_found- end+ stream_shipping_label(shipping_label) { head :not_found }enddef creatediff --git a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rbindex 74d7946dca..52665b6ebe 100644--- a/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb@@ -60,24 +60,22 @@ module Spree# tracking code can never address another tenant's parcel — and to# consignments whose parcel was not canceled, so a recycled code# cannot reopen an old one. The newest wins when a code was reused.+ # Carriers reuse tracking numbers across years, so a code can match+ # more than one consignment. The store-scoped index makes that+ # candidate set tiny — almost always one row — and the stood-down+ # ones are dropped from it rather than from every parcel in the+ # database. The newest survivor wins.+ CANDIDATE_LIMIT = 20+def find_delivery(tracking_code)return if tracking_code.blank?- # Carriers reuse tracking numbers across years, so the filter runs- # in SQL rather than over every historic match: a canceled parcel- # is excluded per owner type, and the newest survivor wins.- live_fulfillments = Spree::Fulfillment.where.not(status: 'canceled').select(:id)- live_returns = Spree::Return.where.not(status: 'canceled').select(:id)-current_store.deliveries.where(tracking_number: tracking_code).- where(- "(owner_type = 'Spree::Fulfillment' AND owner_id IN (?)) OR " \- "(owner_type = 'Spree::Return' AND owner_id IN (?))",- live_fulfillments, live_returns- ).order(created_at: :desc, id: :desc).- first+ limit(CANDIDATE_LIMIT).+ includes(:owner).+ find { |delivery| delivery.owner.present? && !delivery.owner.canceled? }endendenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/shipping_label_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/shipping_label_serializer.rbindex f336913539..002daf7e43 100644--- a/spree/api/app/serializers/spree/api/v3/admin/shipping_label_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/shipping_label_serializer.rb@@ -25,7 +25,7 @@ module Spreerefunded_at: [:string, nullable: true],metadata: 'Record<string, unknown>'- attributes :source, :status, :carrier, :service, :tracking_number, :currency, :format,+ attributes :source, :status, :carrier, :carrier_name, :service, :tracking_number, :currency, :format,:external_id, :metadata, refunded_at: :iso8601, created_at: :iso8601, updated_at: :iso8601attribute :owner_id do |shipping_label|@@ -36,12 +36,6 @@ module Spreeshipping_label.owner_type == 'Spree::Return' ? 'return' : 'fulfillment'end- attribute :carrier_name do |shipping_label|- next if shipping_label.carrier.blank?-- Spree.tracking_carriers.dig(shipping_label.carrier, :name) || shipping_label.carrier- end-attribute :cost do |shipping_label|shipping_label.cost.to_senddiff --git a/spree/core/app/models/concerns/spree/has_tracking_carrier.rb b/spree/core/app/models/concerns/spree/has_tracking_carrier.rbnew file mode 100644index 0000000000..1cf8b19586--- /dev/null+++ b/spree/core/app/models/concerns/spree/has_tracking_carrier.rb@@ -0,0 +1,18 @@+module Spree+ # A carrier a consignment or a label is pinned to.+ #+ # The value is free text by design: +Spree.tracking_carriers+ supplies+ # display names and tracking-page templates for the carriers Spree knows,+ # and anything else — a freight forwarder, a courier a merchant uses once —+ # is a legal value that simply has no entry.+ module HasTrackingCarrier+ extend ActiveSupport::Concern++ # @return [String, nil] the registry's display name, or the value as entered+ def carrier_name+ return if carrier.blank?++ Spree.tracking_carriers.dig(carrier, :name) || carrier+ end+ end+enddiff --git a/spree/core/app/models/spree/delivery.rb b/spree/core/app/models/spree/delivery.rbindex 868be3fb94..88b2c8143e 100644--- a/spree/core/app/models/spree/delivery.rb+++ b/spree/core/app/models/spree/delivery.rb@@ -15,6 +15,7 @@ module Spreehas_prefix_id :dlvinclude Spree::SingleStoreResource+ include Spree::HasTrackingCarrierpublishes_lifecycle_events@@ -46,12 +47,16 @@ module Spreescope :delivered, -> { where(status: 'delivered') }scope :undelivered, -> { where.not(status: 'delivered') }- self.whitelisted_ransackable_attributes = %w[tracking_number carrier status]-- STATUSES.each do |value|- define_method(:"#{value}?") { status == value }+ # The one status with a reader beyond the scopes: arrival is what the+ # fulfillment rolls up from. The rest are read as `status`.+ #+ # @return [Boolean]+ def delivered?+ status == 'delivered'end+ self.whitelisted_ransackable_attributes = %w[tracking_number carrier status]+# The public page where this consignment can be followed, best answer# first: the link stored on the row (pasted by the merchant, or the# provider's tracker page), the pinned carrier's registered tracking@@ -74,16 +79,6 @@ module Spreedetected_tracking_urlend- # The carrier's display name — from the registry when the key is known,- # otherwise the free text as entered.- #- # @return [String, nil]- def carrier_name- return if carrier.blank?-- Spree.tracking_carriers.dig(carrier, :name) || carrier- end-# @return [Boolean] whether the tracking value is a full link rather than a numberdef pasted_link?tracking_number.to_s.start_with?('https://', 'http://')@@ -109,15 +104,21 @@ module Spreeenddef detected_tracking_url- service = Spree.tracking_number_service.new(tracking_number.upcase)- service.tracking_url if service.valid?+ tracking_service&.tracking_url if tracking_service&.valid?enddef detect_carrierreturn if pasted_link?- service = Spree.tracking_number_service.new(tracking_number.upcase)- self.carrier = service.tracking.courier_code.to_s if service.valid?+ self.carrier = tracking_service.tracking.courier_code.to_s if tracking_service&.valid?+ end++ # Parsing a number runs the gem's whole carrier battery, and both the+ # carrier and the URL want the answer.+ def tracking_service+ return if tracking_number.blank?++ @tracking_service ||= Spree.tracking_number_service.new(tracking_number.upcase)endendenddiff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex be72d6cfac..9254c608da 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -612,7 +612,7 @@ module Spree## @return [Spree::FulfillmentProvider::Base]def provider- delivery_method&.provider || Spree::FulfillmentProvider::Manual.new+ @provider ||= delivery_method&.provider || Spree::FulfillmentProvider::Manual.newend# Commission base for multi-seller include_shipping: the cost net of@@ -901,9 +901,7 @@ module Spreereturn if value.blank?deliveries.reset- return primary_delivery.update!(tracking_number: value, status: 'pending') if primary_delivery-- result = Spree.delivery_create_service.call(owner: self, tracking_number: value)+ result = Spree.delivery_upsert_primary_service.call(fulfillment: self, tracking: value)raise ActiveRecord::RecordInvalid, result.value if result.failure?enddiff --git a/spree/core/app/models/spree/return.rb b/spree/core/app/models/spree/return.rbindex 666b7eefb7..4042257dc1 100644--- a/spree/core/app/models/spree/return.rb+++ b/spree/core/app/models/spree/return.rb@@ -85,9 +85,8 @@ module Spreedef to_packagepackage = Spree::Stock::Package.new(stock_location)package.owner = order- return_line_items.includes(:fulfillment_item).each do |line|- package.add(line.fulfillment_item) if line.fulfillment_item- end+ units = return_line_items.includes(:fulfillment_item).filter_map(&:fulfillment_item)+ units.group_by(&:status).each { |status, items| package.add_multiple(items, status.to_sym) }packageenddiff --git a/spree/core/app/models/spree/shipping_label.rb b/spree/core/app/models/spree/shipping_label.rbindex d916bef00e..506bfe2f96 100644--- a/spree/core/app/models/spree/shipping_label.rb+++ b/spree/core/app/models/spree/shipping_label.rb@@ -16,6 +16,7 @@ module Spreeinclude Spree::SingleStoreResourceinclude Spree::HasStatus+ include Spree::HasTrackingCarrierinclude Spree::Metadatapublishes_lifecycle_eventsdiff --git a/spree/core/app/services/spree/deliveries/create.rb b/spree/core/app/services/spree/deliveries/create.rbindex 7c641c137b..fc46e526cf 100644--- a/spree/core/app/services/spree/deliveries/create.rb+++ b/spree/core/app/services/spree/deliveries/create.rb@@ -18,17 +18,22 @@ module Spree# @param service [String, nil]# @param shipping_label [Spree::ShippingLabel, nil] the label that minted this delivery# @param status [String] the carrier status to start at+ # @param adopt [Boolean] when a delivery for this number already exists+ # on the owner, fill its blanks and return it rather than refusing.+ # A label binding the number the merchant typed by hand is the same+ # consignment; a merchant recording that number twice is not.# @return [Spree::ServiceModule::Result] the delivery on success- def call(owner:, tracking_number:, carrier: nil, tracking_url: nil, service: nil, shipping_label: nil, status: 'pending')- delivery = owner.deliveries.new(- store: owner.store,- tracking_number: tracking_number,- carrier: carrier.presence,- tracking_url: tracking_url.presence,- service: service.presence,- shipping_label: shipping_label,- status: status- )+ def call(owner:, tracking_number:, carrier: nil, tracking_url: nil, service: nil,+ shipping_label: nil, status: 'pending', adopt: false)+ existing = adopt ? owner.deliveries.find_by(tracking_number: tracking_number.to_s.squish) : nil+ delivery = existing || owner.deliveries.new(store: owner.store, tracking_number: tracking_number, status: status)++ # Blanks are filled, never overwritten: whichever of the two arrived+ # first said what it knew.+ delivery.carrier = carrier.presence || delivery.carrier+ delivery.service = service.presence || delivery.service+ delivery.tracking_url = tracking_url.presence || delivery.tracking_url+ delivery.shipping_label = shipping_label if shipping_labeldelivery.tracking_url ||= delivery.tracking_number if delivery.pasted_link?delivery.save ? success(delivery) : failure(delivery)diff --git a/spree/core/app/services/spree/deliveries/upsert_primary.rb b/spree/core/app/services/spree/deliveries/upsert_primary.rbnew file mode 100644index 0000000000..525fb3000e--- /dev/null+++ b/spree/core/app/services/spree/deliveries/upsert_primary.rb@@ -0,0 +1,31 @@+module Spree+ module Deliveries+ # The one-parcel shortcut behind `tracking:` on the fulfillment workflows+ # and the tracking field in the dashboard: records the number as the+ # fulfillment's primary consignment, or corrects the one it already has.+ #+ # A corrected number is a different parcel as far as the carrier is+ # concerned, so its journey starts over.+ class UpsertPrimary+ prepend Spree::ServiceModule::Base++ # @param fulfillment [Spree::Fulfillment]+ # @param tracking [String, nil] a carrier number or a full tracking link;+ # blank is a no-op, so callers can pass an omitted parameter straight through+ # @param carrier [String, nil] free text; detected from the number when omitted+ # @return [Spree::ServiceModule::Result] the delivery, or nil when nothing was asked+ def call(fulfillment:, tracking:, carrier: nil)+ return success(nil) if tracking.blank?++ primary = fulfillment.primary_delivery+ return Spree.delivery_create_service.call(owner: fulfillment, tracking_number: tracking, carrier: carrier) if primary.nil?++ attributes = { tracking_number: tracking.to_s.squish }+ attributes[:carrier] = carrier if carrier.present?+ attributes[:status] = 'pending' if attributes[:tracking_number] != primary.tracking_number++ primary.update(attributes) ? success(primary) : failure(primary)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/fulfillments/cancel.rb b/spree/core/app/workflows/spree/fulfillments/cancel.rbindex 038237fa41..6a91846a2e 100644--- a/spree/core/app/workflows/spree/fulfillments/cancel.rb+++ b/spree/core/app/workflows/spree/fulfillments/cancel.rb@@ -80,7 +80,7 @@ module Spree# Refunds every active label, then drops any non-label dispatch.def tell_provider_to_stand_down- Spree::Fulfillments::StandDownProvider.new.call(fulfillment: fulfillment)+ Spree.fulfillment_stand_down_service.call(fulfillment: fulfillment)endendenddiff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rbindex b47fb73ed4..dbac4eb2c3 100644--- a/spree/core/app/workflows/spree/fulfillments/fulfill.rb+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb@@ -275,22 +275,10 @@ module Spree# Recorded before the provider is asked, so a label purchase sees the# admin-entered number and binds to it rather than minting a second- # consignment, and so the shipment email carries it. The primary- # delivery is created, or its number corrected.+ # consignment, and so the shipment email carries it.def apply_tracking- return if tracking.blank?-- primary = @fulfillment.primary_delivery- if primary- attributes = { tracking_number: tracking.to_s.squish }- attributes[:carrier] = tracking_carrier if tracking_carrier.present?- attributes[:status] = 'pending' if attributes[:tracking_number] != primary.tracking_number- primary.update!(attributes)- return- end-- result = Spree.delivery_create_service.call(- owner: @fulfillment, tracking_number: tracking, carrier: tracking_carrier+ result = Spree.delivery_upsert_primary_service.call(+ fulfillment: @fulfillment, tracking: tracking, carrier: tracking_carrier)failure(@source, result.error.to_s) if result.failure?enddiff --git a/spree/core/app/workflows/spree/fulfillments/update.rb b/spree/core/app/workflows/spree/fulfillments/update.rbindex 892769581e..9462736b76 100644--- a/spree/core/app/workflows/spree/fulfillments/update.rb+++ b/spree/core/app/workflows/spree/fulfillments/update.rb@@ -72,19 +72,8 @@ module Spreeenddef apply_tracking- return if @tracking.blank?-- primary = @fulfillment.primary_delivery- if primary- attributes = { tracking_number: @tracking.to_s.squish }- attributes[:carrier] = @tracking_carrier if @tracking_carrier.present?- attributes[:status] = 'pending' if attributes[:tracking_number] != primary.tracking_number- failure(primary) unless primary.update(attributes)- return- end-- result = Spree.delivery_create_service.call(- owner: @fulfillment, tracking_number: @tracking, carrier: @tracking_carrier+ result = Spree.delivery_upsert_primary_service.call(+ fulfillment: @fulfillment, tracking: @tracking, carrier: @tracking_carrier)failure(@fulfillment, result.error.to_s) if result.failure?enddiff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rbindex 7c8729f157..b1bb5794e1 100644--- a/spree/core/app/workflows/spree/orders/cancel.rb+++ b/spree/core/app/workflows/spree/orders/cancel.rb@@ -130,7 +130,7 @@ module Spree# going out either way, and the failure surfaces through the provider.def notify_fulfillment_providersorder.fulfillments.each do |fulfillment|- Spree::Fulfillments::StandDownProvider.new.call(fulfillment: fulfillment)+ Spree.fulfillment_stand_down_service.call(fulfillment: fulfillment)endenddiff --git a/spree/core/app/workflows/spree/shipping_labels/purchase.rb b/spree/core/app/workflows/spree/shipping_labels/purchase.rbindex 98e7756324..3189dfef13 100644--- a/spree/core/app/workflows/spree/shipping_labels/purchase.rb+++ b/spree/core/app/workflows/spree/shipping_labels/purchase.rb@@ -27,6 +27,7 @@ module Spreerun_hooks :validatestep :ensure_purchasable+ step :claim_purchase, on_flow_failure: :release_claim# Carrier I/O — never inside a transaction.external_step :purchase@@ -36,7 +37,7 @@ module Spreestep :record_deliveryend- external_step :store_file+ step :store_fileshipping_label.publish_event('shipping_label.purchased')run_hooks :after_purchase@@ -49,16 +50,9 @@ module Spree@provider ||= owner.providerend- # The active-label check is the idempotency guard, so it reads under the- # owner's row lock: two clicks on "buy label" would otherwise both pass- # it and both charge the carrier. The lock is released before the- # purchase step, which must not hold one across network I/O.def ensure_purchasablefailure(owner, Spree.t('shipping_labels.errors.provider_has_no_labels')) unless provider.class.generates_labels?-- owner.with_lock do- failure(owner, Spree.t('shipping_labels.errors.already_purchased')) if owner.shipping_labels.active.exists?- end+ failure(owner, Spree.t('shipping_labels.errors.already_purchased')) if owner.shipping_labels.active.exists?case ownerwhen Spree::Fulfillment@@ -69,6 +63,28 @@ module Spreeendend+ # The claim, not the check above, is what makes a double click buy one+ # label: it inserts the row the uniqueness index guards before the+ # carrier is called, so the loser of the race is refused by the+ # database rather than by a read that has already gone stale.+ def claim_purchase+ @shipping_label = owner.shipping_labels.create!(+ store: owner.store,+ integration: provider.integration_for(owner),+ source: 'purchased',+ status: 'purchased'+ )+ rescue ActiveRecord::RecordNotUnique+ failure(owner, Spree.t('shipping_labels.errors.already_purchased'))+ end++ # Undoes the claim when the carrier refuses, so a failed purchase does+ # not leave a row that refuses every later attempt.+ def release_claim+ @shipping_label&.destroy+ @shipping_label = nil+ end+def purchase@purchase = provider.purchase_label(owner)@@ -78,11 +94,7 @@ module Spreeenddef record_label- @shipping_label = owner.shipping_labels.create!(- store: owner.store,- integration: provider.integration_for(owner),- source: 'purchased',- status: 'purchased',+ shipping_label.update!(external_id: @purchase.external_id,carrier: @purchase.carrier,service: @purchase.service,@@ -95,22 +107,11 @@ module Spreeend# A label mints its own consignment. When the merchant already typed the- # same number by hand, that delivery becomes the label's rather than a- # duplicate row being refused.+ # same number by hand, the delivery service binds that row rather than+ # letting a duplicate be refused.def record_delivery- existing = owner.deliveries.find_by(tracking_number: @purchase.tracking_number)-- if existing- existing.update!(- shipping_label: shipping_label,- carrier: @purchase.carrier.presence || existing.carrier,- service: @purchase.service.presence || existing.service,- tracking_url: @purchase.tracking_url.presence || existing.tracking_url- )- return- end-result = Spree.delivery_create_service.call(+ adopt: true,owner: owner,tracking_number: @purchase.tracking_number,carrier: @purchase.carrier,@@ -121,14 +122,14 @@ module Spreefailure(shipping_label, result.error.to_s) if result.failure?end- # The purchase is recorded whether or not the file comes down now — a- # slow carrier CDN must not lose a label the merchant has paid for.+ # Fetched in the background rather than in the request: the merchant has+ # already waited on one carrier call, and a slow label CDN would hold+ # the order lock the controller took for as long as it stalls. Until it+ # lands the download proxies the carrier's own copy, which is what+ # +file_pending?+ is for.def store_filereturn if @purchase.file_url.blank?- result = Spree.shipping_label_store_file_service.call(shipping_label: shipping_label)- return if result.success?-Spree::ShippingLabels::StoreFileJob.perform_later(shipping_label.id)endenddiff --git a/spree/core/app/workflows/spree/shipping_labels/record.rb b/spree/core/app/workflows/spree/shipping_labels/record.rbindex 0d62ea1cf4..5ce39b86b0 100644--- a/spree/core/app/workflows/spree/shipping_labels/record.rb+++ b/spree/core/app/workflows/spree/shipping_labels/record.rb@@ -86,14 +86,8 @@ module Spreeenddef record_delivery- existing = owner.deliveries.find_by(tracking_number: shipping_label.tracking_number)-- if existing- existing.update!(shipping_label: shipping_label, carrier: carrier.presence || existing.carrier)- return- end-result = Spree.delivery_create_service.call(+ adopt: true,owner: owner,tracking_number: shipping_label.tracking_number,carrier: carrier,diff --git a/spree/core/app/workflows/spree/shipping_labels/refund.rb b/spree/core/app/workflows/spree/shipping_labels/refund.rbindex f52f208403..bded61d97d 100644--- a/spree/core/app/workflows/spree/shipping_labels/refund.rb+++ b/spree/core/app/workflows/spree/shipping_labels/refund.rb@@ -39,8 +39,10 @@ module Spree# settle refunds asynchronously, and re-filing is how a request that# never came back is re-driven.def ensure_refundable- failure(shipping_label, Spree.t('shipping_labels.errors.uploaded_not_refundable')) if shipping_label.uploaded?- failure(shipping_label, Spree.t('shipping_labels.errors.not_refundable')) unless shipping_label.refundable?+ return if shipping_label.refundable?++ reason = shipping_label.uploaded? ? 'uploaded_not_refundable' : 'not_refundable'+ failure(shipping_label, Spree.t("shipping_labels.errors.#{reason}"))enddef refunddiff --git a/spree/core/db/migrate/20260903000001_create_spree_shipping_labels_and_deliveries.rb b/spree/core/db/migrate/20260903000001_create_spree_shipping_labels_and_deliveries.rbindex 20d9bff138..7fd42b341f 100644--- a/spree/core/db/migrate/20260903000001_create_spree_shipping_labels_and_deliveries.rb+++ b/spree/core/db/migrate/20260903000001_create_spree_shipping_labels_and_deliveries.rb@@ -29,8 +29,19 @@ class CreateSpreeShippingLabelsAndDeliveries < ActiveRecord::Migration[8.1]t.timestampsend- add_index :spree_shipping_labels, [:owner_type, :owner_id, :status],- name: 'index_spree_shipping_labels_on_owner_and_status'+ add_index :spree_shipping_labels, [:owner_type, :owner_id]++ # One live label per parcel, enforced where the race actually happens: two+ # clicks on "buy label" both pass an application-level check, and the+ # loser has to be refused before the carrier is charged. A refunded label+ # is history and does not count, so the index is partial where the+ # database supports it.+ if connection.supports_partial_index?+ add_index :spree_shipping_labels, [:owner_type, :owner_id],+ unique: true,+ where: "status <> 'refunded'",+ name: 'index_spree_shipping_labels_on_active_owner'+ endcreate_table :spree_deliveries do |t|t.references :owner, polymorphic: true, null: falsediff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 3974634a38..8a8fd906df 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -94,6 +94,8 @@ module Spreeshipping_label_store_file_service: 'Spree::ShippingLabels::StoreFile',delivery_update_tracking_workflow: 'Spree::Deliveries::UpdateTracking',delivery_create_service: 'Spree::Deliveries::Create',+ delivery_upsert_primary_service: 'Spree::Deliveries::UpsertPrimary',+ fulfillment_stand_down_service: 'Spree::Fulfillments::StandDownProvider',delivery_destroy_service: 'Spree::Deliveries::Destroy',return_purchase_label_workflow: 'Spree::Returns::PurchaseLabel',diff --git a/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rb b/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rbindex 71a2440724..ab669b9f86 100644--- a/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rb+++ b/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rb@@ -19,7 +19,7 @@ module Spree)end- it 'records the label, mints its delivery and stores the file' do+ it 'records the label, mints its delivery and fetches the file' doresult = subject.call(owner: fulfillment)expect(result).to be_success@@ -31,7 +31,9 @@ module Spreeexpect(label.cost).to eq(7.25)expect(label.currency).to eq('USD')expect(label.metadata).to include('tracker_id' => 'trk_1', 'file_url' => 'https://carrier.example/label.pdf')- expect(label.file).to be_attached+ # The carrier's copy comes down in the background: the merchant has+ # already waited on the purchase itself.+ expect(Spree::ShippingLabels::StoreFileJob).to have_been_enqueued.with(label.id)delivery = label.deliveryexpect(delivery.tracking_number).to eq('1Z879E930346834440')@@ -58,18 +60,26 @@ module Spreeexpect(Spree::Events).to have_received(:publish).with('shipping_label.purchased', anything, anything)end- # The purchase is a fact the moment the carrier charged for it; a slow- # label CDN must not lose it.- it 'keeps the purchase and retries the file in the background when the fetch fails' do- allow(SsrfFilter).to receive(:get).and_raise(SocketError.new('down'))-- expect { subject.call(owner: fulfillment) }.to have_enqueued_job(Spree::ShippingLabels::StoreFileJob)+ # The purchase is a fact the moment the carrier charged for it, and the+ # download proxies the carrier's own copy until the file lands.+ it 'leaves the label printable while the file is still pending' do+ subject.call(owner: fulfillment)label = fulfillment.reload.active_shipping_labelexpect(label).to be_presentexpect(label).to be_file_pendingend+ it 'releases the claim when the carrier refuses, so the merchant can retry' do+ allow(provider).to receive(:purchase_label).and_return(nil)++ expect(subject.call(owner: fulfillment)).to be_failure+ expect(fulfillment.reload.shipping_labels).to be_empty++ allow(provider).to receive(:purchase_label).and_call_original+ expect(subject.call(owner: fulfillment)).to be_success+ end+it 'refuses a second label while one is active — providers are never asked twice' dosubject.call(owner: fulfillment)expect(provider).not_to receive(:purchase_label)