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.

Bring the seller order view to parity with the dashboard

Damian Legawiec3f24a73ac70e
diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yaml
index 1976c97883..9cb712e47d 100644
--- a/docs/api-reference/seller.yaml
+++ b/docs/api-reference/seller.yaml
@@ -420,7 +420,7 @@ paths:
avatar_url:
sellers:
- id: sel_UkLWZg9DAJ
- name: Seller 65
+ name: Seller 67
status: approved
schema:
"$ref": "#/components/schemas/AuthResponse"
@@ -13540,8 +13540,8 @@ paths:
example:
data:
- id: prod_UkLWZg9DAJ
- name: Product 1683250
- slug: product-1683250
+ name: Product 1703250
+ slug: product-1703250
meta_title:
meta_description:
meta_keywords:
@@ -13784,8 +13784,8 @@ paths:
application/json:
example:
id: prod_UkLWZg9DAJ
- name: Product 1716710
- slug: product-1716710
+ name: Product 1736710
+ slug: product-1736710
meta_title:
meta_description:
meta_keywords:
@@ -13864,7 +13864,7 @@ paths:
example:
id: prod_UkLWZg9DAJ
name: Hand-thrown mug, large
- slug: product-1748212
+ slug: product-1768212
meta_title:
meta_description:
meta_keywords:
@@ -13977,8 +13977,8 @@ paths:
application/json:
example:
id: sel_UkLWZg9DAJ
- name: Seller 82
- slug: seller-82
+ name: Seller 84
+ slug: seller-84
about: ''
about_html: ''
logo_url:
@@ -14050,7 +14050,7 @@ paths:
example:
id: sel_UkLWZg9DAJ
name: Acme Supplies
- slug: seller-84
+ slug: seller-86
about: ''
about_html: ''
logo_url:
@@ -15608,6 +15608,18 @@ paths:
name: Product 1579315
sku: SKU-199
options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
deliveries:
- id: dlv_UkLWZg9DAJ
tracking_number: U10000
@@ -15693,6 +15705,18 @@ paths:
name: Product 158961
sku: SKU-200
options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
deliveries:
- id: dlv_UkLWZg9DAJ
tracking_number: TRACK-1
@@ -15795,6 +15819,18 @@ paths:
name: Product 1593170
sku: SKU-201
options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
deliveries:
- id: dlv_UkLWZg9DAJ
tracking_number: TRACK-2
@@ -15877,6 +15913,18 @@ paths:
name: Product 1607276
sku: SKU-202
options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
deliveries:
- id: dlv_UkLWZg9DAJ
tracking_number: U10000
@@ -16026,10 +16074,27 @@ paths:
updated_at: '2026-01-15T12:00:00.000Z'
item_total: '10.0'
display_item_total: "$10.00"
+ delivery_total: '100.0'
+ display_delivery_total: "$100.00"
+ discount_total: '0.0'
+ display_discount_total: "$0.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
tax_total: '0.0'
display_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
+ payment_total: '0.0'
+ display_payment_total: "$0.00"
+ amount_due: '110.0'
+ display_amount_due: "$110.00"
+ canceled_at:
+ cancel_reason_name:
+ cancel_note:
items:
- id: li_UkLWZg9DAJ
name: Product 16295
@@ -16065,6 +16130,18 @@ paths:
name: Product 16295
sku: SKU-204
options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
deliveries:
- id: dlv_UkLWZg9DAJ
tracking_number: U10000
@@ -16190,10 +16267,27 @@ paths:
updated_at: '2026-01-15T12:00:00.000Z'
item_total: '10.0'
display_item_total: "$10.00"
+ delivery_total: '100.0'
+ display_delivery_total: "$100.00"
+ discount_total: '0.0'
+ display_discount_total: "$0.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
tax_total: '0.0'
display_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
+ payment_total: '0.0'
+ display_payment_total: "$0.00"
+ amount_due: '110.0'
+ display_amount_due: "$110.00"
+ canceled_at:
+ cancel_reason_name:
+ cancel_note:
items:
- id: li_UkLWZg9DAJ
name: Product 1639755
@@ -16229,6 +16323,18 @@ paths:
name: Product 1639755
sku: SKU-205
options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
deliveries:
- id: dlv_UkLWZg9DAJ
tracking_number: U10000
@@ -16346,10 +16452,27 @@ paths:
updated_at: '2026-01-15T12:00:00.000Z'
item_total: '10.0'
display_item_total: "$10.00"
+ delivery_total: '100.0'
+ display_delivery_total: "$100.00"
+ discount_total: '0.0'
+ display_discount_total: "$0.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
tax_total: '0.0'
display_tax_total: "$0.00"
total: '110.0'
display_total: "$110.00"
+ payment_total: '0.0'
+ display_payment_total: "$0.00"
+ amount_due: "-0.0"
+ display_amount_due: "$0.00"
+ canceled_at: '2026-01-15T12:00:00Z'
+ cancel_reason_name:
+ cancel_note:
items:
- id: li_UkLWZg9DAJ
name: Product 1666554
@@ -16385,6 +16508,18 @@ paths:
name: Product 1666554
sku: SKU-208
options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
deliveries:
- id: dlv_UkLWZg9DAJ
tracking_number: U10000
@@ -16462,6 +16597,268 @@ paths:
notify_customer:
type: boolean
description: Email the customer about the cancellation
+ "/api/v3/seller/orders/{id}/address":
+ parameters:
+ - name: id
+ in: path
+ description: Prefixed order ID
+ required: true
+ schema:
+ type: string
+ patch:
+ summary: Correct an order address
+ tags:
+ - Orders
+ security:
+ - bearer_auth: []
+ description: |
+ Corrects where the goods go or who the invoice names.
+
+ The seller is merchant of record for their own child order, so a
+ delivery address the buyer got wrong is theirs to fix. Send only the
+ lines that change — the rest of the address is carried over.
+
+ This is the only write against the order itself besides cancelling:
+ nothing else about it, its totals included, is the seller's to change.
+ parameters:
+ - name: X-Spree-Seller-Id
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: address corrected
+ content:
+ application/json:
+ example:
+ id: or_UkLWZg9DAJ
+ number: R1001
+ customer_note:
+ currency: USD
+ total_quantity: 1
+ status: placed
+ fulfillment_status:
+ payment_status:
+ completed_at: '2026-01-15T12:00:00.000Z'
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ item_total: '10.0'
+ display_item_total: "$10.00"
+ delivery_total: '100.0'
+ display_delivery_total: "$100.00"
+ discount_total: '0.0'
+ display_discount_total: "$0.00"
+ adjustment_total: '0.0'
+ display_adjustment_total: "$0.00"
+ included_tax_total: '0.0'
+ display_included_tax_total: "$0.00"
+ additional_tax_total: '0.0'
+ display_additional_tax_total: "$0.00"
+ tax_total: '0.0'
+ display_tax_total: "$0.00"
+ total: '110.0'
+ display_total: "$110.00"
+ payment_total: '0.0'
+ display_payment_total: "$0.00"
+ amount_due: '110.0'
+ display_amount_due: "$110.00"
+ canceled_at:
+ cancel_reason_name:
+ cancel_note:
+ items:
+ - id: li_UkLWZg9DAJ
+ name: Product 1675038
+ options_text: ''
+ quantity: 1
+ currency: USD
+ price: '10.0'
+ display_price: "$10.00"
+ total: '10.0'
+ display_total: "$10.00"
+ variant_id: variant_UkLWZg9DAJ
+ sku: SKU-209
+ thumbnail_url:
+ fulfillments:
+ - id: ful_UkLWZg9DAJ
+ number: R1001-F1
+ status: unfulfilled
+ tracking: U10000
+ tracking_url:
+ fulfilled_at:
+ delivered_at:
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ fulfillment_type: shipping
+ delivery_method_name: UPS Ground
+ stock_location_name: Rudy Mosciski
+ stock_location_id: sloc_UkLWZg9DAJ
+ fulfillment_items:
+ - id: fi_UkLWZg9DAJ
+ quantity: 1
+ line_item_id: li_UkLWZg9DAJ
+ variant_id: variant_UkLWZg9DAJ
+ name: Product 1675038
+ sku: SKU-209
+ options_text: ''
+ selected_delivery_rate_id: dr_gbHJdmfrXB
+ delivery_rates:
+ - id: dr_gbHJdmfrXB
+ name: UPS Ground
+ selected: true
+ cost: '10.0'
+ total: '10.0'
+ carrier:
+ service_level:
+ estimated_delivery_date:
+ display_cost: "$10.00"
+ display_total: "$10.00"
+ deliveries:
+ - id: dlv_UkLWZg9DAJ
+ tracking_number: U10000
+ carrier:
+ carrier_name:
+ service:
+ status: pending
+ tracking_url:
+ estimated_delivery_at:
+ delivered_at:
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ shipping_label_id:
+ labels: []
+ shipping_address:
+ id: addr_EfhxLZ9ck8
+ label:
+ first_name: John
+ last_name: Doe
+ full_name: John Doe
+ address1: 9 Corrected Way
+ address2: Northwest
+ postal_code: '10118'
+ city: Fixedton
+ phone: 555-555-0199
+ company: Company
+ country_name: United States
+ country_code: US
+ state_text: NY
+ state_code: NY
+ quick_checkout: false
+ is_default_billing: false
+ is_default_shipping: true
+ state_abbr: NY
+ country_iso: US
+ state_name: New York
+ billing_address:
+ id: addr_UkLWZg9DAJ
+ label:
+ first_name: John
+ last_name: Doe
+ full_name: John Doe
+ address1: 168 Lovely Street
+ address2: Northwest
+ postal_code: '10118'
+ city: New York
+ phone: 555-555-0199
+ company: Company
+ country_name: United States
+ country_code: US
+ state_text: NY
+ state_code: NY
+ quick_checkout: false
+ is_default_billing: false
+ is_default_shipping: false
+ state_abbr: NY
+ country_iso: US
+ state_name: New York
+ schema:
+ "$ref": "#/components/schemas/Order"
+ '422':
+ description: neither address named
+ content:
+ application/json:
+ example:
+ error:
+ code: validation_error
+ message: shipping_address or billing_address is required
+ details:
+ base:
+ - shipping_address or billing_address is required
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ shipping_address:
+ type: object
+ description: Only the lines that change; the rest is carried over
+ properties:
+ first_name:
+ type: string
+ last_name:
+ type: string
+ company:
+ type: string
+ nullable: true
+ address1:
+ type: string
+ address2:
+ type: string
+ nullable: true
+ city:
+ type: string
+ postal_code:
+ type: string
+ country_code:
+ type: string
+ state_code:
+ type: string
+ nullable: true
+ state_name:
+ type: string
+ nullable: true
+ phone:
+ type: string
+ nullable: true
+ label:
+ type: string
+ nullable: true
+ billing_address:
+ type: object
+ description: Only the lines that change; the rest is carried over
+ properties:
+ first_name:
+ type: string
+ last_name:
+ type: string
+ company:
+ type: string
+ nullable: true
+ address1:
+ type: string
+ address2:
+ type: string
+ nullable: true
+ city:
+ type: string
+ postal_code:
+ type: string
+ country_code:
+ type: string
+ state_code:
+ type: string
+ nullable: true
+ state_name:
+ type: string
+ nullable: true
+ phone:
+ type: string
+ nullable: true
+ label:
+ type: string
+ nullable: true
+ required: true
"/api/v3/seller/order_cancellation_reasons":
get:
summary: List order cancellation reasons
@@ -16627,7 +17024,7 @@ paths:
example:
error:
code: processing_error
- message: Only 1 of Product 1787120 can be returned
+ message: Only 1 of Product 1807120 can be returned
requestBody:
content:
application/json:
@@ -18213,6 +18610,44 @@ components:
- default
- digital
x-typelizer: true
+ DeliveryRate:
+ type: object
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ selected:
+ type: boolean
+ cost:
+ type: string
+ total:
+ type: string
+ carrier:
+ type: string
+ nullable: true
+ service_level:
+ type: string
+ nullable: true
+ estimated_delivery_date:
+ type: string
+ nullable: true
+ display_cost:
+ type: string
+ display_total:
+ type: string
+ required:
+ - id
+ - name
+ - selected
+ - cost
+ - total
+ - carrier
+ - service_level
+ - estimated_delivery_date
+ - display_cost
+ - display_total
+ x-typelizer: true
Delivery:
type: object
properties:
@@ -18507,6 +18942,13 @@ components:
type: array
items:
"$ref": "#/components/schemas/FulfillmentItem"
+ selected_delivery_rate_id:
+ type: string
+ nullable: true
+ delivery_rates:
+ type: array
+ items:
+ "$ref": "#/components/schemas/DeliveryRate"
deliveries:
type: array
items:
@@ -18530,6 +18972,8 @@ components:
- stock_location_name
- stock_location_id
- fulfillment_items
+ - selected_delivery_rate_id
+ - delivery_rates
- deliveries
- labels
x-typelizer: true
@@ -18880,6 +19324,36 @@ components:
display_item_total:
type: string
nullable: true
+ delivery_total:
+ type: string
+ nullable: true
+ display_delivery_total:
+ type: string
+ nullable: true
+ discount_total:
+ type: string
+ nullable: true
+ display_discount_total:
+ type: string
+ nullable: true
+ adjustment_total:
+ type: string
+ nullable: true
+ display_adjustment_total:
+ type: string
+ nullable: true
+ included_tax_total:
+ type: string
+ nullable: true
+ display_included_tax_total:
+ type: string
+ nullable: true
+ additional_tax_total:
+ type: string
+ nullable: true
+ display_additional_tax_total:
+ type: string
+ nullable: true
tax_total:
type: string
nullable: true
@@ -18892,6 +19366,27 @@ components:
display_total:
type: string
nullable: true
+ payment_total:
+ type: string
+ nullable: true
+ display_payment_total:
+ type: string
+ nullable: true
+ amount_due:
+ type: string
+ nullable: true
+ display_amount_due:
+ type: string
+ nullable: true
+ canceled_at:
+ type: string
+ nullable: true
+ cancel_reason_name:
+ type: string
+ nullable: true
+ cancel_note:
+ type: string
+ nullable: true
items:
type: array
items:
@@ -18918,10 +19413,27 @@ components:
- updated_at
- item_total
- display_item_total
+ - delivery_total
+ - display_delivery_total
+ - discount_total
+ - display_discount_total
+ - adjustment_total
+ - display_adjustment_total
+ - included_tax_total
+ - display_included_tax_total
+ - additional_tax_total
+ - display_additional_tax_total
- tax_total
- display_tax_total
- total
- display_total
+ - payment_total
+ - display_payment_total
+ - amount_due
+ - display_amount_due
+ - canceled_at
+ - cancel_reason_name
+ - cancel_note
- items
- fulfillments
- shipping_address
diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.ts
index 36988133b2..4942884f3c 100644
--- a/packages/dashboard-ui/src/index.ts
+++ b/packages/dashboard-ui/src/index.ts
@@ -39,6 +39,7 @@ export * from './spree/data-grid'
export * from './spree/drag-handle'
export * from './spree/file-type-icon'
export * from './spree/form-actions'
+export * from './spree/fulfillment-edit-dialog'
// JsonPreviewDrawer and JsonValueView are intentionally NOT re-exported from
// this barrel: they pull in `@uiw/react-json-view` (~30KB gzip), and
diff --git a/packages/dashboard-ui/src/spree/fulfillment-edit-dialog.tsx b/packages/dashboard-ui/src/spree/fulfillment-edit-dialog.tsx
new file mode 100644
index 0000000000..999780150f
--- /dev/null
+++ b/packages/dashboard-ui/src/spree/fulfillment-edit-dialog.tsx
@@ -0,0 +1,211 @@
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '../ui/button'
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '../ui/dialog'
+import { Field, FieldError, FieldLabel } from '../ui/field'
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'
+
+/** A shelf a parcel can ship from, already labelled by the caller. */
+export type FulfillmentOriginOption = {
+ value: string
+ label: string
+}
+
+/** A priced service the parcel can be carried by, already labelled. */
+export type FulfillmentRateOption = {
+ value: string
+ label: string
+}
+
+export type FulfillmentEditValues = {
+ stockLocationId: string
+ selectedDeliveryRateId: string
+}
+
+/**
+ * Where a parcel ships from and which priced service carries it.
+ *
+ * The two fields are coupled: rates are quoted against an origin, so moving
+ * the parcel invalidates the list on screen. Rather than offering stale
+ * options, a save that changes the origin writes the location first and the
+ * method field stands down until the caller re-quotes — which is why
+ * `onSubmit` reports *which* fields changed and the caller decides the order
+ * of writes.
+ *
+ * Headless: both panels label their own options (the operator marks shelves
+ * that cannot cover the parcel; a seller sees only their own), and both own
+ * their mutations. This holds the shape and the coupling rule so the two
+ * cannot drift.
+ */
+export function FulfillmentEditDialog({
+ open,
+ onOpenChange,
+ originOptions,
+ rateOptions,
+ currentOriginId,
+ currentRateId,
+ onSubmit,
+ pending = false,
+ errorMessage,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ originOptions: FulfillmentOriginOption[]
+ rateOptions: FulfillmentRateOption[]
+ currentOriginId: string
+ currentRateId: string
+ /**
+ * Applies the change. Returning `'requote'` keeps the dialog open and
+ * re-seeds it from the caller's refreshed record — the origin moved, so the
+ * rates on screen described a route the parcel has left.
+ */
+ onSubmit: (
+ values: FulfillmentEditValues,
+ changed: { origin: boolean; rate: boolean },
+ ) => Promise<'requote' | 'done'>
+ pending?: boolean
+ errorMessage?: string
+}) {
+ const { t } = useTranslation()
+
+ const [originId, setOriginId] = useState(currentOriginId)
+ const [rateId, setRateId] = useState(currentRateId)
+
+ // A re-quote lands as a changed record: the caller has moved the parcel and
+ // the server has re-selected a method for the new origin. Adopt that pick,
+ // so the second save confirms a rate that actually applies rather than
+ // re-sending the one quoted for the origin the parcel just left.
+ const seededOrigin = useRef(currentOriginId)
+ useEffect(() => {
+ if (seededOrigin.current === currentOriginId) return
+ seededOrigin.current = currentOriginId
+ setOriginId(currentOriginId)
+ setRateId(currentRateId)
+ }, [currentOriginId, currentRateId])
+
+ // The rates on the record were quoted for the origin it currently has. Once
+ // a different one is picked they describe a route no longer on offer, so the
+ // method field stands down until the server re-quotes.
+ const originMoved = originId !== currentOriginId
+ const originMissing = originId.length === 0
+
+ async function handleSubmit(event: React.FormEvent) {
+ // The order page renders its cards inside their own forms — without
+ // stopping the bubble the browser submits the outer one.
+ event.preventDefault()
+ event.stopPropagation()
+ if (originMissing) return
+
+ const outcome = await onSubmit(
+ { stockLocationId: originId, selectedDeliveryRateId: rateId },
+ { origin: originMoved, rate: rateId !== currentRateId },
+ )
+
+ if (outcome === 'done') onOpenChange(false)
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <form onSubmit={handleSubmit}>
+ <DialogHeader>
+ <DialogTitle>{t('admin.orders.detail.fulfillments.edit_title')}</DialogTitle>
+ <DialogDescription>
+ {t('admin.orders.detail.fulfillments.edit_description')}
+ </DialogDescription>
+ </DialogHeader>
+
+ <DialogBody className="flex flex-col gap-4">
+ {errorMessage && (
+ <p className="text-sm text-destructive" role="alert">
+ {errorMessage}
+ </p>
+ )}
+
+ <Field>
+ <FieldLabel htmlFor="fulfillment-location">
+ {t('admin.orders.detail.fulfillments.ships_from')}
+ </FieldLabel>
+ <Select
+ items={originOptions}
+ value={originId}
+ onValueChange={(value) => setOriginId((value as string) ?? '')}
+ >
+ <SelectTrigger id="fulfillment-location">
+ <SelectValue placeholder={t('admin.common.select_placeholder')} />
+ </SelectTrigger>
+ <SelectContent>
+ {originOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {originMissing && <FieldError>{t('admin.errors.required')}</FieldError>}
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="fulfillment-rate">
+ {t('admin.orders.detail.fulfillments.delivery_method')}
+ </FieldLabel>
+ <Select
+ items={rateOptions}
+ value={rateId}
+ disabled={originMoved || rateOptions.length === 0}
+ onValueChange={(value) => setRateId((value as string) ?? '')}
+ >
+ <SelectTrigger id="fulfillment-rate">
+ <SelectValue placeholder={t('admin.common.select_placeholder')} />
+ </SelectTrigger>
+ <SelectContent>
+ {rateOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ {originMoved && (
+ <span className="text-muted-foreground text-xs">
+ {t('admin.orders.detail.fulfillments.rates_pending_origin')}
+ </span>
+ )}
+ {!originMoved && rateOptions.length === 0 && (
+ <span className="text-muted-foreground text-xs">
+ {t('admin.orders.detail.fulfillments.no_rates')}
+ </span>
+ )}
+ </Field>
+ </DialogBody>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={pending}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={pending || originMissing}>
+ {pending
+ ? t('admin.actions.saving')
+ : originMoved
+ ? t('admin.orders.detail.fulfillments.move_and_requote')
+ : t('admin.actions.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsx b/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsx
index 4d89fada53..da6c74904c 100644
--- a/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsx
+++ b/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsx
@@ -1,46 +1,18 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import type { Fulfillment, Order } from '@spree/admin-sdk'
-import { mapSpreeErrorsToForm, useStockLocations } from '@spree/dashboard-core'
-import {
- Button,
- Dialog,
- DialogBody,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- Field,
- FieldError,
- FieldLabel,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@spree/dashboard-ui'
-import { Controller, useForm } from 'react-hook-form'
+import { type Fulfillment, type Order, SpreeError } from '@spree/admin-sdk'
+import { useStockLocations } from '@spree/dashboard-core'
+import { FulfillmentEditDialog as SharedFulfillmentEditDialog } from '@spree/dashboard-ui'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { z } from 'zod'
import { useFulfillmentActions } from '../../../hooks/use-fulfillments'
import { useOrder } from '../../../hooks/use-order'
import { useStockCoverage } from '../../../hooks/use-stock-coverage'
-const fulfillmentEditSchema = z.object({
- stock_location_id: z.string().min(1),
- selected_delivery_rate_id: z.string(),
-})
-
-type FulfillmentEditFormValues = z.infer<typeof fulfillmentEditSchema>
-
/**
* Where the fulfillment ships from and which priced service carries it.
*
- * The two fields are coupled: rates are quoted against an origin, so moving
- * the fulfillment invalidates the list the merchant is looking at. Rather than
- * offering stale options, a save that changes the origin writes the location
- * first, waits for the server to re-quote, and only then offers the fresh
- * rates — see `handleSubmit`.
+ * The dialog itself is shared with the seller panel; this supplies the
+ * operator's view of it — every warehouse in the store, marked for whether it
+ * can actually cover the parcel — and owns the writes.
*/
export function FulfillmentEditDialog({
order,
@@ -57,27 +29,14 @@ export function FulfillmentEditDialog({
const { update } = useFulfillmentActions(order.id)
const { data: stockLocations } = useStockLocations()
const { refetch: refetchOrder } = useOrder(order.id)
-
- const form = useForm<FulfillmentEditFormValues>({
- resolver: zodResolver(fulfillmentEditSchema),
- defaultValues: {
- stock_location_id: fulfillment.stock_location_id ?? '',
- selected_delivery_rate_id: fulfillment.selected_delivery_rate_id ?? '',
- },
- })
+ const [errorMessage, setErrorMessage] = useState<string>()
const demands = (fulfillment.fulfillment_items ?? []).flatMap((item) =>
item.variant_id ? [{ variantId: item.variant_id, quantity: item.quantity }] : [],
)
const { data: coverage } = useStockCoverage(demands, open)
- const chosenLocationId = form.watch('stock_location_id')
- // The rates on the record were quoted for the origin it currently has. Once
- // the merchant picks a different one they describe a route that is no longer
- // on offer, so the method field stands down until the server re-quotes.
- const originMoved = chosenLocationId !== (fulfillment.stock_location_id ?? '')
-
- const locationOptions = (stockLocations?.data ?? [])
+ const originOptions = (stockLocations?.data ?? [])
.map((location) => {
const covered = coverage?.get(location.id) ?? false
return {
@@ -102,163 +61,58 @@ export function FulfillmentEditDialog({
}`,
}))
- async function onSubmit(values: FulfillmentEditFormValues) {
- const locationChanged = values.stock_location_id !== (fulfillment.stock_location_id ?? '')
- const rateChanged =
- values.selected_delivery_rate_id !== (fulfillment.selected_delivery_rate_id ?? '')
+ const currentOriginId = fulfillment.stock_location_id ?? ''
+ const currentRateId = fulfillment.selected_delivery_rate_id ?? ''
+
+ async function handleSubmit(
+ values: { stockLocationId: string; selectedDeliveryRateId: string },
+ changed: { origin: boolean; rate: boolean },
+ ): Promise<'requote' | 'done'> {
+ setErrorMessage(undefined)
try {
- if (locationChanged) {
+ if (changed.origin) {
await update.mutateAsync({
fulfillmentId: fulfillment.id,
- stock_location_id: values.stock_location_id,
+ stock_location_id: values.stockLocationId,
})
// The server re-quotes on the move and re-selects an equivalent method
- // where the new origin offers one. Pull the fresh fulfillment back and
- // show that pick, rather than writing a rate id quoted for the origin
- // the fulfillment just left. The merchant confirms or changes it in a
- // second save, against rates that actually apply.
- const { data: refreshed } = await refetchOrder()
- const requoted = refreshed?.fulfillments?.find(
- (candidate) => candidate.id === fulfillment.id,
- )
-
- form.reset({
- stock_location_id: values.stock_location_id,
- selected_delivery_rate_id: requoted?.selected_delivery_rate_id ?? '',
- })
- return
+ // where the new origin offers one. Pull the fresh fulfillment back so
+ // the merchant confirms that pick against rates that actually apply,
+ // rather than writing a rate id quoted for the origin it just left.
+ await refetchOrder()
+ return 'requote'
}
- if (rateChanged) {
+ if (changed.rate) {
await update.mutateAsync({
fulfillmentId: fulfillment.id,
- selected_delivery_rate_id: values.selected_delivery_rate_id,
+ selected_delivery_rate_id: values.selectedDeliveryRateId,
})
}
- onOpenChange(false)
+ return 'done'
} catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ // A rejected save keeps the dialog open with the server's reason on it;
+ // anything that is not a validation failure is a real fault and toasts.
+ if (!(err instanceof SpreeError)) throw err
+ setErrorMessage(err.message)
+ return 'requote'
}
}
- const { errors, isSubmitting } = form.formState
-
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <form
- onSubmit={(event) => {
- // The order page renders its cards inside their own forms — without
- // stopping the bubble the browser submits the outer one.
- form.handleSubmit(onSubmit)(event)
- event.stopPropagation()
- }}
- >
- <DialogHeader>
- <DialogTitle>{t('admin.orders.detail.fulfillments.edit_title')}</DialogTitle>
- <DialogDescription>
- {t('admin.orders.detail.fulfillments.edit_description')}
- </DialogDescription>
- </DialogHeader>
-
- <DialogBody className="flex flex-col gap-4">
- {errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {errors.root.message}
- </p>
- )}
-
- <Field>
- <FieldLabel htmlFor="fulfillment-location">
- {t('admin.orders.detail.fulfillments.ships_from')}
- </FieldLabel>
- <Controller
- name="stock_location_id"
- control={form.control}
- render={({ field }) => (
- <Select
- items={locationOptions}
- value={field.value}
- onValueChange={(value) => field.onChange(value as string)}
- >
- <SelectTrigger id="fulfillment-location">
- <SelectValue placeholder={t('admin.common.select_placeholder')} />
- </SelectTrigger>
- <SelectContent>
- {locationOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- <FieldError errors={[errors.stock_location_id]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="fulfillment-rate">
- {t('admin.orders.detail.fulfillments.delivery_method')}
- </FieldLabel>
- <Controller
- name="selected_delivery_rate_id"
- control={form.control}
- render={({ field }) => (
- <Select
- items={rateOptions}
- value={field.value}
- disabled={originMoved || rateOptions.length === 0}
- onValueChange={(value) => field.onChange(value as string)}
- >
- <SelectTrigger id="fulfillment-rate">
- <SelectValue placeholder={t('admin.common.select_placeholder')} />
- </SelectTrigger>
- <SelectContent>
- {rateOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- {originMoved && (
- <span className="text-muted-foreground text-xs">
- {t('admin.orders.detail.fulfillments.rates_pending_origin')}
- </span>
- )}
- {!originMoved && rateOptions.length === 0 && (
- <span className="text-muted-foreground text-xs">
- {t('admin.orders.detail.fulfillments.no_rates')}
- </span>
- )}
- </Field>
- </DialogBody>
-
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={isSubmitting}>
- {isSubmitting
- ? t('admin.actions.saving')
- : originMoved
- ? t('admin.orders.detail.fulfillments.move_and_requote')
- : t('admin.actions.save')}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
+ <SharedFulfillmentEditDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ originOptions={originOptions}
+ rateOptions={rateOptions}
+ currentOriginId={currentOriginId}
+ currentRateId={currentRateId}
+ onSubmit={handleSubmit}
+ pending={update.isPending}
+ errorMessage={errorMessage}
+ />
)
}
diff --git a/packages/seller-dashboard/src/components/orders/fulfillment-edit-dialog.tsx b/packages/seller-dashboard/src/components/orders/fulfillment-edit-dialog.tsx
new file mode 100644
index 0000000000..304e6b43cb
--- /dev/null
+++ b/packages/seller-dashboard/src/components/orders/fulfillment-edit-dialog.tsx
@@ -0,0 +1,95 @@
+import { FulfillmentEditDialog as SharedFulfillmentEditDialog } from '@spree/dashboard-ui'
+import { type Fulfillment, SpreeError } from '@spree/seller-sdk'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useFulfillmentActions } from '../../hooks/use-fulfillments'
+import { useOrder } from '../../hooks/use-order'
+import { useStockLocations } from '../../hooks/use-stock-locations'
+
+/**
+ * Where the parcel ships from and which quoted service carries it.
+ *
+ * The dialog is shared with the operator's order page; this supplies the
+ * seller's view of it. The shelves come from the seller's own endpoint, so the
+ * marketplace's warehouses never appear — and the server refuses one anyway.
+ */
+export function FulfillmentEditDialog({
+ orderId,
+ fulfillment,
+ open,
+ onOpenChange,
+}: {
+ orderId: string
+ fulfillment: Fulfillment
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { update } = useFulfillmentActions(orderId)
+ const { data: locationsData } = useStockLocations(open)
+ const { refetch: refetchOrder } = useOrder(orderId)
+ const [errorMessage, setErrorMessage] = useState<string>()
+
+ const originOptions = (locationsData?.data ?? []).map((location) => ({
+ value: location.id,
+ label: location.name,
+ }))
+
+ const rateOptions = (fulfillment.delivery_rates ?? []).map((rate) => ({
+ value: rate.id,
+ label: `${rate.name} — ${
+ Number.parseFloat(rate.cost) === 0 ? t('orders.fulfillments.free') : rate.display_cost
+ }`,
+ }))
+
+ async function handleSubmit(
+ values: { stockLocationId: string; selectedDeliveryRateId: string },
+ changed: { origin: boolean; rate: boolean },
+ ): Promise<'requote' | 'done'> {
+ setErrorMessage(undefined)
+
+ try {
+ if (changed.origin) {
+ await update.mutateAsync({
+ fulfillmentId: fulfillment.id,
+ stock_location_id: values.stockLocationId,
+ })
+
+ // Moving the parcel re-quotes it: the rates on screen were priced from
+ // the shelf it just left. Pull the fresh parcel back so the seller
+ // confirms a service that actually applies.
+ await refetchOrder()
+ return 'requote'
+ }
+
+ if (changed.rate) {
+ await update.mutateAsync({
+ fulfillmentId: fulfillment.id,
+ selected_delivery_rate_id: values.selectedDeliveryRateId,
+ })
+ }
+
+ return 'done'
+ } catch (err) {
+ // A refused save keeps the dialog open with the server's reason on it;
+ // anything else is a real fault and belongs to the caller's toast.
+ if (!(err instanceof SpreeError)) throw err
+ setErrorMessage(err.message)
+ return 'requote'
+ }
+ }
+
+ return (
+ <SharedFulfillmentEditDialog
+ open={open}
+ onOpenChange={onOpenChange}
+ originOptions={originOptions}
+ rateOptions={rateOptions}
+ currentOriginId={fulfillment.stock_location_id ?? ''}
+ currentRateId={fulfillment.selected_delivery_rate_id ?? ''}
+ onSubmit={handleSubmit}
+ pending={update.isPending}
+ errorMessage={errorMessage}
+ />
+ )
+}
diff --git a/packages/seller-dashboard/src/components/orders/fulfillment-origin-dialog.tsx b/packages/seller-dashboard/src/components/orders/fulfillment-origin-dialog.tsx
deleted file mode 100644
index 425de1fbbb..0000000000
--- a/packages/seller-dashboard/src/components/orders/fulfillment-origin-dialog.tsx
+++ /dev/null
@@ -1,148 +0,0 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { mapSpreeErrorsToForm } from '@spree/dashboard-core'
-import {
- Button,
- Dialog,
- DialogBody,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- Field,
- FieldError,
- FieldLabel,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@spree/dashboard-ui'
-import type { Fulfillment } from '@spree/seller-sdk'
-import { Controller, useForm } from 'react-hook-form'
-import { useTranslation } from 'react-i18next'
-import { z } from 'zod/v4'
-import { useFulfillmentActions } from '../../hooks/use-fulfillments'
-import { useStockLocations } from '../../hooks/use-stock-locations'
-
-const originSchema = z.object({
- stock_location_id: z.string().min(1),
-})
-
-type OriginFormValues = z.infer<typeof originSchema>
-
-/**
- * Moves a parcel to a different shelf of this seller's.
- *
- * The split picks an origin from where the stock sat; a seller who actually
- * picks from another of their warehouses needs to say so, and the rate is
- * requoted from there.
- *
- * The list comes from the seller's own endpoint, so the marketplace's
- * warehouses never appear — and the server refuses one anyway.
- */
-export function FulfillmentOriginDialog({
- orderId,
- fulfillment,
- open,
- onOpenChange,
-}: {
- orderId: string
- fulfillment: Fulfillment
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const { update } = useFulfillmentActions(orderId)
- const { data: locationsData } = useStockLocations(open)
-
- const locationOptions = (locationsData?.data ?? []).map((location) => ({
- value: location.id,
- label: location.name,
- }))
-
- const form = useForm<OriginFormValues>({
- resolver: zodResolver(originSchema),
- defaultValues: { stock_location_id: fulfillment.stock_location_id ?? '' },
- })
-
- async function onSubmit(values: OriginFormValues) {
- try {
- await update.mutateAsync({
- fulfillmentId: fulfillment.id,
- stock_location_id: values.stock_location_id,
- })
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <form
- onSubmit={(event) => {
- // The order page renders its cards inside their own forms — without
- // stopping the bubble the browser submits the outer one.
- form.handleSubmit(onSubmit)(event)
- event.stopPropagation()
- }}
- >
- <DialogHeader>
- <DialogTitle>{t('orders.fulfillments.move_origin_title')}</DialogTitle>
- <DialogDescription>
- {t('orders.fulfillments.move_origin_description')}
- </DialogDescription>
- </DialogHeader>
-
- <DialogBody>
- {form.formState.errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {form.formState.errors.root.message}
- </p>
- )}
-
- <Field>
- <FieldLabel htmlFor="fulfillment-origin">
- {t('orders.fulfillments.ships_from_label')}
- </FieldLabel>
- <Controller
- control={form.control}
- name="stock_location_id"
- render={({ field }) => (
- <Select
- items={locationOptions}
- value={field.value}
- onValueChange={(value) => field.onChange((value as string) ?? '')}
- >
- <SelectTrigger id="fulfillment-origin">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {locationOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- <FieldError errors={[form.formState.errors.stock_location_id]} />
- </Field>
- </DialogBody>
-
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
- {t('common.cancel')}
- </Button>
- <Button type="submit" disabled={update.isPending}>
- {update.isPending ? t('common.saving') : t('common.save')}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx b/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx
index 1dbd0c0b23..ebf359511a 100644
--- a/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx
+++ b/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx
@@ -13,16 +13,26 @@ import {
StatusBadge,
useConfirm,
} from '@spree/dashboard-ui'
-import { EllipsisVerticalIcon, MapPinIcon, TruckIcon } from '@spree/dashboard-ui/icons'
+import {
+ EllipsisVerticalIcon,
+ MapPinIcon,
+ PencilIcon,
+ PrinterIcon,
+ SplitIcon,
+ TagIcon,
+ TruckIcon,
+ XCircleIcon,
+} from '@spree/dashboard-ui/icons'
import type { Delivery, Fulfillment, Order } from '@spree/seller-sdk'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useFulfillmentActions } from '../../hooks/use-fulfillments'
+import { printPackingSlip } from '../../lib/packing-slip'
import { FulfillmentDeliveries } from './fulfillment-deliveries'
import { FulfillmentDeliveryDialog } from './fulfillment-delivery-dialog'
+import { FulfillmentEditDialog } from './fulfillment-edit-dialog'
import { FulfillmentFulfillForm } from './fulfillment-fulfill-form'
import { FulfillmentLabelUploadDialog } from './fulfillment-label-upload-dialog'
-import { FulfillmentOriginDialog } from './fulfillment-origin-dialog'
import { FulfillmentSplitDialog } from './fulfillment-split-dialog'
import { unitLabel } from './line-label'
import { ShippingLabelRow } from './shipping-label-row'
@@ -62,7 +72,7 @@ export function FulfillmentsCard({ order }: { order: Order }) {
fulfillments.map((fulfillment) => (
<FulfillmentRow
key={fulfillment.id}
- orderId={order.id}
+ order={order}
currency={order.currency}
fulfillment={fulfillment}
/>
@@ -74,14 +84,15 @@ export function FulfillmentsCard({ order }: { order: Order }) {
}
function FulfillmentRow({
- orderId,
+ order,
currency,
fulfillment,
}: {
- orderId: string
+ order: Order
currency: string
fulfillment: Fulfillment
}) {
+ const orderId = order.id
const { t } = useTranslation()
const confirm = useConfirm()
const { cancel } = useFulfillmentActions(orderId)
@@ -90,7 +101,7 @@ function FulfillmentRow({
const [deliveryOpen, setDeliveryOpen] = useState(false)
const [editingDelivery, setEditingDelivery] = useState<Delivery | undefined>()
const [labelOpen, setLabelOpen] = useState(false)
- const [originOpen, setOriginOpen] = useState(false)
+ const [editOpen, setEditOpen] = useState(false)
const [splitOpen, setSplitOpen] = useState(false)
const status = fulfillment.status ?? ''
@@ -127,27 +138,35 @@ function FulfillmentRow({
}
/>
<DropdownMenuContent align="end">
+ {shippable && (
+ <DropdownMenuItem onClick={() => setEditOpen(true)}>
+ <PencilIcon className="size-4" />
+ {t('admin.actions.edit')}
+ </DropdownMenuItem>
+ )}
+ {splittable && (
+ <DropdownMenuItem onClick={() => setSplitOpen(true)}>
+ <SplitIcon className="size-4" />
+ {t('orders.fulfillments.split')}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem onClick={() => printPackingSlip(order, fulfillment, t)}>
+ <PrinterIcon className="size-4" />
+ {t('orders.fulfillments.print_packing_slip')}
+ </DropdownMenuItem>
<DropdownMenuItem
onClick={() => {
setEditingDelivery(undefined)
setDeliveryOpen(true)
}}
>
+ <TruckIcon className="size-4" />
{t('orders.fulfillments.add_delivery')}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setLabelOpen(true)}>
+ <TagIcon className="size-4" />
{t('orders.fulfillments.upload_label')}
</DropdownMenuItem>
- {shippable && (
- <DropdownMenuItem onClick={() => setOriginOpen(true)}>
- {t('orders.fulfillments.move_origin')}
- </DropdownMenuItem>
- )}
- {splittable && (
- <DropdownMenuItem onClick={() => setSplitOpen(true)}>
- {t('orders.fulfillments.split')}
- </DropdownMenuItem>
- )}
{cancelable && (
<>
<DropdownMenuSeparator />
@@ -156,6 +175,7 @@ function FulfillmentRow({
disabled={cancel.isPending}
onClick={handleCancel}
>
+ <XCircleIcon className="size-4" />
{t('orders.fulfillments.cancel')}
</DropdownMenuItem>
</>
@@ -238,12 +258,12 @@ function FulfillmentRow({
}}
/>
)}
- {originOpen && (
- <FulfillmentOriginDialog
+ {editOpen && (
+ <FulfillmentEditDialog
orderId={orderId}
fulfillment={fulfillment}
open
- onOpenChange={setOriginOpen}
+ onOpenChange={setEditOpen}
/>
)}
{labelOpen && (
diff --git a/packages/seller-dashboard/src/components/orders/order-cards.tsx b/packages/seller-dashboard/src/components/orders/order-cards.tsx
index 3a81430444..69b9373940 100644
--- a/packages/seller-dashboard/src/components/orders/order-cards.tsx
+++ b/packages/seller-dashboard/src/components/orders/order-cards.tsx
@@ -1,84 +1,179 @@
+import { AddressFormDialog } from '@spree/dashboard-core'
import {
AddressBlock,
+ Button,
Card,
- CardContent,
+ CardAction,
CardHeader,
CardTitle,
- Thumbnail,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Separator,
} from '@spree/dashboard-ui'
-import type { Order } from '@spree/seller-sdk'
+import { EllipsisVerticalIcon, PencilIcon } from '@spree/dashboard-ui/icons'
+import type { Order, OrderAddressParams } from '@spree/seller-sdk'
+import { type ReactNode, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { sellerClient } from '../../api-client'
+import { useOrderMutation } from '../../hooks/use-order'
-/** What was bought. */
-export function OrderItemsCard({ order }: { order: Order }) {
- const { t } = useTranslation()
-
+function SummaryRow({
+ label,
+ value,
+ bold,
+ danger,
+ highlight,
+}: {
+ label: string
+ value: ReactNode
+ bold?: boolean
+ danger?: boolean
+ highlight?: boolean
+}) {
return (
- <Card>
- <CardHeader>
- <CardTitle>{t('orders.items')}</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-col gap-3">
- {(order.items ?? []).map((item) => (
- <div key={item.id} className="flex items-center justify-between gap-3">
- <div className="flex min-w-0 items-center gap-3">
- {item.thumbnail_url && <Thumbnail src={item.thumbnail_url} alt={item.name ?? ''} />}
- <div className="min-w-0">
- <div className="truncate text-sm font-medium">{item.name}</div>
- <div className="truncate text-muted-foreground text-xs">
- {[item.sku, item.options_text].filter(Boolean).join(' · ')}
- </div>
- </div>
- </div>
- <div className="flex shrink-0 items-center gap-4 text-sm">
- <span className="text-muted-foreground">× {item.quantity}</span>
- <span>{item.display_total}</span>
- </div>
- </div>
- ))}
- </CardContent>
- </Card>
+ <div
+ className={cn('flex items-center justify-between px-5 py-2.5', highlight && 'bg-muted/50')}
+ >
+ <span className="text-sm">{label}</span>
+ <span
+ className={cn('text-sm tabular-nums', bold && 'font-bold', danger && 'text-destructive')}
+ >
+ {value}
+ </span>
+ </div>
)
}
+function formatDate(iso: string | null | undefined) {
+ if (!iso) return '—'
+ return new Date(iso).toLocaleString()
+}
+
/**
- * What the sale came to.
+ * What the sale came to, and what has been paid against it.
+ *
+ * The same rows the operator sees on their own order page, so a seller
+ * reconciling a payout is reading the same arithmetic — a row appears only
+ * when it carries a figure, which is why a simple order shows three lines and
+ * a discounted, taxed, shipped one shows eight.
*
- * The seller's own figures — what the goods were worth, the tax on them and
- * the total. How the customer paid the marketplace is not shown here: that is
- * the group's payment, and what the seller is owed is the commission ledger.
+ * The items themselves are listed on the parcels above rather than repeated
+ * here: what a seller needs from a line is which parcel it travels in.
*/
export function OrderSummaryCard({ order }: { order: Order }) {
const { t } = useTranslation()
- const rows = [
- { label: t('orders.summary.item_total'), value: order.display_item_total },
- { label: t('orders.summary.tax_total'), value: order.display_tax_total },
- ].filter((row) => !!row.value)
+ const amount = (value: string | null | undefined) => Number.parseFloat(value ?? '0')
+ const outstanding = amount(order.amount_due)
+ const placed = Boolean(order.completed_at)
return (
- <Card>
- <CardHeader>
+ <Card className="py-0">
+ <CardHeader className="px-5 py-4">
<CardTitle>{t('orders.summary.title')}</CardTitle>
</CardHeader>
- <CardContent className="flex flex-col gap-2 text-sm">
- {rows.map((row) => (
- <div key={row.label} className="flex items-center justify-between gap-3">
- <span className="text-muted-foreground">{row.label}</span>
- <span>{row.value}</span>
- </div>
- ))}
- <div className="flex items-center justify-between gap-3 border-t pt-2 font-medium">
- <span>{t('orders.summary.total')}</span>
- <span>{order.display_total}</span>
- </div>
- </CardContent>
+
+ <div className="flex flex-col pb-2">
+ <Separator />
+
+ <SummaryRow label={t('orders.summary.created_at')} value={formatDate(order.created_at)} />
+ {order.completed_at && (
+ <SummaryRow
+ label={t('orders.summary.completed_at')}
+ value={formatDate(order.completed_at)}
+ />
+ )}
+
+ {order.canceled_at && (
+ <>
+ <Separator />
+ <SummaryRow
+ label={t('orders.summary.canceled_at')}
+ value={formatDate(order.canceled_at)}
+ />
+ {order.cancel_reason_name && (
+ <SummaryRow
+ label={t('orders.summary.cancel_reason')}
+ value={order.cancel_reason_name}
+ />
+ )}
+ {order.cancel_note && (
+ <SummaryRow label={t('orders.summary.cancel_note')} value={order.cancel_note} />
+ )}
+ </>
+ )}
+
+ <Separator />
+
+ <SummaryRow label={t('orders.summary.currency')} value={order.currency} />
+
+ <Separator />
+
+ <SummaryRow label={t('orders.summary.subtotal')} value={order.display_item_total} />
+
+ {amount(order.delivery_total) > 0 && (
+ <SummaryRow label={t('orders.summary.shipping')} value={order.display_delivery_total} />
+ )}
+
+ {amount(order.discount_total) !== 0 && (
+ <SummaryRow label={t('orders.summary.promotions')} value={order.display_discount_total} />
+ )}
+
+ {amount(order.adjustment_total) !== 0 && (
+ <SummaryRow
+ label={t('orders.summary.adjustments')}
+ value={order.display_adjustment_total}
+ />
+ )}
+
+ {amount(order.included_tax_total) > 0 && (
+ <SummaryRow
+ label={t('orders.summary.tax_included')}
+ value={order.display_included_tax_total}
+ />
+ )}
+
+ {/* Shown on a placed order even at zero, so "no tax was charged" reads
+ as an answer rather than a missing row. */}
+ {(amount(order.additional_tax_total) > 0 ||
+ (placed && amount(order.included_tax_total) === 0)) && (
+ <SummaryRow
+ label={t('orders.summary.tax_additional')}
+ value={order.display_additional_tax_total}
+ />
+ )}
+
+ <Separator />
+
+ <SummaryRow label={t('orders.summary.total')} value={order.display_total} bold />
+
+ <Separator />
+
+ <SummaryRow
+ label={t('orders.summary.payment_total')}
+ value={order.display_payment_total}
+ highlight
+ />
+ <SummaryRow
+ label={t('orders.summary.outstanding_balance')}
+ value={order.display_amount_due}
+ highlight
+ danger={outstanding > 0}
+ />
+ </div>
</Card>
)
}
/**
- * Where the parcel goes and who the invoice is for.
+ * Where the parcel goes and who the invoice is for, and correcting either.
+ *
+ * The seller is merchant of record for their own child order, so a delivery
+ * address the buyer got wrong is theirs to fix and the invoice address is
+ * what they bill against.
*
* No email address: a seller reaching the customer about a delivery has the
* phone on the shipping address, and an email is the one contact detail that
@@ -86,29 +181,72 @@ export function OrderSummaryCard({ order }: { order: Order }) {
*/
export function OrderCustomerCard({ order }: { order: Order }) {
const { t } = useTranslation()
+ const [editing, setEditing] = useState<'shipping_address' | 'billing_address' | null>(null)
+
+ const save = useOrderMutation(order.id, (params: { type: string; address: OrderAddressParams }) =>
+ sellerClient().orders.address(order.id, { [params.type]: params.address }),
+ )
+
+ const editable = !order.canceled_at
return (
- <Card>
- <CardHeader>
- <CardTitle>{t('orders.customer.title')}</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-col gap-4">
- {order.shipping_address && (
- <div className="flex flex-col gap-1">
- <p className="text-muted-foreground text-xs uppercase">
- {t('orders.shipping_address')}
- </p>
- <AddressBlock address={order.shipping_address} />
- </div>
- )}
- {order.billing_address && (
- <div className="flex flex-col gap-1">
- <p className="text-muted-foreground text-xs uppercase">{t('orders.billing_address')}</p>
- <AddressBlock address={order.billing_address} />
- </div>
- )}
- </CardContent>
- </Card>
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('orders.customer.title')}</CardTitle>
+ {editable && (
+ <CardAction>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button variant="ghost" size="icon-xs" aria-label={t('common.actions')}>
+ <EllipsisVerticalIcon className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditing('shipping_address')}>
+ <PencilIcon className="size-4" />
+ {t('orders.address_edit.shipping_title')}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setEditing('billing_address')}>
+ <PencilIcon className="size-4" />
+ {t('orders.address_edit.billing_title')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </CardAction>
+ )}
+ </CardHeader>
+ <div className="flex flex-col gap-4 px-6 pb-6">
+ <AddressBlock title={t('orders.shipping_address')} address={order.shipping_address} />
+ <AddressBlock title={t('orders.billing_address')} address={order.billing_address} />
+ </div>
+ </Card>
+
+ {/* Mounted only while open, so the form seeds from the address as it is
+ now rather than freezing at first render. */}
+ {editing && (
+ <AddressFormDialog
+ title={
+ editing === 'shipping_address'
+ ? t('orders.address_edit.shipping_title')
+ : t('orders.address_edit.billing_title')
+ }
+ address={editing === 'shipping_address' ? order.shipping_address : order.billing_address}
+ open
+ onOpenChange={(open) => !open && setEditing(null)}
+ onSave={(address) =>
+ save.mutate(
+ { type: editing, address },
+ // Kept open on failure so the entered address is not lost.
+ { onSuccess: () => setEditing(null) },
+ )
+ }
+ isPending={save.isPending}
+ />
+ )}
+ </>
)
}
@@ -122,9 +260,9 @@ export function OrderNoteCard({ order }: { order: Order }) {
<CardHeader>
<CardTitle>{t('orders.customer_note')}</CardTitle>
</CardHeader>
- <CardContent>
- <p className="text-sm whitespace-pre-wrap">{order.customer_note}</p>
- </CardContent>
+ <div className="px-6 pb-6">
+ <p className="whitespace-pre-wrap text-sm">{order.customer_note}</p>
+ </div>
</Card>
)
}
diff --git a/packages/seller-dashboard/src/hooks/use-fulfillments.ts b/packages/seller-dashboard/src/hooks/use-fulfillments.ts
index 675d1935fe..796cc55c85 100644
--- a/packages/seller-dashboard/src/hooks/use-fulfillments.ts
+++ b/packages/seller-dashboard/src/hooks/use-fulfillments.ts
@@ -54,6 +54,7 @@ export function useFulfillmentActions(orderId: string) {
tracking?: string
tracking_carrier?: string
stock_location_id?: string
+ selected_delivery_rate_id?: string
}) => sellerClient().orders.fulfillments.update(orderId, fulfillmentId, params),
)
diff --git a/packages/seller-dashboard/src/lib/packing-slip.ts b/packages/seller-dashboard/src/lib/packing-slip.ts
new file mode 100644
index 0000000000..f62edf2274
--- /dev/null
+++ b/packages/seller-dashboard/src/lib/packing-slip.ts
@@ -0,0 +1,109 @@
+import type { Fulfillment, Order } from '@spree/seller-sdk'
+import type { TFunction } from 'i18next'
+
+function escapeHtml(value: string): string {
+ return value
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+}
+
+function addressBlock(order: Order): string {
+ const address = order.shipping_address
+ if (!address) return ''
+
+ return [
+ [address.first_name, address.last_name].filter(Boolean).join(' '),
+ address.company,
+ address.address1,
+ address.address2,
+ [address.city, address.state_name ?? address.state_code, address.postal_code]
+ .filter(Boolean)
+ .join(', '),
+ address.country_name || address.country_code,
+ ]
+ .filter(Boolean)
+ .map((line) => escapeHtml(String(line)))
+ .join('<br>')
+}
+
+function itemRows(fulfillment: Fulfillment): string {
+ return (fulfillment.fulfillment_items ?? [])
+ .map(
+ (item) => `
+ <tr>
+ <td>
+ ${escapeHtml(item.name ?? item.id)}
+ ${item.options_text ? `<div class="muted">${escapeHtml(item.options_text)}</div>` : ''}
+ </td>
+ <td class="qty">${item.quantity}</td>
+ </tr>`,
+ )
+ .join('')
+}
+
+/**
+ * Opens a printable packing slip for one parcel in a new window.
+ *
+ * A generated document rather than a panel route: the panel's own chrome
+ * would print with an in-app page, and everything the slip needs is already
+ * loaded on the order screen. No prices — a packing slip says what is in the
+ * box, not what it cost.
+ */
+export function printPackingSlip(order: Order, fulfillment: Fulfillment, t: TFunction): void {
+ const title = t('orders.fulfillments.packing_slip_title', { number: order.number })
+
+ const html = `<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>${escapeHtml(title)}</title>
+<style>
+ body { font-family: -apple-system, system-ui, sans-serif; margin: 40px; color: #111; }
+ h1 { font-size: 20px; margin: 0 0 4px; }
+ .muted { color: #666; font-size: 12px; }
+ .columns { display: flex; gap: 48px; margin: 24px 0; }
+ h2 { font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; color: #666; margin: 0 0 6px; }
+ table { width: 100%; border-collapse: collapse; margin-top: 8px; }
+ th { text-align: left; font-size: 12px; text-transform: uppercase; letter-spacing: 0.05em; color: #666;
+ border-bottom: 1px solid #ddd; padding: 6px 0; }
+ td { padding: 8px 0; border-bottom: 1px solid #eee; font-size: 14px; vertical-align: top; }
+ .qty { text-align: right; width: 60px; }
+</style>
+</head>
+<body>
+ <h1>${escapeHtml(title)}</h1>
+ <div class="muted">${escapeHtml(fulfillment.number ?? '')}</div>
+
+ <div class="columns">
+ <div>
+ <h2>${escapeHtml(t('orders.fulfillments.ship_to'))}</h2>
+ <div>${addressBlock(order)}</div>
+ </div>
+ <div>
+ <h2>${escapeHtml(t('orders.fulfillments.ships_from_label'))}</h2>
+ <div>${escapeHtml(fulfillment.stock_location_name ?? '')}</div>
+ </div>
+ </div>
+
+ <table>
+ <thead>
+ <tr>
+ <th>${escapeHtml(t('orders.items'))}</th>
+ <th class="qty">${escapeHtml(t('orders.columns.quantity'))}</th>
+ </tr>
+ </thead>
+ <tbody>${itemRows(fulfillment)}</tbody>
+ </table>
+</body>
+</html>`
+
+ const printWindow = window.open('', '_blank')
+ if (!printWindow) return
+
+ printWindow.document.write(html)
+ printWindow.document.close()
+ printWindow.focus()
+ printWindow.print()
+}
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index 27e1e315cc..f40dd79c4d 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -83,6 +83,19 @@
"unverified": "Not valid",
"verified": "Verified"
}
+ },
+ "orders": {
+ "detail": {
+ "fulfillments": {
+ "delivery_method": "Delivery method",
+ "edit_description": "Change where this fulfillment ships from and which delivery method carries it.",
+ "edit_title": "Edit fulfillment",
+ "move_and_requote": "Move and re-quote",
+ "no_rates": "No delivery methods are quoted for this fulfillment.",
+ "rates_pending_origin": "Save the new origin to see the delivery methods it offers.",
+ "ships_from": "Ships from"
+ }
+ }
}
},
"app": {
@@ -241,19 +254,36 @@
"under_review": "The marketplace is reviewing your application. We will email you when there is news."
},
"orders": {
+ "address_edit": {
+ "billing_title": "Edit Billing Address",
+ "shipping_title": "Edit Shipping Address"
+ },
+ "billing_address": "Billing address",
"cancel": "Cancel order",
"cancel_confirm": {
"message": "The customer is refunded and any stock goes back on the shelf. This cannot be undone.",
"title": "Cancel this order?"
},
+ "cancel_dialog": {
+ "description": "The goods go back on the shelf and the customer is no longer charged for them. Any money already taken is returned by the marketplace, not here.",
+ "reason_label": "Reason",
+ "no_reason": "No reason given",
+ "note_label": "Note",
+ "notify_customer": "Email the customer"
+ },
"canceled": "Order canceled",
"columns": {
"fulfillment": "Fulfillment",
"number": "Order",
"payment": "Payment",
"placed": "Placed",
+ "quantity": "Quantity",
"total": "Total"
},
+ "customer": {
+ "title": "Customer"
+ },
+ "customer_note": "Customer note",
"empty": "No orders yet. They appear here as customers buy from you.",
"fulfill": "Mark as shipped",
"fulfilled": "Marked as shipped",
@@ -266,89 +296,72 @@
"partial": "Partial",
"unfulfilled": "Unfulfilled"
},
- "items": "Items",
- "not_found": "That order could not be found.",
- "payment_statuses": {
- "none": "Unpaid",
- "authorized": "Authorized",
- "partially_paid": "Partially paid",
- "paid": "Paid",
- "partially_refunded": "Partially refunded",
- "refunded": "Refunded",
- "overcharged": "Overcharged",
- "voided": "Voided"
- },
- "search_placeholder": "Search by order number…",
- "shipping_address": "Ships to",
- "ships_from": "Ships from {{name}}",
- "title": "Orders",
- "tracking": "Tracking {{number}}",
- "tracking_label": "Tracking number",
- "tracking_placeholder": "Optional",
- "billing_address": "Billing address",
- "customer_note": "Customer note",
"fulfillments": {
- "title": "Parcels",
- "empty": "Nothing to send on this order.",
- "carrier_label": "Carrier",
- "carrier_auto": "Detect from number",
+ "add_delivery": "Add tracking number",
"add_tracking": "Add tracking",
"add_tracking_title": "Add tracking",
+ "cancel": "Cancel parcel",
+ "cancel_message": "The goods go back on the shelf and the carrier is stood down.",
+ "cancel_title": "Cancel this parcel?",
+ "carrier_auto": "Detect from number",
+ "carrier_label": "Carrier",
+ "carrier_search": "Search carriers…",
+ "carrier_status_available_for_pickup": "Available for pickup",
+ "carrier_status_delivered": "Delivered",
+ "carrier_status_failure": "Failed",
+ "carrier_status_in_transit": "In transit",
+ "carrier_status_out_for_delivery": "Out for delivery",
+ "carrier_status_pending": "Pending",
+ "carrier_status_pre_transit": "Pre-transit",
+ "carrier_status_return_to_sender": "Return to sender",
+ "carrier_status_unknown": "Unknown",
+ "confirm_delete_delivery": "Remove this tracking number?",
+ "confirm_delete_label": "Remove this label? The file is deleted and cannot be printed again.",
+ "confirm_split": "This takes effect immediately.",
+ "delete_label": "Remove label",
"edit_tracking": "Edit tracking",
"edit_tracking_title": "Edit tracking",
- "tracking_description": "The number the customer follows the parcel with.",
- "track_parcel": "Track parcel",
+ "empty": "Nothing to send on this order.",
+ "free": "Free",
+ "label_cost": "Cost {{amount}}",
+ "label_cost_label": "What it cost",
+ "label_title": "Label",
+ "label_uploaded": "Uploaded",
"notify_customer": "Email the customer",
- "units_selected": "{{selected}} of {{total}} units selected",
+ "packing_slip_title": "Packing slip — order {{number}}",
"partial_warning": "Sending part of this parcel moves the rest onto a new one.",
+ "print_label": "Print label",
+ "print_packing_slip": "Print packing slip",
"quantity_for": "Quantity for {{name}}",
- "cancel": "Cancel parcel",
- "cancel_title": "Cancel this parcel?",
- "cancel_message": "The goods go back on the shelf and the carrier is stood down.",
+ "ship_to": "Ship to",
+ "ships_from_label": "Ships from",
"split": "Split",
- "splitting": "Splitting…",
- "split_title": "Split this parcel",
"split_description": "Move part of what this parcel holds onto one of its own.",
"split_item": "Item",
"split_quantity": "Quantity to move",
+ "split_title": "Split this parcel",
"split_would_empty": "Moving everything would leave this parcel empty.",
- "confirm_split": "This takes effect immediately.",
- "add_delivery": "Add tracking number",
- "carrier_search": "Search carriers…",
- "confirm_delete_delivery": "Remove this tracking number?",
- "carrier_status_pending": "Pending",
- "carrier_status_pre_transit": "Pre-transit",
- "carrier_status_in_transit": "In transit",
- "carrier_status_out_for_delivery": "Out for delivery",
- "carrier_status_available_for_pickup": "Available for pickup",
- "carrier_status_delivered": "Delivered",
- "carrier_status_return_to_sender": "Return to sender",
- "carrier_status_failure": "Failed",
- "carrier_status_unknown": "Unknown",
+ "splitting": "Splitting…",
+ "title": "Parcels",
+ "track_parcel": "Track parcel",
+ "tracking_description": "The number the customer follows the parcel with.",
+ "units_selected": "{{selected}} of {{total}} units selected",
"upload_label": "Upload postage",
- "upload_label_title": "Upload postage",
"upload_label_description": "Record a label you bought elsewhere, so the parcel carries its file and tracking number.",
"upload_label_file": "Label file",
- "label_title": "Label",
- "label_uploaded": "Uploaded",
- "label_cost": "Cost {{amount}}",
- "label_cost_label": "What it cost",
- "print_label": "Print label",
- "delete_label": "Remove label",
- "confirm_delete_label": "Remove this label? The file is deleted and cannot be printed again.",
- "move_origin": "Change where it ships from",
- "move_origin_title": "Change where it ships from",
- "move_origin_description": "Pick the shelf this parcel is actually picked from. The delivery rate is requoted from there.",
- "ships_from_label": "Ships from"
+ "upload_label_title": "Upload postage"
},
- "summary": {
- "title": "Summary",
- "item_total": "Items",
- "tax_total": "Tax",
- "total": "Total"
- },
- "customer": {
- "title": "Customer"
+ "items": "Items",
+ "not_found": "That order could not be found.",
+ "payment_statuses": {
+ "none": "Unpaid",
+ "authorized": "Authorized",
+ "partially_paid": "Partially paid",
+ "paid": "Paid",
+ "partially_refunded": "Partially refunded",
+ "refunded": "Refunded",
+ "overcharged": "Overcharged",
+ "voided": "Voided"
},
"post_sale": {
"reason": "Reason",
@@ -416,13 +429,33 @@
"cancel_message": "The customer is told it will not go ahead."
}
},
- "cancel_dialog": {
- "description": "The goods go back on the shelf and the customer is no longer charged for them. Any money already taken is returned by the marketplace, not here.",
- "reason_label": "Reason",
- "no_reason": "No reason given",
- "note_label": "Note",
- "notify_customer": "Email the customer"
- }
+ "search_placeholder": "Search by order number…",
+ "shipping_address": "Ships to",
+ "ships_from": "Ships from {{name}}",
+ "summary": {
+ "adjustments": "Adjustments",
+ "cancel_note": "Cancellation note",
+ "cancel_reason": "Cancellation reason",
+ "canceled_at": "Canceled at",
+ "completed_at": "Completed at",
+ "created_at": "Created at",
+ "currency": "Currency",
+ "item_total": "Items",
+ "outstanding_balance": "Outstanding balance",
+ "payment_total": "Payment total",
+ "promotions": "Promotions",
+ "shipping": "Shipping",
+ "subtotal": "Subtotal",
+ "tax_additional": "Tax (additional)",
+ "tax_included": "Tax (included)",
+ "tax_total": "Tax",
+ "title": "Summary",
+ "total": "Total"
+ },
+ "title": "Orders",
+ "tracking": "Tracking {{number}}",
+ "tracking_label": "Tracking number",
+ "tracking_placeholder": "Optional"
},
"policies": {
"add": "Add policy",
diff --git a/packages/seller-dashboard/src/pages/order.tsx b/packages/seller-dashboard/src/pages/order.tsx
index ac0208ed4c..87bef92b72 100644
--- a/packages/seller-dashboard/src/pages/order.tsx
+++ b/packages/seller-dashboard/src/pages/order.tsx
@@ -8,7 +8,6 @@ import { FulfillmentsCard } from '../components/orders/fulfillments-card'
import { OrderCancelDialog } from '../components/orders/order-cancel-dialog'
import {
OrderCustomerCard,
- OrderItemsCard,
OrderNoteCard,
OrderSummaryCard,
} from '../components/orders/order-cards'
@@ -95,7 +94,6 @@ export function OrderPage() {
<ClaimsCard order={order} />
</>
)}
- <OrderItemsCard order={order} />
<OrderSummaryCard order={order} />
</>
}
diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.ts
index 29a0943cd3..d58e9642c0 100644
--- a/packages/seller-sdk/src/index.ts
+++ b/packages/seller-sdk/src/index.ts
@@ -16,6 +16,7 @@ export type {
DeliveryZoneListParams,
MeResponse,
OnboardingResponse,
+ OrderAddressParams,
PermissionRule,
ProductParams,
ProfileUpdateParams,
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 5f70a0b86a..2727223e98 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -402,6 +402,22 @@ export class SellerClient {
): Promise<Order> =>
this.request<Order>('PATCH', `/orders/${id}/cancel`, { ...options, body: params }),
+ /**
+ * Corrects where the goods go or who the invoice names.
+ *
+ * Send only the lines that change: the rest of the address is carried
+ * over. Nothing else about the order is writable here.
+ */
+ address: (
+ id: string,
+ params: {
+ shipping_address?: OrderAddressParams
+ billing_address?: OrderAddressParams
+ },
+ options?: RequestOptions,
+ ): Promise<Order> =>
+ this.request<Order>('PATCH', `/orders/${id}/address`, { ...options, body: params }),
+
/** The parcels owed on one order. */
fulfillments: {
list: (orderId: string, options?: RequestOptions): Promise<{ data: Fulfillment[] }> =>
@@ -431,13 +447,8 @@ export class SellerClient {
}),
/**
- * The tracked consignments of one of the seller's parcels. A seller
- * ships on manual methods, so tracking numbers are entered here by hand.
- */
- /**
- * The tracking number and its carrier. Where a parcel ships from and
- * which service carries it are the marketplace's arrangements, so they
- * are not editable here.
+ * The tracking pair, where the parcel ships from, and which quoted
+ * service carries it.
*/
update: (
orderId: string,
@@ -445,8 +456,10 @@ export class SellerClient {
params: {
tracking?: string
tracking_carrier?: string
- /** One of this seller's own shelves; the rate requotes from there. */
+ /** One of this seller's own shelves; the rates requote from there. */
stock_location_id?: string
+ /** One of the rates quoted for this parcel from its current origin. */
+ selected_delivery_rate_id?: string
},
options?: RequestOptions,
): Promise<Fulfillment> =>
@@ -476,6 +489,10 @@ export class SellerClient {
{ ...options, body: params },
),
+ /**
+ * The tracked consignments of one of the seller's parcels. A seller
+ * ships on manual methods, so tracking numbers are entered here by hand.
+ */
deliveries: {
list: (
orderId: string,
@@ -1525,6 +1542,27 @@ export interface ProfileUpdateParams {
accept_terms?: boolean
}
+/**
+ * A correction to one of an order's addresses. Every field is optional: send
+ * the lines that change and the rest of the address is carried over.
+ */
+export interface OrderAddressParams {
+ first_name?: string
+ last_name?: string
+ company?: string
+ address1?: string
+ address2?: string
+ city?: string
+ postal_code?: string
+ zipcode?: string
+ phone?: string
+ alternative_phone?: string
+ country_code?: string
+ state_code?: string
+ state_name?: string
+ label?: string
+}
+
export interface SellerAddressParams {
first_name?: string
last_name?: string
diff --git a/packages/seller-sdk/src/types/generated/DeliveryRate.ts b/packages/seller-sdk/src/types/generated/DeliveryRate.ts
new file mode 100644
index 0000000000..aee5972ae6
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/DeliveryRate.ts
@@ -0,0 +1,18 @@
+// Typelizer digest 6d15eafc9399706573394b1e713b6047
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type DeliveryRate = {
+ id: string;
+ name: string;
+ selected: boolean;
+ cost: string;
+ total: string;
+ carrier: string | null;
+ service_level: string | null;
+ estimated_delivery_date: string | null;
+ display_cost: string;
+ display_total: string;
+}
+
+export default DeliveryRate;
diff --git a/packages/seller-sdk/src/types/generated/Fulfillment.ts b/packages/seller-sdk/src/types/generated/Fulfillment.ts
index 98c090d1b8..cbbfc65294 100644
--- a/packages/seller-sdk/src/types/generated/Fulfillment.ts
+++ b/packages/seller-sdk/src/types/generated/Fulfillment.ts
@@ -1,7 +1,7 @@
-// Typelizer digest 902868040aa1739b22a97c77500a05eb
+// Typelizer digest 8382e252c41007fe85c98aa828e1fe1d
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
-import type {FulfillmentItem, Delivery, ShippingLabel} from '@/types'
+import type {FulfillmentItem, DeliveryRate, Delivery, ShippingLabel} from '@/types'
type Fulfillment = {
id: string;
@@ -18,6 +18,8 @@ type Fulfillment = {
stock_location_name: string | null;
stock_location_id: string | null;
fulfillment_items: Array<FulfillmentItem>;
+ selected_delivery_rate_id: string | null;
+ delivery_rates: Array<DeliveryRate>;
deliveries: Array<Delivery>;
labels: Array<ShippingLabel>;
}
diff --git a/packages/seller-sdk/src/types/generated/Order.ts b/packages/seller-sdk/src/types/generated/Order.ts
index 948a6fba11..aac1bbdacc 100644
--- a/packages/seller-sdk/src/types/generated/Order.ts
+++ b/packages/seller-sdk/src/types/generated/Order.ts
@@ -1,4 +1,4 @@
-// Typelizer digest afcb8676be0f97d4e914ccad7121c0f6
+// Typelizer digest 002e16db3ac4a4ac0be83d07a080d9dd
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {OrderLineItem, Fulfillment, Address} from '@/types'
@@ -17,10 +17,27 @@ type Order = {
updated_at: string;
item_total: string | null;
display_item_total: string | null;
+ delivery_total: string | null;
+ display_delivery_total: string | null;
+ discount_total: string | null;
+ display_discount_total: string | null;
+ adjustment_total: string | null;
+ display_adjustment_total: string | null;
+ included_tax_total: string | null;
+ display_included_tax_total: string | null;
+ additional_tax_total: string | null;
+ display_additional_tax_total: string | null;
tax_total: string | null;
display_tax_total: string | null;
total: string | null;
display_total: string | null;
+ payment_total: string | null;
+ display_payment_total: string | null;
+ amount_due: string | null;
+ display_amount_due: string | null;
+ canceled_at: string | null;
+ cancel_reason_name: string | null;
+ cancel_note: string | null;
items: Array<OrderLineItem>;
fulfillments: Array<Fulfillment>;
shipping_address: Address;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index 7ea7831238..9a1a09b773 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 1c6e6c4f7f20af237f859b4dc2616496
+// Typelizer digest a94a938bb67ba4ce4555b3944e9992fe
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -13,6 +13,7 @@ export type { default as Claim } from './Claim'
export type { default as DeliveryMethodRule } from './DeliveryMethodRule'
export type { default as DeliveryMethod } from './DeliveryMethod'
export type { default as DeliveryProfile } from './DeliveryProfile'
+export type { default as DeliveryRate } from './DeliveryRate'
export type { default as Delivery } from './Delivery'
export type { default as DeliveryZone } from './DeliveryZone'
export type { default as ExchangeLineItem } from './ExchangeLineItem'
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
index a704e4c91a..3747575c6c 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb
@@ -62,10 +62,10 @@ module Spree
# PATCH /api/v3/seller/orders/:order_id/fulfillments/:id
#
- # The tracking pair, and which of the seller's own shelves the
- # parcel ships from — a seller who picks from a different warehouse
- # than the split assumed needs to say so, and the rate is requoted
- # from there.
+ # The tracking pair, which of the seller's own shelves the parcel
+ # ships from, and which quoted service carries it — a seller who
+ # picks from a different warehouse than the split assumed needs to
+ # say so, and the rates are requoted from there.
#
# The origin is resolved through `current_seller.stock_locations`,
# so a marketplace warehouse is unreachable however the id arrives.
@@ -142,10 +142,13 @@ module Spree
:selected_delivery_rate_id)
end
- # The payload the workflow gets. The workflow takes a raw
- # `stock_location_id`, so the prefixed id is resolved through the
- # seller's own shelves first — a marketplace warehouse 404s here
- # rather than reaching the assignment.
+ # The payload the workflow gets. The workflow assigns the origin
+ # raw, so the prefixed id is resolved through the seller's own
+ # shelves first — a marketplace warehouse 404s here rather than
+ # reaching the assignment. The rate needs no such resolution: the
+ # model's own writer takes the prefixed id and looks it up among
+ # this parcel's quotes, so a rate belonging to another package is
+ # already unreachable.
def update_attributes
attributes = update_params.to_h
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
index f96fbed64e..0b51e86ba7 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
@@ -12,16 +12,16 @@ module Spree
# neither an in-flight checkout nor the operator's working document —
# and are unreachable from every endpoint on this branch.
#
- # Read and cancel only. Fulfilling is the fulfillments endpoint under
- # the order, and everything that settles money with the customer —
- # approving, resuming, refunds, payments — stays with the operator,
- # who owns that relationship.
+ # Read, cancel, and correct an address. Fulfilling is the
+ # fulfillments endpoint under the order, and everything that settles
+ # money with the customer — approving, resuming, refunds, payments —
+ # stays with the operator, who owns that relationship.
class OrdersController < Seller::ResourceController
include Spree::Api::V3::OrderLock
scoped_resource :orders
- before_action :set_resource, only: [:show, :cancel]
+ before_action :set_resource, only: [:show, :cancel, :address]
# PATCH /api/v3/seller/orders/:id/cancel
#
@@ -51,6 +51,26 @@ module Spree
end
end
+ # PATCH /api/v3/seller/orders/:id/address
+ #
+ # Corrects where the goods go or who the invoice names. The seller is
+ # merchant of record for their own child order, so a delivery address
+ # the buyer got wrong is theirs to fix.
+ #
+ # Its own action rather than a general PATCH: an order's terms are
+ # the marketplace's, and a write that took whatever the serializer
+ # permits would quietly grow into one a seller could reprice with.
+ def address
+ attributes = address_params
+ return render_validation_error(missing_address_errors) if attributes.blank?
+
+ if @resource.update(attributes)
+ render json: serialize_resource(@resource.reload)
+ else
+ render_validation_error(@resource.errors)
+ end
+ end
+
protected
def model_class
@@ -78,6 +98,61 @@ module Spree
private
+ # Either address, as a correction rather than a replacement: the
+ # sent fields are laid over what the order already holds, so a
+ # request naming one line does not blank out the country and
+ # postcode beside it. The nested writer builds a fresh address row
+ # either way, which is what keeps a shared customer address book
+ # entry from being rewritten by an order-level fix.
+ def address_params
+ permitted = params.permit(
+ shipping_address: address_permitted_keys,
+ billing_address: address_permitted_keys
+ )
+
+ {}.tap do |attributes|
+ if permitted[:shipping_address].present?
+ attributes[:ship_address_attributes] =
+ merged_address(@resource.ship_address, permitted[:shipping_address])
+ end
+
+ if permitted[:billing_address].present?
+ attributes[:bill_address_attributes] =
+ merged_address(@resource.bill_address, permitted[:billing_address])
+ end
+ end
+ end
+
+ def merged_address(address, sent)
+ current = address ? address.attributes.slice(*address_attribute_names) : {}
+ current.merge(sent.to_h)
+ end
+
+ # The permitted keys that are real columns; the rest are the writer
+ # aliases a client may send, which have no value to carry over.
+ def address_attribute_names
+ @address_attribute_names ||=
+ address_permitted_keys.map(&:to_s) & Spree::Address.column_names
+ end
+
+ def address_permitted_keys
+ [
+ :firstname, :lastname, :first_name, :last_name,
+ :address1, :address2, :city,
+ :country_code, :state_code,
+ :zipcode, :postal_code, :phone, :alternative_phone,
+ :state_name, :company, :label
+ ]
+ end
+
+ # A request naming neither address has asked for nothing; saying so
+ # beats a 200 that changed nothing.
+ def missing_address_errors
+ ActiveModel::Errors.new(@resource).tap do |errors|
+ errors.add(:base, :blank, message: 'shipping_address or billing_address is required')
+ end
+ end
+
# The reason a seller picked, resolved through the store's own list so
# a reason belonging to another store reads as missing. Optional —
# the workflow accepts a cancellation with none.
@@ -94,10 +169,10 @@ module Spree
authorize_resource!(@resource)
end
- # Cancelling is a change to the order, so it needs the write key
- # rather than a key of its own.
+ # Cancelling and correcting an address are both changes to the
+ # order, so they need the write key rather than a key of their own.
def authorize_resource!(resource = @resource, action = action_name.to_sym)
- authorize!(action == :cancel ? :update : action, resource)
+ authorize!(%i[cancel address].include?(action) ? :update : action, resource)
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/delivery_rate_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/delivery_rate_serializer.rb
new file mode 100644
index 0000000000..061ff806ca
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/delivery_rate_serializer.rb
@@ -0,0 +1,35 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A priced service one of this seller's parcels could be carried by.
+ #
+ # Declared rather than subclassed from the store's rate, which expands
+ # the delivery method in full: a seller picks between quotes by name
+ # and price, and the method behind one is the operator's arrangement.
+ class DeliveryRateSerializer < V3::BaseSerializer
+ typelize name: :string,
+ selected: :boolean,
+ cost: :string,
+ display_cost: :string,
+ total: :string,
+ display_total: :string,
+ carrier: [:string, nullable: true],
+ service_level: [:string, nullable: true],
+ estimated_delivery_date: [:string, nullable: true]
+
+ attributes :name, :selected, :cost, :total,
+ :carrier, :service_level, :estimated_delivery_date
+
+ attribute :display_cost do |delivery_rate|
+ delivery_rate.display_cost.to_s
+ end
+
+ attribute :display_total do |delivery_rate|
+ delivery_rate.display_total.to_s
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/fulfillment_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/fulfillment_serializer.rb
index 31358e829e..d3a1fa9c2a 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/fulfillment_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/fulfillment_serializer.rb
@@ -4,10 +4,14 @@ module Spree
module Seller
# A parcel this seller owes on one of their orders.
#
- # Declared rather than subclassed from the store's fulfillment, which
- # nests delivery rates and the store's own stock location serializer —
- # rate selection is a checkout concern, and the location a seller cares
- # about is their own shelf, named here rather than expanded.
+ # Declared rather than subclassed from the store's fulfillment, whose
+ # stock location serializer is the store's own — the location a seller
+ # cares about is their own shelf, named here rather than expanded.
+ #
+ # The delivery rates quoted for this parcel are here, because a seller
+ # picking from a different shelf needs to see what that origin can be
+ # carried by. A rate carries only its name and its price, so nothing
+ # about the operator's arrangements comes with it.
class FulfillmentSerializer < V3::BaseSerializer
typelize number: :string,
status: :string,
@@ -16,7 +20,8 @@ module Spree
fulfillment_type: [:string, nullable: true],
delivery_method_name: [:string, nullable: true],
stock_location_name: [:string, nullable: true],
- stock_location_id: [:string, nullable: true]
+ stock_location_id: [:string, nullable: true],
+ selected_delivery_rate_id: [:string, nullable: true]
attributes :number, :status, :tracking, :tracking_url,
fulfilled_at: :iso8601, delivered_at: :iso8601, created_at: :iso8601, updated_at: :iso8601
@@ -55,6 +60,13 @@ module Spree
# The consignments and labels on this parcel — what a seller adds
# when they ship it themselves.
+ attribute :selected_delivery_rate_id do |fulfillment|
+ fulfillment.selected_delivery_rate&.prefixed_id
+ end
+
+ # What this parcel could be carried by from where it currently sits.
+ many :delivery_rates, resource: proc { Spree.api.seller_delivery_rate_serializer }
+
many :deliveries, resource: proc { Spree.api.seller_delivery_serializer }
many :shipping_labels, key: :labels, resource: proc { Spree.api.seller_shipping_label_serializer }
end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/order_serializer.rb
index 624afffdc6..3f35ef7e14 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/order_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/order_serializer.rb
@@ -28,8 +28,18 @@ module Spree
payment_status: [:string, nullable: true],
status: :string,
item_total: [:string, nullable: true], display_item_total: [:string, nullable: true],
+ delivery_total: [:string, nullable: true], display_delivery_total: [:string, nullable: true],
+ discount_total: [:string, nullable: true], display_discount_total: [:string, nullable: true],
+ adjustment_total: [:string, nullable: true], display_adjustment_total: [:string, nullable: true],
+ included_tax_total: [:string, nullable: true], display_included_tax_total: [:string, nullable: true],
+ additional_tax_total: [:string, nullable: true], display_additional_tax_total: [:string, nullable: true],
tax_total: [:string, nullable: true], display_tax_total: [:string, nullable: true],
- total: [:string, nullable: true], display_total: [:string, nullable: true]
+ total: [:string, nullable: true], display_total: [:string, nullable: true],
+ payment_total: [:string, nullable: true], display_payment_total: [:string, nullable: true],
+ amount_due: [:string, nullable: true], display_amount_due: [:string, nullable: true],
+ canceled_at: [:string, nullable: true],
+ cancel_reason_name: [:string, nullable: true],
+ cancel_note: [:string, nullable: true]
attributes :number, :customer_note, :currency, :total_quantity,
:status, :fulfillment_status, :payment_status,
@@ -39,8 +49,28 @@ module Spree
# them. Deliberately not the whole money surface: gift cards, store
# credit and the payment breakdown belong to the marketplace.
money_attributes :item_total, :display_item_total,
+ :delivery_total, :display_delivery_total,
+ :discount_total, :display_discount_total,
+ :adjustment_total, :display_adjustment_total,
+ :included_tax_total, :display_included_tax_total,
+ :additional_tax_total, :display_additional_tax_total,
:tax_total, :display_tax_total,
- :total, :display_total
+ :total, :display_total,
+ :payment_total, :display_payment_total,
+ :amount_due, :display_amount_due
+
+ # Why the sale was called off, when it was. The reason is the
+ # marketplace's vocabulary, so it is rendered as a name rather than
+ # an id a seller has nothing else to do with.
+ attribute :canceled_at do |order|
+ order.canceled_at&.iso8601
+ end
+
+ attribute :cancel_reason_name do |order|
+ order.cancel_reason&.name
+ end
+
+ attributes :cancel_note
many :line_items, key: :items, resource: proc { Spree.api.seller_order_line_item_serializer }
many :fulfillments, resource: proc { Spree.api.seller_fulfillment_serializer }
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 55690f5631..a627b6e039 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -858,9 +858,16 @@ Spree::Core::Engine.add_routes do
# What this seller has sold. Cancelling is a member action because it
# is a workflow with its own arguments, and fulfilling is nested: a
# parcel means nothing outside the order it belongs to.
+ #
+ # No `update`: an order is created by a shopper checking out and its
+ # terms are the marketplace's, so the branch routes no general write.
+ # Correcting a delivery address is the one exception a merchant of
+ # record needs, and it is its own named action rather than a PATCH
+ # that would accept whatever the order serializer happens to permit.
resources :orders, only: [:index, :show] do
member do
patch :cancel
+ patch :address
end
# No `mark_delivered`: that a parcel arrived is the buyer's word,
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 46786f8770..facdcb4518 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -189,6 +189,7 @@ module Spree
seller_fulfillment_serializer: 'Spree::Api::V3::Seller::FulfillmentSerializer',
seller_fulfillment_item_serializer: 'Spree::Api::V3::Seller::FulfillmentItemSerializer',
seller_delivery_serializer: 'Spree::Api::V3::Seller::DeliverySerializer',
+ seller_delivery_rate_serializer: 'Spree::Api::V3::Seller::DeliveryRateSerializer',
seller_shipping_label_serializer: 'Spree::Api::V3::Seller::ShippingLabelSerializer',
seller_return_serializer: 'Spree::Api::V3::Seller::ReturnSerializer',
seller_return_line_item_serializer: 'Spree::Api::V3::Seller::ReturnLineItemSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/orders/fulfillments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/orders/fulfillments_controller_spec.rb
index 1e8c139fad..ee74654cbb 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/orders/fulfillments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/orders/fulfillments_controller_spec.rb
@@ -139,6 +139,35 @@ RSpec.describe Spree::Api::V3::Seller::Orders::FulfillmentsController, type: :co
expect(response).to have_http_status(:not_found)
expect(fulfillment.reload.stock_location_id).to eq(original)
end
+
+ # A seller chooses between the services quoted for their own parcel.
+ it 'selects one of the rates quoted for the parcel' do
+ rate = create(:delivery_rate, fulfillment: fulfillment)
+
+ patch :update, params: {
+ order_id: order.prefixed_id, id: fulfillment.prefixed_id,
+ selected_delivery_rate_id: rate.prefixed_id
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(fulfillment.reload.selected_delivery_rate).to eq(rate)
+ end
+
+ # Rates are quoted per parcel, so one belonging to another package is not
+ # a choice this fulfillment has — the id reads as missing rather than
+ # being assigned to a rate the parcel never offered.
+ it 'refuses a rate quoted for another parcel' do
+ other_fulfillment = create(:fulfillment, order: create(:order, store: store))
+ other_rate = create(:delivery_rate, fulfillment: other_fulfillment)
+
+ patch :update, params: {
+ order_id: order.prefixed_id, id: fulfillment.prefixed_id,
+ selected_delivery_rate_id: other_rate.prefixed_id
+ }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ expect(fulfillment.reload.selected_delivery_rate).not_to eq(other_rate)
+ end
end
describe 'PATCH #cancel' do
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb
index da438ea25f..f4033abc5b 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb
@@ -83,6 +83,72 @@ RSpec.describe Spree::Api::V3::Seller::OrdersController, type: :controller do
end
end
+ # A seller is merchant of record for their own child order, so a delivery
+ # address the buyer got wrong is theirs to correct.
+ describe 'PATCH #address' do
+ it 'corrects the shipping address, keeping the lines it was not sent' do
+ original = mine.ship_address
+ original_line = original.address1
+
+ patch :address, params: {
+ id: mine.prefixed_id,
+ shipping_address: { address1: '9 Corrected Way', city: 'Fixedton' }
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ address = mine.reload.ship_address
+ expect(address.address1).to eq('9 Corrected Way')
+ expect(address.city).to eq('Fixedton')
+ # A request naming two lines must not blank out the rest of the address.
+ expect(address.country_code).to eq(original.country_code)
+ expect(address.postal_code).to eq(original.postal_code)
+ # The order points at a new row: an order-level fix is not a rewrite of
+ # the address the customer may also have saved in their own book.
+ expect(address.id).not_to eq(original.id)
+ expect(original.reload.address1).to eq(original_line)
+ end
+
+ it 'corrects the billing address' do
+ patch :address, params: {
+ id: mine.prefixed_id,
+ billing_address: { address1: '4 Invoice Street' }
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.bill_address.address1).to eq('4 Invoice Street')
+ end
+
+ # Nothing else about the order is the seller's to write, so an attribute
+ # that is not one of the two addresses is simply not read.
+ it 'ignores anything that is not an address' do
+ original_total = mine.total
+
+ patch :address, params: {
+ id: mine.prefixed_id,
+ shipping_address: { city: 'Fixedton' },
+ total: '0.01',
+ customer_note: 'rewritten'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.total).to eq(original_total)
+ end
+
+ it 'refuses a request naming neither address' do
+ patch :address, params: { id: mine.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it "404s on another seller's order" do
+ patch :address, params: {
+ id: theirs.prefixed_id, shipping_address: { city: 'Fixedton' }
+ }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
describe 'GET #show' do
it 'renders what the seller needs to pack the parcel' do
get :show, params: { id: mine.prefixed_id }, as: :json
diff --git a/spree/api/spec/integration/spree/api/v3/seller/orders_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/orders_spec.rb
index 6020675267..e574ca2fe3 100644
--- a/spree/api/spec/integration/spree/api/v3/seller/orders_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/seller/orders_spec.rb
@@ -145,6 +145,77 @@ RSpec.describe 'Seller Orders API', type: :request, swagger_doc: 'api-reference/
end
end
+ path '/api/v3/seller/orders/{id}/address' do
+ parameter name: :id, in: :path, type: :string, description: 'Prefixed order ID'
+
+ patch 'Correct an order address' do
+ tags 'Orders'
+ consumes 'application/json'
+ produces 'application/json'
+ security [bearer_auth: []]
+ description <<~DESC
+ Corrects where the goods go or who the invoice names.
+
+ The seller is merchant of record for their own child order, so a
+ delivery address the buyer got wrong is theirs to fix. Send only the
+ lines that change — the rest of the address is carried over.
+
+ This is the only write against the order itself besides cancelling:
+ nothing else about it, its totals included, is the seller's to change.
+ DESC
+
+ address_correction = {
+ type: :object,
+ description: 'Only the lines that change; the rest is carried over',
+ properties: {
+ first_name: { type: :string },
+ last_name: { type: :string },
+ company: { type: :string, nullable: true },
+ address1: { type: :string },
+ address2: { type: :string, nullable: true },
+ city: { type: :string },
+ postal_code: { type: :string },
+ country_code: { type: :string },
+ state_code: { type: :string, nullable: true },
+ state_name: { type: :string, nullable: true },
+ phone: { type: :string, nullable: true },
+ label: { type: :string, nullable: true }
+ }
+ }
+
+ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true
+ parameter name: :body, in: :body, required: true, schema: {
+ type: :object,
+ properties: {
+ shipping_address: address_correction,
+ billing_address: address_correction
+ }
+ }
+
+ response '200', 'address corrected' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:id) { order.prefixed_id }
+ let(:body) { { shipping_address: { address1: '9 Corrected Way', city: 'Fixedton' } } }
+
+ schema '$ref' => '#/components/schemas/Order'
+
+ run_test! do
+ expect(order.reload.ship_address.city).to eq('Fixedton')
+ end
+ end
+
+ response '422', 'neither address named' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:id) { order.prefixed_id }
+ let(:body) { {} }
+
+ run_test!
+ end
+ end
+ end
+
path '/api/v3/seller/order_cancellation_reasons' do
get 'List order cancellation reasons' do
tags 'Orders'