Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let a seller name why they cancelled
Damian Legawiec72312ca8c965
diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yamlindex 203ddbb6b4..cea5fa4afb 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 64+ name: Seller 65status: approvedschema:"$ref": "#/components/schemas/AuthResponse"@@ -13540,8 +13540,8 @@ paths:example:data:- id: prod_UkLWZg9DAJ- name: Product 1583250- slug: product-1583250+ name: Product 1573250+ slug: product-1573250meta_title:meta_description:meta_keywords:@@ -13784,8 +13784,8 @@ paths:application/json:example:id: prod_UkLWZg9DAJ- name: Product 1616710- slug: product-1616710+ name: Product 1606710+ slug: product-1606710meta_title:meta_description:meta_keywords:@@ -13864,7 +13864,7 @@ paths:example:id: prod_UkLWZg9DAJname: Hand-thrown mug, large- slug: product-1648212+ slug: product-1638212meta_title:meta_description:meta_keywords:@@ -13977,8 +13977,8 @@ paths:application/json:example:id: sel_UkLWZg9DAJ- name: Seller 81- slug: seller-81+ name: Seller 82+ slug: seller-82about: ''about_html: ''logo_url:@@ -14050,7 +14050,7 @@ paths:example:id: sel_UkLWZg9DAJname: Acme Supplies- slug: seller-83+ slug: seller-84about: ''about_html: ''logo_url:@@ -14793,10 +14793,10 @@ paths:application/json:example:direct_upload:- url: http://www.example.com/rails/active_storage/disk/eyJfcmFpbHMiOnsiZGF0YSI6eyJrZXkiOiJuem5oOGdra3VxendvbDc1ODBxNHNwZmpmMjVxIiwiY29udGVudF90eXBlIjoiYXBwbGljYXRpb24vcGRmIiwiY29udGVudF9sZW5ndGgiOjUxMjM0LCJjaGVja3N1bSI6IlZqaHowNGxRdUVHdXY0bkR2aHNhTlE9PSIsInNlcnZpY2VfbmFtZSI6InRlc3QifSwiZXhwIjoiMjAyNi0wMS0xNVQxMjowNTowMC4wMDBaIiwicHVyIjoiYmxvYl90b2tlbiJ9fQ==--646a62035fe9802198cc67c2a36c19e463e623d9+ url: http://www.example.com/rails/active_storage/disk/eyJfcmFpbHMiOnsiZGF0YSI6eyJrZXkiOiJuem5oOGdra3VxendvbDc1ODBxNHNwZmpmMjVxIiwiY29udGVudF90eXBlIjoiYXBwbGljYXRpb24vcGRmIiwiY29udGVudF9sZW5ndGgiOjUxMjM0LCJjaGVja3N1bSI6IlZqaHowNGxRdUVHdXY0bkR2aHNhTlE9PSIsInNlcnZpY2VfbmFtZSI6InRlc3QifSwiZXhwIjoiMjAyNi0wMS0xNVQxMjowNTowMC4wMDBaIiwicHVyIjoiYmxvYl90b2tlbiJ9fQ==--af763bb4884a5488e212eee0e3d07ee6a4e74776headers:Content-Type: application/pdf- signed_id: eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoiYmxvYl9pZCJ9fQ==--05abc4a54ff4795f9255952c049b07263b96fc22+ signed_id: eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoiYmxvYl9pZCJ9fQ==--f775c2b1a726398884efebb8c4a9d44c7ddcb413schema:"$ref": "#/components/schemas/DirectUploadResponse"requestBody:@@ -15601,8 +15601,8 @@ paths:quantity: 1line_item_id: li_UkLWZg9DAJvariant_id: variant_UkLWZg9DAJ- name: Product 1489315- sku: SKU-190+ name: Product 1469315+ sku: SKU-188options_text: ''schema:type: object@@ -15672,8 +15672,8 @@ paths:quantity: 1line_item_id: li_UkLWZg9DAJvariant_id: variant_UkLWZg9DAJ- name: Product 149961- sku: SKU-191+ name: Product 147961+ sku: SKU-189options_text: ''schema:"$ref": "#/components/schemas/Fulfillment"@@ -15760,8 +15760,8 @@ paths:quantity: 1line_item_id: li_UkLWZg9DAJvariant_id: variant_UkLWZg9DAJ- name: Product 1503170- sku: SKU-192+ name: Product 1483170+ sku: SKU-190options_text: ''schema:"$ref": "#/components/schemas/Fulfillment"@@ -15828,8 +15828,8 @@ paths:quantity: 1line_item_id: li_UkLWZg9DAJvariant_id: variant_UkLWZg9DAJ- name: Product 1517276- sku: SKU-193+ name: Product 1497276+ sku: SKU-191options_text: ''schema:"$ref": "#/components/schemas/Fulfillment"@@ -15972,7 +15972,7 @@ paths:display_total: "$110.00"items:- id: li_UkLWZg9DAJ- name: Product 15395+ name: Product 15195options_text: ''quantity: 1currency: USD@@ -15981,7 +15981,7 @@ paths:total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ- sku: SKU-195+ sku: SKU-193thumbnail_url:fulfillments:- id: ful_UkLWZg9DAJ@@ -16002,8 +16002,8 @@ paths:quantity: 1line_item_id: li_UkLWZg9DAJvariant_id: variant_UkLWZg9DAJ- name: Product 15395- sku: SKU-195+ name: Product 15195+ sku: SKU-193options_text: ''shipping_address:id: addr_gbHJdmfrXB@@ -16011,7 +16011,7 @@ paths:first_name: Johnlast_name: Doefull_name: John Doe- address1: 141 Lovely Street+ address1: 137 Lovely Streetaddress2: Northwestpostal_code: '10118'city: New York@@ -16033,7 +16033,7 @@ paths:first_name: Johnlast_name: Doefull_name: John Doe- address1: 140 Lovely Street+ address1: 136 Lovely Streetaddress2: Northwestpostal_code: '10118'city: New York@@ -16122,7 +16122,7 @@ paths:display_total: "$110.00"items:- id: li_UkLWZg9DAJ- name: Product 1549755+ name: Product 1529755options_text: ''quantity: 1currency: USD@@ -16131,7 +16131,7 @@ paths:total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ- sku: SKU-196+ sku: SKU-194thumbnail_url:fulfillments:- id: ful_UkLWZg9DAJ@@ -16152,8 +16152,8 @@ paths:quantity: 1line_item_id: li_UkLWZg9DAJvariant_id: variant_UkLWZg9DAJ- name: Product 1549755- sku: SKU-196+ name: Product 1529755+ sku: SKU-194options_text: ''shipping_address:id: addr_gbHJdmfrXB@@ -16161,7 +16161,7 @@ paths:first_name: Johnlast_name: Doefull_name: John Doe- address1: 143 Lovely Street+ address1: 139 Lovely Streetaddress2: Northwestpostal_code: '10118'city: New York@@ -16183,7 +16183,7 @@ paths:first_name: Johnlast_name: Doefull_name: John Doe- address1: 142 Lovely Street+ address1: 138 Lovely Streetaddress2: Northwestpostal_code: '10118'city: New York@@ -16226,10 +16226,13 @@ paths:security:- bearer_auth: []description: |- Withdraws from an order this seller cannot fulfil.+ Withdraws from an order this seller cannot fulfil, naming a reason from+ the marketplace's own list.- Restocking and any refund are the cancellation's own concern, so a- seller cannot cancel without the money and the stock following.+ The goods go back on the shelf and the payment authorization is+ released. Money already taken is **not** returned: that is the+ operator's decision, so this endpoint accepts no refund arguments at+ all rather than defaulting one a caller could override.parameters:- name: X-Spree-Seller-Idin: header@@ -16261,7 +16264,7 @@ paths:display_total: "$110.00"items:- id: li_UkLWZg9DAJ- name: Product 1576554+ name: Product 1556554options_text: ''quantity: 1currency: USD@@ -16270,7 +16273,7 @@ paths:total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ- sku: SKU-199+ sku: SKU-197thumbnail_url:fulfillments:- id: ful_UkLWZg9DAJ@@ -16291,8 +16294,8 @@ paths:quantity: 1line_item_id: li_UkLWZg9DAJvariant_id: variant_UkLWZg9DAJ- name: Product 1576554- sku: SKU-199+ name: Product 1556554+ sku: SKU-197options_text: ''shipping_address:id: addr_gbHJdmfrXB@@ -16300,7 +16303,7 @@ paths:first_name: Johnlast_name: Doefull_name: John Doe- address1: 149 Lovely Street+ address1: 145 Lovely Streetaddress2: Northwestpostal_code: '10118'city: New York@@ -16322,7 +16325,7 @@ paths:first_name: Johnlast_name: Doefull_name: John Doe- address1: 148 Lovely Street+ address1: 144 Lovely Streetaddress2: Northwestpostal_code: '10118'city: New York@@ -16346,9 +16349,64 @@ paths:schema:type: objectproperties:+ cancel_reason_id:+ type: string+ nullable: true+ description: A reason from GET /order_cancellation_reasons+ cancel_note:+ type: string+ nullable: true+ description: Free text beside the reasonnotify_customer:type: booleandescription: Email the customer about the cancellation+ "/api/v3/seller/order_cancellation_reasons":+ get:+ summary: List order cancellation reasons+ tags:+ - Orders+ security:+ - bearer_auth: []+ description: |+ Why an order was called off, as the marketplace defines it.++ Read-only: a seller picks one when cancelling, and the operator decides+ what the list holds. Retired reasons are left out.+ parameters:+ - name: X-Spree-Seller-Id+ in: header+ required: true+ schema:+ type: string+ responses:+ '200':+ description: reasons listed+ content:+ application/json:+ example:+ data:+ - id: ocr_UkLWZg9DAJ+ name: Out of stock+ active: true+ meta:+ page: 1+ limit: 25+ count: 1+ pages: 1+ from: 1+ to: 1+ in: 1+ previous:+ next:+ schema:+ type: object+ properties:+ data:+ type: array+ items:+ "$ref": "#/components/schemas/Reason"+ required:+ - data"/api/v3/seller/orders/{order_id}/returns":parameters:- name: order_id@@ -16467,7 +16525,7 @@ paths:example:error:code: processing_error- message: Only 1 of Product 1687120 can be returned+ message: Only 1 of Product 1677120 can be returnedrequestBody:content:application/json:diff --git a/packages/seller-dashboard/src/components/orders/order-cancel-dialog.tsx b/packages/seller-dashboard/src/components/orders/order-cancel-dialog.tsxnew file mode 100644index 0000000000..8bf6d9f46c--- /dev/null+++ b/packages/seller-dashboard/src/components/orders/order-cancel-dialog.tsx@@ -0,0 +1,157 @@+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'+import {+ Button,+ Checkbox,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldLabel,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Textarea,+} from '@spree/dashboard-ui'+import { Controller, useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import { useCancelOrder } from '../../hooks/use-order'+import { useReasons } from '../../hooks/use-reasons'++type CancelFormValues = {+ cancel_reason_id: string+ cancel_note: string+ notify_customer: boolean+}++/**+ * Withdrawing from an order this seller cannot fulfil.+ *+ * A dialog rather than a bare confirm, because a cancellation carries a+ * reason the marketplace wants recorded — without one, operator reporting has+ * nothing to say about why a seller pulled out.+ *+ * Deliberately offers no refund control. The goods return to the shelf and+ * the authorization is released either way; giving back money already taken+ * is the operator's decision, and the endpoint accepts no refund arguments at+ * all rather than showing a seller a switch that would be refused.+ */+export function OrderCancelDialog({ orderId, onClose }: { orderId: string; onClose: () => void }) {+ const { t } = useTranslation()+ const cancel = useCancelOrder(orderId)+ const { data: reasonsData } = useReasons('order-cancellation-reasons')++ const reasons = (reasonsData?.data ?? []).filter((reason) => reason.active)+ const reasonOptions = [+ // A marketplace that has not curated the vocabulary can still be pulled+ // out of, so the empty choice stays rather than forcing a reason.+ { value: '', label: t('orders.cancel_dialog.no_reason') },+ ...reasons.map((reason) => ({ value: reason.id, label: reason.name })),+ ]++ const form = useForm<CancelFormValues>({+ defaultValues: { cancel_reason_id: '', cancel_note: '', notify_customer: false },+ })++ async function onSubmit(values: CancelFormValues) {+ try {+ await cancel.mutateAsync({+ cancel_reason_id: values.cancel_reason_id || undefined,+ cancel_note: values.cancel_note.trim() || undefined,+ notify_customer: values.notify_customer,+ })+ onClose()+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+ }++ return (+ <Dialog open onOpenChange={(next) => !next && onClose()}>+ <DialogContent>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <DialogHeader>+ <DialogTitle>{t('orders.cancel_confirm.title')}</DialogTitle>+ <DialogDescription>{t('orders.cancel_dialog.description')}</DialogDescription>+ </DialogHeader>++ <DialogBody>+ {form.formState.errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {form.formState.errors.root.message}+ </p>+ )}++ <div className="flex flex-col gap-4">+ {reasons.length > 0 && (+ <Field>+ <FieldLabel htmlFor="cancel-reason">+ {t('orders.cancel_dialog.reason_label')}+ </FieldLabel>+ <Controller+ control={form.control}+ name="cancel_reason_id"+ render={({ field }) => (+ <Select+ items={reasonOptions}+ value={field.value}+ onValueChange={(value) => field.onChange(value ?? '')}+ >+ <SelectTrigger id="cancel-reason">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {reasonOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ </Field>+ )}++ <Field>+ <FieldLabel htmlFor="cancel-note">+ {t('orders.cancel_dialog.note_label')}+ </FieldLabel>+ <Textarea id="cancel-note" {...form.register('cancel_note')} />+ </Field>++ <label className="flex items-center gap-2 text-sm" htmlFor="cancel-notify">+ <Controller+ control={form.control}+ name="notify_customer"+ render={({ field }) => (+ <Checkbox+ id="cancel-notify"+ checked={field.value}+ onCheckedChange={(checked) => field.onChange(!!checked)}+ />+ )}+ />+ {t('orders.cancel_dialog.notify_customer')}+ </label>+ </div>+ </DialogBody>++ <DialogFooter>+ <Button type="button" variant="outline" onClick={onClose}>+ {t('common.cancel')}+ </Button>+ <Button type="submit" variant="destructive" disabled={cancel.isPending}>+ {t('orders.cancel')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/packages/seller-dashboard/src/hooks/use-order.ts b/packages/seller-dashboard/src/hooks/use-order.tsindex d80d3033e7..2f95dafeff 100644--- a/packages/seller-dashboard/src/hooks/use-order.ts+++ b/packages/seller-dashboard/src/hooks/use-order.ts@@ -15,7 +15,11 @@ export function useOrder(orderId: string) {/** Withdrawing from an order this seller cannot fulfil. */export function useCancelOrder(orderId: string) {- return useOrderMutation(orderId, () => sellerClient().orders.cancel(orderId))+ return useOrderMutation(+ orderId,+ (params?: { cancel_reason_id?: string; cancel_note?: string; notify_customer?: boolean }) =>+ sellerClient().orders.cancel(orderId, params),+ )}/**diff --git a/packages/seller-dashboard/src/hooks/use-reasons.ts b/packages/seller-dashboard/src/hooks/use-reasons.tsindex 0559949371..7aeca0a1eb 100644--- a/packages/seller-dashboard/src/hooks/use-reasons.ts+++ b/packages/seller-dashboard/src/hooks/use-reasons.ts@@ -2,19 +2,22 @@ import { useResourceKey } from '@spree/dashboard-core'import { useQuery } from '@tanstack/react-query'import { sellerClient } from '../api-client'-export type ReasonKind = 'return-reasons' | 'claim-reasons'+export type ReasonKind = 'return-reasons' | 'claim-reasons' | 'order-cancellation-reasons'/**- * The marketplace's vocabulary for why goods came back or what went wrong.- * Operator-owned and slow-moving, so one fetch serves every dialog.+ * The marketplace's vocabulary for why goods came back, what went wrong, or+ * why an order was called off. Operator-owned and slow-moving, so one fetch+ * serves every dialog.*/export function useReasons(kind: ReasonKind, enabled = true) {return useQuery({queryKey: useResourceKey(kind),- queryFn: () =>- kind === 'return-reasons'- ? sellerClient().returnReasons.list()- : sellerClient().claimReasons.list(),+ queryFn: () => {+ const client = sellerClient()+ if (kind === 'return-reasons') return client.returnReasons.list()+ if (kind === 'claim-reasons') return client.claimReasons.list()+ return client.orderCancellationReasons.list()+ },staleTime: 5 * 60 * 1000,enabled,})diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.jsonindex 8602a41c3e..1a01cea8a4 100644--- a/packages/seller-dashboard/src/locales/en.json+++ b/packages/seller-dashboard/src/locales/en.json@@ -387,6 +387,13 @@"cancel_title": "Cancel this claim?","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"}},"policies": {diff --git a/packages/seller-dashboard/src/pages/order.tsx b/packages/seller-dashboard/src/pages/order.tsxindex 3b4dc029ee..ac0208ed4c 100644--- a/packages/seller-dashboard/src/pages/order.tsx+++ b/packages/seller-dashboard/src/pages/order.tsx@@ -1,15 +1,11 @@import { PageHeader } from '@spree/dashboard-core'-import {- DropdownMenuItem,- ResourceLayout,- StatusBadge,- toastManager,- useConfirm,-} from '@spree/dashboard-ui'+import { DropdownMenuItem, ResourceLayout, StatusBadge } from '@spree/dashboard-ui'import { useParams } from '@tanstack/react-router'+import { useState } from 'react'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,OrderItemsCard,@@ -19,7 +15,7 @@ import {import { ClaimsCard, ExchangesCard } from '../components/orders/post-sale-cards'import { ReturnsCard } from '../components/orders/returns-card'import { RetryableError } from '../components/retryable-error'-import { useCancelOrder, useOrder } from '../hooks/use-order'+import { useOrder } from '../hooks/use-order'/*** One order, as the seller needs it to pack, post, and put right.@@ -32,100 +28,84 @@ import { useCancelOrder, useOrder } from '../hooks/use-order'export function OrderPage() {const { t } = useTranslation()const { orderId } = useParams({ from: '/_authenticated/$sellerId/orders/$orderId' })- const confirm = useConfirm()+ const [canceling, setCanceling] = useState(false)const { data: order, isLoading, isError, refetch } = useOrder(orderId)- const cancel = useCancelOrder(orderId)-if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>if (isError) return <RetryableError onRetry={() => refetch()} />if (!order) return <CenteredMessage>{t('orders.not_found')}</CenteredMessage>- async function handleCancel() {- const ok = await confirm({- title: t('orders.cancel_confirm.title'),- message: t('orders.cancel_confirm.message'),- variant: 'destructive',- confirmLabel: t('orders.cancel'),- })- if (!ok) return-- await cancel- .mutateAsync(undefined)- .then(() => toastManager.add({ type: 'success', title: t('orders.canceled') }))- .catch(() => undefined)- }-const cancelable = order.status !== 'canceled'// Nothing can come back from an order that never went out, so the post-sale// cards would only render empty with a disabled button.const placed = !!order.completed_atreturn (- <ResourceLayout- header={- // Cancel sits in the menu's destructive group rather than beside the- // title: it is easy to hit by mistake there, and this is where the- // operator dashboard puts the same action.- <PageHeader- title={order.number}- backTo="orders"- subtitle={order.completed_at ? new Date(order.completed_at).toLocaleString() : undefined}- badges={- <>- {order.fulfillment_status && (- <StatusBadge- status={order.fulfillment_status}- label={t(`orders.fulfillment_statuses.${order.fulfillment_status}`, {- defaultValue: order.fulfillment_status,- })}- />- )}- {order.payment_status && (- <StatusBadge- status={order.payment_status}- label={t(`orders.payment_statuses.${order.payment_status}`, {- defaultValue: order.payment_status,- })}- />- )}- </>- }- resource={{ id: order.id, number: order.number }}- destructiveItems={- cancelable ? (- <DropdownMenuItem- variant="destructive"- disabled={cancel.isPending}- onClick={handleCancel}- >- {t('orders.cancel')}- </DropdownMenuItem>- ) : undefined- }- />- }- main={- <>- <FulfillmentsCard order={order} />- {placed && (- <>- <ReturnsCard order={order} />- <ExchangesCard order={order} />- <ClaimsCard order={order} />- </>- )}- <OrderItemsCard order={order} />- <OrderSummaryCard order={order} />- </>- }- sidebar={- <>- <OrderCustomerCard order={order} />- <OrderNoteCard order={order} />- </>- }- />+ <>+ {canceling && <OrderCancelDialog orderId={orderId} onClose={() => setCanceling(false)} />}+ <ResourceLayout+ header={+ // Cancel sits in the menu's destructive group rather than beside the+ // title: it is easy to hit by mistake there, and this is where the+ // operator dashboard puts the same action.+ <PageHeader+ title={order.number}+ backTo="orders"+ subtitle={+ order.completed_at ? new Date(order.completed_at).toLocaleString() : undefined+ }+ badges={+ <>+ {order.fulfillment_status && (+ <StatusBadge+ status={order.fulfillment_status}+ label={t(`orders.fulfillment_statuses.${order.fulfillment_status}`, {+ defaultValue: order.fulfillment_status,+ })}+ />+ )}+ {order.payment_status && (+ <StatusBadge+ status={order.payment_status}+ label={t(`orders.payment_statuses.${order.payment_status}`, {+ defaultValue: order.payment_status,+ })}+ />+ )}+ </>+ }+ resource={{ id: order.id, number: order.number }}+ destructiveItems={+ cancelable ? (+ <DropdownMenuItem variant="destructive" onClick={() => setCanceling(true)}>+ {t('orders.cancel')}+ </DropdownMenuItem>+ ) : undefined+ }+ />+ }+ main={+ <>+ <FulfillmentsCard order={order} />+ {placed && (+ <>+ <ReturnsCard order={order} />+ <ExchangesCard order={order} />+ <ClaimsCard order={order} />+ </>+ )}+ <OrderItemsCard order={order} />+ <OrderSummaryCard order={order} />+ </>+ }+ sidebar={+ <>+ <OrderCustomerCard order={order} />+ <OrderNoteCard order={order} />+ </>+ }+ />+ </>)}diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.tsindex c06abf5046..fe6012f43f 100644--- a/packages/seller-sdk/src/seller-client.ts+++ b/packages/seller-sdk/src/seller-client.ts@@ -388,10 +388,16 @@ export class SellerClient {get: (id: string, options?: RequestOptions): Promise<Order> =>this.request<Order>('GET', `/orders/${id}`, options),- /** Withdraws from an order this seller cannot fulfil. */+ /**+ * Withdraws from an order this seller cannot fulfil.+ *+ * Takes a reason from the marketplace's own list and an optional note.+ * Never a refund: the authorization is released either way, but returning+ * money already taken is the operator's decision.+ */cancel: (id: string,- params?: { notify_customer?: boolean },+ params?: { cancel_reason_id?: string; cancel_note?: string; notify_customer?: boolean },options?: RequestOptions,): Promise<Order> =>this.request<Order>('PATCH', `/orders/${id}/cancel`, { ...options, body: params }),@@ -811,6 +817,11 @@ export class SellerClient {this.request<{ data: Reason[] }>('GET', '/claim_reasons', options),}+ readonly orderCancellationReasons = {+ list: (options?: RequestOptions): Promise<{ data: Reason[] }> =>+ this.request<{ data: Reason[] }>('GET', '/order_cancellation_reasons', options),+ }+readonly trackingCarriers = {list: (options?: RequestOptions): Promise<{ data: Array<{ id: string; name: string }> }> =>this.request<{ data: Array<{ id: string; name: string }> }>(diff --git a/spree/api/app/controllers/spree/api/v3/seller/order_cancellation_reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/order_cancellation_reasons_controller.rbnew file mode 100644index 0000000000..9def6db552--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/seller/order_cancellation_reasons_controller.rb@@ -0,0 +1,25 @@+module Spree+ module Api+ module V3+ module Seller+ # Why an order was called off.+ #+ # Read-only here, like the other vocabularies, but gated by `orders`+ # rather than the `settings` key the operator's own CRUD sits behind —+ # `settings` is never seller-grantable, and a seller cancelling their+ # own order needs to name a reason from the marketplace's list.+ class OrderCancellationReasonsController < ReasonsController+ protected++ def model_class+ Spree::OrderCancellationReason+ end++ def reasons_association+ :order_cancellation_reasons+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rbindex a085f0e083..f96fbed64e 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@@ -25,17 +25,21 @@ module Spree# PATCH /api/v3/seller/orders/:id/cancel#- # A seller withdrawing from an order they cannot fulfil.+ # A seller withdrawing from an order they cannot fulfil, naming a+ # reason from the marketplace's own list.#- # Restocking and refunding are not asked for here, matching the- # operator's own cancel endpoint: the marketplace owns the money and- # settles with the customer separately, and a seller must not be the- # one deciding a refund.+ # Deliberately takes no `refund_payments` or `refund_amount`: the+ # workflow releases the authorization either way, but returning money+ # already taken is the operator's decision, and leaving the arguments+ # off is what keeps that true rather than a default a caller could+ # override.def cancelwith_order_lock doresult = Spree.order_cancel_workflow.call(order: @resource,canceler: try_spree_current_user,+ reason: cancel_reason,+ note: params[:cancel_note].presence,notify_customer: params[:notify_customer].to_b)@@ -74,6 +78,16 @@ module Spreeprivate+ # 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.+ def cancel_reason+ id = params[:cancel_reason_id].presence+ return if id.nil?++ current_store.order_cancellation_reasons.find_by_prefix_id!(id)+ end+def set_resource@resource = find_resource@order = @resource # OrderLock reads thisdiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 7a7ffe0079..28acb5a31d 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -919,6 +919,7 @@ Spree::Core::Engine.add_routes do# reason, the operator decides what the reasons are.resources :return_reasons, only: [:index]resources :claim_reasons, only: [:index]+ resources :order_cancellation_reasons, only: [:index]# Registry data — which carriers a tracking number can be pinned to.resources :tracking_carriers, only: [:index]diff --git a/spree/api/spec/controllers/spree/api/v3/seller/order_cancellation_reasons_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/order_cancellation_reasons_controller_spec.rbnew file mode 100644index 0000000000..0b41cc7cb6--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/seller/order_cancellation_reasons_controller_spec.rb@@ -0,0 +1,51 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Seller::OrderCancellationReasonsController, 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++ before do+ request.headers['Authorization'] = "Bearer #{token}"+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id+ end++ describe 'GET #index' do+ let!(:reason) { create(:order_cancellation_reason, store: store, name: 'Out of stock') }++ it 'lists the marketplace’s reasons' do+ get :index, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].map { |row| row['name'] }).to include('Out of stock')+ end++ # A withdrawn reason must not be offered: a seller filing against it would+ # be using vocabulary the operator has retired.+ it 'leaves out retired reasons' do+ create(:order_cancellation_reason, store: store, name: 'Obsolete', active: false)++ get :index, as: :json++ expect(json_response['data'].map { |row| row['name'] }).not_to include('Obsolete')+ end++ it 'leaves out another store’s reasons' do+ other_store = create(:store)+ create(:order_cancellation_reason, store: other_store, name: 'Elsewhere')++ get :index, as: :json++ expect(json_response['data'].map { |row| row['name'] }).not_to include('Elsewhere')+ end+ end+enddiff --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.rbindex c99e6993d6..da438ea25f 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@@ -136,4 +136,43 @@ RSpec.describe Spree::Api::V3::Seller::OrdersController, type: :controller doexpect(theirs.reload).not_to be_canceledendend++ describe 'PATCH #cancel with a reason' do+ let!(:order) { create(:completed_order_with_totals, store: store, seller: seller) }+ let(:reason) { create(:order_cancellation_reason, store: store, name: 'Out of stock') }++ it 'records the reason and note the seller picked' do+ patch :cancel, params: {+ id: order.prefixed_id,+ cancel_reason_id: reason.prefixed_id,+ cancel_note: 'Supplier let us down'+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(order.reload.cancel_reason).to eq(reason)+ expect(order.cancel_note).to eq('Supplier let us down')+ end++ # The vocabulary is the marketplace's, and a reason from another store+ # would label this order with words its operator never chose.+ it 'refuses a reason belonging to another store' do+ elsewhere = create(:order_cancellation_reason, store: create(:store), name: 'Elsewhere')++ patch :cancel, params: { id: order.prefixed_id, cancel_reason_id: elsewhere.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ expect(order.reload).not_to be_canceled+ end++ # Releasing the authorization is the cancel's job; giving back money+ # already taken is the operator's, so the seller endpoint passes no refund+ # arguments at all and the workflow's default holds.+ it 'refunds nothing' do+ expect {+ patch :cancel, params: { id: order.prefixed_id }, as: :json+ }.not_to change(Spree::Refund, :count)++ expect(order.reload).to be_canceled+ end+ endenddiff --git a/spree/api/spec/integration/spree/api/v3/seller/orders_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/orders_spec.rbindex b99d46c2e0..6020675267 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@@ -107,16 +107,25 @@ RSpec.describe 'Seller Orders API', type: :request, swagger_doc: 'api-reference/produces 'application/json'security [bearer_auth: []]description <<~DESC- Withdraws from an order this seller cannot fulfil.+ Withdraws from an order this seller cannot fulfil, naming a reason from+ the marketplace's own list.- Restocking and any refund are the cancellation's own concern, so a- seller cannot cancel without the money and the stock following.+ The goods go back on the shelf and the payment authorization is+ released. Money already taken is **not** returned: that is the+ operator's decision, so this endpoint accepts no refund arguments at+ all rather than defaulting one a caller could override.DESCparameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: trueparameter name: :body, in: :body, required: false, schema: {type: :object,properties: {+ cancel_reason_id: {+ type: :string,+ nullable: true,+ description: 'A reason from GET /order_cancellation_reasons'+ },+ cancel_note: { type: :string, nullable: true, description: 'Free text beside the reason' },notify_customer: { type: :boolean, description: 'Email the customer about the cancellation' }}}@@ -135,4 +144,35 @@ RSpec.describe 'Seller Orders API', type: :request, swagger_doc: 'api-reference/endendend++ path '/api/v3/seller/order_cancellation_reasons' do+ get 'List order cancellation reasons' do+ tags 'Orders'+ produces 'application/json'+ security [bearer_auth: []]+ description <<~DESC+ Why an order was called off, as the marketplace defines it.++ Read-only: a seller picks one when cancelling, and the operator decides+ what the list holds. Retired reasons are left out.+ DESC++ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true++ response '200', 'reasons listed' do+ let(:Authorization) { "Bearer #{seller_jwt_token}" }+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }++ before { create(:order_cancellation_reason, store: store, name: 'Out of stock') }++ schema type: :object,+ properties: {+ data: { type: :array, items: { '$ref' => '#/components/schemas/Reason' } }+ },+ required: %w[data]++ run_test!+ end+ end+ endend