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.

Share the post-sale create dialogs and give sellers order notes

Damian Legawiec215f252a1f9b
diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yaml
index 9cb712e47d..4f0959947e 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 67
+ name: Seller 70
status: approved
schema:
"$ref": "#/components/schemas/AuthResponse"
@@ -13540,8 +13540,8 @@ paths:
example:
data:
- id: prod_UkLWZg9DAJ
- name: Product 1703250
- slug: product-1703250
+ name: Product 1733250
+ slug: product-1733250
meta_title:
meta_description:
meta_keywords:
@@ -13784,8 +13784,8 @@ paths:
application/json:
example:
id: prod_UkLWZg9DAJ
- name: Product 1736710
- slug: product-1736710
+ name: Product 1766710
+ slug: product-1766710
meta_title:
meta_description:
meta_keywords:
@@ -13864,7 +13864,7 @@ paths:
example:
id: prod_UkLWZg9DAJ
name: Hand-thrown mug, large
- slug: product-1768212
+ slug: product-1798212
meta_title:
meta_description:
meta_keywords:
@@ -13977,8 +13977,8 @@ paths:
application/json:
example:
id: sel_UkLWZg9DAJ
- name: Seller 84
- slug: seller-84
+ name: Seller 87
+ slug: seller-87
about: ''
about_html: ''
logo_url:
@@ -14050,7 +14050,7 @@ paths:
example:
id: sel_UkLWZg9DAJ
name: Acme Supplies
- slug: seller-86
+ slug: seller-89
about: ''
about_html: ''
logo_url:
@@ -15634,6 +15634,16 @@ paths:
updated_at: '2026-01-15T12:00:00.000Z'
shipping_label_id:
labels: []
+ meta:
+ page: 1
+ limit: 25
+ count: 1
+ pages: 1
+ from: 1
+ to: 1
+ in: 1
+ previous:
+ next:
schema:
type: object
properties:
@@ -16072,6 +16082,8 @@ paths:
completed_at: '2026-01-15T12:00:00.000Z'
created_at: '2026-01-15T12:00:00.000Z'
updated_at: '2026-01-15T12:00:00.000Z'
+ internal_note:
+ internal_note_html:
item_total: '10.0'
display_item_total: "$10.00"
delivery_total: '100.0'
@@ -16265,6 +16277,8 @@ paths:
completed_at: '2026-01-15T12:00:00.000Z'
created_at: '2026-01-15T12:00:00.000Z'
updated_at: '2026-01-15T12:00:00.000Z'
+ internal_note:
+ internal_note_html:
item_total: '10.0'
display_item_total: "$10.00"
delivery_total: '100.0'
@@ -16450,6 +16464,8 @@ paths:
completed_at: '2026-01-15T12:00:00.000Z'
created_at: '2026-01-15T12:00:00.000Z'
updated_at: '2026-01-15T12:00:00.000Z'
+ internal_note:
+ internal_note_html:
item_total: '10.0'
display_item_total: "$10.00"
delivery_total: '100.0'
@@ -16643,6 +16659,8 @@ paths:
completed_at: '2026-01-15T12:00:00.000Z'
created_at: '2026-01-15T12:00:00.000Z'
updated_at: '2026-01-15T12:00:00.000Z'
+ internal_note:
+ internal_note_html:
item_total: '10.0'
display_item_total: "$10.00"
delivery_total: '100.0'
@@ -16859,6 +16877,374 @@ paths:
type: string
nullable: true
required: true
+ "/api/v3/seller/orders/{order_id}/notes":
+ parameters:
+ - name: order_id
+ in: path
+ description: Prefixed order ID
+ required: true
+ schema:
+ type: string
+ get:
+ summary: Get order notes
+ tags:
+ - Orders
+ security:
+ - bearer_auth: []
+ description: |
+ The instructions the buyer left, and the seller's own working note.
+
+ A marketplace basket splits into one order per seller, so the internal
+ note here is this seller's alone rather than the operator's note about
+ the whole sale.
+ parameters:
+ - name: X-Spree-Seller-Id
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: notes
+ 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'
+ internal_note:
+ internal_note_html:
+ 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 1693962
+ 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-211
+ 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: Kecia Pollich
+ stock_location_id: sloc_UkLWZg9DAJ
+ fulfillment_items:
+ - id: fi_UkLWZg9DAJ
+ quantity: 1
+ line_item_id: li_UkLWZg9DAJ
+ variant_id: variant_UkLWZg9DAJ
+ name: Product 1693962
+ sku: SKU-211
+ 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_gbHJdmfrXB
+ label:
+ first_name: John
+ last_name: Doe
+ full_name: John Doe
+ address1: 173 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
+ billing_address:
+ id: addr_UkLWZg9DAJ
+ label:
+ first_name: John
+ last_name: Doe
+ full_name: John Doe
+ address1: 172 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"
+ patch:
+ summary: Update order notes
+ tags:
+ - Orders
+ security:
+ - bearer_auth: []
+ description: |
+ Send only the note that changes: an absent key leaves the other alone,
+ while an empty string clears it.
+
+ `internal_note` accepts HTML and is sanitized on save;
+ `internal_note_html` reads it back.
+ parameters:
+ - name: X-Spree-Seller-Id
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: notes updated
+ 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'
+ internal_note: Packed with the fragile insert.
+ internal_note_html: "<p>Packed with the fragile insert.</p>"
+ 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 1705749
+ 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-212
+ 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: Ophelia Hartmann
+ stock_location_id: sloc_UkLWZg9DAJ
+ fulfillment_items:
+ - id: fi_UkLWZg9DAJ
+ quantity: 1
+ line_item_id: li_UkLWZg9DAJ
+ variant_id: variant_UkLWZg9DAJ
+ name: Product 1705749
+ sku: SKU-212
+ 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_gbHJdmfrXB
+ label:
+ first_name: John
+ last_name: Doe
+ full_name: John Doe
+ address1: 175 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
+ billing_address:
+ id: addr_UkLWZg9DAJ
+ label:
+ first_name: John
+ last_name: Doe
+ full_name: John Doe
+ address1: 174 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 note named
+ content:
+ application/json:
+ example:
+ error:
+ code: validation_error
+ message: customer_note or internal_note is required
+ details:
+ base:
+ - customer_note or internal_note is required
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ customer_note:
+ type: string
+ nullable: true
+ description: What the buyer asked for
+ internal_note:
+ type: string
+ nullable: true
+ description: The seller's own working note, as HTML
+ required: true
"/api/v3/seller/order_cancellation_reasons":
get:
summary: List order cancellation reasons
@@ -17024,7 +17410,7 @@ paths:
example:
error:
code: processing_error
- message: Only 1 of Product 1807120 can be returned
+ message: Only 1 of Product 1837120 can be returned
requestBody:
content:
application/json:
@@ -19318,6 +19704,12 @@ components:
type: string
updated_at:
type: string
+ internal_note:
+ type: string
+ nullable: true
+ internal_note_html:
+ type: string
+ nullable: true
item_total:
type: string
nullable: true
@@ -19411,6 +19803,8 @@ components:
- completed_at
- created_at
- updated_at
+ - internal_note
+ - internal_note_html
- item_total
- display_item_total
- delivery_total
diff --git a/packages/dashboard-ui/src/index.ts b/packages/dashboard-ui/src/index.ts
index 8953a8dc55..8e42889adb 100644
--- a/packages/dashboard-ui/src/index.ts
+++ b/packages/dashboard-ui/src/index.ts
@@ -39,12 +39,14 @@ export * from './spree/country-flag'
export * from './spree/data-grid'
export * from './spree/delivery-form-dialog'
export * from './spree/drag-handle'
+export * from './spree/editable-note-card'
export * from './spree/file-type-icon'
export * from './spree/form-actions'
export * from './spree/fulfill-items-form'
export * from './spree/fulfillment-edit-dialog'
export * from './spree/fulfillment-item-list'
export * from './spree/fulfillment-panel'
+export * from './spree/post-sale-create-dialogs'
export * from './spree/post-sale-fields'
export * from './spree/return-dialogs'
diff --git a/packages/dashboard-ui/src/spree/editable-note-card.tsx b/packages/dashboard-ui/src/spree/editable-note-card.tsx
new file mode 100644
index 0000000000..ed2ee102d6
--- /dev/null
+++ b/packages/dashboard-ui/src/spree/editable-note-card.tsx
@@ -0,0 +1,100 @@
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '../ui/button'
+import { Card, CardAction, CardContent, CardHeader, CardTitle } from '../ui/card'
+import { PencilIcon } from './icons'
+
+/**
+ * A note on a record: shown as read-only text, edited in place behind a
+ * pencil, and reading "None" while empty.
+ *
+ * Shared by every note card on an order — the buyer's instructions, the
+ * merchant's own working note — so they cannot drift into different shapes.
+ * The editor itself comes from the caller, because a plain note and a
+ * rich-text one need different ones.
+ */
+export function EditableNoteCard({
+ title,
+ editing,
+ onEditingChange,
+ children,
+ editor,
+ onSave,
+ pending = false,
+}: {
+ title: string
+ editing: boolean
+ onEditingChange: (editing: boolean) => void
+ /** The read view. Falsy renders the empty state instead. */
+ children?: ReactNode
+ editor: ReactNode
+ onSave: () => void
+ pending?: boolean
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => onEditingChange(!editing)}
+ aria-label={t('admin.actions.edit')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {editing ? (
+ <form
+ className="flex flex-col gap-3"
+ onSubmit={(event) => {
+ // The order page renders its cards inside their own forms —
+ // without stopping the bubble the browser submits the outer one.
+ event.preventDefault()
+ event.stopPropagation()
+ onSave()
+ }}
+ >
+ {editor}
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onEditingChange(false)}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" size="sm" disabled={pending}>
+ {pending ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </div>
+ </form>
+ ) : (
+ (children ?? <p className="text-muted-foreground text-sm">{t('admin.common.none')}</p>)
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+/** A plain-text note as it reads when not being edited. */
+export function NoteText({ value }: { value: string }) {
+ return <p className="whitespace-pre-wrap text-muted-foreground text-sm">{value}</p>
+}
+
+/** A rich-text note as it reads when not being edited. */
+export function NoteHtml({ html }: { html: string }) {
+ return (
+ <div
+ className="prose prose-sm dark:prose-invert max-w-none text-muted-foreground"
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is sanitized server-side via the rich-text pipeline
+ dangerouslySetInnerHTML={{ __html: html }}
+ />
+ )
+}
diff --git a/packages/dashboard-ui/src/spree/post-sale-create-dialogs.tsx b/packages/dashboard-ui/src/spree/post-sale-create-dialogs.tsx
new file mode 100644
index 0000000000..86e97934b1
--- /dev/null
+++ b/packages/dashboard-ui/src/spree/post-sale-create-dialogs.tsx
@@ -0,0 +1,250 @@
+import { type ReactNode, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '../ui/button'
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '../ui/dialog'
+import { Field, FieldLabel } from '../ui/field'
+import { Input } from '../ui/input'
+import { InputGroup, InputGroupAddon, InputGroupInput, InputGroupText } from '../ui/input-group'
+import { Textarea } from '../ui/textarea'
+import {
+ type PostSaleSelection,
+ type PostSaleUnit,
+ QuantityPicker,
+ selectedUnits,
+} from './post-sale-fields'
+
+/**
+ * Opens a return: which units are coming back, why, and any note.
+ *
+ * `extraFields` is where a surface adds what only it can offer — the
+ * operator's shelf picker, for instance — so the shape stays one component.
+ * Shared by the operator's order page and the seller's.
+ */
+export function CreateReturnDialog({
+ units,
+ reasonField,
+ extraFields,
+ onClose,
+ onSubmit,
+ pending = false,
+}: {
+ units: PostSaleUnit[]
+ /** The reason picker, wired to whichever vocabulary the caller reads. */
+ reasonField?: ReactNode
+ extraFields?: ReactNode
+ onClose: () => void
+ onSubmit: (params: {
+ items: Array<{ fulfillment_item_id: string; quantity: number }>
+ memo?: string
+ }) => void
+ pending?: boolean
+}) {
+ const { t } = useTranslation()
+ const [selection, setSelection] = useState<PostSaleSelection>({})
+ const [memo, setMemo] = useState('')
+
+ const chosen = selectedUnits(selection)
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.pages.orders.detail.returns.create_title')}</DialogTitle>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ <QuantityPicker units={units} selection={selection} onChange={setSelection} />
+ {reasonField}
+ {extraFields}
+ <Field>
+ <FieldLabel htmlFor="return-memo">
+ {t('admin.pages.orders.detail.returns.memo')}
+ </FieldLabel>
+ <Textarea
+ id="return-memo"
+ value={memo}
+ onChange={(event) => setMemo(event.target.value)}
+ />
+ </Field>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={onClose} disabled={pending}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="button"
+ disabled={chosen.length === 0 || pending}
+ onClick={() =>
+ onSubmit({
+ items: chosen.map(([id, quantity]) => ({
+ fulfillment_item_id: id,
+ quantity,
+ })),
+ memo: memo.trim() || undefined,
+ })
+ }
+ >
+ {t('admin.pages.orders.detail.returns.actions.create')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+/** A line the claim can name, with what one unit of it cost. */
+export type ClaimableLine = PostSaleUnit & {
+ /** Unit price, used to default the refund to what was actually paid. */
+ price?: string | null
+}
+
+/**
+ * Reports a problem with a delivery: which lines, how many, and what to give
+ * back for each.
+ *
+ * A claim is about what was bought rather than what shipped — goods that
+ * never arrived are exactly what one is for — so the lines come from the
+ * order, not from its fulfillments.
+ */
+export function CreateClaimDialog({
+ lines,
+ currencySymbol,
+ reasonField,
+ onClose,
+ onSubmit,
+ pending = false,
+}: {
+ lines: ClaimableLine[]
+ currencySymbol: string
+ reasonField?: ReactNode
+ onClose: () => void
+ onSubmit: (params: {
+ items: Array<{
+ line_item_id: string
+ quantity: number
+ description?: string
+ refund_amount?: string
+ }>
+ memo?: string
+ }) => void
+ pending?: boolean
+}) {
+ const { t } = useTranslation()
+ const [selection, setSelection] = useState<PostSaleSelection>({})
+ const [amounts, setAmounts] = useState<Record<string, string>>({})
+ const [memo, setMemo] = useState('')
+
+ const chosen = selectedUnits(selection)
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.pages.orders.detail.claims.create_title')}</DialogTitle>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-4">
+ <div className="flex flex-col gap-2">
+ {lines.map((line) => {
+ const chosenQuantity = selection[line.id] ?? 0
+
+ return (
+ <div key={line.id} className="flex flex-col gap-2 rounded-lg border p-3">
+ <div className="flex items-center justify-between gap-4">
+ <span className="min-w-0 truncate text-sm">{line.label}</span>
+ <Input
+ type="number"
+ min={0}
+ max={line.quantity}
+ className="w-20"
+ value={chosenQuantity}
+ aria-label={line.label}
+ onChange={(event) => {
+ const quantity = Math.max(
+ 0,
+ Math.min(Number(event.target.value), line.quantity),
+ )
+ setSelection({ ...selection, [line.id]: quantity })
+ // Default the refund to what was paid for those units;
+ // the merchant can still overwrite it.
+ if (quantity > 0 && !amounts[line.id]) {
+ const unitPrice = Number(line.price)
+ if (Number.isFinite(unitPrice)) {
+ setAmounts((current) => ({
+ ...current,
+ [line.id]: (unitPrice * quantity).toFixed(2),
+ }))
+ }
+ }
+ }}
+ />
+ </div>
+ {chosenQuantity > 0 && (
+ <Field>
+ <FieldLabel htmlFor={`claim-amount-${line.id}`}>
+ {t('admin.pages.orders.detail.claims.refund_amount')}
+ </FieldLabel>
+ <InputGroup>
+ <InputGroupAddon>
+ <InputGroupText>{currencySymbol}</InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ id={`claim-amount-${line.id}`}
+ type="number"
+ step="0.01"
+ min="0"
+ value={amounts[line.id] ?? ''}
+ onChange={(event) =>
+ setAmounts({ ...amounts, [line.id]: event.target.value })
+ }
+ />
+ </InputGroup>
+ </Field>
+ )}
+ </div>
+ )
+ })}
+ </div>
+
+ {reasonField}
+ <Field>
+ <FieldLabel htmlFor="claim-memo">
+ {t('admin.pages.orders.detail.returns.memo')}
+ </FieldLabel>
+ <Textarea
+ id="claim-memo"
+ value={memo}
+ onChange={(event) => setMemo(event.target.value)}
+ />
+ </Field>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={onClose} disabled={pending}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="button"
+ disabled={chosen.length === 0 || pending}
+ onClick={() =>
+ onSubmit({
+ items: chosen.map(([id, quantity]) => ({
+ line_item_id: id,
+ quantity,
+ refund_amount: amounts[id] || undefined,
+ })),
+ memo: memo.trim() || undefined,
+ })
+ }
+ >
+ {t('admin.pages.orders.detail.claims.actions.create')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/orders/order-notes-cards.tsx b/packages/dashboard/src/components/spree/orders/order-notes-cards.tsx
index bbed149f50..3b165620d2 100644
--- a/packages/dashboard/src/components/spree/orders/order-notes-cards.tsx
+++ b/packages/dashboard/src/components/spree/orders/order-notes-cards.tsx
@@ -8,11 +8,14 @@ import {
CardContent,
CardHeader,
CardTitle,
+ EditableNoteCard,
+ NoteHtml,
+ NoteText,
RichTextEditor,
Textarea,
} from '@spree/dashboard-ui'
import { PencilIcon } from '@spree/dashboard-ui/icons'
-import { type FormEvent, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useOrderMutation } from '../../../hooks/use-order'
@@ -21,54 +24,36 @@ export function SpecialInstructionsCard({ order }: { order: Order }) {
const orderId = order.id
const [editing, setEditing] = useState(false)
+ const [note, setNote] = useState(order.customer_note ?? '')
+ const serverNote = order.customer_note ?? ''
+
+ // Track the server value only while the editor is closed: any order
+ // mutation refetches this record, and adopting the incoming value mid-edit
+ // would throw away whatever the user is part-way through typing.
+ useEffect(() => {
+ if (!editing) setNote(serverNote)
+ }, [editing, serverNote])
+
const mutation = useOrderMutation(orderId, (params: { customer_note: string }) =>
adminClient.orders.update(orderId, params),
)
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
- const fd = new FormData(e.currentTarget)
- mutation.mutate(
- { customer_note: fd.get('customer_note') as string },
- { onSuccess: () => setEditing(false) },
- )
- }
-
return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.orders.detail.section_customer_note')}</CardTitle>
- <CardAction>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setEditing(!editing)}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- </CardAction>
- </CardHeader>
- <CardContent>
- {editing ? (
- <form onSubmit={handleSubmit} className="flex flex-col gap-3">
- <Textarea name="customer_note" defaultValue={order.customer_note ?? ''} />
- <div className="flex justify-end gap-2">
- <Button type="button" variant="outline" size="sm" onClick={() => setEditing(false)}>
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" size="sm" disabled={mutation.isPending}>
- {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </div>
- </form>
- ) : order.customer_note ? (
- <p className="text-sm text-muted-foreground whitespace-pre-wrap">{order.customer_note}</p>
- ) : (
- <p className="text-sm text-muted-foreground">{t('admin.common.none')}</p>
- )}
- </CardContent>
- </Card>
+ <EditableNoteCard
+ title={t('admin.orders.detail.section_customer_note')}
+ editing={editing}
+ onEditingChange={(next) => {
+ if (!next) setNote(serverNote)
+ setEditing(next)
+ }}
+ editor={<Textarea value={note} onChange={(event) => setNote(event.target.value)} />}
+ pending={mutation.isPending}
+ onSave={() =>
+ mutation.mutate({ customer_note: note }, { onSuccess: () => setEditing(false) })
+ }
+ >
+ {serverNote ? <NoteText value={serverNote} /> : null}
+ </EditableNoteCard>
)
}
@@ -143,9 +128,6 @@ export function InternalNoteCard({ order }: { order: Order }) {
const [note, setNote] = useState(order.internal_note_html ?? '')
const serverNote = order.internal_note_html ?? ''
- // Track the server value only while the editor is closed. Any order mutation
- // refetches this record, and adopting the incoming value mid-edit would throw
- // away whatever the user is part-way through typing.
useEffect(() => {
if (!editing) setNote(serverNote)
}, [editing, serverNote])
@@ -154,61 +136,23 @@ export function InternalNoteCard({ order }: { order: Order }) {
adminClient.orders.update(orderId, params),
)
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
- mutation.mutate({ internal_note: note }, { onSuccess: () => setEditing(false) })
- }
+ const title = t('admin.orders.detail.section_internal_note')
return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.orders.detail.section_internal_note')}</CardTitle>
- <CardAction>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setEditing(!editing)}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- </CardAction>
- </CardHeader>
- <CardContent>
- {editing ? (
- <form onSubmit={handleSubmit} className="flex flex-col gap-3">
- <RichTextEditor
- ariaLabel={t('admin.orders.detail.section_internal_note')}
- value={note}
- onChange={setNote}
- />
- <div className="flex justify-end gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => {
- setNote(serverNote)
- setEditing(false)
- }}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" size="sm" disabled={mutation.isPending}>
- {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </div>
- </form>
- ) : order.internal_note_html ? (
- <div
- className="prose prose-sm max-w-none text-muted-foreground dark:prose-invert"
- // biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is sanitized server-side via the rich-text pipeline
- dangerouslySetInnerHTML={{ __html: order.internal_note_html }}
- />
- ) : (
- <p className="text-sm text-muted-foreground">{t('admin.common.none')}</p>
- )}
- </CardContent>
- </Card>
+ <EditableNoteCard
+ title={title}
+ editing={editing}
+ onEditingChange={(next) => {
+ if (!next) setNote(serverNote)
+ setEditing(next)
+ }}
+ editor={<RichTextEditor ariaLabel={title} value={note} onChange={setNote} />}
+ pending={mutation.isPending}
+ onSave={() =>
+ mutation.mutate({ internal_note: note }, { onSuccess: () => setEditing(false) })
+ }
+ >
+ {serverNote ? <NoteHtml html={serverNote} /> : null}
+ </EditableNoteCard>
)
}
diff --git a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx
index 6635e21d35..729c3b5277 100644
--- a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx
+++ b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx
@@ -19,11 +19,6 @@ import {
Field,
FieldLabel,
Input,
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
- InputGroupText,
- QuantityPicker,
type RefundMethod,
Select,
SelectContent,
@@ -31,6 +26,8 @@ import {
type PostSaleSelection as Selection,
SelectTrigger,
SelectValue,
+ CreateClaimDialog as SharedCreateClaimDialog,
+ CreateReturnDialog as SharedCreateReturnDialog,
selectedUnits as selectedItems,
Textarea,
} from '@spree/dashboard-ui'
@@ -81,9 +78,6 @@ export function CreateReturnDialog({
}) => void
}) {
const { t } = useTranslation()
- const units = fulfilledUnits(order)
- const [selection, setSelection] = useState<Selection>({})
- const [memo, setMemo] = useState('')
const [reasonId, setReasonId] = useState('')
const [stockLocationId, setStockLocationId] = useState('')
const { data: stockLocationData } = useStockLocations()
@@ -105,74 +99,43 @@ export function CreateReturnDialog({
: t('admin.pages.orders.detail.returns.location_no_returns', { name: location.name }),
}))
- const chosen = selectedItems(selection)
-
return (
- <Dialog open onOpenChange={(open) => !open && onClose()}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('admin.pages.orders.detail.returns.create_title')}</DialogTitle>
- </DialogHeader>
- <DialogBody className="flex flex-col gap-4">
- <QuantityPicker units={units} selection={selection} onChange={setSelection} />
- <ReasonField kind="return-reasons" value={reasonId} onChange={setReasonId} />
- <Field>
- <FieldLabel htmlFor="return-location">
- {t('admin.pages.orders.detail.returns.location')}
- </FieldLabel>
- <Select
- items={locationOptions}
- value={stockLocationId}
- onValueChange={(value) => setStockLocationId(value as string)}
- >
- <SelectTrigger id="return-location">
- <SelectValue
- placeholder={t('admin.pages.orders.detail.returns.location_default')}
- />
- </SelectTrigger>
- <SelectContent>
- {locationOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Field>
- <Field>
- <FieldLabel htmlFor="return-memo">
- {t('admin.pages.orders.detail.returns.memo')}
- </FieldLabel>
- <Textarea
- id="return-memo"
- value={memo}
- onChange={(event) => setMemo(event.target.value)}
- />
- </Field>
- </DialogBody>
- <DialogFooter>
- <Button variant="outline" onClick={onClose}>
- {t('admin.actions.cancel')}
- </Button>
- <Button
- disabled={chosen.length === 0}
- onClick={() =>
- onSubmit({
- items: chosen.map(([id, quantity]) => ({
- fulfillment_item_id: id,
- quantity,
- })),
- memo: memo || undefined,
- reasonId: reasonId || undefined,
- stockLocationId: stockLocationId || undefined,
- })
- }
+ <SharedCreateReturnDialog
+ units={fulfilledUnits(order)}
+ reasonField={<ReasonField kind="return-reasons" value={reasonId} onChange={setReasonId} />}
+ extraFields={
+ <Field>
+ <FieldLabel htmlFor="return-location">
+ {t('admin.pages.orders.detail.returns.location')}
+ </FieldLabel>
+ <Select
+ items={locationOptions}
+ value={stockLocationId}
+ onValueChange={(value) => setStockLocationId(value as string)}
>
- {t('admin.pages.orders.detail.returns.actions.create')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <SelectTrigger id="return-location">
+ <SelectValue placeholder={t('admin.pages.orders.detail.returns.location_default')} />
+ </SelectTrigger>
+ <SelectContent>
+ {locationOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ }
+ onClose={onClose}
+ onSubmit={({ items, memo }) =>
+ onSubmit({
+ items,
+ memo,
+ reasonId: reasonId || undefined,
+ stockLocationId: stockLocationId || undefined,
+ })
+ }
+ />
)
}
@@ -328,128 +291,26 @@ export function CreateClaimDialog({
reasonId?: string
}) => void
}) {
- const { t } = useTranslation()
- const items = order.items ?? []
- const [selection, setSelection] = useState<Selection>({})
- const [amounts, setAmounts] = useState<Record<string, string>>({})
+ const [reasonId, setReasonId] = useState('')
const { defaultCurrency } = useStore()
const { symbol: currencySymbol } = currencyParts(defaultCurrency, i18n.language)
- const [memo, setMemo] = useState('')
- const [reasonId, setReasonId] = useState('')
-
- const chosen = selectedItems(selection)
return (
- <Dialog open onOpenChange={(open) => !open && onClose()}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('admin.pages.orders.detail.claims.create_title')}</DialogTitle>
- </DialogHeader>
- <DialogBody className="flex flex-col gap-4">
- <div className="flex flex-col gap-2">
- {items.map((item) => {
- const label = [item.name, item.options_text].filter(Boolean).join(' — ') || item.id
- const chosenQuantity = selection[item.id] ?? 0
-
- return (
- <div key={item.id} className="flex flex-col gap-2 rounded-lg border p-3">
- <div className="flex items-center justify-between gap-4">
- <span className="text-sm truncate">{label}</span>
- <Input
- type="number"
- min={0}
- max={item.quantity}
- className="w-20"
- value={chosenQuantity}
- onChange={(event) => {
- const quantity = Math.max(
- 0,
- Math.min(Number(event.target.value), item.quantity),
- )
- setSelection({ ...selection, [item.id]: quantity })
- // Default the refund to what was paid for those units;
- // the merchant can still overwrite it.
- if (quantity > 0 && !amounts[item.id]) {
- const unitPrice = Number(item.price)
- if (Number.isFinite(unitPrice)) {
- setAmounts((current) => ({
- ...current,
- [item.id]: (unitPrice * quantity).toFixed(2),
- }))
- }
- }
- }}
- />
- </div>
- {chosenQuantity > 0 && (
- <Field>
- <FieldLabel htmlFor={`claim-amount-${item.id}`}>
- {t('admin.pages.orders.detail.claims.refund_amount')}
- </FieldLabel>
- <InputGroup>
- <InputGroupAddon>
- <InputGroupText>{currencySymbol}</InputGroupText>
- </InputGroupAddon>
- <InputGroupInput
- id={`claim-amount-${item.id}`}
- type="number"
- step="0.01"
- min="0"
- value={amounts[item.id] ?? ''}
- onChange={(event) =>
- setAmounts({ ...amounts, [item.id]: event.target.value })
- }
- />
- </InputGroup>
- </Field>
- )}
- </div>
- )
- })}
- </div>
-
- <ReasonField kind="claim-reasons" value={reasonId} onChange={setReasonId} />
- <Field>
- <FieldLabel htmlFor="claim-memo">
- {t('admin.pages.orders.detail.returns.memo')}
- </FieldLabel>
- <Textarea
- id="claim-memo"
- value={memo}
- onChange={(event) => setMemo(event.target.value)}
- />
- </Field>
- </DialogBody>
- <DialogFooter>
- <Button variant="outline" onClick={onClose}>
- {t('admin.actions.cancel')}
- </Button>
- <Button
- disabled={chosen.length === 0}
- onClick={() =>
- onSubmit({
- items: chosen.map(([id, quantity]) => ({
- line_item_id: id,
- quantity,
- refund_amount: amounts[id] || undefined,
- })),
- memo: memo || undefined,
- reasonId: reasonId || undefined,
- })
- }
- >
- {t('admin.pages.orders.detail.claims.actions.create')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <SharedCreateClaimDialog
+ lines={(order.items ?? []).map((item) => ({
+ id: item.id,
+ label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,
+ quantity: item.quantity,
+ price: item.price,
+ }))}
+ currencySymbol={currencySymbol}
+ reasonField={<ReasonField kind="claim-reasons" value={reasonId} onChange={setReasonId} />}
+ onClose={onClose}
+ onSubmit={({ items, memo }) => onSubmit({ items, memo, reasonId: reasonId || undefined })}
+ />
)
}
-/**
- * Deciding how to make a claim right. This is where the merchant chooses —
- * not at claim creation, when only the customer's complaint is known.
- */
export function ResolveClaimDialog({
claim,
onClose,
diff --git a/packages/seller-dashboard/src/components/orders/order-cards.tsx b/packages/seller-dashboard/src/components/orders/order-cards.tsx
index fea0c1b845..c2dc5b95e1 100644
--- a/packages/seller-dashboard/src/components/orders/order-cards.tsx
+++ b/packages/seller-dashboard/src/components/orders/order-cards.tsx
@@ -247,20 +247,3 @@ export function OrderCustomerCard({ order }: { order: Order }) {
</>
)
}
-
-/** What the customer asked for when they placed the order. */
-export function OrderNoteCard({ order }: { order: Order }) {
- const { t } = useTranslation()
- if (!order.customer_note) return null
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('orders.customer_note')}</CardTitle>
- </CardHeader>
- <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/components/orders/order-notes-cards.tsx b/packages/seller-dashboard/src/components/orders/order-notes-cards.tsx
new file mode 100644
index 0000000000..10fd276999
--- /dev/null
+++ b/packages/seller-dashboard/src/components/orders/order-notes-cards.tsx
@@ -0,0 +1,83 @@
+import { EditableNoteCard, NoteHtml, NoteText, RichTextEditor, Textarea } from '@spree/dashboard-ui'
+import type { Order } from '@spree/seller-sdk'
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useUpdateOrderNotes } from '../../hooks/use-order'
+
+/** What the buyer asked for when they placed the order. */
+export function SpecialInstructionsCard({ order }: { order: Order }) {
+ const { t } = useTranslation()
+
+ const [editing, setEditing] = useState(false)
+ const [note, setNote] = useState(order.customer_note ?? '')
+ const serverNote = order.customer_note ?? ''
+
+ // Track the server value only while the editor is closed: any order
+ // mutation refetches this record, and adopting the incoming value mid-edit
+ // would throw away whatever the seller is part-way through typing.
+ useEffect(() => {
+ if (!editing) setNote(serverNote)
+ }, [editing, serverNote])
+
+ const mutation = useUpdateOrderNotes(order.id)
+
+ return (
+ <EditableNoteCard
+ title={t('admin.orders.detail.section_customer_note')}
+ editing={editing}
+ onEditingChange={(next) => {
+ if (!next) setNote(serverNote)
+ setEditing(next)
+ }}
+ editor={<Textarea value={note} onChange={(event) => setNote(event.target.value)} />}
+ pending={mutation.isPending}
+ onSave={() =>
+ mutation.mutate({ customer_note: note }, { onSuccess: () => setEditing(false) })
+ }
+ >
+ {serverNote ? <NoteText value={serverNote} /> : null}
+ </EditableNoteCard>
+ )
+}
+
+/**
+ * The seller's own working note.
+ *
+ * A marketplace basket splits into one order per seller, so this note is
+ * theirs alone rather than the operator's note about the whole sale.
+ */
+export function InternalNoteCard({ order }: { order: Order }) {
+ const { t } = useTranslation()
+
+ const [editing, setEditing] = useState(false)
+ // Edit the HTML, not the plain-text projection: `internal_note` has its
+ // markup stripped, so round-tripping it through the `internal_note_html`
+ // write would flatten an existing note on a save that changed nothing.
+ const [note, setNote] = useState(order.internal_note_html ?? '')
+ const serverNote = order.internal_note_html ?? ''
+
+ useEffect(() => {
+ if (!editing) setNote(serverNote)
+ }, [editing, serverNote])
+
+ const mutation = useUpdateOrderNotes(order.id)
+ const title = t('admin.orders.detail.section_internal_note')
+
+ return (
+ <EditableNoteCard
+ title={title}
+ editing={editing}
+ onEditingChange={(next) => {
+ if (!next) setNote(serverNote)
+ setEditing(next)
+ }}
+ editor={<RichTextEditor ariaLabel={title} value={note} onChange={setNote} />}
+ pending={mutation.isPending}
+ onSave={() =>
+ mutation.mutate({ internal_note: note }, { onSuccess: () => setEditing(false) })
+ }
+ >
+ {serverNote ? <NoteHtml html={serverNote} /> : null}
+ </EditableNoteCard>
+ )
+}
diff --git a/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx b/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx
index 9c7d69c3f4..bc401b2594 100644
--- a/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx
+++ b/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx
@@ -1,24 +1,23 @@
+import { currencyParts } from '@spree/dashboard-core'
import {
- Button,
- Dialog,
- DialogBody,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
Field,
FieldLabel,
- QuantityPicker,
ReasonField,
- type PostSaleSelection as Selection,
- selectedUnits as selectedItems,
- Textarea,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ CreateClaimDialog as SharedCreateClaimDialog,
+ CreateReturnDialog as SharedCreateReturnDialog,
} from '@spree/dashboard-ui'
import type { Order } from '@spree/seller-sdk'
+import i18n from 'i18next'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useClaimActions, useReturnActions } from '../../hooks/use-post-sale'
import { useReasons } from '../../hooks/use-reasons'
+import { useStockLocations } from '../../hooks/use-stock-locations'
import { unitLabel } from './line-label'
/** Units that actually went out, which is all that can come back. */
@@ -32,6 +31,14 @@ export function fulfilledUnits(order: Order) {
)
}
+/**
+ * Takes goods back on one of this seller's orders.
+ *
+ * The shelf list is the seller's own, so a marketplace warehouse never
+ * appears — and the server refuses one anyway. Shelves that accept returns
+ * lead, the rest stay selectable, since a one-off return has to be routable
+ * somewhere even when none is flagged.
+ */
export function CreateReturnDialog({
order,
open,
@@ -43,66 +50,72 @@ export function CreateReturnDialog({
}) {
const { t } = useTranslation()
const { create } = useReturnActions(order.id)
- const units = fulfilledUnits(order)
-
- const [selection, setSelection] = useState<Selection>({})
const [reasonId, setReasonId] = useState('')
- const [memo, setMemo] = useState('')
+ const [stockLocationId, setStockLocationId] = useState('')
+ const { data: locationsData } = useStockLocations(open)
- const chosen = selectedItems(selection)
+ const locationOptions = (locationsData?.data ?? [])
+ .filter((location) => location.active)
+ .sort((a, b) => Number(b.returns_enabled) - Number(a.returns_enabled))
+ .map((location) => ({
+ value: location.id,
+ label: location.returns_enabled
+ ? location.name
+ : t('admin.pages.orders.detail.returns.location_no_returns', { name: location.name }),
+ }))
- async function handleCreate() {
- await create
- .mutateAsync({
- items: chosen.map(([id, quantity]) => ({ fulfillment_item_id: id, quantity })),
- reason_id: reasonId || undefined,
- memo: memo.trim() || undefined,
- })
- .then(() => {
- setSelection({})
- setMemo('')
- onOpenChange(false)
- })
- .catch(() => undefined)
- }
+ if (!open) return null
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('orders.post_sale.returns.create_title')}</DialogTitle>
- </DialogHeader>
- <DialogBody>
- <div className="flex flex-col gap-4">
- <QuantityPicker units={units} selection={selection} onChange={setSelection} />
- <ReturnReasonField value={reasonId} onChange={setReasonId} />
- <Field>
- <FieldLabel htmlFor="return-memo">{t('orders.post_sale.memo')}</FieldLabel>
- <Textarea
- id="return-memo"
- value={memo}
- onChange={(event) => setMemo(event.target.value)}
- />
- </Field>
- </div>
- </DialogBody>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- disabled={chosen.length === 0 || create.isPending}
- onClick={handleCreate}
+ <SharedCreateReturnDialog
+ units={fulfilledUnits(order)}
+ reasonField={<ReturnReasonField value={reasonId} onChange={setReasonId} />}
+ extraFields={
+ <Field>
+ <FieldLabel htmlFor="return-location">
+ {t('admin.pages.orders.detail.returns.location')}
+ </FieldLabel>
+ <Select
+ items={locationOptions}
+ value={stockLocationId}
+ onValueChange={(value) => setStockLocationId((value as string) ?? '')}
>
- {t('orders.post_sale.returns.create')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <SelectTrigger id="return-location">
+ <SelectValue placeholder={t('admin.pages.orders.detail.returns.location_default')} />
+ </SelectTrigger>
+ <SelectContent>
+ {locationOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ }
+ onClose={() => onOpenChange(false)}
+ pending={create.isPending}
+ onSubmit={({ items, memo }) => {
+ create
+ .mutateAsync({
+ items,
+ memo,
+ reason_id: reasonId || undefined,
+ stock_location_id: stockLocationId || undefined,
+ })
+ .then(() => onOpenChange(false))
+ .catch(() => undefined)
+ }}
+ />
)
}
+/**
+ * Reports a problem with a delivery on one of this seller's orders.
+ *
+ * The lines come from the order rather than its parcels: a claim is about
+ * what was bought, and goods that never arrived are exactly what one is for.
+ */
export function CreateClaimDialog({
order,
open,
@@ -112,77 +125,31 @@ export function CreateClaimDialog({
open: boolean
onOpenChange: (open: boolean) => void
}) {
- const { t } = useTranslation()
const { create } = useClaimActions(order.id)
-
- // A claim is about what was bought, not about what shipped — goods that
- // never arrived are exactly what one is for.
- const units = (order.items ?? []).map((item) => ({
- id: item.id,
- label: unitLabel(item),
- quantity: item.quantity,
- }))
-
- const [selection, setSelection] = useState<Selection>({})
const [reasonId, setReasonId] = useState('')
- const [description, setDescription] = useState('')
+ const { symbol: currencySymbol } = currencyParts(order.currency, i18n.language)
- const chosen = selectedItems(selection)
-
- async function handleCreate() {
- await create
- .mutateAsync({
- items: chosen.map(([id, quantity]) => ({
- line_item_id: id,
- quantity,
- description: description.trim() || undefined,
- })),
- reason_id: reasonId || undefined,
- })
- .then(() => {
- setSelection({})
- setDescription('')
- onOpenChange(false)
- })
- .catch(() => undefined)
- }
+ if (!open) return null
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('orders.post_sale.claims.create_title')}</DialogTitle>
- </DialogHeader>
- <DialogBody>
- <div className="flex flex-col gap-4">
- <QuantityPicker units={units} selection={selection} onChange={setSelection} />
- <ClaimReasonField value={reasonId} onChange={setReasonId} />
- <Field>
- <FieldLabel htmlFor="claim-description">
- {t('orders.post_sale.claims.description')}
- </FieldLabel>
- <Textarea
- id="claim-description"
- value={description}
- onChange={(event) => setDescription(event.target.value)}
- />
- </Field>
- </div>
- </DialogBody>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
- {t('common.cancel')}
- </Button>
- <Button
- type="button"
- disabled={chosen.length === 0 || create.isPending}
- onClick={handleCreate}
- >
- {t('orders.post_sale.claims.create')}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ <SharedCreateClaimDialog
+ lines={(order.items ?? []).map((item) => ({
+ id: item.id,
+ label: unitLabel(item),
+ quantity: item.quantity,
+ price: item.price,
+ }))}
+ currencySymbol={currencySymbol}
+ reasonField={<ClaimReasonField value={reasonId} onChange={setReasonId} />}
+ onClose={() => onOpenChange(false)}
+ pending={create.isPending}
+ onSubmit={({ items, memo }) => {
+ create
+ .mutateAsync({ items, memo, reason_id: reasonId || undefined })
+ .then(() => onOpenChange(false))
+ .catch(() => undefined)
+ }}
+ />
)
}
diff --git a/packages/seller-dashboard/src/hooks/use-order.ts b/packages/seller-dashboard/src/hooks/use-order.ts
index 2f95dafeff..c9851f5134 100644
--- a/packages/seller-dashboard/src/hooks/use-order.ts
+++ b/packages/seller-dashboard/src/hooks/use-order.ts
@@ -22,6 +22,13 @@ export function useCancelOrder(orderId: string) {
)
}
+/** The seller's working note, and what the buyer asked for. */
+export function useUpdateOrderNotes(orderId: string) {
+ return useOrderMutation(orderId, (params: { customer_note?: string; internal_note?: string }) =>
+ sellerClient().orders.notes.update(orderId, params),
+ )
+}
+
/**
* A write against the order itself. Refreshes the order and the list behind
* it — a canceled order reads differently in both places.
diff --git a/packages/seller-dashboard/src/hooks/use-post-sale.ts b/packages/seller-dashboard/src/hooks/use-post-sale.ts
index 5f6eab933e..a9b73f5551 100644
--- a/packages/seller-dashboard/src/hooks/use-post-sale.ts
+++ b/packages/seller-dashboard/src/hooks/use-post-sale.ts
@@ -71,6 +71,7 @@ export function useReturnActions(orderId: string) {
items: Array<{ fulfillment_item_id: string; quantity: number }>
memo?: string
reason_id?: string
+ stock_location_id?: string
}) => returns().create(orderId, params),
)
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index 8d1edaff3f..c1ab619370 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -133,7 +133,12 @@
"original_payment": "Original payment",
"store_credit": "Store credit"
},
- "reason": "Reason"
+ "reason": "Reason",
+ "location": "Return to",
+ "location_default": "Default returns location",
+ "location_no_returns": "{{name}} (does not accept returns)",
+ "memo": "Note",
+ "create_title": "New return"
},
"claims": {
"resolve_title": "Resolve claim",
@@ -146,8 +151,10 @@
"refund_amount": "Refund amount",
"replacement_items": "Send a replacement for",
"actions": {
- "resolve": "Resolve"
- }
+ "resolve": "Resolve",
+ "create": "New claim"
+ },
+ "create_title": "New claim"
}
}
}
diff --git a/packages/seller-dashboard/src/pages/order.tsx b/packages/seller-dashboard/src/pages/order.tsx
index 87bef92b72..aafd1b9c9c 100644
--- a/packages/seller-dashboard/src/pages/order.tsx
+++ b/packages/seller-dashboard/src/pages/order.tsx
@@ -6,11 +6,8 @@ import { useTranslation } from 'react-i18next'
import { CenteredMessage } from '../components/centered-message'
import { FulfillmentsCard } from '../components/orders/fulfillments-card'
import { OrderCancelDialog } from '../components/orders/order-cancel-dialog'
-import {
- OrderCustomerCard,
- OrderNoteCard,
- OrderSummaryCard,
-} from '../components/orders/order-cards'
+import { OrderCustomerCard, OrderSummaryCard } from '../components/orders/order-cards'
+import { InternalNoteCard, SpecialInstructionsCard } from '../components/orders/order-notes-cards'
import { ClaimsCard, ExchangesCard } from '../components/orders/post-sale-cards'
import { ReturnsCard } from '../components/orders/returns-card'
import { RetryableError } from '../components/retryable-error'
@@ -100,7 +97,8 @@ export function OrderPage() {
sidebar={
<>
<OrderCustomerCard order={order} />
- <OrderNoteCard order={order} />
+ <SpecialInstructionsCard order={order} />
+ <InternalNoteCard order={order} />
</>
}
/>
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 2727223e98..c3219ceeae 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -418,6 +418,30 @@ export class SellerClient {
): Promise<Order> =>
this.request<Order>('PATCH', `/orders/${id}/address`, { ...options, body: params }),
+ /**
+ * The notes on an order: the instructions the buyer left, and the
+ * seller's own working note.
+ *
+ * A marketplace basket splits into one order per seller, so the internal
+ * note here is the seller's alone.
+ */
+ notes: {
+ get: (orderId: string, options?: RequestOptions): Promise<Order> =>
+ this.request<Order>('GET', `/orders/${orderId}/notes`, options),
+
+ /**
+ * Send only the note that changes: an absent key leaves the other
+ * alone, while an empty string clears it. `internal_note` takes HTML
+ * and is sanitized on save — `internal_note_html` reads it back.
+ */
+ update: (
+ orderId: string,
+ params: { customer_note?: string; internal_note?: string },
+ options?: RequestOptions,
+ ): Promise<Order> =>
+ this.request<Order>('PATCH', `/orders/${orderId}/notes`, { ...options, body: params }),
+ },
+
/** The parcels owed on one order. */
fulfillments: {
list: (orderId: string, options?: RequestOptions): Promise<{ data: Fulfillment[] }> =>
diff --git a/packages/seller-sdk/src/types/generated/Order.ts b/packages/seller-sdk/src/types/generated/Order.ts
index aac1bbdacc..d8c01fc4aa 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 002e16db3ac4a4ac0be83d07a080d9dd
+// Typelizer digest f41f8a763c2f425aae72c02a21df513d
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {OrderLineItem, Fulfillment, Address} from '@/types'
@@ -15,6 +15,8 @@ type Order = {
completed_at: string;
created_at: string;
updated_at: string;
+ internal_note: string | null;
+ internal_note_html: string | null;
item_total: string | null;
display_item_total: string | null;
delivery_total: string | null;
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/notes_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/notes_controller.rb
new file mode 100644
index 0000000000..5f1894a4c9
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/notes_controller.rb
@@ -0,0 +1,82 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ module Orders
+ # The notes on one of this seller's orders: the instructions the
+ # buyer left, and the seller's own working note.
+ #
+ # A marketplace basket splits into one order per seller, so the
+ # internal note on this row is the seller's alone — never the
+ # operator's note about the whole sale.
+ #
+ # Singular, because an order has one set of notes: reading and
+ # writing them is a resource rather than a verb on the order.
+ class NotesController < BaseController
+ # The notes are columns on the order, not a nested collection, so
+ # there is no member record to fetch.
+ skip_before_action :set_resource, raise: false
+
+ # GET /api/v3/seller/orders/:order_id/notes
+ def show
+ render json: serialize_resource(@order)
+ end
+
+ # PATCH /api/v3/seller/orders/:order_id/notes
+ #
+ # Send only the note that changes: an absent key leaves the other
+ # alone, while an empty string clears it.
+ def update
+ attributes = notes_params
+ return render_validation_error(missing_notes_errors) if attributes.empty?
+
+ if @order.update(attributes)
+ render json: serialize_resource(@order.reload)
+ else
+ render_validation_error(@order.errors)
+ end
+ end
+
+ protected
+
+ def model_class
+ Spree::Order
+ end
+
+ # The whole order, so a client refreshing a note gets the same
+ # shape it renders the page from.
+ def serializer_class
+ Spree.api.seller_order_serializer
+ end
+
+ def read_actions
+ %w[show]
+ end
+
+ private
+
+ # The rich-text note is written through `internal_note`, which the
+ # model sanitizes — the `_html` reader is its round-trip partner,
+ # never a write.
+ def notes_params
+ permitted = params.permit(:customer_note, :internal_note)
+
+ {}.tap do |attributes|
+ attributes[:customer_note] = permitted[:customer_note] if params.key?(:customer_note)
+ attributes[:internal_note] = permitted[:internal_note] if params.key?(:internal_note)
+ end
+ end
+
+ # A request naming neither note has asked for nothing; saying so
+ # beats a 200 that changed nothing.
+ def missing_notes_errors
+ ActiveModel::Errors.new(@order).tap do |errors|
+ errors.add(:base, :blank, message: 'customer_note or internal_note is required')
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+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 3f35ef7e14..cdbf333d5b 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
@@ -39,12 +39,25 @@ module Spree
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]
+ cancel_note: [:string, nullable: true],
+ internal_note: [:string, nullable: true],
+ internal_note_html: [:string, nullable: true]
attributes :number, :customer_note, :currency, :total_quantity,
:status, :fulfillment_status, :payment_status,
completed_at: :iso8601, created_at: :iso8601, updated_at: :iso8601
+ # The seller's own working note. A marketplace basket is split into
+ # one order per seller, so this row — and the note on it — is theirs
+ # alone; it is never the operator's note about the whole sale.
+ attribute :internal_note do |order|
+ Spree::RichTextHelper.to_plain_text(order.internal_note).presence
+ end
+
+ attribute :internal_note_html do |order|
+ order.internal_note.presence
+ end
+
# What this seller is owed for the goods, and what the buyer paid for
# them. Deliberately not the whole money surface: gift cards, store
# credit and the payment breakdown belong to the marketplace.
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index a627b6e039..1feb20f0f0 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -870,6 +870,10 @@ Spree::Core::Engine.add_routes do
patch :address
end
+ # Singular: an order has one set of notes, so they are a resource to
+ # read and update rather than a verb on the order.
+ resource :notes, only: [:show, :update], controller: 'orders/notes'
+
# No `mark_delivered`: that a parcel arrived is the buyer's word,
# not the sender's, so confirming receipt stays with the operator
# and the carrier feed.
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/orders/notes_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/orders/notes_controller_spec.rb
new file mode 100644
index 0000000000..c0cbf25a7d
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/orders/notes_controller_spec.rb
@@ -0,0 +1,97 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Seller::Orders::NotesController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ let(:seller_user) do
+ create(:admin_user, :without_admin_role).tap { |user| seller.add_user(user) }
+ end
+ let(:token) do
+ Spree::Api::V3::TestingSupport.generate_jwt(
+ seller_user, audience: Spree::Api::V3::JwtAuthentication::JWT_AUDIENCE_SELLER
+ )
+ end
+
+ let(:other_seller) { create(:seller, :approved, store: store) }
+ let!(:mine) { create(:completed_order_with_totals, store: store, seller: seller) }
+ let!(:theirs) { create(:completed_order_with_totals, store: store, seller: other_seller) }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'GET #show' do
+ it 'renders the notes on the order' do
+ mine.update!(customer_note: 'Ring the bell')
+
+ get :show, params: { order_id: mine.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['customer_note']).to eq('Ring the bell')
+ end
+
+ it "404s on another seller's order" do
+ get :show, params: { order_id: theirs.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'PATCH #update' do
+ # A marketplace basket splits into one order per seller, so the note on
+ # this row belongs to this seller alone.
+ it 'records the seller’s own working note' do
+ patch :update, params: {
+ order_id: mine.prefixed_id, internal_note: '<p>Packed with the fragile insert.</p>'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.internal_note.to_s).to include('fragile insert')
+ end
+
+ it 'records what the buyer asked for' do
+ patch :update, params: {
+ order_id: mine.prefixed_id, customer_note: 'Leave with the neighbour'
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.customer_note).to eq('Leave with the neighbour')
+ end
+
+ # An absent key leaves that note alone; only an empty string clears it.
+ it 'leaves the note it was not sent' do
+ mine.update!(customer_note: 'Ring the bell')
+
+ patch :update, params: { order_id: mine.prefixed_id, internal_note: '<p>Noted.</p>' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.customer_note).to eq('Ring the bell')
+ end
+
+ it 'clears a note sent as an empty string' do
+ mine.update!(customer_note: 'Ring the bell')
+
+ patch :update, params: { order_id: mine.prefixed_id, customer_note: '' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload.customer_note).to be_blank
+ end
+
+ it 'refuses a request naming neither note' do
+ patch :update, params: { order_id: mine.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it "404s on another seller's order" do
+ patch :update, params: {
+ order_id: theirs.prefixed_id, internal_note: '<p>Nope.</p>'
+ }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
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 e574ca2fe3..c3adc49779 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
@@ -216,6 +216,88 @@ RSpec.describe 'Seller Orders API', type: :request, swagger_doc: 'api-reference/
end
end
+ path '/api/v3/seller/orders/{order_id}/notes' do
+ parameter name: :order_id, in: :path, type: :string, description: 'Prefixed order ID'
+
+ get 'Get order notes' do
+ tags 'Orders'
+ produces 'application/json'
+ security [bearer_auth: []]
+ description <<~DESC
+ The instructions the buyer left, and the seller's own working note.
+
+ A marketplace basket splits into one order per seller, so the internal
+ note here is this seller's alone rather than the operator's note about
+ the whole sale.
+ DESC
+
+ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true
+
+ response '200', 'notes' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:order_id) { order.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/Order'
+
+ run_test!
+ end
+ end
+
+ patch 'Update order notes' do
+ tags 'Orders'
+ consumes 'application/json'
+ produces 'application/json'
+ security [bearer_auth: []]
+ description <<~DESC
+ Send only the note that changes: an absent key leaves the other alone,
+ while an empty string clears it.
+
+ `internal_note` accepts HTML and is sanitized on save;
+ `internal_note_html` reads it back.
+ DESC
+
+ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true
+ parameter name: :body, in: :body, required: true, schema: {
+ type: :object,
+ properties: {
+ customer_note: {
+ type: :string,
+ nullable: true,
+ description: "What the buyer asked for"
+ },
+ internal_note: {
+ type: :string,
+ nullable: true,
+ description: "The seller's own working note, as HTML"
+ }
+ }
+ }
+
+ response '200', 'notes updated' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:order_id) { order.prefixed_id }
+ let(:body) { { internal_note: '<p>Packed with the fragile insert.</p>' } }
+
+ schema '$ref' => '#/components/schemas/Order'
+
+ run_test! do
+ expect(order.reload.internal_note.to_s).to include('fragile insert')
+ end
+ end
+
+ response '422', 'neither note named' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:order_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'