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
Added @spree/dashboard/orders so plugins can build their own order pages (#15067)
Damian Legawiec7152857e0c2d
diff --git a/.changeset/dashboard-orders-exports.md b/.changeset/dashboard-orders-exports.mdnew file mode 100644index 0000000000..3ccdf175ab--- /dev/null+++ b/.changeset/dashboard-orders-exports.md@@ -0,0 +1,5 @@+---+"@spree/dashboard": patch+---++Plugins can build their own order pages from the order page's building blocks, exported from `@spree/dashboard/orders`: `useOrderItemsEditor` (staged line editing with negotiated draft prices and a one-transaction save), `OrderEditItemsTable`, `AddLineItemDialog`, `OrderTotalsCard`, `useOrder`, the customer, logistics, purchase order, discounts and notes cards, and the new-order page's company and customer pickers. The order edit page now runs on the same hook.diff --git a/docs/developer/dashboard/public-api.mdx b/docs/developer/dashboard/public-api.mdxindex 15b9a8dcb3..c17448c870 100644--- a/docs/developer/dashboard/public-api.mdx+++ b/docs/developer/dashboard/public-api.mdx@@ -242,6 +242,27 @@ import { loginFormSchema, resetPasswordFormSchema } from '@spree/dashboard/schemTheir translations ship with `@spree/dashboard-core`, so they render translated as soon as its i18n instance is loaded.+A plugin page that works on an order in its own layout — a quote over a draft order, say — reuses the order page's building blocks from one subpath:++```ts+import {+ useOrder, // the order with the expands the order page loads+ useOrderItemsEditor, // staged line editing: form, picker hand-off, one-transaction save+ OrderEditItemsTable, // quantities, removals and, on drafts, negotiated unit prices+ AddLineItemDialog, // the variant picker+ OrderTotalsCard, // totals that preview the staged edits+ CustomerCard,+ OrderLogisticsCard,+ OrderPurchaseOrderCard,+ companyAutocompleteProps, // the new-order page's pickers: companies, then+ customerAutocompleteProps, // the customers who can buy for the chosen one+} from '@spree/dashboard/orders'+```++The same entry also exports the order page's other sidebar cards (`DiscountsCard`, `OrderSummaryCard`, `TagsCard`, `SpecialInstructionsCard`, `InternalNoteCard`), `CompanyComboboxOption` for rendering the company picker's options, and `useOrderMutation` for a save that refreshes the order.++`useOrderItemsEditor(order)` returns the `form` and `fields` the table renders, `items` for the totals card, `stageVariant` for the picker's `onSelect`, and `save(values)` / `discard()`. Nothing reaches the server until `save`, which resolves `true` once the lines are saved and re-baselines the form on the saved order. Once the order has loaded, render `OrderTotalsCard` against `savedOrder` (`{savedOrder && <OrderTotalsCard order={savedOrder} items={items} />}`) — it follows the save even before your `order` refreshes — and lock the editing controls while `isSaving` (`<OrderEditItemsTable disabled={isSaving} />`, and the button that opens the picker): the save replaces the form when it finishes. Their copy lives in `@spree/dashboard`'s locales, which the dashboard loads, so they render translated on any page the dashboard routes to.+A few names exist in both re-exported packages — the design system ships a presentational component and the framework wraps it with data (`ResourceCombobox`, `StatusCard`, `Slot`, `DateRange`, `ResourceMultiAutocomplete`). The facade gives you the framework's version, which is the one an application wants. Reach past it when you want the presentational half:```tsdiff --git a/packages/dashboard/e2e/orders.spec.ts b/packages/dashboard/e2e/orders.spec.tsindex ec4e69bc0d..237e36eeaf 100644--- a/packages/dashboard/e2e/orders.spec.ts+++ b/packages/dashboard/e2e/orders.spec.ts@@ -343,6 +343,50 @@ test.describe('order editing', () => {await expect(page.getByText(/^negotiated$/i)).toBeVisible()await expect(page.getByRole('button', { name: /reset .* to catalog price/i })).toBeVisible()})++ // The save replaces the lines when it finishes, so a variant picked during+ // it would be dropped without a word: Mod+S does nothing while the product+ // picker is open.+ test('does not save from the keyboard while the product picker is open', async ({ page }) => {+ const creds = await login(page)+ await page.goto(NEW_ORDER_PATH(creds.store_id))+ await expect(page.getByRole('heading', { name: CTA })).toBeVisible({ timeout: 15_000 })++ await fillNewOrderForm(page, `e2e-order-picker-${Date.now()}@example.com`)+ await page.locator('button[type="submit"]').click()+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/orders/or_[^/]+$`), {+ timeout: 15_000,+ })++ const editUrl = `${page.url()}/edit`+ await page.goto(editUrl)+ await expect(page.getByRole('heading', { name: /edit order/i })).toBeVisible({+ timeout: 15_000,+ })++ // A dirty form is what the shortcut would otherwise save.+ const quantity = page.locator('input[type="number"]').first()+ await expect(quantity).toBeVisible({ timeout: 15_000 })+ await quantity.fill('2')++ await page.getByRole('button', { name: /^add product$/i }).click()+ const picker = page.getByRole('dialog', { name: /add line item/i })+ await expect(picker).toBeVisible()++ const updates: string[] = []+ page.on('request', (request) => {+ if (request.method() === 'PATCH' && /\/orders\/or_[^/]+$/.test(request.url())) {+ updates.push(request.url())+ }+ })+ await page.keyboard.press('ControlOrMeta+s')++ // Give a save that should not happen the time it would need to be sent.+ await page.waitForTimeout(1_000)+ expect(updates).toEqual([])+ await expect(picker).toBeVisible()+ await expect(page).toHaveURL(editUrl)+ })})test.describe('order addresses', () => {diff --git a/packages/dashboard/package.json b/packages/dashboard/package.jsonindex 94ad357601..2d45dbaa33 100644--- a/packages/dashboard/package.json+++ b/packages/dashboard/package.json@@ -34,7 +34,8 @@"./components/spree/auth-shell": "./src/components/spree/auth-shell.tsx","./components/spree/store-setup-fields": "./src/components/spree/store-setup-fields.tsx","./hooks/use-auth-providers": "./src/hooks/use-auth-providers.ts",- "./schemas/auth": "./src/schemas/auth.ts"+ "./schemas/auth": "./src/schemas/auth.ts",+ "./orders": "./src/orders.ts"},"files": ["src",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.tsxindex 80f71e3105..aae3787b22 100644--- a/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsx+++ b/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsx@@ -27,18 +27,25 @@ import {* sent until the page's Save. `pricesEditable` is on for drafts only — a* negotiated price is a pre-placement gesture.*- * The field array lives on the page because the catalog picker appends to it- * too, and two `useFieldArray` calls on one name keep separate row lists.+ * The field array lives in `useOrderItemsEditor` because the catalog picker+ * appends to it too, and two `useFieldArray` calls on one name keep separate+ * row lists.*/export function OrderEditItemsTable({form,fields,pricesEditable = false,+ disabled = false,currency,}: {form: UseFormReturn<OrderEditFormValues>fields: FieldArrayWithId<OrderEditFormValues, 'items', 'id'>[]pricesEditable?: boolean+ /**+ * Locks every control, e.g. while a save is in flight: the post-save reset+ * would otherwise erase what is typed meanwhile.+ */+ disabled?: boolean/** Order currency, for formatting the projected line totals. */currency: string}) {@@ -49,28 +56,34 @@ export function OrderEditItemsTable({}return (- <Table>- <TableHeader>- <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}- pricesEditable={pricesEditable}- currency={currency}- />- ))}- </TableBody>- </Table>+ <fieldset disabled={disabled} className="contents">+ <Table>+ <TableHeader>+ <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}+ pricesEditable={pricesEditable}+ currency={currency}+ />+ ))}+ </TableBody>+ </Table>+ </fieldset>)}diff --git a/packages/dashboard/src/components/spree/orders/order-totals-card.tsx b/packages/dashboard/src/components/spree/orders/order-totals-card.tsxnew file mode 100644index 0000000000..5832bbbae5--- /dev/null+++ b/packages/dashboard/src/components/spree/orders/order-totals-card.tsx@@ -0,0 +1,121 @@+import type { Order } from '@spree/admin-sdk'+import { compareMoney, isZeroMoney } from '@spree/core'+import { isPositiveMoney, Money } from '@spree/dashboard-core'+import { Card, CardContent, CardHeader, CardTitle, cn, Separator } from '@spree/dashboard-ui'+import type { ReactNode } from 'react'+import { useTranslation } from 'react-i18next'+import { type OrderEditItemValues, projectedSubtotal } from '../../../schemas/order'++function TotalRow({ label, value, bold }: { label: string; value: ReactNode; bold?: boolean }) {+ return (+ <div className="flex items-center justify-between px-5 py-2.5">+ <span className="text-sm">{label}</span>+ <span className={cn('text-sm', bold && 'font-bold')}>{value}</span>+ </div>+ )+}++/**+ * The order's totals, previewing staged edits. The subtotal is exact+ * (price × quantity); the grand total is only projected when every other line+ * is zero, since shipping, tax and promotions are recomputed server-side.+ */+export function OrderTotalsCard({ order, items }: { order: Order; items: OrderEditItemValues[] }) {+ const { t } = useTranslation()++ const projected = projectedSubtotal(items)+ const subtotalChanged = projected !== null && compareMoney(projected, order.item_total) !== 0++ // Derived from the order's own totals, so charges not itemised here count.+ const totalProjectable = subtotalChanged && compareMoney(order.total, order.item_total) === 0++ return (+ <Card className="gap-0 py-0">+ <CardHeader>+ <CardTitle>{t('admin.orders.edit.totals_title')}</CardTitle>+ </CardHeader>++ <div className="py-2">+ <TotalRow+ label={t('admin.fields.subtotal.label')}+ value={+ subtotalChanged ? (+ <span className="flex items-center justify-end gap-2">+ <span className="text-muted-foreground line-through">+ <Money amount={order.item_total} currency={order.currency} />+ </span>+ <span className="font-medium">+ <Money amount={projected} currency={order.currency} />+ </span>+ </span>+ ) : (+ <Money amount={order.item_total} currency={order.currency} />+ )+ }+ />++ {isPositiveMoney(order.delivery_total) && (+ <TotalRow+ label={t('admin.fields.shipping.label')}+ value={<Money amount={order.delivery_total} currency={order.currency} />}+ />+ )}++ {!isZeroMoney(order.discount_total) && (+ <TotalRow+ label={t('admin.orders.detail.summary.promotions')}+ value={<Money amount={order.discount_total} currency={order.currency} />}+ />+ )}++ {isPositiveMoney(order.included_tax_total) && (+ <TotalRow+ label={t('admin.orders.detail.summary.tax_included')}+ value={<Money amount={order.included_tax_total} currency={order.currency} />}+ />+ )}++ {(isPositiveMoney(order.additional_tax_total) ||+ (Boolean(order.completed_at) && isZeroMoney(order.included_tax_total))) && (+ <TotalRow+ label={t('admin.orders.detail.summary.tax_additional')}+ value={<Money amount={order.additional_tax_total} currency={order.currency} />}+ />+ )}++ <Separator />++ <TotalRow+ label={t('admin.fields.total.label')}+ value={+ totalProjectable ? (+ <span className="flex items-center justify-end gap-2">+ <span className="font-normal text-muted-foreground line-through">+ <Money amount={order.total} currency={order.currency} />+ </span>+ <span>+ <Money amount={projected} currency={order.currency} />+ </span>+ </span>+ ) : (+ <Money amount={order.total} currency={order.currency} />+ )+ }+ bold+ />+ </div>++ <Separator />++ <CardContent className="px-5 py-4">+ <p className="text-xs text-muted-foreground">+ {!subtotalChanged+ ? t('admin.orders.edit.totals_hint')+ : totalProjectable+ ? t('admin.orders.edit.totals_preview_confirm_hint')+ : t('admin.orders.edit.totals_preview_hint')}+ </p>+ </CardContent>+ </Card>+ )+}diff --git a/packages/dashboard/src/hooks/use-order-items-editor.ts b/packages/dashboard/src/hooks/use-order-items-editor.tsnew file mode 100644index 0000000000..61e88b3d43--- /dev/null+++ b/packages/dashboard/src/hooks/use-order-items-editor.ts@@ -0,0 +1,259 @@+import { zodResolver } from '@hookform/resolvers/zod'+import type { Order, Variant } from '@spree/admin-sdk'+import { adminClient, mapSpreeErrorsToForm, useResourceKey } from '@spree/dashboard-core'+import { toastManager } from '@spree/dashboard-ui'+import { useQueryClient } from '@tanstack/react-query'+import { useEffect, useRef, useState } from 'react'+import { useFieldArray, useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import {+ buildOrderItemsPayload,+ type OrderEditFormValues,+ type OrderItemsPayload,+ orderEditFormSchema,+ orderToEditForm,+} from '../schemas/order'+import { useOrderMutation } from './use-order'++function editFormFor(order: Order): OrderEditFormValues {+ return orderToEditForm(order.items ?? [], order.fulfillments ?? [])+}++/**+ * Staged line-item editing for one order: the form behind the items table,+ * the picker hand-off and the save. Quantity changes, removals, added variants+ * and (on drafts) negotiated prices live in form state until `save`, which is+ * a single `PATCH /orders/:id` the server runs in one transaction.+ *+ * The order edit page is built on it, and so can any page that edits an+ * order's lines in its own layout — render `OrderEditItemsTable` with `form`+ * and `fields`, `AddLineItemDialog` with `stageVariant`, and+ * `OrderTotalsCard` with `items`.+ *+ * `save` replaces the form with the saved lines when it finishes, so lock the+ * editing controls while `isSaving`: pass `disabled={isSaving}` to+ * `OrderEditItemsTable` and disable whatever opens the picker. Anything typed+ * meanwhile would be erased; a variant picked meanwhile is ignored.+ */+export function useOrderItemsEditor(order: Order | undefined) {+ const { t } = useTranslation()++ const form = useForm<OrderEditFormValues>({+ resolver: zodResolver(orderEditFormSchema),+ defaultValues: { items: [] },+ })++ const { fields, append } = useFieldArray({ control: form.control, name: 'items' })+ // Watched, not read once: the totals card previews staged edits, so it has+ // to re-render on every keystroke in the items table.+ const items = form.watch('items')++ // Hydrate from the server rows, unless the merchant has staged edits in+ // flight on this same order. A different order always replaces the rows:+ // staged lines of one order must never be saved against another.+ const hydratedOrderId = useRef<string | undefined>(undefined)+ // The order on screen right now — undefined while the next one loads —+ // which a save in flight checks before it touches the form.+ const shownOrderId = useRef<string | undefined>(undefined)+ shownOrderId.current = order?.id+ // The order the form's saved values come from: the `order` prop, or what a+ // save read back when the caller's prop has not caught up yet.+ const [savedOrder, setSavedOrder] = useState<Order | undefined>(order)++ function rebaseline(next: Order) {+ hydratedOrderId.current = next.id+ setSavedOrder(next)+ form.reset(editFormFor(next))+ }++ useEffect(() => {+ if (!order) return+ // The saved side follows every refresh — discard and the totals read it —+ // even when staged edits keep the form from re-hydrating.+ setSavedOrder(order)+ if (form.formState.isDirty && hydratedOrderId.current === order.id) return+ hydratedOrderId.current = order.id+ form.reset(editFormFor(order))+ }, [order, form])++ // Covers the whole save, the read-back included: the form is replaced at+ // the end, so nothing may be staged until then. The ref answers the same+ // question synchronously for `stageVariant`.+ const [isSaving, setIsSaving] = useState(false)+ const savingRef = useRef(false)++ const queryClient = useQueryClient()+ const orderKey = useResourceKey('orders', order?.id ?? '')+ const saveMutation = useOrderMutation(order?.id ?? '', (payload: OrderItemsPayload) =>+ adminClient.orders.update(order?.id ?? '', { items: payload }),+ )++ /**+ * Saves the staged edits. Resolves `true` once they are saved (or there was+ * nothing to send), `false` when the server rejected them — field errors are+ * then on the form, anything else was toasted. Also `false` when the page+ * moved to another order while the save was in flight: the save went through+ * for the order it was made on, but nothing the caller does next (leaving the+ * page, refreshing) applies to the order it now shows.+ */+ async function save(values: OrderEditFormValues): Promise<boolean> {+ // Rows the merchant staged and then unstaged net out to nothing, so the+ // payload can legitimately be empty even on a dirty form.+ const payload = buildOrderItemsPayload(values.items)+ const startedAt = Date.now()+ // The order these rows belong to. If the page moves to another order+ // while the save is in flight, nothing below may touch the form.+ const savingOrderId = order?.id+ const stillShown = () => shownOrderId.current === savingOrderId++ // One save at a time: the first to finish would unlock the editor while+ // the other is still in flight.+ if (savingRef.current) return false++ if (payload.length > 0 && !savingOrderId) {+ toastManager.add({ type: 'error', title: t('admin.errors.failed_to_save') })+ return false+ }++ if (payload.length === 0) {+ if (!stillShown()) return false+ // Nothing was sent, so every remaining row is as the server has it:+ // re-baseline them as they are, server totals included. Leaving the+ // form dirty would trip the unsaved-changes guard on the way out.+ form.reset({+ items: values.items+ .filter((item) => !item.added && !item.removed)+ .map((item) => ({ ...item, revert_price: false })),+ })+ return true+ }++ savingRef.current = true+ setIsSaving(true)+ let patched = false+ try {+ await saveMutation.mutateAsync(payload)+ patched = true+ } catch (err) {+ if (!stillShown()) return false+ if (mapSpreeErrorsToForm(err, form.setError)) return false+ toastManager.add({ type: 'error', title: t('admin.errors.failed_to_save') })+ return false+ } finally {+ // A failed save unlocks here; one that went through stays locked until+ // the read-back below has replaced the form.+ if (!patched) {+ savingRef.current = false+ setIsSaving(false)+ }+ }++ try {+ if (!stillShown()) return false+ // Re-baseline on what the server saved — the client cannot know a saved+ // line's adjustments. The mutation awaits the order refetch, so a page+ // that loads the order through `useOrder` already has it in the cache;+ // any other page reads it once here.+ const cached = queryClient.getQueryState<Order>(orderKey)+ const saved =+ cached?.data && cached.dataUpdatedAt >= startedAt+ ? cached.data+ : await adminClient.orders+ .get(savingOrderId as string, { expand: ['items', 'fulfillments'] })+ .catch(() => null)+ if (!stillShown()) return false+ if (saved) {+ rebaseline(saved)+ } else {+ // The lines were saved but could not be read back. Keep what was+ // sent as the saved values, so the form is pristine and the next+ // read of the order re-hydrates it with the server's totals.+ toastManager.add({ type: 'warning', title: t('admin.orders.edit.saved_not_reloaded') })+ form.reset({+ items: values.items+ .filter((item) => !item.removed)+ .map((item) => ({+ ...item,+ added: false,+ saved_quantity: item.quantity,+ saved_price: item.price,+ revert_price: false,+ })),+ })+ }+ return true+ } finally {+ savingRef.current = false+ setIsSaving(false)+ }+ }++ /** Drops every staged edit and returns to the saved lines. */+ function discard() {+ const saved = savedOrder?.id === order?.id ? savedOrder : order+ if (saved) form.reset(editFormFor(saved))+ }++ /**+ * Stages a picked variant. Picking one the order already carries (or one that+ * is sitting removed) bumps the existing row rather than adding a duplicate —+ * the endpoint is keyed by variant, so two rows for one variant could not both+ * survive a save.+ */+ function stageVariant(variant: Variant, quantity: number) {+ // The post-save reset would erase a row staged while the save is pending.+ if (savingRef.current) return+ const current = form.getValues('items')+ const existingIndex = current.findIndex((item) => item.variant_id === variant.id)++ if (existingIndex >= 0) {+ const existing = current[existingIndex]+ form.setValue(+ `items.${existingIndex}`,+ {+ ...existing,+ removed: false,+ quantity: existing.removed ? quantity : existing.quantity + quantity,+ },+ { shouldDirty: true, shouldValidate: true },+ )+ return+ }++ append({+ variant_id: variant.id,+ quantity,+ removed: false,+ added: true,+ saved_quantity: 0,+ fulfilled_quantity: 0,+ // Seeded as both current and saved value, so an untouched price is+ // omitted from the payload and the server prices the line itself.+ price: variant.price?.amount ?? '0',+ saved_price: variant.price?.amount ?? '0',+ price_source: null,+ catalog_price: variant.price?.amount ?? null,+ revert_price: false,+ name: variant.product_name,+ options_text: variant.options_text ?? '',+ thumbnail_url: variant.thumbnail_url,+ total: null,+ })+ }++ return {+ form,+ fields,+ items,+ save,+ discard,+ stageVariant,+ isSaving,+ /**+ * The order as last saved — render `OrderTotalsCard` against it. Usually+ * the `order` passed in; after a save on a page whose `order` has not+ * refreshed yet, the order the save read back.+ */+ savedOrder: savedOrder?.id === order?.id ? savedOrder : order,+ }+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 19c36b4d58..97486b7fc2 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -3341,6 +3341,7 @@"empty": "لا يحتوي هذا الطلب على أي عناصر.","fully_fulfilled": "تم الوفاء بهذا الطلب بالكامل ولم يعد من الممكن تعديله.","items_title": "العناصر",+ "saved_not_reloaded": "تم الحفظ، لكن تعذّرت إعادة تحميل الطلب. حدّث الصفحة لرؤية أحدث الإجماليات.","subtitle": "الطلب {{number}}","title": "تعديل الطلب","totals_hint": "يُعيد الخادم احتساب الإجماليات بعد الحفظ.",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex ab3490e664..e489487000 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -3321,6 +3321,7 @@"empty": "Diese Bestellung enthält keine Artikel.","fully_fulfilled": "Diese Bestellung ist vollständig abgewickelt und kann nicht mehr bearbeitet werden.","items_title": "Artikel",+ "saved_not_reloaded": "Gespeichert, aber die Bestellung konnte nicht neu geladen werden. Aktualisiere die Seite, um die aktuellen Summen zu sehen.","subtitle": "Bestellung {{number}}","title": "Bestellung bearbeiten","totals_hint": "Die Summen werden nach dem Speichern vom Server neu berechnet.",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex ff937fbe41..06c8fae994 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -3321,6 +3321,7 @@"empty": "This order has no items.","fully_fulfilled": "This order is fully fulfilled and can no longer be edited.","items_title": "Items",+ "saved_not_reloaded": "Saved, but the order couldn't be reloaded. Refresh the page to see the latest totals.","subtitle": "Order {{number}}","title": "Edit order","totals_hint": "Totals are recalculated by the server after you save.",diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 4826349011..3d3f151f8a 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -3046,6 +3046,7 @@"empty": "Este pedido no tiene artículos.","fully_fulfilled": "Este pedido está completamente cumplido y ya no se puede editar.","items_title": "Artículos",+ "saved_not_reloaded": "Guardado, pero no se pudo volver a cargar el pedido. Actualiza la página para ver los totales más recientes.","subtitle": "Pedido {{number}}","title": "Editar pedido","totals_hint": "El servidor recalcula los totales después de guardar.",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex e6ad24c43d..e3a9b06761 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -3321,6 +3321,7 @@"empty": "Cette commande ne contient aucun article.","fully_fulfilled": "Cette commande est entièrement traitée et ne peut plus être modifiée.","items_title": "Articles",+ "saved_not_reloaded": "Enregistré, mais la commande n'a pas pu être rechargée. Actualisez la page pour voir les derniers totaux.","subtitle": "Commande {{number}}","title": "Modifier la commande","totals_hint": "Les totaux sont recalculés par le serveur après l'enregistrement.",diff --git a/packages/dashboard/src/locales/ja.json b/packages/dashboard/src/locales/ja.jsonindex f04afff527..b9e2eb798a 100644--- a/packages/dashboard/src/locales/ja.json+++ b/packages/dashboard/src/locales/ja.json@@ -3321,6 +3321,7 @@"empty": "この注文には品目がありません。","fully_fulfilled": "この注文はすべて処理済みなので、もう編集できません。","items_title": "品目",+ "saved_not_reloaded": "保存しましたが、注文を再読み込みできませんでした。最新の合計を表示するにはページを更新してください。","subtitle": "注文 {{number}}","title": "注文を編集","totals_hint": "保存すると、サーバーが合計を再計算します。",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 76765298f5..a9eb2d4cd5 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -3351,6 +3351,7 @@"empty": "To zamówienie nie zawiera pozycji.","fully_fulfilled": "To zamówienie jest w pełni zrealizowane i nie można go już edytować.","items_title": "Pozycje",+ "saved_not_reloaded": "Zapisano, ale nie udało się ponownie wczytać zamówienia. Odśwież stronę, aby zobaczyć aktualne sumy.","subtitle": "Zamówienie {{number}}","title": "Edytuj zamówienie","totals_hint": "Sumy są przeliczane przez serwer po zapisaniu zmian.",diff --git a/packages/dashboard/src/locales/vi.json b/packages/dashboard/src/locales/vi.jsonindex 4744c073af..2bd143895f 100644--- a/packages/dashboard/src/locales/vi.json+++ b/packages/dashboard/src/locales/vi.json@@ -3321,6 +3321,7 @@"empty": "Đơn hàng này không có mặt hàng nào.","fully_fulfilled": "Lệnh này đã được thực hiện đầy đủ và không thể chỉnh sửa được nữa.","items_title": "Mặt hàng",+ "saved_not_reloaded": "Đã lưu, nhưng không thể tải lại đơn hàng. Hãy làm mới trang để xem tổng mới nhất.","subtitle": "Đặt hàng {{number}}","title": "Chỉnh sửa đơn hàng","totals_hint": "Tổng số được máy chủ tính toán lại sau khi bạn lưu.",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 0e41f76f6f..18530bae3e 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -3313,6 +3313,7 @@"empty": "此订单没有商品。","fully_fulfilled": "此订单已全部履行,无法再编辑。","items_title": "商品",+ "saved_not_reloaded": "已保存,但无法重新加载订单。请刷新页面以查看最新合计。","subtitle": "订单 {{number}}","title": "编辑订单","totals_hint": "保存后,服务器会重新计算金额。",diff --git a/packages/dashboard/src/orders.ts b/packages/dashboard/src/orders.tsnew file mode 100644index 0000000000..8a14eb83c2--- /dev/null+++ b/packages/dashboard/src/orders.ts@@ -0,0 +1,30 @@+// @spree/dashboard/orders — the order building blocks, for plugins whose+// pages work on an order in their own layout (a quote over a draft order, an+// approval queue) instead of slotting cards into the order page.+//+// The editor is staged: `useOrderItemsEditor` owns the form, the table and+// picker write to it, and nothing reaches the server until its `save`. The+// cards read the order they are given and save their own edits, as they do on+// the order page.++export { CompanyComboboxOption } from './components/spree/company-combobox-option'+export { AddLineItemDialog } from './components/spree/orders/line-item-dialogs'+export { CustomerCard } from './components/spree/orders/order-customer-card'+export { DiscountsCard } from './components/spree/orders/order-discounts-sidebar-card'+export { OrderEditItemsTable } from './components/spree/orders/order-edit-items-table'+export { OrderLogisticsCard } from './components/spree/orders/order-logistics-card'+export {+ InternalNoteCard,+ SpecialInstructionsCard,+ TagsCard,+} from './components/spree/orders/order-notes-cards'+export { OrderPurchaseOrderCard } from './components/spree/orders/order-purchase-order-card'+export { OrderSummaryCard } from './components/spree/orders/order-summary-card'+export { OrderTotalsCard } from './components/spree/orders/order-totals-card'+// The pickers the new-order page starts an order with: companies, then the+// customers who can buy for the chosen one.+export { companyAutocompleteProps } from './hooks/use-companies'+export { customerAutocompleteProps } from './hooks/use-customers'+export { useOrder, useOrderMutation } from './hooks/use-order'+export { useOrderItemsEditor } from './hooks/use-order-items-editor'+export type { OrderEditFormValues, OrderEditItemValues } from './schemas/order'diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsxindex 3e05615d7e..56c44cebd8 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx@@ -1,14 +1,4 @@-import { zodResolver } from '@hookform/resolvers/zod'-import { type Order, SpreeError, type Variant } from '@spree/admin-sdk'-import { compareMoney, isZeroMoney } from '@spree/core'-import {- adminClient,- GONE_STATUSES,- isPositiveMoney,- Money,- mapSpreeErrorsToForm,- PageHeader,-} from '@spree/dashboard-core'+import { GONE_STATUSES, PageHeader } from '@spree/dashboard-core'import {Alert,AlertDescription,@@ -17,150 +7,26 @@ import {CardContent,CardHeader,CardTitle,- cn,ErrorState,FormActions,ResourceLayout,- Separator,- toastManager,useFormSubmitShortcut,} from '@spree/dashboard-ui'import { InfoIcon, PlusIcon } from '@spree/dashboard-ui/icons'import { createFileRoute, useNavigate } from '@tanstack/react-router'-import { type ReactNode, useEffect, useState } from 'react'-import { useFieldArray, useForm } from 'react-hook-form'+import { useState } from 'react'import { useTranslation } from 'react-i18next'import { AddLineItemDialog } from '../../../../../components/spree/orders/line-item-dialogs'import { OrderEditItemsTable } from '../../../../../components/spree/orders/order-edit-items-table'-import { useOrder, useOrderMutation } from '../../../../../hooks/use-order'-import {- buildOrderItemsPayload,- type OrderEditFormValues,- type OrderEditItemValues,- type OrderItemsPayload,- orderEditFormSchema,- orderToEditForm,- projectedSubtotal,-} from '../../../../../schemas/order'+import { OrderTotalsCard } from '../../../../../components/spree/orders/order-totals-card'+import { useOrder } from '../../../../../hooks/use-order'+import { useOrderItemsEditor } from '../../../../../hooks/use-order-items-editor'+import type { OrderEditFormValues } from '../../../../../schemas/order'export const Route = createFileRoute('/_authenticated/$storeId/orders/$orderId/edit')({component: OrderEditPage,})-function TotalRow({ label, value, bold }: { label: string; value: ReactNode; bold?: boolean }) {- return (- <div className="flex items-center justify-between px-5 py-2.5">- <span className="text-sm">{label}</span>- <span className={cn('text-sm', bold && 'font-bold')}>{value}</span>- </div>- )-}--/**- * The order's totals, previewing staged edits. The subtotal is exact- * (price × quantity); the grand total is only projected when every other line- * is zero, since shipping, tax and promotions are recomputed server-side.- */-function OrderTotalsCard({ order, items }: { order: Order; items: OrderEditItemValues[] }) {- const { t } = useTranslation()-- const projected = projectedSubtotal(items)- const subtotalChanged = projected !== null && compareMoney(projected, order.item_total) !== 0-- // Derived from the order's own totals, so charges not itemised here count.- const totalProjectable = subtotalChanged && compareMoney(order.total, order.item_total) === 0-- return (- <Card className="gap-0 py-0">- <CardHeader>- <CardTitle>{t('admin.orders.edit.totals_title')}</CardTitle>- </CardHeader>-- <div className="py-2">- <TotalRow- label={t('admin.fields.subtotal.label')}- value={- subtotalChanged ? (- <span className="flex items-center justify-end gap-2">- <span className="text-muted-foreground line-through">- <Money amount={order.item_total} currency={order.currency} />- </span>- <span className="font-medium">- <Money amount={projected} currency={order.currency} />- </span>- </span>- ) : (- <Money amount={order.item_total} currency={order.currency} />- )- }- />-- {isPositiveMoney(order.delivery_total) && (- <TotalRow- label={t('admin.fields.shipping.label')}- value={<Money amount={order.delivery_total} currency={order.currency} />}- />- )}-- {!isZeroMoney(order.discount_total) && (- <TotalRow- label={t('admin.orders.detail.summary.promotions')}- value={<Money amount={order.discount_total} currency={order.currency} />}- />- )}-- {isPositiveMoney(order.included_tax_total) && (- <TotalRow- label={t('admin.orders.detail.summary.tax_included')}- value={<Money amount={order.included_tax_total} currency={order.currency} />}- />- )}-- {(isPositiveMoney(order.additional_tax_total) ||- (Boolean(order.completed_at) && isZeroMoney(order.included_tax_total))) && (- <TotalRow- label={t('admin.orders.detail.summary.tax_additional')}- value={<Money amount={order.additional_tax_total} currency={order.currency} />}- />- )}-- <Separator />-- <TotalRow- label={t('admin.fields.total.label')}- value={- totalProjectable ? (- <span className="flex items-center justify-end gap-2">- <span className="font-normal text-muted-foreground line-through">- <Money amount={order.total} currency={order.currency} />- </span>- <span>- <Money amount={projected} currency={order.currency} />- </span>- </span>- ) : (- <Money amount={order.total} currency={order.currency} />- )- }- bold- />- </div>-- <Separator />-- <CardContent className="px-5 py-4">- <p className="text-xs text-muted-foreground">- {!subtotalChanged- ? t('admin.orders.edit.totals_hint')- : totalProjectable- ? t('admin.orders.edit.totals_preview_confirm_hint')- : t('admin.orders.edit.totals_preview_hint')}- </p>- </CardContent>- </Card>- )-}-/*** Post-placement line-item management. Quantity changes, removals and picker* additions are staged in form state and applied together on Save, which is a@@ -172,118 +38,20 @@ function OrderEditPage() {const navigate = useNavigate()const { data: order, isLoading, error, refetch } = useOrder(orderId)const [addingItem, setAddingItem] = useState(false)-- const form = useForm<OrderEditFormValues>({- resolver: zodResolver(orderEditFormSchema),- defaultValues: { items: [] },- })-- const { fields, append } = useFieldArray({ control: form.control, name: 'items' })- // Watched, not read once: the totals card previews staged edits, so it has- // to re-render on every keystroke in the items table.- const watchedItems = form.watch('items')-- // Hydrate (and re-baseline after save) from the server rows, unless the- // merchant has staged edits in flight.- useEffect(() => {- if (!order || form.formState.isDirty) return- form.reset(orderToEditForm(order.items ?? [], order.fulfillments ?? []))- }, [order, form])-- const saveMutation = useOrderMutation(orderId, (items: OrderItemsPayload) =>- adminClient.orders.update(orderId, { items }),- )+ const editor = useOrderItemsEditor(order)+ const { form } = editorasync function onSubmit(values: OrderEditFormValues) {- // Rows the merchant staged and then unstaged net out to nothing, so the- // payload can legitimately be empty even on a dirty form.- const payload = buildOrderItemsPayload(values.items)-- try {- if (payload.length > 0) await saveMutation.mutateAsync(payload)- // Drop the rows that are gone and re-baseline the rest, so the form is- // pristine before the refetch lands — leaving it dirty would trip the- // unsaved-changes guard on the way out.- form.reset({- items: values.items- .filter((item) => !item.removed)- .map((item) => {- // A revert re-prices server-side; carry the catalog estimate until- // the refetch corrects it.- const reverted = item.revert_price- const price = reverted ? (item.catalog_price ?? item.price) : item.price-- return {- ...item,- added: false,- saved_quantity: item.quantity,- price,- saved_price: price,- price_source: reverted- ? null- : item.price !== item.saved_price- ? 'manual'- : item.price_source,- revert_price: false,- }- }),- })- // Editing is a detour from the order, not a place to stay: hand the- // merchant back the view that shows what the edit did.+ // Editing is a detour from the order, not a place to stay: hand the+ // merchant back the view that shows what the edit did.+ if (await editor.save(values)) {navigate({ to: '/$storeId/orders/$orderId', params: { storeId, orderId } })- } catch (err) {- if (mapSpreeErrorsToForm(err, form.setError)) return- if (err instanceof SpreeError) throw err- toastManager.add({ type: 'error', title: t('admin.errors.failed_to_save') })}}- useFormSubmitShortcut(form, onSubmit)-- /**- * Stages a picked variant. Picking one the order already carries (or one that- * is sitting removed) bumps the existing row rather than adding a duplicate —- * the endpoint is keyed by variant, so two rows for one variant could not both- * survive a save.- */- function stageVariant(variant: Variant, quantity: number) {- const items = form.getValues('items')- const existingIndex = items.findIndex((item) => item.variant_id === variant.id)-- if (existingIndex >= 0) {- const existing = items[existingIndex]- form.setValue(- `items.${existingIndex}`,- {- ...existing,- removed: false,- quantity: existing.removed ? quantity : existing.quantity + quantity,- },- { shouldDirty: true, shouldValidate: true },- )- return- }-- append({- variant_id: variant.id,- quantity,- removed: false,- added: true,- saved_quantity: 0,- fulfilled_quantity: 0,- // Seeded as both current and saved value, so an untouched price is- // omitted from the payload and the server prices the line itself.- price: variant.price?.amount ?? '0',- saved_price: variant.price?.amount ?? '0',- price_source: null,- catalog_price: variant.price?.amount ?? null,- revert_price: false,- name: variant.product_name,- options_text: variant.options_text ?? '',- thumbnail_url: variant.thumbnail_url,- total: null,- })- }+ // Not while the picker is open: a variant picked during the save would be+ // ignored, and the dialog closes on pick with no word of it.+ useFormSubmitShortcut(form, (values) => (addingItem ? undefined : onSubmit(values)))if (!order && isLoading) return null@@ -336,16 +104,16 @@ function OrderEditPage() {backTo={`orders/${orderId}`}actions={<>- <Button type="button" variant="outline" onClick={() => setAddingItem(true)}>+ <Button+ type="button"+ variant="outline"+ disabled={editor.isSaving}+ onClick={() => setAddingItem(true)}+ ><PlusIcon className="size-4" />{t('admin.orders.edit.actions.add_product')}</Button>- <FormActions- form={form}- onDiscard={() =>- form.reset(orderToEditForm(order.items ?? [], order.fulfillments ?? []))- }- />+ <FormActions form={form} onDiscard={editor.discard} /></>}/>@@ -360,14 +128,15 @@ function OrderEditPage() {order's money edits stay fees and discounts. */}<OrderEditItemsTableform={form}- fields={fields}+ fields={editor.fields}pricesEditable={order.status === 'draft'}+ disabled={editor.isSaving}currency={order.currency}/></CardContent></Card>}- sidebar={<OrderTotalsCard order={order} items={watchedItems} />}+ sidebar={<OrderTotalsCard order={editor.savedOrder ?? order} items={editor.items} />}/></form>@@ -376,7 +145,7 @@ function OrderEditPage() {orderId={orderId}open={addingItem}onOpenChange={setAddingItem}- onSelect={stageVariant}+ onSelect={editor.stageVariant}/>)}</>