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.

Respect shipped units in order editing and fulfillment creation

Damian Legawiecf777e7f62de5
diff --git a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx
index 972597ed8c..4b9e67eb39 100644
--- a/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx
+++ b/packages/dashboard/src/components/spree/orders/fulfillments-card.tsx
@@ -51,7 +51,6 @@ import { useStockLocations } from '../../../hooks/use-stock-locations'
import {
type FulfillmentItemRow,
fulfillmentItemRows,
- hasFulfillableUnits,
unfulfilledItemRows,
} from '../../../lib/fulfillment-items'
import { FulfillmentEditDialog } from './fulfillment-edit-dialog'
@@ -82,15 +81,15 @@ function unitsOf(fulfillment: Fulfillment): FulfillmentUnit[] {
}
/**
- * Line items still available to put into a new fulfillment. The backend moves
- * units out of their existing fulfillments, so everything on the order is
- * offered — it re-shapes the source rather than refusing.
+ * Units no fulfillment has claimed, shaped for the create dialog. Only the
+ * unclaimed remainder is offered: units already sitting in a fulfillment move
+ * via Split, and shipped ones do not move at all.
*/
function orderUnits(order: Order): Array<{ itemId: string; label: string; quantity: number }> {
- return (order.items ?? []).map((item) => ({
- itemId: item.id,
- label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,
- quantity: item.quantity,
+ return unfulfilledItemRows(order.items ?? [], order.fulfillments ?? []).map((row) => ({
+ itemId: row.key,
+ label: [row.name, row.optionsText].filter(Boolean).join(' — ') || row.key,
+ quantity: row.quantity,
}))
}
@@ -254,7 +253,7 @@ function SplitFulfillmentDialog({
)
}
-/** Creates a fulfillment, moving the chosen quantities out of the existing ones. */
+/** Creates a fulfillment for chosen quantities of the not-yet-claimed units. */
function CreateFulfillmentDialog({
order,
open,
@@ -287,7 +286,9 @@ function CreateFulfillmentDialog({
create.mutate(
{
stock_location_id: stockLocationId,
- items: items.length > 0 ? items : undefined,
+ // Always explicit: the backend reads a missing list as "every
+ // not-yet-shipped unit", which would drain existing fulfillments.
+ items,
},
{
onSuccess: () => {
@@ -370,7 +371,7 @@ function CreateFulfillmentDialog({
</Button>
<Button
type="button"
- disabled={!stockLocationId || create.isPending}
+ disabled={!stockLocationId || items.length === 0 || create.isPending}
onClick={handleSubmit}
>
{create.isPending ? t('admin.actions.saving') : t('admin.actions.create')}
@@ -592,10 +593,10 @@ export function FulfillmentsCard({ order }: { order: Order }) {
// 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.
- // 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)
+ // completed orders"). And it is only for units no fulfillment has claimed —
+ // once everything is allocated, rearranging lives on each fulfillment's
+ // Split action, not here.
+ const canCreate = !!order.completed_at && unfulfilled.length > 0
const groupCount = fulfillments.length + (unfulfilled.length > 0 ? 1 : 0)
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
index 678280cb52..61a11cdd3b 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
@@ -92,6 +92,13 @@ function OrderEditItemRow({
{row.removed && (
<Badge variant="outline">{t('admin.orders.edit.badges.removed')}</Badge>
)}
+ {row.fulfilled_quantity > 0 && (
+ <Badge variant="secondary">
+ {t('admin.orders.edit.badges.fulfilled_count', {
+ count: row.fulfilled_quantity,
+ })}
+ </Badge>
+ )}
</div>
{row.options_text && (
<div className="truncate text-xs text-muted-foreground">{row.options_text}</div>
@@ -109,7 +116,7 @@ function OrderEditItemRow({
render={({ field }) => (
<Input
type="number"
- min={1}
+ min={Math.max(1, row.fulfilled_quantity)}
inputMode="numeric"
className="ml-auto w-24 text-right"
disabled={row.removed}
@@ -133,23 +140,27 @@ function OrderEditItemRow({
</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>
+ {/* A row with shipped units cannot be struck out — those units are
+ physically gone, so the only edit left is raising the quantity. */}
+ {row.fulfilled_quantity === 0 && (
+ <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 67100c9423..8663b47756 100644
--- a/packages/dashboard/src/components/spree/orders/order-header.tsx
+++ b/packages/dashboard/src/components/spree/orders/order-header.tsx
@@ -158,12 +158,16 @@ export function OrderHeader({ order }: { order: Order }) {
badges={badges}
actions={
<>
- <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>
+ {/* Fully fulfilled means every unit has shipped, so there is
+ nothing left an edit could lawfully change. */}
+ {order.fulfillment_status !== 'fulfilled' && (
+ <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
diff --git a/packages/dashboard/src/lib/fulfillment-items.test.ts b/packages/dashboard/src/lib/fulfillment-items.test.ts
index 4879231d1f..21b0f8c1aa 100644
--- a/packages/dashboard/src/lib/fulfillment-items.test.ts
+++ b/packages/dashboard/src/lib/fulfillment-items.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest'
import {
+ fulfilledQuantities,
fulfillmentItemRows,
type GroupableFulfillment,
type GroupableLineItem,
- hasFulfillableUnits,
unfulfilledItemRows,
} from './fulfillment-items'
@@ -149,63 +149,51 @@ describe('unfulfilledItemRows', () => {
})
})
-describe('hasFulfillableUnits', () => {
- it('is true while units remain unclaimed', () => {
- expect(hasFulfillableUnits([lineItem({ quantity: 2 })], [])).toBe(true)
- })
+describe('fulfilledQuantities', () => {
+ it('sums units per line item across fulfilled fulfillments', () => {
+ const quantities = fulfilledQuantities([
+ fulfillment({
+ status: 'fulfilled',
+ fulfillment_items: [
+ { line_item_id: 'li_1', variant_id: 'variant_1', quantity: 1 },
+ { line_item_id: 'li_2', variant_id: 'variant_2', quantity: 2 },
+ ],
+ }),
+ fulfillment({
+ status: 'fulfilled',
+ fulfillment_items: [{ line_item_id: 'li_1', variant_id: 'variant_1', quantity: 2 }],
+ }),
+ ])
- 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)
+ expect(quantities.get('li_1')).toBe(3)
+ expect(quantities.get('li_2')).toBe(2)
})
- 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)
- })
+ // Canceled fulfillments restock; pending ones have not shipped. Neither
+ // pins an edit.
+ it('ignores fulfillments that have not shipped', () => {
+ const quantities = fulfilledQuantities([
+ fulfillment({
+ status: 'pending',
+ fulfillment_items: [{ line_item_id: 'li_1', variant_id: 'variant_1', quantity: 2 }],
+ }),
+ fulfillment({
+ status: 'canceled',
+ fulfillment_items: [{ line_item_id: 'li_1', variant_id: 'variant_1', quantity: 1 }],
+ }),
+ ])
- 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)
+ expect(quantities.size).toBe(0)
})
- it('is false on an order with no items at all', () => {
- expect(hasFulfillableUnits([], [])).toBe(false)
- })
+ it('skips fulfillment items that reference no line item', () => {
+ const quantities = fulfilledQuantities([
+ fulfillment({
+ status: 'fulfilled',
+ fulfillment_items: [{ line_item_id: null, variant_id: 'variant_1', quantity: 2 }],
+ }),
+ ])
- 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)
+ expect(quantities.size).toBe(0)
})
})
diff --git a/packages/dashboard/src/lib/fulfillment-items.ts b/packages/dashboard/src/lib/fulfillment-items.ts
index 59edd42ce3..d688e0f812 100644
--- a/packages/dashboard/src/lib/fulfillment-items.ts
+++ b/packages/dashboard/src/lib/fulfillment-items.ts
@@ -48,14 +48,6 @@ export interface FulfillmentItemRow {
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
@@ -74,6 +66,27 @@ function claimedQuantities(fulfillments: GroupableFulfillment[]): Map<string, nu
return claimed
}
+/**
+ * Sums, per line item, how many units sit in fulfilled fulfillments. Those
+ * units have left the building, so an edit can neither remove the row nor push
+ * its quantity below them. Canceled fulfillments restock their units and do
+ * not count.
+ */
+export function fulfilledQuantities(fulfillments: GroupableFulfillment[]): Map<string, number> {
+ const fulfilled = new Map<string, number>()
+
+ for (const fulfillment of fulfillments) {
+ if (fulfillment.status !== 'fulfilled') continue
+
+ for (const item of fulfillment.fulfillment_items ?? []) {
+ if (!item.line_item_id) continue
+ fulfilled.set(item.line_item_id, (fulfilled.get(item.line_item_id) ?? 0) + item.quantity)
+ }
+ }
+
+ return fulfilled
+}
+
/** Builds a row, preferring the line item's own copy over the fulfillment item's. */
function buildRow(
key: string,
@@ -149,22 +162,3 @@ export function unfulfilledItemRows(
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.json
index 9b1b552ea2..6f79ab8539 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -1927,8 +1927,15 @@
"totals_title": "الإجماليات",
"badges": {
"pending": "غير محفوظ",
- "removed": "قيد الإزالة"
- }
+ "removed": "قيد الإزالة",
+ "fulfilled_count_one": "تم الوفاء بـ {{count}}",
+ "fulfilled_count_other": "تم الوفاء بـ {{count}}"
+ },
+ "validation": {
+ "below_fulfilled_one": "لا يمكن النزول تحت {{count}} وحدة تم الوفاء بها",
+ "below_fulfilled_other": "لا يمكن النزول تحت {{count}} وحدات تم الوفاء بها"
+ },
+ "fully_fulfilled": "تم الوفاء بهذا الطلب بالكامل ولم يعد من الممكن تعديله."
},
"fulfill": {
"action": "وضع علامة كمشحون",
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 5c0e5e04f0..d4728c01c9 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -1917,8 +1917,15 @@
"totals_title": "Summen",
"badges": {
"pending": "Nicht gespeichert",
- "removed": "Wird entfernt"
- }
+ "removed": "Wird entfernt",
+ "fulfilled_count_one": "{{count}} abgewickelt",
+ "fulfilled_count_other": "{{count}} abgewickelt"
+ },
+ "validation": {
+ "below_fulfilled_one": "Darf {{count}} abgewickelte Einheit nicht unterschreiten",
+ "below_fulfilled_other": "Darf {{count}} abgewickelte Einheiten nicht unterschreiten"
+ },
+ "fully_fulfilled": "Diese Bestellung ist vollständig abgewickelt und kann nicht mehr bearbeitet werden."
},
"fulfill": {
"action": "Als versendet markieren",
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 7aee235086..6bf307ab91 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -1917,8 +1917,15 @@
"totals_title": "Totals",
"badges": {
"pending": "Not saved",
- "removed": "Removing"
- }
+ "removed": "Removing",
+ "fulfilled_count_one": "{{count}} fulfilled",
+ "fulfilled_count_other": "{{count}} fulfilled"
+ },
+ "validation": {
+ "below_fulfilled_one": "Can't go below {{count}} fulfilled unit",
+ "below_fulfilled_other": "Can't go below {{count}} fulfilled units"
+ },
+ "fully_fulfilled": "This order is fully fulfilled and can no longer be edited."
},
"fulfill": {
"action": "Mark as fulfilled",
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index f5494caf14..edb9cfe599 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -1917,8 +1917,15 @@
"totals_title": "Totaux",
"badges": {
"pending": "Non enregistré",
- "removed": "À retirer"
- }
+ "removed": "À retirer",
+ "fulfilled_count_one": "{{count}} traité",
+ "fulfilled_count_other": "{{count}} traités"
+ },
+ "validation": {
+ "below_fulfilled_one": "Impossible de descendre sous {{count}} unité traitée",
+ "below_fulfilled_other": "Impossible de descendre sous {{count}} unités traitées"
+ },
+ "fully_fulfilled": "Cette commande est entièrement traitée et ne peut plus être modifiée."
},
"fulfill": {
"action": "Marquer comme expédié",
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 01602dd640..19e0e98258 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -1935,8 +1935,19 @@
"totals_title": "Sumy",
"badges": {
"pending": "Niezapisane",
- "removed": "Do usunięcia"
- }
+ "removed": "Do usunięcia",
+ "fulfilled_count_one": "{{count}} zrealizowana",
+ "fulfilled_count_few": "{{count}} zrealizowane",
+ "fulfilled_count_many": "{{count}} zrealizowanych",
+ "fulfilled_count_other": "{{count}} zrealizowanych"
+ },
+ "validation": {
+ "below_fulfilled_one": "Nie można zejść poniżej {{count}} zrealizowanej sztuki",
+ "below_fulfilled_few": "Nie można zejść poniżej {{count}} zrealizowanych sztuk",
+ "below_fulfilled_many": "Nie można zejść poniżej {{count}} zrealizowanych sztuk",
+ "below_fulfilled_other": "Nie można zejść poniżej {{count}} zrealizowanych sztuk"
+ },
+ "fully_fulfilled": "To zamówienie jest w pełni zrealizowane i nie można go już edytować."
},
"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 de9baabc85..383e505e72 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -1913,8 +1913,15 @@
"totals_title": "金额",
"badges": {
"pending": "未保存",
- "removed": "待移除"
- }
+ "removed": "待移除",
+ "fulfilled_count_one": "已履行 {{count}} 件",
+ "fulfilled_count_other": "已履行 {{count}} 件"
+ },
+ "validation": {
+ "below_fulfilled_one": "不能低于已履行的 {{count}} 件",
+ "below_fulfilled_other": "不能低于已履行的 {{count}} 件"
+ },
+ "fully_fulfilled": "此订单已全部履行,无法再编辑。"
},
"fulfill": {
"action": "标记为已发货",
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx
index 63329f0751..3163eae904 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx
@@ -2,6 +2,8 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { type Order, SpreeError, type Variant } from '@spree/admin-sdk'
import { adminClient, formatPrice, mapSpreeErrorsToForm, PageHeader } from '@spree/dashboard-core'
import {
+ Alert,
+ AlertDescription,
Button,
Card,
CardContent,
@@ -15,7 +17,7 @@ import {
useFormSubmitShortcut,
} from '@spree/dashboard-ui'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import { PlusIcon } from 'lucide-react'
+import { InfoIcon, PlusIcon } from 'lucide-react'
import { type ReactNode, useEffect, useState } from 'react'
import { useFieldArray, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
@@ -125,7 +127,7 @@ function OrderEditPage() {
// merchant has staged edits in flight.
useEffect(() => {
if (!order || form.formState.isDirty) return
- form.reset(orderToEditForm(order.items ?? []))
+ form.reset(orderToEditForm(order.items ?? [], order.fulfillments ?? []))
}, [order, form])
const saveMutation = useOrderMutation(orderId, (items: OrderItemsPayload) =>
@@ -189,6 +191,7 @@ function OrderEditPage() {
removed: false,
added: true,
saved_quantity: 0,
+ fulfilled_quantity: 0,
name: variant.product_name,
options_text: variant.options_text ?? '',
thumbnail_url: variant.thumbnail_url,
@@ -210,6 +213,28 @@ function OrderEditPage() {
)
}
+ // The header hides its edit link on fulfilled orders, but the URL stays
+ // reachable — and the per-row clamps below would still allow additions.
+ if (order.fulfillment_status === 'fulfilled') {
+ return (
+ <ResourceLayout
+ header={
+ <PageHeader
+ title={t('admin.orders.edit.title')}
+ subtitle={t('admin.orders.edit.subtitle', { number: order.number })}
+ backTo={`${storeId}/orders/${orderId}`}
+ />
+ }
+ main={
+ <Alert variant="warning">
+ <InfoIcon />
+ <AlertDescription>{t('admin.orders.edit.fully_fulfilled')}</AlertDescription>
+ </Alert>
+ }
+ />
+ )
+ }
+
return (
<>
<form onSubmit={form.handleSubmit(onSubmit)}>
@@ -237,7 +262,9 @@ function OrderEditPage() {
</Button>
<FormActions
form={form}
- onDiscard={() => form.reset(orderToEditForm(order.items ?? []))}
+ onDiscard={() =>
+ form.reset(orderToEditForm(order.items ?? [], order.fulfillments ?? []))
+ }
/>
</>
}
diff --git a/packages/dashboard/src/schemas/order.test.ts b/packages/dashboard/src/schemas/order.test.ts
index 167ebc7598..4b2f1e4fea 100644
--- a/packages/dashboard/src/schemas/order.test.ts
+++ b/packages/dashboard/src/schemas/order.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { buildOrderItemsPayload, type OrderEditItemValues } from './order'
+import { buildOrderItemsPayload, type OrderEditItemValues, orderEditItemSchema } from './order'
function row(overrides: Partial<OrderEditItemValues>): OrderEditItemValues {
return {
@@ -8,6 +8,7 @@ function row(overrides: Partial<OrderEditItemValues>): OrderEditItemValues {
removed: false,
added: false,
saved_quantity: 1,
+ fulfilled_quantity: 0,
name: 'Shirt',
options_text: '',
thumbnail_url: null,
@@ -52,3 +53,40 @@ describe('buildOrderItemsPayload', () => {
).toEqual([{ variant_id: 'variant_1', quantity: 0 }])
})
})
+
+// Shipped units are physical fact — the schema refuses edits that pretend
+// they can come back.
+describe('orderEditItemSchema fulfilled clamp', () => {
+ it('rejects a quantity below the fulfilled count', () => {
+ const result = orderEditItemSchema.safeParse(
+ row({ quantity: 1, saved_quantity: 3, fulfilled_quantity: 2 }),
+ )
+
+ expect(result.success).toBe(false)
+ expect(result.error?.issues[0]?.path).toEqual(['quantity'])
+ })
+
+ it('rejects removing a row with fulfilled units', () => {
+ const result = orderEditItemSchema.safeParse(
+ row({ removed: true, quantity: 3, saved_quantity: 3, fulfilled_quantity: 3 }),
+ )
+
+ expect(result.success).toBe(false)
+ })
+
+ it('accepts trimming down to exactly the fulfilled count', () => {
+ const result = orderEditItemSchema.safeParse(
+ row({ quantity: 2, saved_quantity: 3, fulfilled_quantity: 2 }),
+ )
+
+ expect(result.success).toBe(true)
+ })
+
+ it('accepts removing a row with nothing fulfilled', () => {
+ const result = orderEditItemSchema.safeParse(
+ row({ removed: true, quantity: 3, saved_quantity: 3 }),
+ )
+
+ expect(result.success).toBe(true)
+ })
+})
diff --git a/packages/dashboard/src/schemas/order.ts b/packages/dashboard/src/schemas/order.ts
index 1ed28134c1..f97231cf30 100644
--- a/packages/dashboard/src/schemas/order.ts
+++ b/packages/dashboard/src/schemas/order.ts
@@ -1,6 +1,7 @@
import type { LineItem, OrderUpdateParams } from '@spree/admin-sdk'
import { i18n } from '@spree/dashboard-core'
import { z } from 'zod/v4'
+import { fulfilledQuantities, type GroupableFulfillment } from '../lib/fulfillment-items'
/**
* New-order form schema. The "customer OR email" rule is enforced at the
@@ -51,28 +52,47 @@ export type FeeKind = (typeof FEE_KINDS)[number]
* `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'),
+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(),
+ /** Units already shipped in fulfilled fulfillments; 0 for staged additions. */
+ fulfilled_quantity: z.number().int(),
+ name: z.string(),
+ options_text: z.string(),
+ thumbnail_url: z.string().nullable(),
+ display_price: z.string(),
+ display_total: z.string(),
+ })
+ .superRefine((item, ctx) => {
+ // Shipped units are physical fact: a row can neither be struck out nor
+ // set below what already left the warehouse. Removal counts as zero, so
+ // one rule covers both edits.
+ const effectiveQuantity = item.removed ? 0 : item.quantity
+
+ if (effectiveQuantity < item.fulfilled_quantity) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['quantity'],
+ message: i18n.t('admin.orders.edit.validation.below_fulfilled', {
+ count: item.fulfilled_quantity,
}),
- }),
- 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>
@@ -83,13 +103,14 @@ export const orderEditFormSchema = z.object({
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 {
+export function lineItemToEditRow(item: LineItem, fulfilledQuantity = 0): OrderEditItemValues {
return {
variant_id: item.variant_id,
quantity: item.quantity,
removed: false,
added: false,
saved_quantity: item.quantity,
+ fulfilled_quantity: fulfilledQuantity,
name: item.name,
options_text: item.options_text ?? '',
thumbnail_url: item.thumbnail_url,
@@ -98,8 +119,13 @@ export function lineItemToEditRow(item: LineItem): OrderEditItemValues {
}
}
-export function orderToEditForm(items: LineItem[]): OrderEditFormValues {
- return { items: items.map(lineItemToEditRow) }
+export function orderToEditForm(
+ items: LineItem[],
+ fulfillments: GroupableFulfillment[] = [],
+): OrderEditFormValues {
+ const fulfilled = fulfilledQuantities(fulfillments)
+
+ return { items: items.map((item) => lineItemToEditRow(item, fulfilled.get(item.id) ?? 0)) }
}
/**