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
Let merchants manage fulfillments from the order page
Damian Legawiec1c536f279eea
diff --git a/packages/admin-sdk/examples/order-fulfillments/split.ts b/packages/admin-sdk/examples/order-fulfillments/split.tsindex 70f435145c..8ac3d68748 100644--- a/packages/admin-sdk/examples/order-fulfillments/split.ts+++ b/packages/admin-sdk/examples/order-fulfillments/split.ts@@ -6,9 +6,19 @@ const client = createAdminClient({})// region:example-const fulfillment = await client.orders.fulfillments.split('or_UkLWZg9DAJ', 'ful_UkLWZg9DAJ', {- quantity: 1,-})+// Splitting moves a quantity of one variant into its own fulfillment, so the+// response is the order's full set: the source is re-shaped, and disappears+// when the split drains it. Pass stock_location_id to send the new+// fulfillment out from a different origin.+const { data: fulfillments } = await client.orders.fulfillments.split(+ 'or_UkLWZg9DAJ',+ 'ful_UkLWZg9DAJ',+ {+ variant_id: 'variant_86Rf07xd4z',+ quantity: 1,+ },+)+// endregion:example-export { fulfillment }+export { fulfillments }diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 5500bda57d..c950390271 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -137,6 +137,7 @@ import type {ExchangeUpdateParams,ExportCreateParams,FulfillmentCreateParams,+ FulfillmentSplitParams,FulfillmentUpdateParams,GiftCardApplyParams,GiftCardBatchCreateParams,@@ -1067,16 +1068,23 @@ export class AdminClient {resume: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/resume`, options),+ // Returns every fulfillment on the order, since a split re-shapes the+ // source as well as creating the new one (and destroys the source when+ // it is fully drained).split: (orderId: string,id: string,- params: { quantity: number; line_item_id?: string },+ params: FulfillmentSplitParams,options?: RequestOptions,- ): Promise<Fulfillment> =>- this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/split`, {- ...options,- body: params,- }),+ ): Promise<{ data: Fulfillment[] }> =>+ this.request<{ data: Fulfillment[] }>(+ 'PATCH',+ `/orders/${orderId}/fulfillments/${id}/split`,+ {+ ...options,+ body: params,+ },+ ),},returns: {diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex c36d2957ab..83d8c85a9a 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -133,6 +133,21 @@ export interface FulfillmentUpdateParams {/** Carrier tracking number or a full `https://` tracking link; see {@link FulfillmentCreateParams.tracking} */tracking?: stringselected_delivery_rate_id?: string+ /** Move the fulfillment to another origin (sloc_...); re-prices it against that location's rates. */+ stock_location_id?: string+}++/**+ * Moves `quantity` units of one variant out of a fulfillment into a new one.+ * Splitting is per variant — a fulfillment holding several variants needs one+ * call each.+ */+export interface FulfillmentSplitParams {+ /** The variant being moved out (variant_...) */+ variant_id: string+ quantity: number+ /** Origin of the new fulfillment (sloc_...); defaults to the source fulfillment's location. */+ stock_location_id?: string}export interface ReturnCreateParams {diff --git a/packages/dashboard/e2e/order-fulfillments.spec.ts b/packages/dashboard/e2e/order-fulfillments.spec.tsnew file mode 100644index 0000000000..6d3c2cdb2a--- /dev/null+++ b/packages/dashboard/e2e/order-fulfillments.spec.ts@@ -0,0 +1,59 @@+import { expect, type Page, test } from '@playwright/test'+import { FIXTURE_PROMO_PRODUCT, login } from './helpers'++const NEW_ORDER_PATH = (storeId: string) => `/${storeId}/orders/new`++/**+ * Creates a draft order with a single line item and lands on its detail page.+ * A draft built this way has no shipping address yet, so it carries no+ * fulfillments — the state a merchant starts from.+ */+async function createDraftOrder(page: Page, storeId: string) {+ await page.goto(NEW_ORDER_PATH(storeId))+ await expect(page.getByRole('heading', { name: /new order/i })).toBeVisible({ timeout: 15_000 })++ await page.locator('#order-email').fill(`e2e-fulfillment-${Date.now()}@example.com`)+ await page.getByPlaceholder(/search variant/i).fill(FIXTURE_PROMO_PRODUCT)+ await page+ .getByRole('button', { name: new RegExp(FIXTURE_PROMO_PRODUCT, 'i') })+ .first()+ .click()++ await page.locator('button[type="submit"]').click()+ await expect(page).toHaveURL(new RegExp(`/${storeId}/orders/or_[^/]+$`), { timeout: 15_000 })+}++/**+ * The Fulfillments card. Filtering `div` by contained text would match every+ * ancestor too — including the page wrapper, whose first "Add" button belongs+ * to the Items card — so anchor on the card element itself.+ */+function fulfillmentsCard(page: Page) {+ return page.locator('[data-slot="card"]').filter({+ has: page.getByText(/^fulfillments$/i),+ })+}++test.describe('order fulfillments', () => {+ test('shows the empty state on a draft with no shipping address', async ({ page }) => {+ const creds = await login(page)+ await createDraftOrder(page, creds.store_id)++ await expect(page.getByText(/no fulfillments on this order yet/i)).toBeVisible({+ timeout: 15_000,+ })+ })++ // Manual creation is a completed-order operation — Spree::Fulfillments::Create+ // rejects it otherwise — so the card must not offer an action that can only+ // fail. A draft's fulfillments come from the delivery step instead.+ test('does not offer manual creation on an incomplete order', async ({ page }) => {+ const creds = await login(page)+ await createDraftOrder(page, creds.store_id)++ await expect(page.getByText(/no fulfillments on this order yet/i)).toBeVisible({+ timeout: 15_000,+ })+ await expect(fulfillmentsCard(page).getByRole('button', { name: /^add$/i })).toHaveCount(0)+ })+})diff --git a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsxnew file mode 100644index 0000000000..7c76df4fef--- /dev/null+++ b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx@@ -0,0 +1,766 @@+import type { Fulfillment, Order } from '@spree/admin-sdk'+import {+ Badge,+ Button,+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Field,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ RelativeTime,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ StatusBadge,+ useConfirm,+} from '@spree/dashboard-ui'+import {+ EllipsisVerticalIcon,+ MapPinIcon,+ PencilIcon,+ PlusIcon,+ RotateCcwIcon,+ SplitIcon,+ TruckIcon,+ XCircleIcon,+} from 'lucide-react'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useFulfillmentActions } from '../../../hooks/use-fulfillments'+import { useStockLocations } from '../../../hooks/use-stock-locations'++/**+ * A unit sitting in one fulfillment. Splitting moves units per variant rather+ * than per line item, because that is what the backend's transfer takes.+ */+type FulfillmentUnit = {+ variantId: string+ label: string+ quantity: number+}++function unitsOf(fulfillment: Fulfillment): FulfillmentUnit[] {+ return (fulfillment.fulfillment_items ?? []).flatMap((item) => {+ if (!item.variant_id) return []+ return [+ {+ variantId: item.variant_id,+ label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.variant_id,+ quantity: item.quantity,+ },+ ]+ })+}++/**+ * Line items still available to put into a new fulfillment. The backend moves+ * units out of their existing fulfillments, so everything on the order is+ * offered — it re-shapes the source rather than refusing.+ */+function orderUnits(order: Order): Array<{ itemId: string; label: string; quantity: number }> {+ return (order.items ?? []).map((item) => ({+ itemId: item.id,+ label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,+ quantity: item.quantity,+ }))+}++/**+ * The delivery options a fulfillment can be moved between. Each rate is a+ * priced service — with a carrier provider one method yields several, so the+ * rate rather than the method is what a merchant picks.+ */+function RateSelect({+ fulfillment,+ orderId,+ disabled,+}: {+ fulfillment: Fulfillment+ orderId: string+ disabled: boolean+}) {+ const { t } = useTranslation()+ const { update } = useFulfillmentActions(orderId)++ const rates = fulfillment.delivery_rates ?? []+ if (rates.length === 0) return null++ const options = rates.map((rate) => ({+ value: rate.id,+ label: `${rate.name} — ${+ Number.parseFloat(rate.cost) === 0+ ? t('admin.orders.detail.fulfillments.free')+ : rate.display_cost+ }`,+ }))++ return (+ <Field>+ <FieldLabel htmlFor={`rate-${fulfillment.id}`}>+ {t('admin.orders.detail.fulfillments.delivery_method')}+ </FieldLabel>+ <Select+ items={options}+ value={fulfillment.selected_delivery_rate_id ?? ''}+ disabled={disabled || update.isPending}+ onValueChange={(value) =>+ update.mutate({+ fulfillmentId: fulfillment.id,+ selected_delivery_rate_id: value as string,+ })+ }+ >+ <SelectTrigger id={`rate-${fulfillment.id}`} size="sm">+ <SelectValue placeholder={t('admin.common.select_placeholder')} />+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ )+}++/** Where the fulfillment ships from. Changing it re-prices against that origin. */+function StockLocationSelect({+ fulfillment,+ orderId,+ disabled,+}: {+ fulfillment: Fulfillment+ orderId: string+ disabled: boolean+}) {+ const { t } = useTranslation()+ const { update } = useFulfillmentActions(orderId)+ const { data } = useStockLocations()++ const locations = data?.data ?? []+ if (locations.length === 0) return null++ const options = locations.map((location) => ({ value: location.id, label: location.name }))++ return (+ <Field>+ <FieldLabel htmlFor={`location-${fulfillment.id}`}>+ {t('admin.orders.detail.fulfillments.ships_from')}+ </FieldLabel>+ <Select+ items={options}+ value={fulfillment.stock_location_id ?? ''}+ disabled={disabled || update.isPending}+ onValueChange={(value) =>+ update.mutate({ fulfillmentId: fulfillment.id, stock_location_id: value as string })+ }+ >+ <SelectTrigger id={`location-${fulfillment.id}`} size="sm">+ <SelectValue placeholder={t('admin.common.select_placeholder')} />+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ )+}++function EditTrackingDialog({+ orderId,+ fulfillment,+ open,+ onOpenChange,+}: {+ orderId: string+ fulfillment: Fulfillment+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const { update } = useFulfillmentActions(orderId)+ const [tracking, setTracking] = useState(fulfillment.tracking ?? '')++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('admin.orders.detail.tracking.edit_title')}</DialogTitle>+ <DialogDescription>{t('admin.orders.detail.tracking.description')}</DialogDescription>+ </DialogHeader>+ <DialogBody>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="tracking">{t('admin.orders.detail.tracking.label')}</FieldLabel>+ <Input+ id="tracking"+ value={tracking}+ onChange={(event) => setTracking(event.target.value)}+ />+ </Field>+ </FieldGroup>+ </DialogBody>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button+ type="button"+ disabled={update.isPending}+ onClick={() =>+ update.mutate(+ { fulfillmentId: fulfillment.id, tracking },+ { onSuccess: () => onOpenChange(false) },+ )+ }+ >+ {update.isPending ? t('admin.actions.saving') : t('admin.actions.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/**+ * Moves units into a new fulfillment. One variant per submit, because that is+ * the granularity the backend's transfer works at — splitting several variants+ * apart is several splits.+ */+function SplitFulfillmentDialog({+ orderId,+ fulfillment,+ open,+ onOpenChange,+}: {+ orderId: string+ fulfillment: Fulfillment+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const { split } = useFulfillmentActions(orderId)+ const { data } = useStockLocations()++ const units = unitsOf(fulfillment)+ const [variantId, setVariantId] = useState(units[0]?.variantId ?? '')+ const [quantity, setQuantity] = useState(1)+ const [stockLocationId, setStockLocationId] = useState(fulfillment.stock_location_id ?? '')++ const unit = units.find((candidate) => candidate.variantId === variantId)+ const totalUnits = units.reduce((sum, candidate) => sum + candidate.quantity, 0)++ // Splitting off everything would leave the source empty — the backend+ // destroys it, which is a move rather than a split and almost never what was+ // meant. Changing the origin of the whole fulfillment does that properly.+ const wouldEmptySource = quantity >= totalUnits+ const invalid = !unit || quantity < 1 || quantity > unit.quantity || wouldEmptySource++ const variantOptions = units.map((candidate) => ({+ value: candidate.variantId,+ label: `${candidate.label} (${candidate.quantity})`,+ }))+ const locationOptions = (data?.data ?? []).map((location) => ({+ value: location.id,+ label: location.name,+ }))++ async function handleSubmit() {+ if (invalid) return+ if (+ !(await confirm({+ message: t('admin.orders.detail.fulfillments.confirm_split'),+ variant: 'destructive',+ confirmLabel: t('admin.orders.detail.fulfillments.split'),+ }))+ ) {+ return+ }++ split.mutate(+ {+ fulfillmentId: fulfillment.id,+ variant_id: variantId,+ quantity,+ stock_location_id: stockLocationId || undefined,+ },+ { onSuccess: () => onOpenChange(false) },+ )+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('admin.orders.detail.fulfillments.split_title')}</DialogTitle>+ <DialogDescription>+ {t('admin.orders.detail.fulfillments.split_description')}+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="split-variant">+ {t('admin.orders.detail.fulfillments.split_item')}+ </FieldLabel>+ <Select+ items={variantOptions}+ value={variantId}+ onValueChange={(value) => {+ setVariantId(value as string)+ setQuantity(1)+ }}+ >+ <SelectTrigger id="split-variant">+ <SelectValue placeholder={t('admin.common.select_placeholder')} />+ </SelectTrigger>+ <SelectContent>+ {variantOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>++ <Field>+ <FieldLabel htmlFor="split-quantity">+ {t('admin.orders.detail.fulfillments.split_quantity')}+ </FieldLabel>+ <Input+ id="split-quantity"+ type="number"+ min={1}+ max={unit?.quantity ?? 1}+ value={quantity}+ onChange={(event) => setQuantity(Number(event.target.value))}+ />+ {wouldEmptySource && (+ <FieldError>{t('admin.orders.detail.fulfillments.split_would_empty')}</FieldError>+ )}+ </Field>++ {locationOptions.length > 0 && (+ <Field>+ <FieldLabel htmlFor="split-location">+ {t('admin.orders.detail.fulfillments.ships_from')}+ </FieldLabel>+ <Select+ items={locationOptions}+ value={stockLocationId}+ onValueChange={(value) => setStockLocationId(value as string)}+ >+ <SelectTrigger id="split-location">+ <SelectValue placeholder={t('admin.common.select_placeholder')} />+ </SelectTrigger>+ <SelectContent>+ {locationOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ )}+ </FieldGroup>+ </DialogBody>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="button" disabled={invalid || split.isPending} onClick={handleSubmit}>+ {split.isPending+ ? t('admin.actions.saving')+ : t('admin.orders.detail.fulfillments.split')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/** Creates a fulfillment, moving the chosen quantities out of the existing ones. */+function CreateFulfillmentDialog({+ order,+ open,+ onOpenChange,+}: {+ order: Order+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const { create } = useFulfillmentActions(order.id)+ const { data } = useStockLocations()++ const units = orderUnits(order)+ const locations = data?.data ?? []+ const [stockLocationId, setStockLocationId] = useState('')+ const [selection, setSelection] = useState<Record<string, number>>({})++ const items = Object.entries(selection)+ .filter(([, quantity]) => quantity > 0)+ .map(([itemId, quantity]) => ({ item_id: itemId, quantity }))++ const locationOptions = locations.map((location) => ({+ value: location.id,+ label: location.name,+ }))++ function handleSubmit() {+ if (!stockLocationId) return+ create.mutate(+ {+ stock_location_id: stockLocationId,+ items: items.length > 0 ? items : undefined,+ },+ {+ onSuccess: () => {+ setSelection({})+ setStockLocationId('')+ onOpenChange(false)+ },+ },+ )+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('admin.orders.detail.fulfillments.create_title')}</DialogTitle>+ <DialogDescription>+ {t('admin.orders.detail.fulfillments.create_description')}+ </DialogDescription>+ </DialogHeader>+ <DialogBody>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="create-location">+ {t('admin.orders.detail.fulfillments.ships_from')}+ </FieldLabel>+ <Select+ items={locationOptions}+ value={stockLocationId}+ onValueChange={(value) => setStockLocationId(value as string)}+ >+ <SelectTrigger id="create-location">+ <SelectValue placeholder={t('admin.common.select_placeholder')} />+ </SelectTrigger>+ <SelectContent>+ {locationOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>++ <Field>+ <FieldLabel>{t('admin.orders.detail.fulfillments.create_items')}</FieldLabel>+ <div className="flex flex-col gap-2">+ {units.map((unit) => (+ <div+ key={unit.itemId}+ className="flex items-center justify-between gap-4 rounded-lg border p-3"+ >+ <span className="text-sm truncate">{unit.label}</span>+ <Input+ type="number"+ min={0}+ max={unit.quantity}+ className="w-20"+ aria-label={unit.label}+ value={selection[unit.itemId] ?? 0}+ onChange={(event) =>+ setSelection((current) => ({+ ...current,+ [unit.itemId]: Math.max(+ 0,+ Math.min(Number(event.target.value), unit.quantity),+ ),+ }))+ }+ />+ </div>+ ))}+ </div>+ </Field>+ </FieldGroup>+ </DialogBody>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button+ type="button"+ disabled={!stockLocationId || create.isPending}+ onClick={handleSubmit}+ >+ {create.isPending ? t('admin.actions.saving') : t('admin.actions.create')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++// Which transitions the backend's state machine actually offers, so the menu+// does not present an action that can only 422.+const CAN_SHIP = ['ready', 'ready_for_pickup']+const CAN_CANCEL = ['pending', 'ready', 'ready_for_pickup']+const CAN_EDIT = ['pending', 'ready', 'ready_for_pickup']++function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: Fulfillment }) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const orderId = order.id+ const { fulfill, cancel, resume } = useFulfillmentActions(orderId)++ const [trackingOpen, setTrackingOpen] = useState(false)+ const [splitOpen, setSplitOpen] = useState(false)++ const editable = CAN_EDIT.includes(fulfillment.status)+ const splittable = editable && unitsOf(fulfillment).length > 0++ return (+ <div className="rounded-lg border p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <StatusBadge status={fulfillment.status} />+ <span className="text-sm font-medium">{fulfillment.number}</span>+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-xs">+ <EllipsisVerticalIcon className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem onClick={() => setTrackingOpen(true)}>+ <PencilIcon className="size-4" />+ {fulfillment.tracking+ ? t('admin.orders.detail.tracking.edit_title')+ : t('admin.orders.detail.tracking.add_title')}+ </DropdownMenuItem>++ {splittable && (+ <DropdownMenuItem onClick={() => setSplitOpen(true)}>+ <SplitIcon className="size-4" />+ {t('admin.orders.detail.fulfillments.split')}+ </DropdownMenuItem>+ )}++ {CAN_SHIP.includes(fulfillment.status) && (+ <DropdownMenuItem+ onClick={async () => {+ if (+ await confirm({+ message: t('admin.orders.detail.confirm.ship_message'),+ variant: 'default',+ confirmLabel: t('admin.pages.orders.detail.actions.ship'),+ })+ ) {+ fulfill.mutate(fulfillment.id)+ }+ }}+ >+ <TruckIcon className="size-4" />+ {t('admin.pages.orders.detail.actions.ship')}+ </DropdownMenuItem>+ )}++ {fulfillment.status === 'canceled' && (+ <DropdownMenuItem onClick={() => resume.mutate(fulfillment.id)}>+ <RotateCcwIcon className="size-4" />+ {t('admin.pages.orders.detail.actions.resume')}+ </DropdownMenuItem>+ )}++ {CAN_CANCEL.includes(fulfillment.status) && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="text-destructive focus:text-destructive"+ onClick={async () => {+ if (+ await confirm({+ message: t('admin.orders.detail.confirm.cancel_shipment_message'),+ variant: 'destructive',+ confirmLabel: t('admin.actions.cancel'),+ })+ ) {+ cancel.mutate(fulfillment.id)+ }+ }}+ >+ <XCircleIcon className="size-4" />+ {t('admin.actions.cancel')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ {editable ? (+ <div className="grid gap-3 sm:grid-cols-2">+ <RateSelect fulfillment={fulfillment} orderId={orderId} disabled={!editable} />+ <StockLocationSelect fulfillment={fulfillment} orderId={orderId} disabled={!editable} />+ </div>+ ) : (+ <>+ {(fulfillment.delivery_method || Number.parseFloat(fulfillment.cost) > 0) && (+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted-foreground">+ {fulfillment.delivery_method?.name ??+ t('admin.pages.orders.detail.no_delivery_method')}+ </span>+ <span>{fulfillment.display_cost}</span>+ </div>+ )}+ {fulfillment.stock_location && (+ <div className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <MapPinIcon className="size-3" />+ {fulfillment.stock_location.name}+ </div>+ )}+ </>+ )}++ {fulfillment.tracking && (+ <div className="text-sm">+ <span className="text-muted-foreground">+ {t('admin.orders.detail.tracking.prefix')}:{' '}+ </span>+ {fulfillment.tracking_url ? (+ <a+ href={fulfillment.tracking_url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 hover:underline"+ >+ {fulfillment.tracking}+ </a>+ ) : (+ <span>{fulfillment.tracking}</span>+ )}+ </div>+ )}++ {fulfillment.fulfilled_at && (+ <span className="text-xs text-muted-foreground">+ <RelativeTime+ iso={fulfillment.fulfilled_at}+ prefix={t('admin.orders.detail.tracking.shipped_prefix')}+ fallback=""+ />+ </span>+ )}++ {trackingOpen && (+ <EditTrackingDialog+ orderId={orderId}+ fulfillment={fulfillment}+ open={trackingOpen}+ onOpenChange={setTrackingOpen}+ />+ )}++ {splitOpen && (+ <SplitFulfillmentDialog+ orderId={orderId}+ fulfillment={fulfillment}+ open={splitOpen}+ onOpenChange={setSplitOpen}+ />+ )}+ </div>+ )+}++/**+ * Fulfillments on an order, editable while they are still open: which priced+ * service carries them, where they ship from, and how the units are grouped.+ * Once shipped or canceled they read back flat, since the backend refuses the+ * writes anyway.+ */+export function FulfillmentsCard({ order }: { order: Order }) {+ const { t } = useTranslation()+ const [createOpen, setCreateOpen] = useState(false)++ const fulfillments = order.fulfillments ?? []+ // Manual creation is a completed-order operation: Fulfillments::Create+ // rejects it otherwise ("Fulfillments can only be created manually on+ // completed orders"). A draft's fulfillments come from the delivery step.+ const canCreate = (order.items ?? []).length > 0 && !!order.completed_at++ return (+ <>+ <Card>+ <CardHeader>+ <CardTitle>+ <TruckIcon className="size-4" />+ {t('admin.pages.orders.detail.section_fulfillments')}+ {fulfillments.length > 0 && <Badge variant="outline">{fulfillments.length}</Badge>}+ </CardTitle>+ <CardAction className="flex items-center gap-2">+ {order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}+ {canCreate && (+ <Button size="sm" variant="outline" onClick={() => setCreateOpen(true)}>+ <PlusIcon data-icon="inline-start" />+ {t('admin.actions.add')}+ </Button>+ )}+ </CardAction>+ </CardHeader>+ {fulfillments.length === 0 ? (+ <CardContent>+ <p className="text-center text-muted-foreground py-8">+ {t('admin.orders.detail.fulfillments.empty')}+ </p>+ </CardContent>+ ) : (+ <CardContent className="flex flex-col gap-4">+ {fulfillments.map((fulfillment) => (+ <FulfillmentRow key={fulfillment.id} order={order} fulfillment={fulfillment} />+ ))}+ </CardContent>+ )}+ </Card>++ {createOpen && (+ <CreateFulfillmentDialog order={order} open={createOpen} onOpenChange={setCreateOpen} />+ )}+ </>+ )+}diff --git a/packages/dashboard/src/hooks/use-fulfillments.ts b/packages/dashboard/src/hooks/use-fulfillments.tsnew file mode 100644index 0000000000..a504c25eb6--- /dev/null+++ b/packages/dashboard/src/hooks/use-fulfillments.ts@@ -0,0 +1,71 @@+import type { FulfillmentCreateParams, FulfillmentSplitParams } from '@spree/admin-sdk'+import { adminClient, useResourceKeyBuilder } from '@spree/dashboard-core'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++/**+ * A fulfillment mutation refreshes the order itself — every one of these moves+ * units, re-prices the fulfillment, or both, and the order totals and+ * fulfillment status are derived from that.+ */+function useFulfillmentMutation<TParams>(+ orderId: string,+ mutationFn: (params: TParams) => Promise<unknown>,+) {+ const queryClient = useQueryClient()+ const buildKey = useResourceKeyBuilder()++ return useMutation({+ mutationFn,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: buildKey('orders', orderId) })+ },+ onError: (error) => {+ toast.error(error instanceof Error ? error.message : String(error))+ },+ })+}++/**+ * Every write the fulfillments card offers. The status transitions are+ * separate endpoints rather than a writable status field, because the server+ * decides which ones a fulfillment can currently make.+ */+export function useFulfillmentActions(orderId: string) {+ const create = useFulfillmentMutation(orderId, (params: FulfillmentCreateParams) =>+ adminClient.orders.fulfillments.create(orderId, params),+ )++ const update = useFulfillmentMutation(+ orderId,+ ({+ fulfillmentId,+ ...params+ }: {+ fulfillmentId: string+ tracking?: string+ selected_delivery_rate_id?: string+ stock_location_id?: string+ }) => adminClient.orders.fulfillments.update(orderId, fulfillmentId, params),+ )++ const split = useFulfillmentMutation(+ orderId,+ ({ fulfillmentId, ...params }: { fulfillmentId: string } & FulfillmentSplitParams) =>+ adminClient.orders.fulfillments.split(orderId, fulfillmentId, params),+ )++ const fulfill = useFulfillmentMutation(orderId, (fulfillmentId: string) =>+ adminClient.orders.fulfillments.fulfill(orderId, fulfillmentId),+ )++ const cancel = useFulfillmentMutation(orderId, (fulfillmentId: string) =>+ adminClient.orders.fulfillments.cancel(orderId, fulfillmentId),+ )++ const resume = useFulfillmentMutation(orderId, (fulfillmentId: string) =>+ adminClient.orders.fulfillments.resume(orderId, fulfillmentId),+ )++ return { create, update, split, fulfill, cancel, resume }+}diff --git a/packages/dashboard/src/hooks/use-order.ts b/packages/dashboard/src/hooks/use-order.tsindex b5875f1401..9854361ca5 100644--- a/packages/dashboard/src/hooks/use-order.ts+++ b/packages/dashboard/src/hooks/use-order.ts@@ -12,6 +12,8 @@ export function useOrder(orderId: string) {'fulfillments.fulfillment_items','fulfillments.delivery_method','fulfillments.stock_location',+ 'fulfillments.delivery_rates',+ 'fulfillments.delivery_rates.delivery_method','payments','payments.payment_method','billing_address',diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex e622523fac..e071bddf14 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1821,6 +1821,22 @@"confirmation_send_failed": "فشل في إرسال التأكيد","resume_failed": "فشل في استئناف الطلب"},+ "fulfillments": {+ "confirm_split": "نقل هذه الوحدات إلى شحنة جديدة؟ يسري هذا فوراً.",+ "create_description": "تنشئ شحنة وتنقل إليها الكميات المختارة.",+ "create_items": "العناصر",+ "create_title": "إضافة شحنة",+ "delivery_method": "طريقة التوصيل",+ "empty": "لا توجد شحنات لهذا الطلب بعد.",+ "free": "مجاني",+ "ships_from": "الشحن من",+ "split": "تقسيم",+ "split_description": "انقل بعض الوحدات إلى شحنة جديدة. منتج واحد في كل مرة.",+ "split_item": "المنتج",+ "split_quantity": "الكمية المراد نقلها",+ "split_title": "تقسيم الشحنة",+ "split_would_empty": "اترك وحدة واحدة على الأقل، أو غيّر مصدر الشحنة بالكامل بدلاً من ذلك."+ },"gift_card_section": {"applied_suffix": "مُطبَّق","apply_balance": "قم بتطبيق الرصيد المتاح لـ العميل",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex ac4702116a..f29501e2b6 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1810,6 +1810,22 @@"confirmation_send_failed": "Bestätigung konnte nicht gesendet werden","resume_failed": "Auftrag konnte nicht wieder aufgenommen werden"},+ "fulfillments": {+ "confirm_split": "Diese Einheiten in eine neue Sendung verschieben? Die Änderung wird sofort wirksam.",+ "create_description": "Erstellt eine Sendung und verschiebt die gewählten Mengen hinein.",+ "create_items": "Artikel",+ "create_title": "Sendung hinzufügen",+ "delivery_method": "Versandart",+ "empty": "Noch keine Sendungen für diese Bestellung.",+ "free": "Kostenlos",+ "ships_from": "Versand ab",+ "split": "Aufteilen",+ "split_description": "Verschieben Sie einzelne Einheiten in eine neue Sendung. Ein Produkt nach dem anderen.",+ "split_item": "Produkt",+ "split_quantity": "Zu verschiebende Menge",+ "split_title": "Sendung aufteilen",+ "split_would_empty": "Lassen Sie mindestens eine Einheit zurück oder ändern Sie stattdessen den Ursprung der gesamten Sendung."+ },"gift_card_section": {"applied_suffix": "angewendet","apply_balance": "Verfügbares Guthaben des Kunden anwenden",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 8e88096888..f9847684e6 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1810,6 +1810,22 @@"confirmation_send_failed": "Failed to send confirmation","resume_failed": "Failed to resume order"},+ "fulfillments": {+ "confirm_split": "Move these units into a new fulfillment? This takes effect immediately.",+ "create_description": "Creates a fulfillment and moves the chosen quantities into it.",+ "create_items": "Items",+ "create_title": "Add fulfillment",+ "delivery_method": "Delivery method",+ "empty": "No fulfillments on this order yet.",+ "free": "Free",+ "ships_from": "Ships from",+ "split": "Split",+ "split_description": "Move some units into a new fulfillment. One product at a time.",+ "split_item": "Product",+ "split_quantity": "Quantity to move",+ "split_title": "Split fulfillment",+ "split_would_empty": "Leave at least one unit behind, or change the origin of the whole fulfillment instead."+ },"gift_card_section": {"applied_suffix": "applied","apply_balance": "Apply customer's available balance",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 075998440b..aa03af430e 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1810,6 +1810,22 @@"confirmation_send_failed": "Échec de l'envoi de la confirmation","resume_failed": "Échec de la reprise de la commande"},+ "fulfillments": {+ "confirm_split": "Déplacer ces unités vers une nouvelle expédition ? L'effet est immédiat.",+ "create_description": "Crée une expédition et y déplace les quantités choisies.",+ "create_items": "Articles",+ "create_title": "Ajouter une expédition",+ "delivery_method": "Mode de livraison",+ "empty": "Aucune expédition pour cette commande.",+ "free": "Gratuit",+ "ships_from": "Expédié depuis",+ "split": "Diviser",+ "split_description": "Déplacez certaines unités vers une nouvelle expédition. Un produit à la fois.",+ "split_item": "Produit",+ "split_quantity": "Quantité à déplacer",+ "split_title": "Diviser l'expédition",+ "split_would_empty": "Laissez au moins une unité, ou modifiez plutôt l'origine de toute l'expédition."+ },"gift_card_section": {"applied_suffix": "appliqué","apply_balance": "Appliquer le solde disponible du client",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 601511726e..21b30d7e3e 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1826,6 +1826,22 @@"confirmation_send_failed": "Nie udało się wysłać potwierdzenia","resume_failed": "Nie udało się wznowić zamówienia"},+ "fulfillments": {+ "confirm_split": "Przenieść te sztuki do nowej przesyłki? Zmiana zadziała natychmiast.",+ "create_description": "Tworzy przesyłkę i przenosi do niej wybrane ilości.",+ "create_items": "Pozycje",+ "create_title": "Dodaj przesyłkę",+ "delivery_method": "Sposób dostawy",+ "empty": "Brak przesyłek dla tego zamówienia.",+ "free": "Za darmo",+ "ships_from": "Wysyłka z",+ "split": "Podziel",+ "split_description": "Przenieś część sztuk do nowej przesyłki. Po jednym produkcie naraz.",+ "split_item": "Produkt",+ "split_quantity": "Liczba do przeniesienia",+ "split_title": "Podziel przesyłkę",+ "split_would_empty": "Pozostaw co najmniej jedną sztukę albo zmień miejsce wysyłki całej przesyłki."+ },"gift_card_section": {"applied_suffix": "zastosowano","apply_balance": "Zastosuj dostępne saldo klienta",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 60bdcb68c7..c0293ddbbd 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1807,6 +1807,22 @@"confirmation_send_failed": "发送确认失败","resume_failed": "恢复订单失败"},+ "fulfillments": {+ "confirm_split": "将这些数量移入新的发货单?此操作立即生效。",+ "create_description": "创建发货单并将所选数量移入其中。",+ "create_items": "商品项",+ "create_title": "添加发货单",+ "delivery_method": "配送方式",+ "empty": "此订单暂无发货单。",+ "free": "免费",+ "ships_from": "发货地",+ "split": "拆分",+ "split_description": "将部分数量移入新的发货单。每次操作一个商品。",+ "split_item": "商品",+ "split_quantity": "移动数量",+ "split_title": "拆分发货单",+ "split_would_empty": "请至少保留一件,或改为修改整个发货单的发货地。"+ },"gift_card_section": {"applied_suffix": "已应用","apply_balance": "应用客户的可用余额",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex f930901cdc..3eeedf20dd 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -78,7 +78,6 @@ import {EllipsisVerticalIcon,ExternalLinkIcon,MailIcon,- MapPinIcon,PackageIcon,PencilIcon,PlusIcon,@@ -86,7 +85,6 @@ import {ShieldCheckIcon,ShoppingCartIcon,TrashIcon,- TruckIcon,XCircleIcon,} from 'lucide-react'import { type FormEvent, type ReactNode, useEffect, useState } from 'react'@@ -100,6 +98,7 @@ import {OrderExchangesCard,} from '../../../../components/spree/order-post-sale-cards'import { OrderReturnsCard } from '../../../../components/spree/order-returns-card'+import { FulfillmentsCard } from '../../../../components/spree/orders/fulfillments-card'import {orderQueryKey,useOrder,@@ -733,235 +732,6 @@ function LineItemsCard({ order }: { order: Order }) {)}-// ----------------------------------------------------------------------------// Fulfillments-// -----------------------------------------------------------------------------function EditTrackingDialog({- orderId,- fulfillmentId,- currentTracking,- open,- onOpenChange,-}: {- orderId: string- fulfillmentId: string- currentTracking: string | null- open: boolean- onOpenChange: (open: boolean) => void-}) {- const { t } = useTranslation()- const mutation = useOrderMutation(orderId, (params: { tracking: string }) =>- adminClient.orders.fulfillments.update(orderId, fulfillmentId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { tracking: fd.get('tracking') as string },- { onSuccess: () => onOpenChange(false) },- )- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t('admin.orders.detail.tracking.edit_title')}</DialogTitle>- <DialogDescription>{t('admin.orders.detail.tracking.description')}</DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit}>- <DialogBody>- <FieldGroup>- <Field>- <FieldLabel htmlFor="tracking">- {t('admin.orders.detail.tracking.label')}- </FieldLabel>- <Input id="tracking" name="tracking" defaultValue={currentTracking ?? ''} />- </Field>- </FieldGroup>- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- {t('admin.actions.cancel')}- </Button>- <Button type="submit" disabled={mutation.isPending}>- {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}--function FulfillmentsCard({ order }: { order: Order }) {- const { t } = useTranslation()- const { orderId } = Route.useParams()- const confirm = useConfirm()-- const fulfillments = order.fulfillments ?? []- const [editTracking, setEditTracking] = useState<{- id: string- tracking: string | null- } | null>(null)-- const fulfillMutation = useOrderMutation(orderId, (fulfillmentId: string) =>- adminClient.orders.fulfillments.fulfill(orderId, fulfillmentId, {}),- )- const cancelFulfillmentMutation = useOrderMutation(orderId, (fulfillmentId: string) =>- adminClient.orders.fulfillments.cancel(orderId, fulfillmentId, {}),- )-- if (fulfillments.length === 0) return null-- return (- <>- <Card>- <CardHeader>- <CardTitle>- <TruckIcon className="size-4" />- {t('admin.pages.orders.detail.section_fulfillments')}- <Badge variant="outline">{fulfillments.length}</Badge>- </CardTitle>- <CardAction className="flex items-center gap-2">- {order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}- </CardAction>- </CardHeader>- <CardContent className="flex flex-col gap-4">- {fulfillments.map((fulfillment) => (- <div key={fulfillment.id} className="rounded-lg border p-4 flex flex-col gap-3">- <div className="flex items-center justify-between">- <div className="flex items-center gap-2">- <StatusBadge status={fulfillment.status} />- <span className="text-sm font-medium">{fulfillment.number}</span>- </div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() =>- setEditTracking({ id: fulfillment.id, tracking: fulfillment.tracking })- }- >- <PencilIcon className="size-4" />- {fulfillment.tracking- ? t('admin.orders.detail.tracking.edit_title')- : t('admin.orders.detail.tracking.add_title')}- </DropdownMenuItem>- {fulfillment.status === 'ready' && (- <DropdownMenuItem- onClick={async () => {- if (- await confirm({- message: t('admin.orders.detail.confirm.ship_message'),- variant: 'default',- confirmLabel: t('admin.pages.orders.detail.actions.ship'),- })- ) {- fulfillMutation.mutate(fulfillment.id)- }- }}- >- <TruckIcon className="size-4" />- {t('admin.pages.orders.detail.actions.ship')}- </DropdownMenuItem>- )}- {['pending', 'ready'].includes(fulfillment.status) && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={async () => {- if (- await confirm({- message: t('admin.orders.detail.confirm.cancel_shipment_message'),- variant: 'destructive',- confirmLabel: t('admin.actions.cancel'),- })- ) {- cancelFulfillmentMutation.mutate(fulfillment.id)- }- }}- >- <XCircleIcon className="size-4" />- {t('admin.actions.cancel')}- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- </div>-- {(fulfillment.delivery_method || Number.parseFloat(fulfillment.cost) > 0) && (- <div className="flex items-center justify-between text-sm">- <span className="text-muted-foreground">- {fulfillment.delivery_method?.name ??- t('admin.pages.orders.detail.no_delivery_method')}- </span>- <span>{fulfillment.display_cost}</span>- </div>- )}-- {fulfillment.stock_location && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground">- <MapPinIcon className="size-3" />- {fulfillment.stock_location.name}- </div>- )}-- {fulfillment.tracking && (- <div className="text-sm">- <span className="text-muted-foreground">- {t('admin.orders.detail.tracking.prefix')}:{' '}- </span>- {fulfillment.tracking_url ? (- <a- href={fulfillment.tracking_url}- target="_blank"- rel="noopener noreferrer"- className="text-blue-600 hover:underline"- >- {fulfillment.tracking}- </a>- ) : (- <span>{fulfillment.tracking}</span>- )}- </div>- )}-- {fulfillment.fulfilled_at && (- <span className="text-xs text-muted-foreground">- <RelativeTime- iso={fulfillment.fulfilled_at}- prefix={t('admin.orders.detail.tracking.shipped_prefix')}- fallback=""- />- </span>- )}- </div>- ))}- </CardContent>- </Card>-- {editTracking && (- <EditTrackingDialog- orderId={orderId}- fulfillmentId={editTracking.id}- currentTracking={editTracking.tracking}- open={!!editTracking}- onOpenChange={(open) => !open && setEditTracking(null)}- />- )}- </>- )-}-// ---------------------------------------------------------------------------// Payments// ---------------------------------------------------------------------------