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
Show what each fulfillment is shipping
Damian Legawiec415bbc33b00a
diff --git a/packages/dashboard/e2e/order-fulfillments.spec.ts b/packages/dashboard/e2e/order-fulfillments.spec.tsindex 6d3c2cdb2a..a30366ad5c 100644--- a/packages/dashboard/e2e/order-fulfillments.spec.ts+++ b/packages/dashboard/e2e/order-fulfillments.spec.ts@@ -25,35 +25,40 @@ async function createDraftOrder(page: Page, storeId: string) {/*** 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.+ * ancestor too, so anchor on the card element itself.*/function fulfillmentsCard(page: Page) {+ // The title holds an icon and a count badge beside the word, so match the+ // text loosely; anchoring on the card element keeps sibling cards out.return page.locator('[data-slot="card"]').filter({- has: page.getByText(/^fulfillments$/i),+ has: page.locator('[data-slot="card-title"]', { hasText: /fulfillments/i }),})}test.describe('order fulfillments', () => {- test('shows the empty state on a draft with no shipping address', async ({ page }) => {+ // A draft carries no fulfillments, so its line item has nobody to claim it+ // and lands in the unfulfilled group at the top of the card — which is what+ // tells the merchant the goods still need shipping.+ test('lists the unclaimed line item 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,- })+ const card = fulfillmentsCard(page)+ await expect(card.getByText(/unfulfilled \(\d+\)/i)).toBeVisible({ timeout: 15_000 })+ await expect(card.getByText(new RegExp(FIXTURE_PROMO_PRODUCT, 'i')).first()).toBeVisible()})// 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.+ // fail. A draft's fulfillments come from the delivery step instead. "Add+ // item" sits in the same header and stays available.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)+ const card = fulfillmentsCard(page)+ await expect(card.getByText(/unfulfilled \(\d+\)/i)).toBeVisible({ timeout: 15_000 })+ await expect(card.getByRole('button', { name: /^add fulfillment$/i })).toHaveCount(0)+ await expect(card.getByRole('button', { name: /^add item$/i })).toBeVisible()})})diff --git a/packages/dashboard/src/components/spree/orders/fulfillment-item-list.tsx b/packages/dashboard/src/components/spree/orders/fulfillment-item-list.tsxnew file mode 100644index 0000000000..8236a34edf--- /dev/null+++ b/packages/dashboard/src/components/spree/orders/fulfillment-item-list.tsx@@ -0,0 +1,140 @@+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ useConfirm,+} from '@spree/dashboard-ui'+import { EllipsisVerticalIcon, PackageIcon, PencilIcon, TrashIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import type { FulfillmentItemRow } from '../../../lib/fulfillment-items'++/**+ * One item inside a fulfillment group: what it looks like, what it costs and+ * how many units this group holds. The row-level menu is optional — only the+ * unfulfilled group can still edit or remove a line item, since units already+ * handed to a fulfillment are edited through the fulfillment itself.+ */+function ItemRow({+ row,+ onEdit,+ onRemove,+}: {+ row: FulfillmentItemRow+ onEdit?: (row: FulfillmentItemRow) => void+ onRemove?: (row: FulfillmentItemRow) => void+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const hasMenu = !!onEdit || !!onRemove++ return (+ <div className="flex items-center gap-3 py-3">+ {row.thumbnailUrl ? (+ <img+ src={row.thumbnailUrl}+ alt={row.name}+ className="size-10 shrink-0 rounded-lg border object-cover"+ />+ ) : (+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border bg-muted">+ <PackageIcon className="size-4 text-muted-foreground" />+ </div>+ )}++ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium">{row.name}</div>+ {row.optionsText && (+ <div className="truncate text-xs text-muted-foreground">{row.optionsText}</div>+ )}+ </div>++ <div className="shrink-0 text-right text-sm whitespace-nowrap text-muted-foreground">+ {row.displayPrice ? (+ <span>+ {row.displayPrice} × {row.quantity}+ </span>+ ) : (+ <span>× {row.quantity}</span>+ )}+ </div>++ {hasMenu && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={t('admin.orders.detail.items_table.item_actions', { name: row.name })}+ >+ <EllipsisVerticalIcon className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {onEdit && (+ <DropdownMenuItem onClick={() => onEdit(row)}>+ <PencilIcon className="size-4" />+ {t('admin.orders.detail.dropdown.edit_quantity')}+ </DropdownMenuItem>+ )}+ {onEdit && onRemove && <DropdownMenuSeparator />}+ {onRemove && (+ <DropdownMenuItem+ className="text-destructive focus:text-destructive"+ onClick={async () => {+ if (+ await confirm({+ message: t('admin.orders.detail.confirm.remove_item_message'),+ variant: 'destructive',+ confirmLabel: t('admin.actions.remove'),+ })+ ) {+ onRemove(row)+ }+ }}+ >+ <TrashIcon className="size-4" />+ {t('admin.actions.remove')}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ )+}++/**+ * The item list rendered inside a fulfillment group.+ *+ * @param canRemove decides per row whether removal is offered at all; a row it+ * rejects shows no remove action rather than one that would do nothing.+ */+export function FulfillmentItemList({+ rows,+ onEdit,+ onRemove,+ canRemove,+}: {+ rows: FulfillmentItemRow[]+ onEdit?: (row: FulfillmentItemRow) => void+ onRemove?: (row: FulfillmentItemRow) => void+ canRemove?: (row: FulfillmentItemRow) => boolean+}) {+ if (rows.length === 0) return null++ return (+ <div className="divide-y">+ {rows.map((row) => (+ <ItemRow+ key={row.key}+ row={row}+ onEdit={onEdit}+ onRemove={onRemove && (!canRemove || canRemove(row)) ? onRemove : undefined}+ />+ ))}+ </div>+ )+}diff --git a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsxindex a60161fecf..aac1811b3f 100644--- a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx+++ b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx@@ -1,4 +1,5 @@import type { Fulfillment, Order } from '@spree/admin-sdk'+import { adminClient } from '@spree/dashboard-core'import {Badge,Button,@@ -36,6 +37,7 @@ import {import {EllipsisVerticalIcon,MapPinIcon,+ PackageIcon,PencilIcon,PlusIcon,RotateCcwIcon,@@ -47,8 +49,17 @@ import {import { useState } from 'react'import { useTranslation } from 'react-i18next'import { useFulfillmentActions } from '../../../hooks/use-fulfillments'+import { useOrderMutation } from '../../../hooks/use-order'import { useStockLocations } from '../../../hooks/use-stock-locations'+import {+ type FulfillmentItemRow,+ fulfillmentItemRows,+ hasFulfillableUnits,+ unfulfilledItemRows,+} from '../../../lib/fulfillment-items'import { FulfillmentEditDialog } from './fulfillment-edit-dialog'+import { FulfillmentItemList } from './fulfillment-item-list'+import { AddLineItemDialog, EditQuantityDialog } from './line-item-dialogs'/*** A unit sitting in one fulfillment. Splitting moves units per variant rather@@ -581,6 +592,8 @@ function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: Ful</span>)}+ <FulfillmentItemList rows={fulfillmentItemRows(fulfillment, order.items ?? [])} />+{editOpen && (<FulfillmentEditDialogorder={order}@@ -611,21 +624,79 @@ function FulfillmentRow({ order, fulfillment }: { order: Order; fulfillment: Ful)}+/**+ * Units nobody has put into a fulfillment yet. Reads like a fulfillment group+ * so the eye can compare it against the real ones, minus the status and number+ * it does not have. Line items are still editable here — once units belong to+ * a fulfillment they are edited through that fulfillment instead.+ */+function UnfulfilledGroup({+ orderId,+ rows,+ onEditItem,+}: {+ orderId: string+ rows: FulfillmentItemRow[]+ onEditItem: (row: FulfillmentItemRow) => void+}) {+ const { t } = useTranslation()++ const deleteMutation = useOrderMutation(orderId, (lineItemId: string) =>+ adminClient.orders.items.delete(orderId, lineItemId),+ )++ const totalUnits = rows.reduce((sum, row) => sum + row.quantity, 0)++ return (+ <div className="rounded-lg border p-4 flex flex-col gap-3">+ <div className="flex items-center gap-2">+ <PackageIcon className="size-4 text-muted-foreground" />+ <span className="text-sm font-medium">+ {t('admin.orders.detail.fulfillments.unfulfilled', { count: totalUnits })}+ </span>+ </div>++ <FulfillmentItemList+ rows={rows}+ onEdit={onEditItem}+ onRemove={(row) => row.lineItem && deleteMutation.mutate(row.lineItem.id)}+ // Removal deletes the whole line item, so it is only offered while+ // every one of its units is still unclaimed — otherwise it would+ // silently pull units out of an existing fulfillment too.+ canRemove={(row) => !!row.lineItem && row.quantity === row.lineItem.quantity}+ />+ </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.+ *+ * Each group lists the items it carries, so a multi-fulfillment order says+ * which goods went where rather than leaving that to be inferred from a+ * separate basket-wide list.*/export function FulfillmentsCard({ order }: { order: Order }) {const { t } = useTranslation()const [createOpen, setCreateOpen] = useState(false)+ const [addItemOpen, setAddItemOpen] = useState(false)+ const [editItem, setEditItem] = useState<{ id: string; quantity: number } | null>(null)const fulfillments = order.fulfillments ?? []+ const lineItems = order.items ?? []+ const unfulfilled = unfulfilledItemRows(lineItems, 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+ // It also needs units it can actually move — offering it on a fully shipped+ // order would only ever produce an empty fulfillment.+ const canCreate = !!order.completed_at && hasFulfillableUnits(lineItems, fulfillments)++ const groupCount = fulfillments.length + (unfulfilled.length > 0 ? 1 : 0)return (<>@@ -634,19 +705,23 @@ export function FulfillmentsCard({ order }: { order: Order }) {<CardTitle><TruckIcon className="size-4" />{t('admin.pages.orders.detail.section_fulfillments')}- {fulfillments.length > 0 && <Badge variant="outline">{fulfillments.length}</Badge>}+ {groupCount > 0 && <Badge variant="outline">{groupCount}</Badge>}</CardTitle><CardAction className="flex items-center gap-2">{order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}+ <Button size="sm" variant="outline" onClick={() => setAddItemOpen(true)}>+ <PlusIcon data-icon="inline-start" />+ {t('admin.orders.detail.fulfillments.add_item')}+ </Button>{canCreate && (<Button size="sm" variant="outline" onClick={() => setCreateOpen(true)}><PlusIcon data-icon="inline-start" />- {t('admin.actions.add')}+ {t('admin.orders.detail.fulfillments.create_title')}</Button>)}</CardAction></CardHeader>- {fulfillments.length === 0 ? (+ {groupCount === 0 ? (<CardContent><p className="text-center text-muted-foreground py-8">{t('admin.orders.detail.fulfillments.empty')}@@ -654,6 +729,16 @@ export function FulfillmentsCard({ order }: { order: Order }) {</CardContent>) : (<CardContent className="flex flex-col gap-4">+ {unfulfilled.length > 0 && (+ <UnfulfilledGroup+ orderId={order.id}+ rows={unfulfilled}+ onEditItem={(row) =>+ row.lineItem &&+ setEditItem({ id: row.lineItem.id, quantity: row.lineItem.quantity })+ }+ />+ )}{fulfillments.map((fulfillment) => (<FulfillmentRow key={fulfillment.id} order={order} fulfillment={fulfillment} />))}@@ -664,6 +749,18 @@ export function FulfillmentsCard({ order }: { order: Order }) {{createOpen && (<CreateFulfillmentDialog order={order} open={createOpen} onOpenChange={setCreateOpen} />)}++ <AddLineItemDialog orderId={order.id} open={addItemOpen} onOpenChange={setAddItemOpen} />++ {editItem && (+ <EditQuantityDialog+ orderId={order.id}+ lineItemId={editItem.id}+ currentQuantity={editItem.quantity}+ open={!!editItem}+ onOpenChange={(open) => !open && setEditItem(null)}+ />+ )}</>)}diff --git a/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx b/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsxnew file mode 100644index 0000000000..5fea3e68cb--- /dev/null+++ b/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx@@ -0,0 +1,242 @@+import type { Variant } from '@spree/admin-sdk'+import { adminClient, formatPrice } from '@spree/dashboard-core'+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldGroup,+ FieldLabel,+ Input,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from '@spree/dashboard-ui'+import { useQuery } from '@tanstack/react-query'+import { XCircleIcon } from 'lucide-react'+import { type FormEvent, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useOrderMutation } from '../../../hooks/use-order'++/** Searches the catalog and adds the chosen variant to the order. */+export function AddLineItemDialog({+ orderId,+ open,+ onOpenChange,+}: {+ orderId: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const [search, setSearch] = useState('')+ const [selectedVariant, setSelectedVariant] = useState<Variant | null>(null)+ const [quantity, setQuantity] = useState(1)++ const { data: variantsData } = useQuery({+ queryKey: ['variants', 'search', search],+ queryFn: () => adminClient.variants.list({ search, limit: 10 }),+ enabled: search.length >= 3,+ staleTime: 30_000,+ })++ const variants = variantsData?.data ?? []++ const mutation = useOrderMutation(orderId, (params: { variant_id: string; quantity: number }) =>+ adminClient.orders.items.create(orderId, params),+ )++ function handleSubmit(e: FormEvent<HTMLFormElement>) {+ e.preventDefault()+ if (!selectedVariant) return+ mutation.mutate(+ { variant_id: selectedVariant.id, quantity },+ {+ onSuccess: () => {+ onOpenChange(false)+ setSelectedVariant(null)+ setSearch('')+ setQuantity(1)+ },+ },+ )+ }++ return (+ <Sheet open={open} onOpenChange={(o) => onOpenChange(o as boolean)}>+ <SheetContent side="right">+ <SheetHeader>+ <SheetTitle>{t('admin.orders.detail.add_line_item.title')}</SheetTitle>+ <SheetDescription>{t('admin.orders.detail.variant_search.description')}</SheetDescription>+ </SheetHeader>+ <form onSubmit={handleSubmit} className="flex flex-col flex-1 overflow-hidden">+ <div className="flex-1 overflow-y-auto p-4">+ <FieldGroup>+ <Field>+ <FieldLabel>{t('admin.orders.detail.variant_search.label')}</FieldLabel>+ <Input+ placeholder={t('admin.orders.detail.variant_search.placeholder')}+ value={search}+ onChange={(e) => {+ setSearch(e.target.value)+ setSelectedVariant(null)+ }}+ autoFocus+ />+ {search.length >= 3 && variants.length > 0 && !selectedVariant && (+ <div className="mt-1 rounded-lg border border-border bg-popover text-popover-foreground shadow-xs max-h-[280px] overflow-y-auto">+ {variants.map((v) => (+ <button+ key={v.id}+ type="button"+ onClick={() => {+ setSelectedVariant(v)+ setSearch('')+ }}+ className="flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm hover:bg-muted transition-colors border-b last:border-0"+ >+ <div className="min-w-0 flex-1">+ <div className="font-medium truncate">{v.product_name ?? v.sku}</div>+ <div className="text-xs text-muted-foreground">+ {v.options_text && <span>{v.options_text} · </span>}+ {t('admin.orders.detail.variant_search.sku_prefix')}: {v.sku || '—'}+ </div>+ </div>+ <div className="text-sm font-medium whitespace-nowrap">+ {formatPrice(v.price)}+ </div>+ </button>+ ))}+ </div>+ )}+ {search.length >= 3 && variants.length === 0 && !selectedVariant && (+ <p className="mt-1 text-xs text-muted-foreground">+ {t('admin.orders.detail.variant_search.empty')}+ </p>+ )}+ </Field>++ {selectedVariant && (+ <div className="flex items-center justify-between rounded-lg border border-primary/30 bg-primary/5 p-3">+ <div>+ <div className="text-sm font-medium">+ {selectedVariant.product_name ?? selectedVariant.sku}+ </div>+ <div className="text-xs text-muted-foreground">+ {selectedVariant.options_text && (+ <span>{selectedVariant.options_text} · </span>+ )}+ {t('admin.orders.detail.variant_search.sku_prefix')}:{' '}+ {selectedVariant.sku || '—'} · {formatPrice(selectedVariant.price)}+ </div>+ </div>+ <button+ type="button"+ onClick={() => setSelectedVariant(null)}+ className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"+ aria-label={t('admin.a11y.clear_selection')}+ >+ <XCircleIcon className="size-4" />+ </button>+ </div>+ )}++ <Field>+ <FieldLabel htmlFor="quantity">{t('admin.fields.quantity.label')}</FieldLabel>+ <Input+ id="quantity"+ type="number"+ min={1}+ value={quantity}+ onChange={(e) => setQuantity(Number(e.target.value) || 1)}+ />+ </Field>+ </FieldGroup>+ </div>+ <SheetFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={!selectedVariant || mutation.isPending}>+ {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.add')}+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>+ )+}++/** Changes how many units of one line item the order carries. */+export function EditQuantityDialog({+ orderId,+ lineItemId,+ currentQuantity,+ open,+ onOpenChange,+}: {+ orderId: string+ lineItemId: string+ currentQuantity: number+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const mutation = useOrderMutation(orderId, (params: { quantity: number }) =>+ adminClient.orders.items.update(orderId, lineItemId, params),+ )++ function handleSubmit(e: FormEvent<HTMLFormElement>) {+ e.preventDefault()+ const fd = new FormData(e.currentTarget)+ mutation.mutate(+ { quantity: Number(fd.get('quantity')) || 1 },+ { onSuccess: () => onOpenChange(false) },+ )+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('admin.orders.detail.edit_quantity.title')}</DialogTitle>+ <DialogDescription>+ {t('admin.orders.detail.edit_quantity.description')}+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit}>+ <DialogBody>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="edit-quantity">{t('admin.fields.quantity.label')}</FieldLabel>+ <Input+ id="edit-quantity"+ name="quantity"+ type="number"+ min={1}+ defaultValue={currentQuantity}+ />+ </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>+ )+}diff --git a/packages/dashboard/src/lib/fulfillment-items.test.ts b/packages/dashboard/src/lib/fulfillment-items.test.tsnew file mode 100644index 0000000000..4879231d1f--- /dev/null+++ b/packages/dashboard/src/lib/fulfillment-items.test.ts@@ -0,0 +1,211 @@+import { describe, expect, it } from 'vitest'+import {+ fulfillmentItemRows,+ type GroupableFulfillment,+ type GroupableLineItem,+ hasFulfillableUnits,+ unfulfilledItemRows,+} from './fulfillment-items'++function lineItem(overrides: Partial<GroupableLineItem> = {}): GroupableLineItem {+ return {+ id: 'li_1',+ name: 'Shirt',+ options_text: 'Blue / M',+ quantity: 2,+ thumbnail_url: 'https://example.test/shirt.jpg',+ display_price: '$10.00',+ ...overrides,+ }+}++function fulfillment(overrides: Partial<GroupableFulfillment> = {}): GroupableFulfillment {+ return {+ status: 'pending',+ fulfillment_items: [],+ ...overrides,+ }+}++describe('fulfillmentItemRows', () => {+ it('joins a fulfillment item to its line item for the image and price', () => {+ const rows = fulfillmentItemRows(+ fulfillment({+ fulfillment_items: [{ line_item_id: 'li_1', variant_id: 'variant_1', quantity: 1 }],+ }),+ [lineItem()],+ )++ expect(rows).toEqual([+ {+ key: 'li_1',+ lineItem: expect.objectContaining({ id: 'li_1' }),+ name: 'Shirt',+ optionsText: 'Blue / M',+ thumbnailUrl: 'https://example.test/shirt.jpg',+ displayPrice: '$10.00',+ quantity: 1,+ },+ ])+ })++ it('merges several fulfillment items descending from one line item', () => {+ const rows = fulfillmentItemRows(+ fulfillment({+ fulfillment_items: [+ { line_item_id: 'li_1', quantity: 1 },+ { line_item_id: 'li_1', quantity: 2 },+ ],+ }),+ [lineItem({ quantity: 3 })],+ )++ expect(rows).toHaveLength(1)+ expect(rows[0].quantity).toBe(3)+ })++ it('falls back to the fulfillment item copy when the line item is missing', () => {+ const rows = fulfillmentItemRows(+ fulfillment({+ fulfillment_items: [+ { line_item_id: 'li_gone', name: 'Removed item', options_text: 'Red', quantity: 1 },+ ],+ }),+ [],+ )++ expect(rows[0]).toMatchObject({+ name: 'Removed item',+ optionsText: 'Red',+ thumbnailUrl: null,+ displayPrice: null,+ })+ })++ it('keys an item with no line item by its variant so it still renders', () => {+ const rows = fulfillmentItemRows(+ fulfillment({+ fulfillment_items: [{ variant_id: 'variant_9', name: 'Loose unit', quantity: 1 }],+ }),+ [],+ )++ expect(rows).toHaveLength(1)+ expect(rows[0].key).toBe('variant_9')+ })+})++describe('unfulfilledItemRows', () => {+ it('reports the quantity no fulfillment claims', () => {+ const rows = unfulfilledItemRows(+ [lineItem({ quantity: 5 })],+ [fulfillment({ fulfillment_items: [{ line_item_id: 'li_1', quantity: 2 }] })],+ )++ expect(rows).toHaveLength(1)+ expect(rows[0].quantity).toBe(3)+ })++ it('sums claims across several fulfillments', () => {+ const rows = unfulfilledItemRows(+ [lineItem({ quantity: 4 })],+ [+ fulfillment({ fulfillment_items: [{ line_item_id: 'li_1', quantity: 1 }] }),+ fulfillment({+ status: 'shipped',+ fulfillment_items: [{ line_item_id: 'li_1', quantity: 2 }],+ }),+ ],+ )++ expect(rows[0].quantity).toBe(1)+ })++ it('returns nothing when the fulfillments account for every unit', () => {+ const rows = unfulfilledItemRows(+ [lineItem({ quantity: 2 })],+ [fulfillment({ fulfillment_items: [{ line_item_id: 'li_1', quantity: 2 }] })],+ )++ expect(rows).toEqual([])+ })++ it('never reports a negative remainder', () => {+ const rows = unfulfilledItemRows(+ [lineItem({ quantity: 1 })],+ [fulfillment({ fulfillment_items: [{ line_item_id: 'li_1', quantity: 3 }] })],+ )++ expect(rows).toEqual([])+ })++ it('ignores fulfillment items that reference no line item', () => {+ const rows = unfulfilledItemRows(+ [lineItem({ quantity: 2 })],+ [fulfillment({ fulfillment_items: [{ variant_id: 'variant_1', quantity: 2 }] })],+ )++ expect(rows[0].quantity).toBe(2)+ })+})++describe('hasFulfillableUnits', () => {+ it('is true while units remain unclaimed', () => {+ expect(hasFulfillableUnits([lineItem({ quantity: 2 })], [])).toBe(true)+ })++ it('is true when a pending fulfillment still holds units to move', () => {+ expect(+ hasFulfillableUnits(+ [lineItem({ quantity: 2 })],+ [fulfillment({ fulfillment_items: [{ line_item_id: 'li_1', quantity: 2 }] })],+ ),+ ).toBe(true)+ })++ it('is false once every unit sits in a shipped fulfillment', () => {+ expect(+ hasFulfillableUnits(+ [lineItem({ quantity: 2 })],+ [+ fulfillment({+ status: 'shipped',+ fulfillment_items: [{ line_item_id: 'li_1', quantity: 2 }],+ }),+ ],+ ),+ ).toBe(false)+ })++ it('is false when a canceled fulfillment holds the units', () => {+ expect(+ hasFulfillableUnits(+ [lineItem({ quantity: 2 })],+ [+ fulfillment({+ status: 'canceled',+ fulfillment_items: [{ line_item_id: 'li_1', quantity: 2 }],+ }),+ ],+ ),+ ).toBe(false)+ })++ it('is false on an order with no items at all', () => {+ expect(hasFulfillableUnits([], [])).toBe(false)+ })++ it('counts a ready_for_pickup fulfillment as movable', () => {+ expect(+ hasFulfillableUnits(+ [lineItem({ quantity: 1 })],+ [+ fulfillment({+ status: 'ready_for_pickup',+ fulfillment_items: [{ line_item_id: 'li_1', quantity: 1 }],+ }),+ ],+ ),+ ).toBe(true)+ })+})diff --git a/packages/dashboard/src/lib/fulfillment-items.ts b/packages/dashboard/src/lib/fulfillment-items.tsnew file mode 100644index 0000000000..59edd42ce3--- /dev/null+++ b/packages/dashboard/src/lib/fulfillment-items.ts@@ -0,0 +1,170 @@+/**+ * Which line items sit in which fulfillment, and which units nobody has+ * claimed yet. The order payload describes the two halves separately —+ * `order.items` is the full basket, each fulfillment carries its own+ * `fulfillment_items` — so the card has to join them back together to say+ * what is being shipped where.+ */++/** The line-item fields the grouping reads. */+export interface GroupableLineItem {+ id: string+ name: string+ options_text?: string | null+ quantity: number+ thumbnail_url?: string | null+ display_price?: string | null+ display_total?: string | null+}++/** The fulfillment-item fields the grouping reads. */+export interface GroupableFulfillmentItem {+ line_item_id?: string | null+ variant_id?: string | null+ name?: string | null+ options_text?: string | null+ quantity: number+}++/** The fulfillment fields the grouping reads. */+export interface GroupableFulfillment {+ status: string+ fulfillment_items?: GroupableFulfillmentItem[] | null+}++/**+ * One row in a fulfillment's (or the unfulfilled group's) item list: the+ * line item it descends from, plus how many of its units this group holds.+ */+export interface FulfillmentItemRow {+ /** Stable within one group — a line item appears at most once per group. */+ key: string+ lineItem: GroupableLineItem | null+ /** Falls back to the fulfillment item's own copy when the line item is gone. */+ name: string+ optionsText: string | null+ thumbnailUrl: string | null+ displayPrice: string | null+ quantity: number+}++/**+ * Statuses whose units `Spree::Fulfillments::Create` will still move into a+ * new fulfillment. Anything shipped or canceled is settled and its units are+ * no longer fulfillable — mirrors `fulfillable_units` in+ * `spree/core/app/workflows/spree/fulfillments/create.rb`.+ */+const MOVABLE_STATUSES = ['pending', 'ready', 'ready_for_pickup']++/**+ * Sums, per line item, how many units every fulfillment claims. Fulfillment+ * items that reference no line item are skipped — there is nothing to join+ * them to, and counting them would understate the remainder.+ */+function claimedQuantities(fulfillments: GroupableFulfillment[]): Map<string, number> {+ const claimed = new Map<string, number>()++ for (const fulfillment of fulfillments) {+ for (const item of fulfillment.fulfillment_items ?? []) {+ if (!item.line_item_id) continue+ claimed.set(item.line_item_id, (claimed.get(item.line_item_id) ?? 0) + item.quantity)+ }+ }++ return claimed+}++/** Builds a row, preferring the line item's own copy over the fulfillment item's. */+function buildRow(+ key: string,+ lineItem: GroupableLineItem | undefined,+ fallback: Pick<GroupableFulfillmentItem, 'name' | 'options_text'> | null,+ quantity: number,+): FulfillmentItemRow {+ return {+ key,+ lineItem: lineItem ?? null,+ name: lineItem?.name ?? fallback?.name ?? '',+ optionsText: lineItem?.options_text ?? fallback?.options_text ?? null,+ thumbnailUrl: lineItem?.thumbnail_url ?? null,+ displayPrice: lineItem?.display_price ?? null,+ quantity,+ }+}++/**+ * The items one fulfillment holds, joined to their line items for the image+ * and the price the fulfillment item does not carry. Several fulfillment+ * items can descend from the same line item (units split by on-hand versus+ * backordered status), so they are merged into a single row.+ */+export function fulfillmentItemRows(+ fulfillment: GroupableFulfillment,+ lineItems: GroupableLineItem[],+): FulfillmentItemRow[] {+ const byId = new Map(lineItems.map((lineItem) => [lineItem.id, lineItem]))+ const rows = new Map<string, FulfillmentItemRow>()++ for (const item of fulfillment.fulfillment_items ?? []) {+ // A fulfillment item with no line item still ships; key it by variant so+ // it renders rather than vanishing.+ const key = item.line_item_id ?? item.variant_id+ if (!key) continue++ const existing = rows.get(key)+ if (existing) {+ existing.quantity += item.quantity+ continue+ }++ rows.set(+ key,+ buildRow(+ key,+ item.line_item_id ? byId.get(item.line_item_id) : undefined,+ item,+ item.quantity,+ ),+ )+ }++ return [...rows.values()]+}++/**+ * Line-item units no fulfillment has claimed: the ordered quantity minus what+ * every fulfillment holds. Only positive remainders are returned, so an order+ * whose fulfillments account for everything yields an empty list.+ */+export function unfulfilledItemRows(+ lineItems: GroupableLineItem[],+ fulfillments: GroupableFulfillment[],+): FulfillmentItemRow[] {+ const claimed = claimedQuantities(fulfillments)++ return lineItems.flatMap((lineItem) => {+ const remainder = lineItem.quantity - (claimed.get(lineItem.id) ?? 0)+ if (remainder <= 0) return []++ return [buildRow(lineItem.id, lineItem, null, remainder)]+ })+}++/**+ * Whether anything is left to put into a new fulfillment: either units nobody+ * has claimed, or units sitting in a fulfillment that has not shipped yet and+ * can therefore still be moved. Without this the create workflow would happily+ * build an empty fulfillment on a fully shipped order.+ */+export function hasFulfillableUnits(+ lineItems: GroupableLineItem[],+ fulfillments: GroupableFulfillment[],+): boolean {+ const movable = fulfillments.some(+ (fulfillment) =>+ MOVABLE_STATUSES.includes(fulfillment.status) &&+ (fulfillment.fulfillment_items ?? []).some((item) => item.quantity > 0),+ )++ return movable || unfulfilledItemRows(lineItems, fulfillments).length > 0+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex f42782fdad..14e11fec97 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1822,6 +1822,7 @@"resume_failed": "فشل في استئناف الطلب"},"fulfillments": {+ "add_item": "إضافة عنصر","confirm_split": "نقل هذه الوحدات إلى شحنة جديدة؟ يسري هذا فوراً.","create_description": "تنشئ شحنة وتنقل إليها الكميات المختارة.","create_items": "العناصر",@@ -1841,7 +1842,8 @@"split_item": "المنتج","split_quantity": "الكمية المراد نقلها","split_title": "تقسيم الشحنة",- "split_would_empty": "اترك وحدة واحدة على الأقل، أو غيّر مصدر الشحنة بالكامل بدلاً من ذلك."+ "split_would_empty": "اترك وحدة واحدة على الأقل، أو غيّر مصدر الشحنة بالكامل بدلاً من ذلك.",+ "unfulfilled_other": "غير مُنفَّذ ({{count}})"},"gift_card_section": {"applied_suffix": "مُطبَّق",@@ -1856,9 +1858,7 @@"title": "الخصومات والرصيد"},"items_table": {- "item": "غرض",- "price": "سعر",- "qty": "الكمية"+ "item_actions": "إجراءات لـ {{name}}"},"load_failed_message": "لم نتمكن من تحميل الطلب {{orderId}}.","messages": {@@ -1872,7 +1872,6 @@"voided": "تم إلغاء الدفع"},"no_customer": "لا توجد معلومات العميل",- "no_line_items": "لا توجد عناصر","payment_form": {"amount_help": "اتركه فارغًا لتقصير الرصيد المستحق.","capture_immediately": "التقط على الفور",@@ -2180,7 +2179,6 @@"section_fulfillments": "عمليات التنفيذ","section_history": "تاريخ","section_internal_note": "ملاحظة داخلية",- "section_items": "أغراض","section_payments": "المدفوعات","section_returns": "المرتجعات","section_shipping_address": "عنوان الشحن",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex d74f9ba609..319d0c3efc 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1811,6 +1811,7 @@"resume_failed": "Auftrag konnte nicht wieder aufgenommen werden"},"fulfillments": {+ "add_item": "Artikel hinzufügen","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",@@ -1830,7 +1831,9 @@"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."+ "split_would_empty": "Lassen Sie mindestens eine Einheit zurück oder ändern Sie stattdessen den Ursprung der gesamten Sendung.",+ "unfulfilled_one": "Nicht versandt ({{count}})",+ "unfulfilled_other": "Nicht versandt ({{count}})"},"gift_card_section": {"applied_suffix": "angewendet",@@ -1845,9 +1848,7 @@"title": "Rabatte & Guthaben"},"items_table": {- "item": "Artikel",- "price": "Preis",- "qty": "Anz."+ "item_actions": "Aktionen für {{name}}"},"load_failed_message": "Auftrag {{orderId}} konnte nicht geladen werden.","messages": {@@ -1861,7 +1862,6 @@"voided": "Zahlung storniert"},"no_customer": "Keine Kundeninformationen",- "no_line_items": "Keine Positionen","payment_form": {"amount_help": "Leer lassen, um standardmäßig den offenen Saldo zu verwenden.","capture_immediately": "Sofort einziehen",@@ -2169,7 +2169,6 @@"section_fulfillments": "Fulfillments","section_history": "Verlauf","section_internal_note": "Interne Notiz",- "section_items": "Artikel","section_payments": "Zahlungen","section_returns": "Retouren","section_shipping_address": "Lieferadresse",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 1ae6d12e81..14c7dbf2f3 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1811,6 +1811,7 @@"resume_failed": "Failed to resume order"},"fulfillments": {+ "add_item": "Add item","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",@@ -1830,7 +1831,9 @@"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."+ "split_would_empty": "Leave at least one unit behind, or change the origin of the whole fulfillment instead.",+ "unfulfilled_one": "Unfulfilled ({{count}})",+ "unfulfilled_other": "Unfulfilled ({{count}})"},"gift_card_section": {"applied_suffix": "applied",@@ -1845,9 +1848,7 @@"title": "Discounts & Credit"},"items_table": {- "item": "Item",- "price": "Price",- "qty": "Qty"+ "item_actions": "Actions for {{name}}"},"load_failed_message": "We couldn't load order {{orderId}}.","messages": {@@ -1861,7 +1862,6 @@"voided": "Payment voided"},"no_customer": "No customer information",- "no_line_items": "No line items","payment_form": {"amount_help": "Leave blank to default to the outstanding balance.","capture_immediately": "Capture immediately",@@ -2169,7 +2169,6 @@"section_fulfillments": "Fulfillments","section_history": "History","section_internal_note": "Internal note",- "section_items": "Items","section_payments": "Payments","section_returns": "Returns","section_shipping_address": "Shipping address",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 1e6933f1a1..7763fbedca 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1811,6 +1811,7 @@"resume_failed": "Échec de la reprise de la commande"},"fulfillments": {+ "add_item": "Ajouter un article","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",@@ -1830,7 +1831,9 @@"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."+ "split_would_empty": "Laissez au moins une unité, ou modifiez plutôt l'origine de toute l'expédition.",+ "unfulfilled_one": "Non expédié ({{count}})",+ "unfulfilled_other": "Non expédiés ({{count}})"},"gift_card_section": {"applied_suffix": "appliqué",@@ -1845,9 +1848,7 @@"title": "Remises et avoirs"},"items_table": {- "item": "Article",- "price": "Prix",- "qty": "Qté"+ "item_actions": "Actions pour {{name}}"},"load_failed_message": "Impossible de charger la commande {{orderId}}.","messages": {@@ -1861,7 +1862,6 @@"voided": "Paiement annulé"},"no_customer": "Aucune information client",- "no_line_items": "Aucun article","payment_form": {"amount_help": "Laissez vide pour utiliser par défaut le solde restant dû.","capture_immediately": "Capturer immédiatement",@@ -2169,7 +2169,6 @@"section_fulfillments": "Traitements","section_history": "Historique","section_internal_note": "Note interne",- "section_items": "Articles","section_payments": "Paiements","section_returns": "Retours","section_shipping_address": "Adresse de livraison",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 1125d0a3ad..a311985e4d 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1827,6 +1827,7 @@"resume_failed": "Nie udało się wznowić zamówienia"},"fulfillments": {+ "add_item": "Dodaj pozycję","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",@@ -1846,7 +1847,11 @@"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."+ "split_would_empty": "Pozostaw co najmniej jedną sztukę albo zmień miejsce wysyłki całej przesyłki.",+ "unfulfilled_few": "Niezrealizowane ({{count}})",+ "unfulfilled_many": "Niezrealizowane ({{count}})",+ "unfulfilled_one": "Niezrealizowane ({{count}})",+ "unfulfilled_other": "Niezrealizowane ({{count}})"},"gift_card_section": {"applied_suffix": "zastosowano",@@ -1861,9 +1866,7 @@"title": "Rabaty i środki"},"items_table": {- "item": "Pozycja",- "price": "Cena",- "qty": "Ilość"+ "item_actions": "Akcje dla {{name}}"},"load_failed_message": "Nie udało się załadować zamówienia {{orderId}}.","messages": {@@ -1877,7 +1880,6 @@"voided": "Płatność unieważniona"},"no_customer": "Brak informacji o kliencie",- "no_line_items": "Brak pozycji","payment_form": {"amount_help": "Pozostaw puste, aby użyć domyślnie pozostałego salda.","capture_immediately": "Pobierz natychmiast",@@ -2187,7 +2189,6 @@"section_fulfillments": "Realizacje","section_history": "Historia","section_internal_note": "Notatka wewnętrzna",- "section_items": "Pozycje","section_payments": "Płatności","section_returns": "Zwroty","section_shipping_address": "Adres dostawy",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex aae7af9355..b4b958fb8d 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1808,6 +1808,7 @@"resume_failed": "恢复订单失败"},"fulfillments": {+ "add_item": "添加商品","confirm_split": "将这些数量移入新的发货单?此操作立即生效。","create_description": "创建发货单并将所选数量移入其中。","create_items": "商品项",@@ -1827,7 +1828,8 @@"split_item": "商品","split_quantity": "移动数量","split_title": "拆分发货单",- "split_would_empty": "请至少保留一件,或改为修改整个发货单的发货地。"+ "split_would_empty": "请至少保留一件,或改为修改整个发货单的发货地。",+ "unfulfilled_other": "未发货({{count}})"},"gift_card_section": {"applied_suffix": "已应用",@@ -1842,9 +1844,7 @@"title": "折扣与余额"},"items_table": {- "item": "商品",- "price": "价格",- "qty": "数量"+ "item_actions": "{{name}} 的操作"},"load_failed_message": "无法加载订单 {{orderId}}。","messages": {@@ -1858,7 +1858,6 @@"voided": "付款已作废"},"no_customer": "无客户信息",- "no_line_items": "无订单项","payment_form": {"amount_help": "留空则默认为未结清的余额。","capture_immediately": "立即扣款",@@ -2166,7 +2165,6 @@"section_fulfillments": "履约单","section_history": "历史记录","section_internal_note": "内部备注",- "section_items": "商品","section_payments": "付款","section_returns": "退货","section_shipping_address": "收货地址",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex 3eeedf20dd..94832b9d1d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -1,4 +1,4 @@-import type { Discount, Fee, Order, Variant } from '@spree/admin-sdk'+import type { Discount, Fee, Order } from '@spree/admin-sdk'import {AddressFormDialog,type AddressParams,@@ -51,12 +51,6 @@ import {SelectTrigger,SelectValue,Separator,- Sheet,- SheetContent,- SheetDescription,- SheetFooter,- SheetHeader,- SheetTitle,Skeleton,StatusBadge,Switch,@@ -78,12 +72,10 @@ import {EllipsisVerticalIcon,ExternalLinkIcon,MailIcon,- PackageIcon,PencilIcon,PlusIcon,RotateCcwIcon,ShieldCheckIcon,- ShoppingCartIcon,TrashIcon,XCircleIcon,} from 'lucide-react'@@ -156,7 +148,6 @@ function OrderDetailPage() {header={<OrderHeader order={order} />}main={<>- <LineItemsCard order={order} /><FulfillmentsCard order={order} /><OrderReturnsCard order={order} /><OrderExchangesCard order={order} />@@ -363,375 +354,6 @@ function OrderHeader({ order }: { order: Order }) {)}-// ----------------------------------------------------------------------------// Line Items-// -----------------------------------------------------------------------------function AddLineItemDialog({- orderId,- open,- onOpenChange,-}: {- orderId: string- open: boolean- onOpenChange: (open: boolean) => void-}) {- const { t } = useTranslation()- const [search, setSearch] = useState('')- const [selectedVariant, setSelectedVariant] = useState<Variant | null>(null)- const [quantity, setQuantity] = useState(1)-- const { data: variantsData } = useQuery({- queryKey: ['variants', 'search', search],- queryFn: () => adminClient.variants.list({ search, limit: 10 }),- enabled: search.length >= 3,- staleTime: 30_000,- })-- const variants = variantsData?.data ?? []-- const mutation = useOrderMutation(orderId, (params: { variant_id: string; quantity: number }) =>- adminClient.orders.items.create(orderId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- if (!selectedVariant) return- mutation.mutate(- { variant_id: selectedVariant.id, quantity },- {- onSuccess: () => {- onOpenChange(false)- setSelectedVariant(null)- setSearch('')- setQuantity(1)- },- },- )- }-- return (- <Sheet open={open} onOpenChange={(o) => onOpenChange(o as boolean)}>- <SheetContent side="right">- <SheetHeader>- <SheetTitle>{t('admin.orders.detail.add_line_item.title')}</SheetTitle>- <SheetDescription>{t('admin.orders.detail.variant_search.description')}</SheetDescription>- </SheetHeader>- <form onSubmit={handleSubmit} className="flex flex-col flex-1 overflow-hidden">- <div className="flex-1 overflow-y-auto p-4">- <FieldGroup>- <Field>- <FieldLabel>{t('admin.orders.detail.variant_search.label')}</FieldLabel>- <Input- placeholder={t('admin.orders.detail.variant_search.placeholder')}- value={search}- onChange={(e) => {- setSearch(e.target.value)- setSelectedVariant(null)- }}- autoFocus- />- {search.length >= 3 && variants.length > 0 && !selectedVariant && (- <div className="mt-1 rounded-lg border border-border bg-popover text-popover-foreground shadow-xs max-h-[280px] overflow-y-auto">- {variants.map((v) => (- <button- key={v.id}- type="button"- onClick={() => {- setSelectedVariant(v)- setSearch('')- }}- className="flex w-full items-center gap-3 px-3 py-2.5 text-left text-sm hover:bg-muted transition-colors border-b last:border-0"- >- <div className="min-w-0 flex-1">- <div className="font-medium truncate">{v.product_name ?? v.sku}</div>- <div className="text-xs text-muted-foreground">- {v.options_text && <span>{v.options_text} · </span>}- {t('admin.orders.detail.variant_search.sku_prefix')}: {v.sku || '—'}- </div>- </div>- <div className="text-sm font-medium whitespace-nowrap">- {formatPrice(v.price)}- </div>- </button>- ))}- </div>- )}- {search.length >= 3 && variants.length === 0 && !selectedVariant && (- <p className="mt-1 text-xs text-muted-foreground">- {t('admin.orders.detail.variant_search.empty')}- </p>- )}- </Field>-- {selectedVariant && (- <div className="flex items-center justify-between rounded-lg border border-primary/30 bg-primary/5 p-3">- <div>- <div className="text-sm font-medium">- {selectedVariant.product_name ?? selectedVariant.sku}- </div>- <div className="text-xs text-muted-foreground">- {selectedVariant.options_text && (- <span>{selectedVariant.options_text} · </span>- )}- {t('admin.orders.detail.variant_search.sku_prefix')}:{' '}- {selectedVariant.sku || '—'} · {formatPrice(selectedVariant.price)}- </div>- </div>- <button- type="button"- onClick={() => setSelectedVariant(null)}- className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"- aria-label={t('admin.a11y.clear_selection')}- >- <XCircleIcon className="size-4" />- </button>- </div>- )}-- <Field>- <FieldLabel htmlFor="quantity">{t('admin.fields.quantity.label')}</FieldLabel>- <Input- id="quantity"- type="number"- min={1}- value={quantity}- onChange={(e) => setQuantity(Number(e.target.value) || 1)}- />- </Field>- </FieldGroup>- </div>- <SheetFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- {t('admin.actions.cancel')}- </Button>- <Button type="submit" disabled={!selectedVariant || mutation.isPending}>- {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.add')}- </Button>- </SheetFooter>- </form>- </SheetContent>- </Sheet>- )-}--function EditQuantityDialog({- orderId,- lineItemId,- currentQuantity,- open,- onOpenChange,-}: {- orderId: string- lineItemId: string- currentQuantity: number- open: boolean- onOpenChange: (open: boolean) => void-}) {- const { t } = useTranslation()- const mutation = useOrderMutation(orderId, (params: { quantity: number }) =>- adminClient.orders.items.update(orderId, lineItemId, params),- )-- function handleSubmit(e: FormEvent<HTMLFormElement>) {- e.preventDefault()- const fd = new FormData(e.currentTarget)- mutation.mutate(- { quantity: Number(fd.get('quantity')) || 1 },- { onSuccess: () => onOpenChange(false) },- )- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t('admin.orders.detail.edit_quantity.title')}</DialogTitle>- <DialogDescription>- {t('admin.orders.detail.edit_quantity.description')}- </DialogDescription>- </DialogHeader>- <form onSubmit={handleSubmit}>- <DialogBody>- <FieldGroup>- <Field>- <FieldLabel htmlFor="edit-quantity">{t('admin.fields.quantity.label')}</FieldLabel>- <Input- id="edit-quantity"- name="quantity"- type="number"- min={1}- defaultValue={currentQuantity}- />- </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 LineItemsCard({ order }: { order: Order }) {- const { t } = useTranslation()- const { orderId } = Route.useParams()- const confirm = useConfirm()-- const items = order.items ?? []- const [addOpen, setAddOpen] = useState(false)- const [editItem, setEditItem] = useState<{ id: string; quantity: number } | null>(null)-- const deleteMutation = useOrderMutation(orderId, (lineItemId: string) =>- adminClient.orders.items.delete(orderId, lineItemId),- )-- return (- <>- <Card>- <CardHeader>- <CardTitle>- <ShoppingCartIcon className="size-4" />- {t('admin.pages.orders.detail.section_items')}- {items.length > 0 && <Badge variant="outline">{items.length}</Badge>}- </CardTitle>- <CardAction className="flex items-center gap-2">- <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>- <PlusIcon data-icon="inline-start" />- {t('admin.actions.add')}- </Button>- </CardAction>- </CardHeader>- {items.length > 0 ? (- <div className="overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="border-b bg-muted/50 text-muted-foreground">- <th className="p-3 pl-5 text-left font-normal">- {t('admin.orders.detail.items_table.item')}- </th>- <th className="p-3 text-right font-normal">- {t('admin.orders.detail.items_table.price')}- </th>- <th className="p-3 text-right font-normal">- {t('admin.orders.detail.items_table.qty')}- </th>- <th className="p-3 text-right font-normal">{t('admin.fields.tax.label')}</th>- <th className="p-3 text-right font-normal">{t('admin.fields.discount.label')}</th>- <th className="p-3 text-right font-normal">{t('admin.fields.total.label')}</th>- <th className="p-3 pr-5 w-10" />- </tr>- </thead>- <tbody>- {items.map((item) => (- <tr key={item.id} className="border-b last:border-b-0">- <td className="p-3 pl-5">- <div className="flex items-center gap-3">- {item.thumbnail_url ? (- <img- src={item.thumbnail_url}- alt={item.name}- className="size-10 rounded-lg border object-cover"- />- ) : (- <div className="flex size-10 items-center justify-center rounded-lg border bg-muted">- <PackageIcon className="size-4 text-muted-foreground" />- </div>- )}- <div className="min-w-0">- <div className="truncate font-medium">{item.name}</div>- {item.options_text && (- <div className="truncate text-xs text-muted-foreground">- {item.options_text}- </div>- )}- </div>- </div>- </td>- <td className="p-3 text-right whitespace-nowrap">{item.display_price}</td>- <td className="p-3 text-right">{item.quantity}</td>- <td className="p-3 text-right whitespace-nowrap">- {item.display_additional_tax_total}- </td>- <td className="p-3 text-right whitespace-nowrap">- {Number.parseFloat(item.discount_total) !== 0- ? item.display_discount_total- : '—'}- </td>- <td className="p-3 text-right font-medium whitespace-nowrap">- {item.display_total}- </td>- <td className="p-3 pr-5">- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="ghost" size="icon-xs">- <EllipsisVerticalIcon className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- <DropdownMenuItem- onClick={() => setEditItem({ id: item.id, quantity: item.quantity })}- >- <PencilIcon className="size-4" />- {t('admin.orders.detail.dropdown.edit_quantity')}- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- className="text-destructive focus:text-destructive"- onClick={async () => {- if (- await confirm({- message: t('admin.orders.detail.confirm.remove_item_message'),- variant: 'destructive',- confirmLabel: t('admin.actions.remove'),- })- ) {- deleteMutation.mutate(item.id)- }- }}- >- <TrashIcon className="size-4" />- {t('admin.actions.remove')}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </td>- </tr>- ))}- </tbody>- </table>- </div>- ) : (- <CardContent>- <p className="text-center text-muted-foreground py-8">- {t('admin.orders.detail.no_line_items')}- </p>- </CardContent>- )}- </Card>-- <AddLineItemDialog orderId={orderId} open={addOpen} onOpenChange={setAddOpen} />-- {editItem && (- <EditQuantityDialog- orderId={orderId}- lineItemId={editItem.id}- currentQuantity={editItem.quantity}- open={!!editItem}- onOpenChange={(open) => !open && setEditItem(null)}- />- )}- </>- )-}-// ---------------------------------------------------------------------------// Payments// ---------------------------------------------------------------------------