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
Show exchanges and claims on the order page
Damian Legawiece1c1d07da737
diff --git a/packages/dashboard/src/components/spree/order-post-sale-cards.tsx b/packages/dashboard/src/components/spree/order-post-sale-cards.tsxnew file mode 100644index 0000000000..c835f15734--- /dev/null+++ b/packages/dashboard/src/components/spree/order-post-sale-cards.tsx@@ -0,0 +1,261 @@+import type { Claim, Exchange } from '@spree/admin-sdk'+import {+ Badge,+ Button,+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ StatusBadge,+ useConfirm,+} from '@spree/dashboard-ui'+import {+ BanknoteIcon,+ CheckCircleIcon,+ EllipsisVerticalIcon,+ PackageCheckIcon,+ RepeatIcon,+ ShieldAlertIcon,+ TruckIcon,+ XCircleIcon,+} from 'lucide-react'+import { useTranslation } from 'react-i18next'+import {+ useClaimActions,+ useExchangeActions,+ useOrderClaims,+ useOrderExchanges,+} from '../../hooks/use-post-sale'++/** Exchanges on an order, with the actions available at each status. */+export function OrderExchangesCard({ orderId }: { orderId: string }) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const { data } = useOrderExchanges(orderId)+ const { approve, receive, fulfill, cancel } = useExchangeActions(orderId)++ const exchanges = data?.data ?? []+ if (exchanges.length === 0) return null++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <RepeatIcon className="size-4" />+ {t('admin.pages.orders.detail.section_exchanges')}+ <Badge variant="outline">{exchanges.length}</Badge>+ </CardTitle>+ </CardHeader>+ <CardContent className="flex flex-col gap-4">+ {exchanges.map((exchange: Exchange) => (+ <div key={exchange.id} className="rounded-lg border p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <StatusBadge status={exchange.status} />+ <span className="text-sm font-medium">{exchange.number}</span>+ </div>++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-xs">+ <EllipsisVerticalIcon className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {exchange.status === 'requested' && (+ <DropdownMenuItem onClick={() => approve.mutate(exchange.id)}>+ <CheckCircleIcon className="size-4" />+ {t('admin.pages.orders.detail.returns.actions.approve')}+ </DropdownMenuItem>+ )}+ {exchange.status === 'approved' && (+ <DropdownMenuItem onClick={() => receive.mutate({ exchangeId: exchange.id })}>+ <PackageCheckIcon className="size-4" />+ {t('admin.pages.orders.detail.returns.actions.receive')}+ </DropdownMenuItem>+ )}+ {exchange.status === 'received' && (+ <DropdownMenuItem onClick={() => fulfill.mutate({ exchangeId: exchange.id })}>+ <TruckIcon className="size-4" />+ {t('admin.pages.orders.detail.exchanges.actions.fulfill')}+ </DropdownMenuItem>+ )}+ {['requested', 'approved'].includes(exchange.status) && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="text-destructive focus:text-destructive"+ onClick={async () => {+ if (+ await confirm({+ message: t('admin.pages.orders.detail.returns.confirm.cancel'),+ variant: 'destructive',+ confirmLabel: t('admin.actions.cancel'),+ })+ ) {+ cancel.mutate({ exchangeId: exchange.id })+ }+ }}+ >+ <XCircleIcon className="size-4" />+ {t('admin.actions.cancel')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ <div className="flex flex-col gap-1.5">+ {(exchange.exchange_line_items ?? []).map((line) => (+ <div key={line.id} className="flex items-center justify-between text-sm">+ <span className="truncate">+ {line.original_variant?.product_name ?? line.original_variant_id}+ {' → '}+ {line.new_variant?.options_text || line.new_variant?.sku || line.new_variant_id}+ </span>+ <span className="text-muted-foreground">×{line.quantity}</span>+ </div>+ ))}+ </div>++ <div className="flex items-center justify-between text-sm border-t pt-3">+ <span className="text-muted-foreground">+ {t('admin.pages.orders.detail.exchanges.price_difference')}+ </span>+ <span className="font-medium">{exchange.display_price_difference}</span>+ </div>+ </div>+ ))}+ </CardContent>+ </Card>+ )+}++/** Claims on an order. Resolution is chosen at resolve time, not up front. */+export function OrderClaimsCard({ orderId }: { orderId: string }) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const { data } = useOrderClaims(orderId)+ const { approve, resolve, deny, cancel } = useClaimActions(orderId)++ const claims = data?.data ?? []+ if (claims.length === 0) return null++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ <ShieldAlertIcon className="size-4" />+ {t('admin.pages.orders.detail.section_claims')}+ <Badge variant="outline">{claims.length}</Badge>+ </CardTitle>+ </CardHeader>+ <CardContent className="flex flex-col gap-4">+ {claims.map((claim: Claim) => (+ <div key={claim.id} className="rounded-lg border p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-2">+ <StatusBadge status={claim.status} />+ <span className="text-sm font-medium">{claim.number}</span>+ <Badge variant="outline">+ {t(`admin.pages.orders.detail.claims.types.${claim.claim_type}`, {+ defaultValue: claim.claim_type,+ })}+ </Badge>+ </div>++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon-xs">+ <EllipsisVerticalIcon className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {claim.status === 'open' && (+ <DropdownMenuItem onClick={() => approve.mutate(claim.id)}>+ <CheckCircleIcon className="size-4" />+ {t('admin.pages.orders.detail.returns.actions.approve')}+ </DropdownMenuItem>+ )}+ {claim.status === 'approved' && (+ <>+ <DropdownMenuItem+ onClick={() => resolve.mutate({ claimId: claim.id, resolution: 'refund' })}+ >+ <BanknoteIcon className="size-4" />+ {t('admin.pages.orders.detail.claims.actions.resolve_refund')}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() =>+ resolve.mutate({ claimId: claim.id, resolution: 'replacement' })+ }+ >+ <TruckIcon className="size-4" />+ {t('admin.pages.orders.detail.claims.actions.resolve_replacement')}+ </DropdownMenuItem>+ </>+ )}+ {claim.status === 'open' && (+ <DropdownMenuItem onClick={() => deny.mutate({ claimId: claim.id })}>+ <XCircleIcon className="size-4" />+ {t('admin.pages.orders.detail.claims.actions.deny')}+ </DropdownMenuItem>+ )}+ {['open', 'approved'].includes(claim.status) && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className="text-destructive focus:text-destructive"+ onClick={async () => {+ if (+ await confirm({+ message: t('admin.pages.orders.detail.returns.confirm.cancel'),+ variant: 'destructive',+ confirmLabel: t('admin.actions.cancel'),+ })+ ) {+ cancel.mutate({ claimId: claim.id })+ }+ }}+ >+ <XCircleIcon className="size-4" />+ {t('admin.actions.cancel')}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ <div className="flex flex-col gap-1.5">+ {(claim.claim_line_items ?? []).map((line) => (+ <div key={line.id} className="flex items-center justify-between text-sm">+ <span className="truncate">+ {line.variant?.product_name ?? line.variant_id}+ {line.description && (+ <span className="text-muted-foreground"> — {line.description}</span>+ )}+ </span>+ <span className="text-muted-foreground">×{line.quantity}</span>+ </div>+ ))}+ </div>++ <div className="flex items-center justify-between text-sm border-t pt-3">+ <span className="text-muted-foreground">+ {t('admin.pages.orders.detail.returns.refund_total')}+ </span>+ <span className="font-medium">{claim.display_refund_total}</span>+ </div>+ </div>+ ))}+ </CardContent>+ </Card>+ )+}diff --git a/packages/dashboard/src/hooks/use-post-sale.ts b/packages/dashboard/src/hooks/use-post-sale.tsnew file mode 100644index 0000000000..08fac58d95--- /dev/null+++ b/packages/dashboard/src/hooks/use-post-sale.ts@@ -0,0 +1,136 @@+import { adminClient, useResourceKey, useResourceKeyBuilder } from '@spree/dashboard-core'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'++/**+ * Exchanges and claims on an order. Fetched separately from the order for the+ * same reason returns are — most orders have neither.+ */+export function useOrderExchanges(orderId: string) {+ return useQuery({+ queryKey: useResourceKey('order-exchanges', orderId),+ queryFn: () =>+ adminClient.orders.exchanges.list(orderId, {+ expand: [+ 'exchange_line_items',+ 'exchange_line_items.original_variant',+ 'exchange_line_items.new_variant',+ ],+ }),+ enabled: !!orderId,+ })+}++export function useOrderClaims(orderId: string) {+ return useQuery({+ queryKey: useResourceKey('order-claims', orderId),+ queryFn: () =>+ adminClient.orders.claims.list(orderId, {+ expand: ['claim_line_items', 'claim_line_items.variant'],+ }),+ enabled: !!orderId,+ })+}++/**+ * Post-sale mutations refresh their own list and the order, since fulfilling+ * an exchange or resolving a claim moves the order's totals and fulfillments.+ */+function usePostSaleMutation<TParams>(+ orderId: string,+ resourceKey: string,+ mutationFn: (params: TParams) => Promise<unknown>,+) {+ const queryClient = useQueryClient()+ const buildKey = useResourceKeyBuilder()++ return useMutation({+ mutationFn,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: buildKey(resourceKey, orderId) })+ queryClient.invalidateQueries({ queryKey: buildKey('orders', orderId) })+ },+ })+}++export function useExchangeActions(orderId: string) {+ const approve = usePostSaleMutation(orderId, 'order-exchanges', (exchangeId: string) =>+ adminClient.orders.exchanges.approve(orderId, exchangeId),+ )++ const receive = usePostSaleMutation(+ orderId,+ 'order-exchanges',+ ({+ exchangeId,+ items,+ }: {+ exchangeId: string+ items?: Array<{ exchange_line_item_id: string; quantity: number; resellable?: boolean }>+ }) => adminClient.orders.exchanges.receive(orderId, exchangeId, items ? { items } : undefined),+ )++ const fulfill = usePostSaleMutation(+ orderId,+ 'order-exchanges',+ ({+ exchangeId,+ refundMethod,+ }: {+ exchangeId: string+ refundMethod?: 'original_payment' | 'store_credit'+ }) =>+ adminClient.orders.exchanges.fulfill(orderId, exchangeId, { refund_method: refundMethod }),+ )++ const cancel = usePostSaleMutation(+ orderId,+ 'order-exchanges',+ ({ exchangeId, reason }: { exchangeId: string; reason?: string }) =>+ adminClient.orders.exchanges.cancel(orderId, exchangeId, { reason }),+ )++ return { approve, receive, fulfill, cancel }+}++export function useClaimActions(orderId: string) {+ const approve = usePostSaleMutation(orderId, 'order-claims', (claimId: string) =>+ adminClient.orders.claims.approve(orderId, claimId),+ )++ const resolve = usePostSaleMutation(+ orderId,+ 'order-claims',+ ({+ claimId,+ resolution,+ refundMethod,+ amount,+ }: {+ claimId: string+ resolution: 'refund' | 'replacement' | 'refund_and_replacement'+ refundMethod?: 'original_payment' | 'store_credit'+ amount?: string+ }) =>+ adminClient.orders.claims.resolve(orderId, claimId, {+ resolution,+ refund_method: refundMethod,+ amount,+ }),+ )++ const deny = usePostSaleMutation(+ orderId,+ 'order-claims',+ ({ claimId, reason }: { claimId: string; reason?: string }) =>+ adminClient.orders.claims.deny(orderId, claimId, { reason }),+ )++ const cancel = usePostSaleMutation(+ orderId,+ 'order-claims',+ ({ claimId, reason }: { claimId: string; reason?: string }) =>+ adminClient.orders.claims.cancel(orderId, claimId, { reason }),+ )++ return { approve, resolve, deny, cancel }+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 1d86ebb89a..e99f416b81 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1700,6 +1700,19 @@"ship": "وضع علامة على أنه تم الشحن","void": "Void"},+ "claims": {+ "actions": {+ "resolve_refund": "الحل بالاسترداد",+ "resolve_replacement": "الحل بالاستبدال",+ "deny": "رفض"+ },+ "types": {+ "damaged": "تالف",+ "missing": "مفقود",+ "wrong_item": "منتج خاطئ",+ "other": "أخرى"+ }+ },"dialogs": {"approve_title": "الموافقة على الطلب؟","cancel_title": "هل تريد إلغاء الطلب؟",@@ -1708,6 +1721,12 @@"empty_history": "لا يوجد تاريخ بعد.","empty_payments": "لا توجد مدفوعات حتى الآن.","empty_shipments": "لا توجد شحنات حتى الآن.",+ "exchanges": {+ "actions": {+ "fulfill": "شحن البديل"+ },+ "price_difference": "فرق السعر"+ },"no_delivery_method": "لم يتم اختيار طريقة توصيل.","returns": {"actions": {@@ -1733,8 +1752,10 @@}},"section_billing_address": "عنوان إرسال الفواتير",+ "section_claims": "المطالبات","section_customer": "العميل","section_customer_note": "ملاحظة العميل",+ "section_exchanges": "الاستبدالات","section_fulfillments": "عمليات التنفيذ","section_history": "تاريخ","section_internal_note": "ملاحظة داخلية",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex be9d5f98a3..a0ae98e176 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1700,6 +1700,19 @@"ship": "Als versendet markieren","void": "Stornieren"},+ "claims": {+ "actions": {+ "resolve_refund": "Mit Erstattung lösen",+ "resolve_replacement": "Mit Ersatz lösen",+ "deny": "Ablehnen"+ },+ "types": {+ "damaged": "Beschädigt",+ "missing": "Fehlt",+ "wrong_item": "Falscher Artikel",+ "other": "Sonstiges"+ }+ },"dialogs": {"approve_title": "Bestellung genehmigen?","cancel_title": "Bestellung stornieren?",@@ -1708,6 +1721,12 @@"empty_history": "Noch kein Verlauf.","empty_payments": "Noch keine Zahlungen.","empty_shipments": "Noch keine Sendungen.",+ "exchanges": {+ "actions": {+ "fulfill": "Ersatz versenden"+ },+ "price_difference": "Preisdifferenz"+ },"no_delivery_method": "Keine Versandmethode ausgewählt.","returns": {"actions": {@@ -1733,8 +1752,10 @@}},"section_billing_address": "Rechnungsadresse",+ "section_claims": "Reklamationen","section_customer": "Kunde","section_customer_note": "Kundennotiz",+ "section_exchanges": "Umtausch","section_fulfillments": "Fulfillments","section_history": "Verlauf","section_internal_note": "Interne Notiz",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 48c9bfc6cf..180b252b9f 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1700,6 +1700,19 @@"ship": "Mark as shipped","void": "Void"},+ "claims": {+ "actions": {+ "resolve_refund": "Resolve with refund",+ "resolve_replacement": "Resolve with replacement",+ "deny": "Deny"+ },+ "types": {+ "damaged": "Damaged",+ "missing": "Missing",+ "wrong_item": "Wrong item",+ "other": "Other"+ }+ },"dialogs": {"approve_title": "Approve order?","cancel_title": "Cancel order?",@@ -1708,6 +1721,12 @@"empty_history": "No history yet.","empty_payments": "No payments yet.","empty_shipments": "No shipments yet.",+ "exchanges": {+ "actions": {+ "fulfill": "Ship replacement"+ },+ "price_difference": "Price difference"+ },"no_delivery_method": "No delivery method selected.","returns": {"actions": {@@ -1733,8 +1752,10 @@}},"section_billing_address": "Billing address",+ "section_claims": "Claims","section_customer": "Customer","section_customer_note": "Customer note",+ "section_exchanges": "Exchanges","section_fulfillments": "Fulfillments","section_history": "History","section_internal_note": "Internal note",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex c62f553b91..3d1028c216 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1700,6 +1700,19 @@"ship": "Marquer comme expédiée","void": "Annuler"},+ "claims": {+ "actions": {+ "resolve_refund": "Résoudre par remboursement",+ "resolve_replacement": "Résoudre par remplacement",+ "deny": "Refuser"+ },+ "types": {+ "damaged": "Endommagé",+ "missing": "Manquant",+ "wrong_item": "Mauvais article",+ "other": "Autre"+ }+ },"dialogs": {"approve_title": "Approuver la commande ?","cancel_title": "Annuler la commande ?",@@ -1708,6 +1721,12 @@"empty_history": "Aucun historique pour le moment.","empty_payments": "Aucun paiement pour le moment.","empty_shipments": "Aucune expédition pour le moment.",+ "exchanges": {+ "actions": {+ "fulfill": "Expédier le remplacement"+ },+ "price_difference": "Différence de prix"+ },"no_delivery_method": "Aucune méthode de livraison sélectionnée.","returns": {"actions": {@@ -1733,8 +1752,10 @@}},"section_billing_address": "Adresse de facturation",+ "section_claims": "Réclamations","section_customer": "Client","section_customer_note": "Note du client",+ "section_exchanges": "Échanges","section_fulfillments": "Traitements","section_history": "Historique","section_internal_note": "Note interne",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex db468466ec..16c13700f7 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1708,6 +1708,19 @@"ship": "Oznacz jako wysłane","void": "Unieważnij"},+ "claims": {+ "actions": {+ "resolve_refund": "Rozwiąż zwrotem płatności",+ "resolve_replacement": "Rozwiąż zamiennikiem",+ "deny": "Odrzuć"+ },+ "types": {+ "damaged": "Uszkodzony",+ "missing": "Brakujący",+ "wrong_item": "Niewłaściwy produkt",+ "other": "Inne"+ }+ },"dialogs": {"approve_title": "Zatwierdzić zamówienie?","cancel_title": "Anulować zamówienie?",@@ -1716,6 +1729,12 @@"empty_history": "Brak historii.","empty_payments": "Brak płatności.","empty_shipments": "Brak przesyłek.",+ "exchanges": {+ "actions": {+ "fulfill": "Wyślij zamiennik"+ },+ "price_difference": "Różnica w cenie"+ },"no_delivery_method": "Nie wybrano metody dostawy.","returns": {"actions": {@@ -1741,8 +1760,10 @@}},"section_billing_address": "Adres rozliczeniowy",+ "section_claims": "Reklamacje","section_customer": "Klient","section_customer_note": "Notatka klienta",+ "section_exchanges": "Wymiany","section_fulfillments": "Realizacje","section_history": "Historia","section_internal_note": "Notatka wewnętrzna",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 4dcb01ce38..571b62b4b4 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1700,6 +1700,19 @@"ship": "标记为已发货","void": "作废"},+ "claims": {+ "actions": {+ "resolve_refund": "以退款解决",+ "resolve_replacement": "以换货解决",+ "deny": "拒绝"+ },+ "types": {+ "damaged": "已损坏",+ "missing": "缺失",+ "wrong_item": "商品错误",+ "other": "其他"+ }+ },"dialogs": {"approve_title": "批准订单?","cancel_title": "取消订单?",@@ -1708,6 +1721,12 @@"empty_history": "暂无历史记录。","empty_payments": "暂无付款。","empty_shipments": "暂无发货。",+ "exchanges": {+ "actions": {+ "fulfill": "寄出替换商品"+ },+ "price_difference": "差价"+ },"no_delivery_method": "未选择配送方式。","returns": {"actions": {@@ -1733,8 +1752,10 @@}},"section_billing_address": "账单地址",+ "section_claims": "索赔","section_customer": "客户","section_customer_note": "客户备注",+ "section_exchanges": "换货","section_fulfillments": "履约单","section_history": "历史记录","section_internal_note": "内部备注",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex 5096a0ba0b..4c43ef6ae9 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -88,6 +88,10 @@ import {CustomFieldsInlineCard,EditableApiCustomFieldsProvider,} from '../../../../components/spree/custom-fields/custom-fields-inline'+import {+ OrderClaimsCard,+ OrderExchangesCard,+} from '../../../../components/spree/order-post-sale-cards'import { OrderReturnsCard } from '../../../../components/spree/order-returns-card'import {orderQueryKey,@@ -149,6 +153,8 @@ function OrderDetailPage() {<LineItemsCard order={order} /><FulfillmentsCard order={order} /><OrderReturnsCard orderId={orderId} />+ <OrderExchangesCard orderId={orderId} />+ <OrderClaimsCard orderId={orderId} /><PaymentsCard order={order} /><AdjustmentLinesCard order={order} /><OrderSummaryCard order={order} />