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.

Refuse to fulfill draft orders; carrier picker on the fulfill form

Damian Legawiecf10be3e23c8c
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index d323cb2d06..0e3585eb54 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -162,6 +162,8 @@ export interface FulfillmentFulfillParams {
items?: Array<{ item_id: string; quantity: number }>
/** Carrier tracking number or a full `https://` tracking link, stored on the fulfillment that ships */
tracking?: string
+ /** Which carrier the number belongs to (a `trackingCarriers.list()` slug); detected from the number when omitted */
+ tracking_carrier?: string
/**
* Whether the customer gets the shipment email. Defaults to true; pass false
* to suppress it for this dispatch only (a correction, a re-ship, goods
diff --git a/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx b/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx
index 6679a7aedf..7c2386b343 100644
--- a/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx
+++ b/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx
@@ -10,6 +10,11 @@ import {
Field,
FieldLabel,
Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
Thumbnail,
} from '@spree/dashboard-ui'
import { PackageIcon, TriangleAlertIcon } from 'lucide-react'
@@ -17,6 +22,7 @@ import { useEffect, useRef } from 'react'
import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { useFulfillmentActions } from '../../../hooks/use-fulfillments'
+import { useTrackingCarriers } from '../../../hooks/use-tracking-carriers'
import { type FulfillmentItemRow, fulfillmentItemRows } from '../../../lib/fulfillment-items'
import { type FulfillItemsFormValues, fulfillItemsFormSchema } from '../../../schemas/fulfillment'
@@ -136,6 +142,12 @@ export function FulfillmentFulfillForm({
}) {
const { t } = useTranslation()
const { fulfill } = useFulfillmentActions(order.id)
+ const { data: carriersData } = useTrackingCarriers()
+
+ const carrierOptions = [
+ { value: '', label: t('admin.orders.detail.fulfillments.carrier_auto') },
+ ...(carriersData?.data ?? []).map((carrier) => ({ value: carrier.id, label: carrier.name })),
+ ]
const idPrefix = `fulfill-${fulfillment.id}`
const rows = fulfillableRows(fulfillmentItemRows(fulfillment, order.items ?? []))
@@ -145,6 +157,7 @@ export function FulfillmentFulfillForm({
defaultValues: {
items: rows.map((row) => ({ item_id: row.itemId, selected: true, quantity: row.quantity })),
tracking: fulfillment.tracking ?? '',
+ tracking_carrier: fulfillment.tracking_carrier ?? '',
notify_customer: true,
},
})
@@ -199,6 +212,7 @@ export function FulfillmentFulfillForm({
fulfillmentId: fulfillment.id,
items: everything ? undefined : items,
tracking: tracking || undefined,
+ tracking_carrier: values.tracking_carrier || undefined,
notify_customer: values.notify_customer,
})
onDone()
@@ -232,16 +246,46 @@ export function FulfillmentFulfillForm({
</div>
)}
- <Field className="p-3 border-t">
- <FieldLabel htmlFor={`${idPrefix}-tracking`}>
- {t('admin.orders.fulfill.tracking_label')}
- </FieldLabel>
- <Input
- id={`${idPrefix}-tracking`}
- placeholder={t('admin.orders.fulfill.tracking_placeholder')}
- {...form.register('tracking')}
- />
- </Field>
+ <div className="grid grid-cols-1 gap-4 p-3 border-t sm:grid-cols-2">
+ <Field>
+ <FieldLabel htmlFor={`${idPrefix}-tracking`}>
+ {t('admin.orders.fulfill.tracking_label')}
+ </FieldLabel>
+ <Input
+ id={`${idPrefix}-tracking`}
+ placeholder={t('admin.orders.fulfill.tracking_placeholder')}
+ {...form.register('tracking')}
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor={`${idPrefix}-tracking-carrier`}>
+ {t('admin.orders.detail.fulfillments.carrier_label')}
+ </FieldLabel>
+ <Controller
+ control={form.control}
+ name="tracking_carrier"
+ render={({ field }) => (
+ <Select
+ items={carrierOptions}
+ value={field.value}
+ onValueChange={(value) => field.onChange(value ?? '')}
+ >
+ <SelectTrigger id={`${idPrefix}-tracking-carrier`}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {carrierOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </Field>
+ </div>
<Controller
control={form.control}
diff --git a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx
index 9c91895bb6..45032d60f1 100644
--- a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx
+++ b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx
@@ -405,7 +405,9 @@ function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: Ful
const editable = CAN_EDIT.includes(fulfillment.status)
const splittable = editable && unitsOf(fulfillment).length > 0
- const shippable = CAN_SHIP.includes(fulfillment.status)
+ // A draft is not a commitment yet — nothing has been agreed, so nothing can
+ // ship. The backend refuses too; this just keeps the button honest.
+ const shippable = CAN_SHIP.includes(fulfillment.status) && order.status !== 'draft'
// Confirming receipt is the merchant's next move on a parcel that has gone
// out, so it sits in the card rather than behind the menu. Adding tracking
// joins it as the primary action while the number is still missing.
diff --git a/packages/dashboard/src/schemas/fulfillment.ts b/packages/dashboard/src/schemas/fulfillment.ts
index 2ec7f38b1c..3d953e6f83 100644
--- a/packages/dashboard/src/schemas/fulfillment.ts
+++ b/packages/dashboard/src/schemas/fulfillment.ts
@@ -27,6 +27,8 @@ export const fulfillItemsFormSchema = z.object({
}),
),
tracking: z.string(),
+ // '' = detect from the number; slugs come from trackingCarriers.list().
+ tracking_carrier: z.string(),
notify_customer: z.boolean(),
})
diff --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.rb
index 66551a2d94..a4c021447d 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
@@ -66,6 +66,7 @@ module Spree
fulfillment: @resource,
items: items_for_fulfill,
tracking: fulfill_params[:tracking],
+ tracking_carrier: fulfill_params[:tracking_carrier],
notify_customer: notify_customer?(fulfill_params[:notify_customer]),
force: ActiveModel::Type::Boolean.new.cast(fulfill_params[:force]).present?
)
@@ -200,7 +201,7 @@ module Spree
end
def fulfill_params
- @fulfill_params ||= params.permit(:tracking, :notify_customer, :force, items: [:item_id, :quantity])
+ @fulfill_params ||= params.permit(:tracking, :tracking_carrier, :notify_customer, :force, items: [:item_id, :quantity])
end
def mark_delivered_params
diff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
index f6aec220ee..b8390b9c0e 100644
--- a/spree/core/app/workflows/spree/fulfillments/fulfill.rb
+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb
@@ -31,6 +31,8 @@ module Spree
# to ship; nil or empty fulfills every unit the fulfillment holds
# @param tracking [String, nil] carrier tracking number or full tracking URL,
# stored on the fulfillment that ships
+ # @param tracking_carrier [String, nil] which carrier the number belongs
+ # to (a Spree.tracking_carriers slug); detected from the number when omitted
# @param notify_customer [Boolean] whether the shipment email goes out;
# false suppresses it for this dispatch only
# @param force [Boolean] dispatch even when the order is unpaid or holds
@@ -38,7 +40,7 @@ module Spree
# against an invoice is ordinary trade, and the old pending/ready
# statuses made it impossible to express.
# @return [Spree::ServiceModule::Result] the fulfilled fulfillment on success
- def perform(fulfillment:, items: nil, tracking: nil, notify_customer: true, force: false)
+ def perform(fulfillment:, items: nil, tracking: nil, tracking_carrier: nil, notify_customer: true, force: false)
super
@source = fulfillment
@@ -86,10 +88,20 @@ module Spree
def ensure_fulfillable
failure(@source, Spree.t('fulfillments.errors.cannot_fulfill')) unless @source.can_fulfill?
+ ensure_order_placed
ensure_ready_to_hand_over
ensure_requested_units_available
end
+ # Not skippable by force. Forcing past an unpaid invoice is ordinary
+ # trade; a draft is not a commitment yet — nothing has been agreed, so
+ # there is nothing to hand over. Completing the draft is the way out.
+ def ensure_order_placed
+ return unless @source.order&.draft?
+
+ failure(@source, Spree.t('fulfillments.errors.order_draft'))
+ end
+
# What the pending/ready statuses used to encode, asked once at the
# moment it matters instead of being recomputed onto every fulfillment
# whenever the order changed. A validate hook can wave either rule
@@ -178,10 +190,15 @@ module Spree
# (run_provider_create_fulfillment) sees an admin-entered number and
# leaves it alone, and so the shipment email carries it.
#
+ # update! rather than update_columns so the carrier-detection callback
+ # runs — a number typed without a carrier still gets its badge and URL.
def apply_tracking
- return if tracking.blank?
+ attributes = {}
+ attributes[:tracking] = tracking.to_s.squish if tracking.present?
+ attributes[:tracking_carrier] = tracking_carrier if tracking_carrier.present?
+ return if attributes.empty?
- @fulfillment.update_columns(tracking: tracking.to_s.squish, updated_at: Time.current)
+ @fulfillment.update!(attributes)
end
# The suppression flag rides on the record because the event publisher
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index f5521ab0b1..3e62cb8993 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -970,6 +970,7 @@ en:
no_items_to_fulfill: Order has no unfulfilled items
not_in_fulfillment: Requested quantity (%{requested}) for item %{item} exceeds the %{available} held by this fulfillment
order_canceled: Fulfillments cannot be created on a canceled order
+ 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
unknown_tracking_status: "%{status} is not a known tracking status"
diff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
index 788f7cc6e0..50f4f85b86 100644
--- a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb
@@ -105,6 +105,18 @@ module Spree
expect(fulfillment.reload).to be_fulfilled
end
+ # force exists for unpaid invoices; a draft has not been agreed at all,
+ # so not even force hands its goods over.
+ it 'refuses a draft order, even with force' do
+ order.update_columns(status: 'draft', completed_at: nil)
+
+ result = subject.call(fulfillment: fulfillment, force: true)
+
+ expect(result.success?).to eq(false)
+ expect(result.error.to_s).to eq(Spree.t('fulfillments.errors.order_draft'))
+ expect(fulfillment.reload).not_to be_fulfilled
+ end
+
it 'refuses a fulfillment already fulfilled' do
fulfillment.update!(status: 'fulfilled')
@@ -216,6 +228,21 @@ module Spree
end
end
+ describe 'tracking carrier' do
+ it 'stores an explicit carrier beside the number' do
+ subject.call(fulfillment: fulfillment, tracking: '421432', tracking_carrier: 'inpost')
+
+ expect(fulfillment.reload.tracking_carrier).to eq('inpost')
+ expect(fulfillment.tracking_url).to include('inpost.pl')
+ end
+
+ it 'detects the carrier from a recognisable number' do
+ subject.call(fulfillment: fulfillment, tracking: '1Z879E930346834440')
+
+ expect(fulfillment.reload.tracking_carrier).to eq('ups')
+ end
+ end
+
describe 'hooks' do
before { Spree.hooks.clear! }
after { Spree.hooks.clear! }