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
Say why the carrier refused to sell a label
Damian Legawiecb4d19b47d595
diff --git a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsxindex 1a001f08a6..bae5b0c869 100644--- a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx+++ b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx@@ -33,6 +33,7 @@ import {SelectTrigger,SelectValue,StatusBadge,+ toastManager,useConfirm,} from '@spree/dashboard-ui'import {@@ -600,7 +601,23 @@ function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: FulconfirmLabel: t('admin.orders.detail.fulfillments.buy_label'),})) {- buyLabel.mutate({ fulfillmentId: fulfillment.id })+ // Toasted here rather than on the hook: the same+ // mutation backs the upload sheet, which shows its+ // rejection inline. A button has nowhere to put one.+ buyLabel.mutate(+ { fulfillmentId: fulfillment.id },+ {+ onError: (mutationError) => {+ toastManager.add({+ type: 'error',+ title:+ mutationError instanceof Error+ ? mutationError.message+ : t('admin.errors.unexpected'),+ })+ },+ },+ )}}}>diff --git a/packages/dashboard/src/hooks/use-fulfillments.ts b/packages/dashboard/src/hooks/use-fulfillments.tsindex e2a517090f..cd173ea7ec 100644--- a/packages/dashboard/src/hooks/use-fulfillments.ts+++ b/packages/dashboard/src/hooks/use-fulfillments.ts@@ -16,12 +16,16 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'* units, re-prices the fulfillment, or both, and the order totals and* fulfillment status are derived from that.*- * A 422 is left untoasted: the caller is a form that renders the same message- * next to the offending input, so toasting it too would say it twice.+ * A 422 is left untoasted for a mutation a form drives, since the form renders+ * the same message next to the offending input and toasting it would say it+ * twice. A mutation driven by a plain button has nowhere to put it, so those+ * opt out with `toastValidationErrors` — silence there reads as a button that+ * simply did nothing.*/function useFulfillmentMutation<TParams>(orderId: string,mutationFn: (params: TParams) => Promise<unknown>,+ { toastValidationErrors = false }: { toastValidationErrors?: boolean } = {},) {const queryClient = useQueryClient()const buildKey = useResourceKeyBuilder()@@ -32,7 +36,7 @@ function useFulfillmentMutation<TParams>(queryClient.invalidateQueries({ queryKey: buildKey('orders', orderId) })},onError: (error) => {- if (error instanceof SpreeError && error.status === 422) return+ if (!toastValidationErrors && error instanceof SpreeError && error.status === 422) returntoastManager.add({type: 'error',title: error instanceof Error ? error.message : String(error),@@ -86,12 +90,17 @@ export function useFulfillmentActions(orderId: string) {},)- const cancel = useFulfillmentMutation(orderId, (fulfillmentId: string) =>- adminClient.orders.fulfillments.cancel(orderId, fulfillmentId),+ const cancel = useFulfillmentMutation(+ orderId,+ (fulfillmentId: string) => adminClient.orders.fulfillments.cancel(orderId, fulfillmentId),+ { toastValidationErrors: true },)- const markDelivered = useFulfillmentMutation(orderId, (fulfillmentId: string) =>- adminClient.orders.fulfillments.markDelivered(orderId, fulfillmentId),+ const markDelivered = useFulfillmentMutation(+ orderId,+ (fulfillmentId: string) =>+ adminClient.orders.fulfillments.markDelivered(orderId, fulfillmentId),+ { toastValidationErrors: true },)// Buying with no body; a `file` records postage bought elsewhere instead.@@ -105,12 +114,14 @@ export function useFulfillmentActions(orderId: string) {orderId,({ fulfillmentId, labelId }: { fulfillmentId: string; labelId: string }) =>adminClient.orders.fulfillments.labels.refund(orderId, fulfillmentId, labelId),+ { toastValidationErrors: true },)const deleteLabel = useFulfillmentMutation(orderId,({ fulfillmentId, labelId }: { fulfillmentId: string; labelId: string }) =>adminClient.orders.fulfillments.labels.delete(orderId, fulfillmentId, labelId),+ { toastValidationErrors: true },)const createDelivery = useFulfillmentMutation(@@ -133,12 +144,14 @@ export function useFulfillmentActions(orderId: string) {orderId,({ fulfillmentId, deliveryId }: { fulfillmentId: string; deliveryId: string }) =>adminClient.orders.fulfillments.deliveries.delete(orderId, fulfillmentId, deliveryId),+ { toastValidationErrors: true },)const markDeliveryDelivered = useFulfillmentMutation(orderId,({ fulfillmentId, deliveryId }: { fulfillmentId: string; deliveryId: string }) =>adminClient.orders.fulfillments.deliveries.markDelivered(orderId, fulfillmentId, deliveryId),+ { toastValidationErrors: true },)return {diff --git a/spree/core/app/workflows/spree/shipping_labels/purchase.rb b/spree/core/app/workflows/spree/shipping_labels/purchase.rbindex 1a8bc34c63..c00e26da0d 100644--- a/spree/core/app/workflows/spree/shipping_labels/purchase.rb+++ b/spree/core/app/workflows/spree/shipping_labels/purchase.rb@@ -97,12 +97,17 @@ module Spree@shipping_label = nilend+ # A provider that knows why the carrier said no raises with its words;+ # anything else falls back to the generic line, since a nil tells us+ # nothing worth passing on.def purchase@purchase = provider.purchase_label(owner)return if @purchase.is_a?(Spree::LabelPurchase) && @purchase.valid?failure(owner, Spree.t('fulfillments.errors.label_purchase_failed'))+ rescue Spree::Core::LabelPurchaseRefused => e+ failure(owner, e.message)enddef record_labeldiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex f772af305c..669e671d19 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -822,6 +822,12 @@ module Spree# sees why there is no label.class LabelPurchaseFailed < RuntimeError; end+ # A carrier refusing to sell a label, in its own words. Raised by a+ # provider when it knows why — a warehouse with no address, an+ # unserviceable destination — so the merchant reads the actual reason+ # instead of being sent to check a connection that is fine.+ class LabelPurchaseRefused < RuntimeError; end+# A label the carrier refused to refund while a parcel was being# cancelled. The cancellation proceeds; the postage is the merchant's to# chase, so it is reported rather than dropped.diff --git a/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rb b/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rbindex 582362dc68..c400c495c7 100644--- a/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rb+++ b/spree/core/spec/workflows/spree/shipping_labels/purchase_spec.rb@@ -109,6 +109,19 @@ module Spreeexpect(fulfillment.reload.shipping_labels).to be_emptyend+ # "Check the carrier connection" is the wrong advice when the connection+ # is fine and the warehouse simply has no address on it.+ it 'reports the carrier own reason when the provider knows it' do+ allow(provider).to receive(:purchase_label).+ and_raise(Spree::Core::LabelPurchaseRefused, 'Origin address is missing a street')++ result = subject.call(owner: fulfillment)++ expect(result).to be_failure+ expect(result.error.to_s).to eq('Origin address is missing a street')+ expect(fulfillment.reload.shipping_labels).to be_empty+ end+it 'refuses a provider without labels' doallow_any_instance_of(Spree::Fulfillment).to receive(:provider).and_return(Spree::FulfillmentProvider::Manual.new)diff --git a/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb b/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rbindex dea1592b91..70960bc872 100644--- a/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb+++ b/spree/providers/easypost/app/models/spree_easypost/fulfillment_provider.rb@@ -70,6 +70,12 @@ module SpreeEasyPostreturn if shipment.nil?label_purchase(shipment)+ rescue EasyPost::Errors::EasyPostError => e+ # EasyPost says exactly what is wrong — an incomplete origin address, an+ # unserviceable destination — and the merchant is the only one who can+ # fix it. Passed through rather than reported as a connection problem.+ report(e, owner)+ raise Spree::Core::LabelPurchaseRefused, e.messagerescue StandardError => ereport(e, owner)nil@@ -144,7 +150,14 @@ module SpreeEasyPost# the delivery method no longer pins one (it offers many).selected = fulfillment.selected_delivery_rateaddress = fulfillment.address || fulfillment.order&.ship_address- return if selected&.carrier.blank? || selected.service_level.blank? || address.nil?++ # Each of these is the merchant's to fix, so each says so rather than+ # failing as "check the carrier connection".+ raise Spree::Core::LabelPurchaseRefused, Spree.t('easypost.errors.no_destination') if address.nil?++ if selected&.carrier.blank? || selected.service_level.blank?+ raise Spree::Core::LabelPurchaseRefused, Spree.t('easypost.errors.rate_not_quoted')+ endshipment = integration.client.shipment.create(**SpreeEasyPost.shipment_params(@@ -154,7 +167,13 @@ module SpreeEasyPostrate = shipment.rates.find do |candidate|candidate.carrier == selected.carrier && candidate.service == selected.service_levelend- return if rate.nil?++ # Silently buying a different service than the customer paid for is+ # worse than no label, so this refuses and names the service.+ if rate.nil?+ raise Spree::Core::LabelPurchaseRefused,+ Spree.t('easypost.errors.service_unavailable', service: "#{selected.carrier} #{selected.service_level}")+ endbuy(integration, fulfillment.stock_location, fulfillment.store, shipment.id, rate.id)enddiff --git a/spree/providers/easypost/config/locales/en.yml b/spree/providers/easypost/config/locales/en.ymlindex 207ea4891a..9421e75676 100644--- a/spree/providers/easypost/config/locales/en.yml+++ b/spree/providers/easypost/config/locales/en.yml@@ -1,6 +1,11 @@---en:spree:+ easypost:+ errors:+ no_destination: This parcel has no delivery address, so no carrier can quote it.+ rate_not_quoted: This delivery rate was not quoted by EasyPost. Re-quote the fulfillment and pick a carrier service before buying a label.+ service_unavailable: "%{service} is no longer offered for this parcel. Re-quote the fulfillment and pick another service."integrations:easy_post:description: Live multi-carrier delivery rates at checkout through your EasyPost account, including your own negotiated carrier contracts.