Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Stage order edits and apply them together on Save

Damian Legawiec93e547993b73
diff --git a/CLAUDE.md b/CLAUDE.md
index b702410703..a130acbe61 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -52,7 +52,7 @@ Multi-version plans (some phases shipped, some pending):
- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.
Pending design work (drafts, no implementation yet):
-- `6.1-order-change-substrate.md` — `Spree::OrderChange` + `Spree::OrderChangeAction`: one preview-then-apply substrate behind every post-placement mutation (admin order edits, returns, exchanges, claims, draft-order amendments), replacing four per-domain draft models with one `begin → request → confirm → cancel` lifecycle. Actions are typed `kind` + concrete FKs (never polymorphic); **preview is computed in memory and never persisted**; confirm is a workflow with the balance settlement as an `external_step`. Deliberately 6.1 — new schema + new extension API, and 6.0 already carries the Cart/Order split, typed adjustments and the returns rework. **Resolved 2026-08-10:** a change set belongs to one `Order`, never an `OrderGroup` (multi-vendor edits = N change sets, each settling against its own order); a pending change set does **not** hold stock (`add_item` takes stock at confirm — reservations are checkout-scoped and would have no expiry trigger here). Phase 3 replaces the **6.0 immediate-write order edit screen** (`/orders/$orderId/edit`, shipped 2026-08-10) — it writes on every interaction and shows no delta, and Phase 3 adds `begin`/preview/`confirm` behind the same route. 6.0 constraints: don't build a per-domain persisted preview/draft model (including a client-side pending-edit buffer in React state), expose post-placement money math through a service returning a value object, and keep line-item mutation on the edit screen rather than the fulfillment card.
+- `6.1-order-change-substrate.md` — `Spree::OrderChange` + `Spree::OrderChangeAction`: one preview-then-apply substrate behind every post-placement mutation (admin order edits, returns, exchanges, claims, draft-order amendments), replacing four per-domain draft models with one `begin → request → confirm → cancel` lifecycle. Actions are typed `kind` + concrete FKs (never polymorphic); **preview is computed in memory and never persisted**; confirm is a workflow with the balance settlement as an `external_step`. Deliberately 6.1 — new schema + new extension API, and 6.0 already carries the Cart/Order split, typed adjustments and the returns rework. **Resolved 2026-08-10:** a change set belongs to one `Order`, never an `OrderGroup` (multi-vendor edits = N change sets, each settling against its own order); a pending change set does **not** hold stock (`add_item` takes stock at confirm — reservations are checkout-scoped and would have no expiry trigger here). Phase 3 replaces the **6.0 order edit screen** (`/orders/$orderId/edit`) — quantities as inputs, `x` marks a row removed, Save applies the batch (**reshaped 2026-08-11**, reversing the original immediate-write rule); Phase 3 adds `begin`/preview/`confirm` behind the Save/Discard it already has. 6.0 constraints: don't **persist** a draft/preview model (transient React form state is fine and is the shape the substrate wants), don't compute projected totals client-side to fake a preview, expose post-placement money math through a service returning a value object, and keep line-item mutation on the edit screen rather than the fulfillment card. Known gap: the batch save is not atomic (no bulk endpoint; Phase 3's `Confirm` fixes it in one transaction).
- `6.0-payment-method-rules.md` — `Spree::PaymentMethodRule` STI on PaymentMethod (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the PromotionRule/PriceRule/OrderRoutingRule pattern. Enforced solely through `Order#collect_frontend_payment_methods` (listing + `Payments::Create` + payment sessions all flow through it); admin/backoffice bypasses; no rules = available everywhere. Dashboard-only management (nested Admin API CRUD + `/payment_method_rules/types` discovery). Supersedes the "no distribution concept" rationale in `5.6-6.0-single-store-promotions-payment-methods.md`; per-channel provider credentials (multiple Stripe accounts, multi-entity setups) explicitly deferred for grooming — see decisions.md 2026-07-23.
- `6.0-channel-delivery.md` — **Implemented in PR #14404 (2026-08-09).** Optional Channel→StockLocations allowlist (`spree_channel_stock_locations`, empty = all): constrains which fulfillment origins serve a channel's traffic, enforced origin-side (Coordinator allocation + pickup discovery intersect `Channel#serves_location?`) — never on profiles/groups (channel constraint composes from outside; Medusa-shaped transitive delivery). `preferred_stock_location_id` must be a served location. **Per-channel rates** are a separate axis: `DeliveryMethodRules::ChannelRule` (STI, beside ItemTotal/Weight/ExcludedProducts) gates which methods a channel is *offered* from origins it already reaches — origins decide whether a channel can be served, rules decide what it sees.
- `6.0-channel-markets.md` — Optional Channel→Markets allowlist (`spree_channel_markets` join, empty = all markets). Enforced in market resolution (`set_market_from_country` + channel-aware `Spree::Current.market` fallback), channel-filtered Store API `/store/markets`, and order-level `market must be served by channel` validation. Composes with `MarketRule` from the payment-method-rules plan.
diff --git a/docs/plans/6.1-order-change-substrate.md b/docs/plans/6.1-order-change-substrate.md
index a46bcc15da..0b1689ab58 100644
--- a/docs/plans/6.1-order-change-substrate.md
+++ b/docs/plans/6.1-order-change-substrate.md
@@ -280,27 +280,48 @@ migrate, it is the simplest financially (add/remove/update items, re-settle the
difference), and it immediately replaces the current post-placement edit path
that writes rows directly and re-sums.
-**What it replaces (shipped in 6.0, 2026-08-10):** a dedicated admin order edit
-screen at `/orders/$orderId/edit` that manages line items — add, remove, change
-quantity — against a placed order. It writes immediately: each mutation hits the
-existing line-item endpoints and the order re-sums server-side, so the merchant
-sees the new totals only *after* committing. There is no preview, no pending
-change set and no persisted draft, because 6.0 cannot project totals without
-writing rows.
-
-That screen exists because merchants need post-placement line-item editing in
-6.0 and the fulfillment card is the wrong home for it (the card manages
-fulfillments; the edit screen manages what the order contains). Its money math
-goes through a value-object-returning service specifically so Phase 3 can
-re-point it at `OrderChanges::Preview` without touching callers, per the
-constraint below.
-
-Phase 3 keeps the screen and its route, and changes what sits behind it:
-`begin` on entry, an action per edit, `Preview` driving a live totals delta, and
-`confirm`/`cancel` on the footer buttons. The immediate-write path becomes the
-`confirm` of a single-action change set. Expect the UI diff to be additive —
-the delta display and the explicit save/discard footer are what 6.0 cannot
-offer.
+**What it replaces (shipped in 6.0, 2026-08-10; reshaped 2026-08-11):** a
+dedicated admin order edit screen at `/orders/$orderId/edit` that manages line
+items — add, remove, change quantity — against a placed order.
+
+The screen **stages edits and applies them on Save.** Quantities are inputs, a
+row's `×` marks it removed (struck through, reversible until save), and Save
+applies the batch while Discard drops it. There is still no preview and no
+persisted draft: the projected totals cannot be computed in 6.0, so the totals
+card shows the order's current figures and re-reads after the save lands.
+
+*This reverses the original constraint that the screen must write immediately,
+one interaction per request (see decisions.md 2026-08-11).* That rule was
+written to forbid a **persisted** per-domain draft — a shadow order in the
+database that Phase 3 would have to migrate — and wrongly extended to transient
+form state. A React form holding "quantity 2 → 3, line 4 removed" until submit
+persists nothing, so there is nothing for Phase 3 to unpick; it is the same
+dirty-tracked form pattern used across the dashboard. Immediate writes were also
+worse on their own terms: every quantity keystroke fired a request and re-summed
+the order, and removing a line was irreversible behind a confirm dialog.
+
+Staged edits are the *better* fit for the substrate, not a worse one.
+`OrderChange` is `begin → request → confirm → cancel` — accumulate actions, then
+confirm — so a screen that already batches behind Save maps onto it directly.
+The immediate-write shape is the one that would have needed reshaping, having no
+confirm moment at all.
+
+Its money math goes through a value-object-returning service specifically so
+Phase 3 can re-point it at `OrderChanges::Preview` without touching callers, per
+the constraint below.
+
+**Known 6.0 limitation:** the batch is not atomic. There is no bulk line-item
+endpoint, so Save issues N calls against the existing per-item create/update/
+delete routes; a failure partway leaves earlier writes applied. The screen
+reports what succeeded and keeps the rest staged. Phase 3 fixes this for free —
+`OrderChanges::Confirm` applies every action in one transaction, which is a
+reason to prefer the substrate over adding a bulk endpoint now.
+
+Phase 3 keeps the screen, its route and its staged-edit shape, and changes what
+sits behind it: `begin` on entry, an action per staged edit, `Preview` driving a
+live totals delta, and `confirm`/`cancel` behind the Save/Discard the screen
+already has. Expect the UI diff to be additive — the delta display is the main
+thing 6.0 cannot offer.
### Phase 4 — returns, exchanges, claims adopt it
@@ -331,11 +352,15 @@ These apply during 6.0, before any of this is implemented:
- **New post-placement flows expose their money math through a service that
returns a value object**, so it can be re-pointed at `OrderChanges::Preview`
in 6.1 without changing callers.
-- **The 6.0 order edit screen writes immediately and shows no delta.** Do not
- add a client-side pending-edit buffer to fake a preview — accumulating edits
- in React state and submitting them together is a per-domain draft living in
- the browser, and it would have to be unpicked for Phase 3. One interaction,
- one request, totals re-read from the server.
+- **Do not persist a draft; transient form state is fine** (revised 2026-08-11,
+ reversing "the 6.0 edit screen writes immediately"). The prohibition is on a
+ *persisted* shadow order — a draft model, a pending-changes table, anything
+ Phase 3 would have to migrate. Staging edits in component state until the
+ merchant hits Save persists nothing and is the shape the substrate wants, so
+ the order edit screen batches its writes. What remains forbidden: computing a
+ projected total client-side to fake a preview (6.0 cannot project totals, and
+ a hand-rolled approximation would disagree with the server), and any schema
+ that stores pending edits.
- **Post-placement line-item mutation belongs to the edit screen, not the
fulfillment card.** The card manages fulfillments (what ships, from where,
under which method); the edit screen manages what the order contains. Keeping
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 5139d8453d..b2529c8574 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,43 @@
+## 2026-08-11: The order edit screen stages edits and saves in bulk (reverses 2026-08-10)
+
+The 6.0 admin order edit screen was specified to write immediately — one
+interaction, one request — and shipped that way: a dialog per quantity change, a
+confirm dialog per removal. That is the wrong shape for an order editor and the
+constraint behind it was wrong.
+
+It now works as a form. Quantities are inputs, a row's `x` marks it removed
+(struck through, reversible), Save applies the batch and Discard drops it.
+
+**Why the original constraint was wrong.** It existed to forbid a *persisted*
+per-domain draft: a shadow order in the database that
+`6.1-order-change-substrate.md` Phase 3 would have to migrate onto `OrderChange`.
+That reasoning holds. But it was extended to cover transient React form state,
+which is a different thing entirely — a form holding "quantity 2 -> 3, line 4
+removed" until submit persists nothing, so there is nothing to unpick later. It
+is the same dirty-tracked form pattern the dashboard uses everywhere else.
+
+**Staged edits fit the substrate better, not worse.** `OrderChange` is
+`begin -> request -> confirm -> cancel`: accumulate actions, then confirm. A
+screen that already batches behind Save maps onto that directly, and Phase 3
+becomes additive (a totals delta, `begin` on entry). The immediate-write version
+is the one that would have needed reshaping, having no confirm moment at all.
+
+**Immediate writes were also worse on their own terms.** Every keystroke in a
+quantity field fired a request and re-summed the order server-side, and removing
+a line was irreversible with only a confirm dialog in the way. Staging gives the
+merchant a Discard.
+
+**Accepted limitation.** There is no bulk line-item endpoint, so Save issues N
+calls against the existing per-item routes and a mid-batch failure leaves
+earlier writes applied. The screen reports what succeeded and keeps the rest
+staged. Deliberately not fixed with a new bulk endpoint: Phase 3's
+`OrderChanges::Confirm` applies every action in one transaction, so building one
+now would be work thrown away.
+
+**What stays forbidden:** persisting pending edits in any schema, and computing
+a projected total client-side to fake a preview — 6.0 cannot project totals, and
+an approximation would disagree with the server.
+
## 2026-08-10: Fulfillment side effects move to workflows; the state machine keeps the status column
Answers "should Fulfillment follow Order and lose its state machine?" with
diff --git a/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx b/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx
index 5fea3e68cb..538a31a015 100644
--- a/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx
+++ b/packages/dashboard/src/components/spree/orders/line-item-dialogs.tsx
@@ -2,13 +2,6 @@ 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,
@@ -24,17 +17,20 @@ 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. */
+/**
+ * Catalog picker for the order edit screen. It writes nothing — the chosen
+ * variant and quantity are handed back to the caller, which stages them as a
+ * pending row until the merchant saves the order.
+ */
export function AddLineItemDialog({
- orderId,
open,
onOpenChange,
+ onSelect,
}: {
- orderId: string
open: boolean
onOpenChange: (open: boolean) => void
+ onSelect: (variant: Variant, quantity: number) => void
}) {
const { t } = useTranslation()
const [search, setSearch] = useState('')
@@ -50,24 +46,15 @@ export function AddLineItemDialog({
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()
+ e.stopPropagation()
if (!selectedVariant) return
- mutation.mutate(
- { variant_id: selectedVariant.id, quantity },
- {
- onSuccess: () => {
- onOpenChange(false)
- setSelectedVariant(null)
- setSearch('')
- setQuantity(1)
- },
- },
- )
+ onSelect(selectedVariant, quantity)
+ onOpenChange(false)
+ setSelectedVariant(null)
+ setSearch('')
+ setQuantity(1)
}
return (
@@ -165,8 +152,8 @@ export function AddLineItemDialog({
<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 type="submit" disabled={!selectedVariant}>
+ {t('admin.actions.add')}
</Button>
</SheetFooter>
</form>
@@ -174,69 +161,3 @@ export function AddLineItemDialog({
</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/components/spree/orders/order-edit-items-table.tsx b/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsx
new file mode 100644
index 0000000000..678280cb52
--- /dev/null
+++ b/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsx
@@ -0,0 +1,156 @@
+import {
+ Badge,
+ Button,
+ cn,
+ Input,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Thumbnail,
+} from '@spree/dashboard-ui'
+import { PackageIcon, RotateCcwIcon, XIcon } from 'lucide-react'
+import { Controller, type FieldArrayWithId, type UseFormReturn } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import type { OrderEditFormValues } from '../../../schemas/order'
+
+/**
+ * The staged items table. Every control writes to form state only — quantities,
+ * removals and picker additions all wait for the page's Save. A removed row
+ * stays on screen struck through so the merchant can put it back before saving.
+ *
+ * The field array lives on the page rather than here because the catalog picker
+ * appends to it too, and two `useFieldArray` calls on one name keep separate
+ * row lists.
+ */
+export function OrderEditItemsTable({
+ form,
+ fields,
+}: {
+ form: UseFormReturn<OrderEditFormValues>
+ fields: FieldArrayWithId<OrderEditFormValues, 'items', 'id'>[]
+}) {
+ const { t } = useTranslation()
+
+ if (fields.length === 0) {
+ return <p className="py-8 text-center text-muted-foreground">{t('admin.orders.edit.empty')}</p>
+ }
+
+ return (
+ <Table>
+ <TableHeader className="border-b">
+ <TableRow>
+ <TableHead>{t('admin.orders.edit.columns.product')}</TableHead>
+ <TableHead className="text-right">{t('admin.orders.edit.columns.unit_price')}</TableHead>
+ <TableHead className="w-32 text-right">{t('admin.fields.quantity.label')}</TableHead>
+ <TableHead className="text-right">{t('admin.orders.edit.columns.line_total')}</TableHead>
+ <TableHead className="w-16" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {fields.map((field, index) => (
+ <OrderEditItemRow key={field.id} form={form} index={index} />
+ ))}
+ </TableBody>
+ </Table>
+ )
+}
+
+function OrderEditItemRow({
+ form,
+ index,
+}: {
+ form: UseFormReturn<OrderEditFormValues>
+ index: number
+}) {
+ const { t } = useTranslation()
+ const row = form.watch(`items.${index}`)
+ const quantityError = form.formState.errors.items?.[index]?.quantity?.message
+
+ function toggleRemoved() {
+ form.setValue(`items.${index}.removed`, !row.removed, {
+ shouldDirty: true,
+ shouldValidate: true,
+ })
+ }
+
+ return (
+ <TableRow className={cn(row.removed && 'opacity-50')}>
+ <TableCell>
+ <div className="flex items-center gap-3">
+ <Thumbnail src={row.thumbnail_url} size="lg" fallback={<PackageIcon />} />
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <span className={cn('truncate text-sm font-medium', row.removed && 'line-through')}>
+ {row.name}
+ </span>
+ {row.added && !row.removed && (
+ <Badge variant="secondary">{t('admin.orders.edit.badges.pending')}</Badge>
+ )}
+ {row.removed && (
+ <Badge variant="outline">{t('admin.orders.edit.badges.removed')}</Badge>
+ )}
+ </div>
+ {row.options_text && (
+ <div className="truncate text-xs text-muted-foreground">{row.options_text}</div>
+ )}
+ </div>
+ </div>
+ </TableCell>
+
+ <TableCell className="text-right whitespace-nowrap">{row.display_price}</TableCell>
+
+ <TableCell className="text-right">
+ <Controller
+ control={form.control}
+ name={`items.${index}.quantity`}
+ render={({ field }) => (
+ <Input
+ type="number"
+ min={1}
+ inputMode="numeric"
+ className="ml-auto w-24 text-right"
+ disabled={row.removed}
+ aria-invalid={!!quantityError}
+ aria-label={t('admin.orders.edit.actions.quantity_for', { name: row.name })}
+ value={field.value}
+ onChange={(event) => field.onChange(Number(event.target.value))}
+ onBlur={field.onBlur}
+ />
+ )}
+ />
+ {quantityError && (
+ <p className="mt-1 text-xs text-destructive" role="alert">
+ {quantityError}
+ </p>
+ )}
+ </TableCell>
+
+ <TableCell className="text-right whitespace-nowrap">
+ {row.added ? '—' : row.display_total}
+ </TableCell>
+
+ <TableCell className="text-right">
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={toggleRemoved}
+ aria-label={
+ row.removed
+ ? t('admin.orders.edit.actions.restore_item', { name: row.name })
+ : t('admin.orders.edit.actions.remove_item', { name: row.name })
+ }
+ >
+ {row.removed ? (
+ <RotateCcwIcon className="size-4" />
+ ) : (
+ <XIcon className="size-4 text-destructive" />
+ )}
+ </Button>
+ </TableCell>
+ </TableRow>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/orders/order-header.tsx b/packages/dashboard/src/components/spree/orders/order-header.tsx
index 829e6e046b..67100c9423 100644
--- a/packages/dashboard/src/components/spree/orders/order-header.tsx
+++ b/packages/dashboard/src/components/spree/orders/order-header.tsx
@@ -73,24 +73,6 @@ export function OrderHeader({ order }: { order: Order }) {
const dropdownItems = (
<>
- {order.status === 'draft' && (
- <DropdownMenuItem
- onClick={async () => {
- if (
- await confirm({
- message: t('admin.orders.detail.confirm.complete_message'),
- confirmLabel: t('admin.orders.detail.dropdown.complete_order'),
- })
- ) {
- completeMutation.mutate(undefined)
- }
- }}
- disabled={completeMutation.isPending}
- >
- <CheckCircleIcon className="size-4" />
- {t('admin.orders.detail.dropdown.complete_order')}
- </DropdownMenuItem>
- )}
{order.considered_risky && !order.approved_at && (
<DropdownMenuItem
onClick={async () => {
@@ -175,12 +157,34 @@ export function OrderHeader({ order }: { order: Order }) {
backTo={backFallback}
badges={badges}
actions={
- <Button asChild variant="outline">
- <Link to="/$storeId/orders/$orderId/edit" params={{ storeId, orderId }}>
- <PencilIcon className="size-4" />
- {t('admin.orders.edit.action_label')}
- </Link>
- </Button>
+ <>
+ <Button variant="outline" size="sm" asChild>
+ <Link to="/$storeId/orders/$orderId/edit" params={{ storeId, orderId }}>
+ <PencilIcon className="size-4" />
+ {t('admin.orders.edit.action_label')}
+ </Link>
+ </Button>
+
+ {order.status === 'draft' && (
+ <Button
+ size="sm"
+ onClick={async () => {
+ if (
+ await confirm({
+ message: t('admin.orders.detail.confirm.complete_message'),
+ confirmLabel: t('admin.orders.detail.dropdown.complete_order'),
+ })
+ ) {
+ completeMutation.mutate(undefined)
+ }
+ }}
+ disabled={completeMutation.isPending}
+ >
+ <CheckCircleIcon />
+ {t('admin.orders.detail.dropdown.complete_order')}
+ </Button>
+ )}
+ </>
}
dropdownItems={dropdownItems}
resource={{ id: order.id, number: order.number }}
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 95c3342755..9b1b552ea2 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -1810,10 +1810,6 @@
"resend_confirmation": "Resend Confirmation",
"void_payment": "Void Payment"
},
- "edit_quantity": {
- "description": "قم بتعيين الكمية لهذا البند.",
- "title": "Edit Quantity"
- },
"errors": {
"approve_failed": "فشلت الموافقة على الطلب",
"cancel_failed": "فشل في إلغاء الطلب",
@@ -1914,25 +1910,25 @@
"action_label": "تعديل الطلب",
"actions": {
"add_product": "إضافة منتج",
- "edit_quantity_for": "تعديل كمية {{name}}",
- "remove": "إزالة",
- "remove_item": "إزالة {{name}}"
+ "remove_item": "إزالة {{name}}",
+ "quantity_for": "كمية {{name}}",
+ "restore_item": "الإبقاء على {{name}}"
},
"columns": {
"line_total": "إجمالي السطر",
"product": "المنتج",
"unit_price": "سعر الوحدة"
},
- "confirm": {
- "remove_message": "إزالة \"{{name}}\" من هذا الطلب؟ يسري هذا فوراً ويُعاد احتساب إجماليات الطلب.",
- "remove_title": "إزالة السطر"
- },
"empty": "لا يحتوي هذا الطلب على أي عناصر.",
"items_title": "العناصر",
"subtitle": "الطلب {{number}}",
"title": "تعديل الطلب",
- "totals_hint": "يُعيد الخادم احتساب الإجماليات بعد كل تغيير.",
- "totals_title": "الإجماليات"
+ "totals_hint": "يُعيد الخادم احتساب الإجماليات بعد الحفظ.",
+ "totals_title": "الإجماليات",
+ "badges": {
+ "pending": "غير محفوظ",
+ "removed": "قيد الإزالة"
+ }
},
"fulfill": {
"action": "وضع علامة كمشحون",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index b9c73ab763..5c0e5e04f0 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -1799,10 +1799,6 @@
"resend_confirmation": "Bestätigung erneut senden",
"void_payment": "Zahlung stornieren"
},
- "edit_quantity": {
- "description": "Legen Sie die Menge für diese Position fest.",
- "title": "Menge bearbeiten"
- },
"errors": {
"approve_failed": "Auftrag konnte nicht genehmigt werden",
"cancel_failed": "Auftrag konnte nicht storniert werden",
@@ -1904,25 +1900,25 @@
"action_label": "Bestellung bearbeiten",
"actions": {
"add_product": "Produkt hinzufügen",
- "edit_quantity_for": "Menge von {{name}} bearbeiten",
- "remove": "Entfernen",
- "remove_item": "{{name}} entfernen"
+ "remove_item": "{{name}} entfernen",
+ "quantity_for": "Menge von {{name}}",
+ "restore_item": "{{name}} behalten"
},
"columns": {
"line_total": "Positionssumme",
"product": "Produkt",
"unit_price": "Einzelpreis"
},
- "confirm": {
- "remove_message": "„{{name}}“ aus dieser Bestellung entfernen? Dies wird sofort wirksam und die Bestellsummen werden neu berechnet.",
- "remove_title": "Position entfernen"
- },
"empty": "Diese Bestellung enthält keine Artikel.",
"items_title": "Artikel",
"subtitle": "Bestellung {{number}}",
"title": "Bestellung bearbeiten",
- "totals_hint": "Die Summen werden nach jeder Änderung vom Server neu berechnet.",
- "totals_title": "Summen"
+ "totals_hint": "Die Summen werden nach dem Speichern vom Server neu berechnet.",
+ "totals_title": "Summen",
+ "badges": {
+ "pending": "Nicht gespeichert",
+ "removed": "Wird entfernt"
+ }
},
"fulfill": {
"action": "Als versendet markieren",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index a881a42de5..7aee235086 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -1799,10 +1799,6 @@
"resend_confirmation": "Resend Confirmation",
"void_payment": "Void Payment"
},
- "edit_quantity": {
- "description": "Set the quantity for this line item.",
- "title": "Edit Quantity"
- },
"errors": {
"approve_failed": "Failed to approve order",
"cancel_failed": "Failed to cancel order",
@@ -1904,25 +1900,25 @@
"action_label": "Edit order",
"actions": {
"add_product": "Add product",
- "edit_quantity_for": "Edit quantity of {{name}}",
- "remove": "Remove",
- "remove_item": "Remove {{name}}"
+ "remove_item": "Remove {{name}}",
+ "quantity_for": "Quantity of {{name}}",
+ "restore_item": "Keep {{name}}"
},
"columns": {
"line_total": "Line total",
"product": "Product",
"unit_price": "Unit price"
},
- "confirm": {
- "remove_message": "Remove \"{{name}}\" from this order? This takes effect immediately and the order totals are recalculated.",
- "remove_title": "Remove line item"
- },
"empty": "This order has no items.",
"items_title": "Items",
"subtitle": "Order {{number}}",
"title": "Edit order",
- "totals_hint": "Totals are recalculated by the server after each change.",
- "totals_title": "Totals"
+ "totals_hint": "Totals are recalculated by the server after you save.",
+ "totals_title": "Totals",
+ "badges": {
+ "pending": "Not saved",
+ "removed": "Removing"
+ }
},
"fulfill": {
"action": "Mark as fulfilled",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 77f2459e42..f5494caf14 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -1799,10 +1799,6 @@
"resend_confirmation": "Renvoyer la confirmation",
"void_payment": "Annuler le paiement"
},
- "edit_quantity": {
- "description": "Définissez la quantité pour cette ligne d'article.",
- "title": "Modifier la quantité"
- },
"errors": {
"approve_failed": "Échec de l'approbation de la commande",
"cancel_failed": "Échec de l'annulation de la commande",
@@ -1904,25 +1900,25 @@
"action_label": "Modifier la commande",
"actions": {
"add_product": "Ajouter un produit",
- "edit_quantity_for": "Modifier la quantité de {{name}}",
- "remove": "Retirer",
- "remove_item": "Retirer {{name}}"
+ "remove_item": "Retirer {{name}}",
+ "quantity_for": "Quantité de {{name}}",
+ "restore_item": "Conserver {{name}}"
},
"columns": {
"line_total": "Total de la ligne",
"product": "Produit",
"unit_price": "Prix unitaire"
},
- "confirm": {
- "remove_message": "Retirer « {{name}} » de cette commande ? Cela prend effet immédiatement et les totaux de la commande sont recalculés.",
- "remove_title": "Retirer la ligne"
- },
"empty": "Cette commande ne contient aucun article.",
"items_title": "Articles",
"subtitle": "Commande {{number}}",
"title": "Modifier la commande",
- "totals_hint": "Les totaux sont recalculés par le serveur après chaque modification.",
- "totals_title": "Totaux"
+ "totals_hint": "Les totaux sont recalculés par le serveur après l'enregistrement.",
+ "totals_title": "Totaux",
+ "badges": {
+ "pending": "Non enregistré",
+ "removed": "À retirer"
+ }
},
"fulfill": {
"action": "Marquer comme expédié",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 18939ba7e0..01602dd640 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -1815,10 +1815,6 @@
"resend_confirmation": "Wyślij ponownie potwierdzenie",
"void_payment": "Unieważnij płatność"
},
- "edit_quantity": {
- "description": "Ustaw ilość dla tej pozycji.",
- "title": "Edytuj ilość"
- },
"errors": {
"approve_failed": "Nie udało się zatwierdzić zamówienia",
"cancel_failed": "Nie udało się anulować zamówienia",
@@ -1922,25 +1918,25 @@
"action_label": "Edytuj zamówienie",
"actions": {
"add_product": "Dodaj produkt",
- "edit_quantity_for": "Edytuj ilość dla {{name}}",
- "remove": "Usuń",
- "remove_item": "Usuń {{name}}"
+ "remove_item": "Usuń {{name}}",
+ "quantity_for": "Ilość dla {{name}}",
+ "restore_item": "Zachowaj {{name}}"
},
"columns": {
"line_total": "Wartość pozycji",
"product": "Produkt",
"unit_price": "Cena jednostkowa"
},
- "confirm": {
- "remove_message": "Usunąć „{{name}}” z tego zamówienia? Zmiana zostanie zastosowana natychmiast, a sumy zamówienia zostaną przeliczone.",
- "remove_title": "Usuń pozycję"
- },
"empty": "To zamówienie nie zawiera pozycji.",
"items_title": "Pozycje",
"subtitle": "Zamówienie {{number}}",
"title": "Edytuj zamówienie",
- "totals_hint": "Sumy są przeliczane przez serwer po każdej zmianie.",
- "totals_title": "Sumy"
+ "totals_hint": "Sumy są przeliczane przez serwer po zapisaniu zmian.",
+ "totals_title": "Sumy",
+ "badges": {
+ "pending": "Niezapisane",
+ "removed": "Do usunięcia"
+ }
},
"fulfill": {
"action": "Oznacz jako wysłane",
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 588e5750bc..de9baabc85 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -1796,10 +1796,6 @@
"resend_confirmation": "重新发送确认",
"void_payment": "作废付款"
},
- "edit_quantity": {
- "description": "设置该订单行项目的数量。",
- "title": "编辑数量"
- },
"errors": {
"approve_failed": "批准订单失败",
"cancel_failed": "取消订单失败",
@@ -1900,25 +1896,25 @@
"action_label": "编辑订单",
"actions": {
"add_product": "添加商品",
- "edit_quantity_for": "编辑 {{name}} 的数量",
- "remove": "移除",
- "remove_item": "移除 {{name}}"
+ "remove_item": "移除 {{name}}",
+ "quantity_for": "{{name}} 的数量",
+ "restore_item": "保留 {{name}}"
},
"columns": {
"line_total": "小计",
"product": "商品",
"unit_price": "单价"
},
- "confirm": {
- "remove_message": "要从此订单中移除“{{name}}”吗?此操作将立即生效,订单金额会重新计算。",
- "remove_title": "移除订单行"
- },
"empty": "此订单没有商品。",
"items_title": "商品",
"subtitle": "订单 {{number}}",
"title": "编辑订单",
- "totals_hint": "每次更改后,服务器都会重新计算金额。",
- "totals_title": "金额"
+ "totals_hint": "保存后,服务器会重新计算金额。",
+ "totals_title": "金额",
+ "badges": {
+ "pending": "未保存",
+ "removed": "待移除"
+ }
},
"fulfill": {
"action": "标记为已发货",
diff --git a/packages/dashboard/src/schemas/order.test.ts b/packages/dashboard/src/schemas/order.test.ts
new file mode 100644
index 0000000000..167ebc7598
--- /dev/null
+++ b/packages/dashboard/src/schemas/order.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest'
+import { buildOrderItemsPayload, type OrderEditItemValues } from './order'
+
+function row(overrides: Partial<OrderEditItemValues>): OrderEditItemValues {
+ return {
+ variant_id: 'variant_1',
+ quantity: 1,
+ removed: false,
+ added: false,
+ saved_quantity: 1,
+ name: 'Shirt',
+ options_text: '',
+ thumbnail_url: null,
+ display_price: '$10.00',
+ display_total: '$10.00',
+ ...overrides,
+ }
+}
+
+describe('buildOrderItemsPayload', () => {
+ it('omits rows the merchant did not touch', () => {
+ expect(buildOrderItemsPayload([row({ quantity: 2, saved_quantity: 2 })])).toEqual([])
+ })
+
+ it('sends the new quantity for a changed row', () => {
+ expect(buildOrderItemsPayload([row({ quantity: 5, saved_quantity: 2 })])).toEqual([
+ { variant_id: 'variant_1', quantity: 5 },
+ ])
+ })
+
+ it('sends quantity 0 for a removed row', () => {
+ expect(
+ buildOrderItemsPayload([row({ removed: true, quantity: 3, saved_quantity: 3 })]),
+ ).toEqual([{ variant_id: 'variant_1', quantity: 0 }])
+ })
+
+ it('sends the quantity for a staged addition', () => {
+ expect(buildOrderItemsPayload([row({ added: true, quantity: 4, saved_quantity: 0 })])).toEqual([
+ { variant_id: 'variant_1', quantity: 4 },
+ ])
+ })
+
+ it('drops an addition that was staged and then removed', () => {
+ expect(
+ buildOrderItemsPayload([row({ added: true, removed: true, quantity: 4, saved_quantity: 0 })]),
+ ).toEqual([])
+ })
+
+ it('ignores a quantity edit made on a row that is also removed', () => {
+ expect(
+ buildOrderItemsPayload([row({ removed: true, quantity: 9, saved_quantity: 3 })]),
+ ).toEqual([{ variant_id: 'variant_1', quantity: 0 }])
+ })
+})
diff --git a/packages/dashboard/src/schemas/order.ts b/packages/dashboard/src/schemas/order.ts
index 3baea08be9..1ed28134c1 100644
--- a/packages/dashboard/src/schemas/order.ts
+++ b/packages/dashboard/src/schemas/order.ts
@@ -1,3 +1,4 @@
+import type { LineItem, OrderUpdateParams } from '@spree/admin-sdk'
import { i18n } from '@spree/dashboard-core'
import { z } from 'zod/v4'
@@ -41,3 +42,91 @@ export const NEW_ORDER_DEFAULTS: NewOrderFormValues = {
export const FEE_KINDS = ['surcharge', 'handling', 'gift_wrap', 'cod', 'payment'] as const
export type FeeKind = (typeof FEE_KINDS)[number]
+
+/**
+ * One row of the order edit table. Everything here is a primitive on purpose:
+ * embedding an SDK entity would make react-hook-form's `Path<T>` walk the whole
+ * order graph (see CLAUDE.md), so the display columns are copied in flat.
+ *
+ * `removed` and `added` are staging flags — they say what the merchant has
+ * asked for, not what the server holds. Nothing leaves the browser until Save.
+ */
+export const orderEditItemSchema = z.object({
+ variant_id: z.string(),
+ quantity: z
+ .number()
+ .int()
+ .min(1, {
+ error: () =>
+ i18n.t('admin.validation.positive_number', {
+ field: i18n.t('admin.fields.quantity.label'),
+ }),
+ }),
+ removed: z.boolean(),
+ /** True for rows the picker staged that the order does not have yet. */
+ added: z.boolean(),
+ /** Quantity the server currently holds; 0 for staged additions. */
+ saved_quantity: z.number().int(),
+ name: z.string(),
+ options_text: z.string(),
+ thumbnail_url: z.string().nullable(),
+ display_price: z.string(),
+ display_total: z.string(),
+})
+
+export type OrderEditItemValues = z.infer<typeof orderEditItemSchema>
+
+export const orderEditFormSchema = z.object({
+ items: z.array(orderEditItemSchema),
+})
+
+export type OrderEditFormValues = z.infer<typeof orderEditFormSchema>
+
+/** Builds the staged row for a line item the order already carries. */
+export function lineItemToEditRow(item: LineItem): OrderEditItemValues {
+ return {
+ variant_id: item.variant_id,
+ quantity: item.quantity,
+ removed: false,
+ added: false,
+ saved_quantity: item.quantity,
+ name: item.name,
+ options_text: item.options_text ?? '',
+ thumbnail_url: item.thumbnail_url,
+ display_price: item.display_price,
+ display_total: item.display_total,
+ }
+}
+
+export function orderToEditForm(items: LineItem[]): OrderEditFormValues {
+ return { items: items.map(lineItemToEditRow) }
+}
+
+/**
+ * Reduces staged rows to the `items` upsert the Admin API expects. The endpoint
+ * is keyed by variant and touches only what it is sent, so untouched rows are
+ * omitted, staged removals become `quantity: 0`, and additions carry their
+ * quantity like any other change.
+ *
+ * A row that was staged and then unstaged in the same session contributes
+ * nothing, which is why an addition whose `removed` flag is set drops out
+ * entirely rather than sending a pointless `0`.
+ */
+export type OrderItemsPayload = NonNullable<OrderUpdateParams['items']>
+
+export function buildOrderItemsPayload(items: OrderEditItemValues[]): OrderItemsPayload {
+ const payload: OrderItemsPayload = []
+
+ for (const item of items) {
+ if (item.removed) {
+ if (!item.added) payload.push({ variant_id: item.variant_id, quantity: 0 })
+ continue
+ }
+
+ if (item.added || item.quantity !== item.saved_quantity) {
+ payload.push({ variant_id: item.variant_id, quantity: item.quantity })
+ }
+ }
+
+ return payload
+}