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.

Extract large dashboard route files into components (#14487)

Damian Legawiec137e6dd84608
diff --git a/packages/dashboard/e2e/api-keys.spec.ts b/packages/dashboard/e2e/api-keys.spec.ts
new file mode 100644
index 0000000000..05ed9dfbc7
--- /dev/null
+++ b/packages/dashboard/e2e/api-keys.spec.ts
@@ -0,0 +1,73 @@
+import { expect, type Page, test } from '@playwright/test'
+import { gotoIndex, login } from './helpers'
+
+const API_KEYS_PATH = (storeId: string) => `/${storeId}/settings/api-keys`
+const CTA = /new key/i
+
+/**
+ * Creates a read-only secret key and dismisses the one-shot token dialog.
+ * Read-only because the suite never uses these keys to call the API — they
+ * only need to exist as rows.
+ */
+async function createSecretKey(page: Page, name: string) {
+ await page.getByRole('button', { name: CTA }).click()
+ const sheet = page.getByRole('dialog')
+ await expect(sheet.getByText(/create api key/i)).toBeVisible()
+
+ await sheet.locator('#api-key-name').fill(name)
+ await expect(sheet.getByText(/full access/i)).toBeVisible()
+ await sheet.getByText(/read all \(read_all\)/i).click()
+
+ await sheet.getByRole('button', { name: /create key/i }).click()
+
+ // The plaintext token is shown exactly once, behind its own dialog.
+ await expect(page.getByText(/copy.*secret|save.*secret/i).first()).toBeVisible({
+ timeout: 15_000,
+ })
+ await page.getByRole('button', { name: /^done$/i }).click()
+}
+
+test.describe('api keys', () => {
+ test('lists the publishable and secret sections', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, API_KEYS_PATH(creds.store_id), CTA)
+
+ await expect(page.getByText('Publishable keys', { exact: true })).toBeVisible()
+ await expect(page.getByText('Secret keys', { exact: true })).toBeVisible()
+ })
+
+ // A secret key is the default choice, so the scope picker has to be there.
+ test('creates a secret key and reveals its token once', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, API_KEYS_PATH(creds.store_id), CTA)
+
+ const name = `CI key ${Date.now()}`
+ await createSecretKey(page, name)
+
+ await expect(page.getByText(name)).toBeVisible()
+ })
+
+ // Renames a key this test created rather than a seeded one, so the fixtures
+ // other specs read stay as they were seeded.
+ test('renames a key through the edit sheet', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, API_KEYS_PATH(creds.store_id), CTA)
+
+ const original = `Rename me ${Date.now()}`
+ await createSecretKey(page, original)
+
+ const row = page.locator('tbody tr').filter({ hasText: original })
+ await expect(row).toBeVisible({ timeout: 15_000 })
+ await row.getByRole('button').last().click()
+ await page.getByRole('menuitem', { name: /^edit$/i }).click()
+
+ const sheet = page.getByRole('dialog')
+ await expect(sheet.getByText(/edit api key/i)).toBeVisible()
+
+ const renamed = `${original} renamed`
+ await sheet.locator('#edit-api-key-name').fill(renamed)
+ await sheet.getByRole('button', { name: /^save$/i }).click()
+
+ await expect(page.getByText(renamed)).toBeVisible({ timeout: 15_000 })
+ })
+})
diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-create-sheet.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-create-sheet.tsx
new file mode 100644
index 0000000000..720ffd5c85
--- /dev/null
+++ b/packages/dashboard/src/components/spree/api-keys/api-key-create-sheet.tsx
@@ -0,0 +1,199 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { type ApiKey, type ApiKeyCreateParams, SpreeError } from '@spree/admin-sdk'
+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'
+import {
+ Button,
+ Field,
+ FieldLabel,
+ RadioGroup,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ toastManager,
+} from '@spree/dashboard-ui'
+import type { TFunction } from 'i18next'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { z } from 'zod/v4'
+import { useCreateApiKey } from '../../../hooks/use-api-keys'
+import {
+ ApiKeyNameField,
+ ChannelBindingSelect,
+ FormErrorBanner,
+ KeyTypeChoice,
+} from './api-key-form-fields'
+import { ScopePicker } from './api-key-scope-picker'
+
+// `channel_id` holds the raw channel selection: `''` means "All channels"
+// (store-wide) and is dropped on submit; a prefixed `ch_…` binds a publishable
+// key to that channel. Only publishable keys can bind — the value is ignored
+// (and never sent) for secret keys.
+const buildCreateSchema = (t: TFunction) =>
+ z
+ .object({
+ name: z.string().min(1, t('admin.fields.api_key.name.required')),
+ key_type: z.enum(['publishable', 'secret']),
+ scopes: z.array(z.string()),
+ channel_id: z.string(),
+ })
+ .refine((v) => v.key_type !== 'secret' || v.scopes.length > 0, {
+ message: t('admin.api_keys.validation.scope_required'),
+ path: ['scopes'],
+ })
+
+type CreateFormValues = z.infer<ReturnType<typeof buildCreateSchema>>
+
+// Create UX is a side Sheet (not a Dialog) because the scope grid makes the
+// form taller than most viewports — Sheet handles overflow with internal
+// scroll and avoids the centered-modal "content cut off" problem.
+export function CreateApiKeyDialog({
+ open,
+ onOpenChange,
+ onCreated,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onCreated: (key: ApiKey) => void
+}) {
+ const { t } = useTranslation()
+ const createMutation = useCreateApiKey()
+
+ const form = useForm<CreateFormValues>({
+ resolver: zodResolver(buildCreateSchema(t)),
+ defaultValues: { name: '', key_type: 'secret', scopes: [], channel_id: '' },
+ })
+
+ const keyType = form.watch('key_type')
+
+ async function onSubmit(values: CreateFormValues) {
+ const isPublishable = values.key_type === 'publishable'
+ const params: ApiKeyCreateParams = {
+ name: values.name,
+ key_type: values.key_type,
+ scopes: isPublishable ? undefined : values.scopes,
+ // Channel binding is publishable-only; omit for secret keys and for the
+ // "All channels" default (empty string) so the key stays store-wide.
+ channel_id: isPublishable && values.channel_id ? values.channel_id : undefined,
+ }
+ try {
+ const key = await createMutation.mutateAsync(params)
+ toastManager.add({ type: 'success', title: t('admin.messages.key_created') })
+ form.reset({ name: '', key_type: 'secret', scopes: [], channel_id: '' })
+ onCreated(key)
+ } catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
+ toastManager.add({
+ type: 'error',
+ title: err instanceof Error ? err.message : t('admin.api_keys.errors.failed_to_create'),
+ })
+ }
+ }
+
+ return (
+ <Sheet
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) form.reset({ name: '', key_type: 'secret', scopes: [], channel_id: '' })
+ onOpenChange(next)
+ }}
+ >
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.api_keys.create_sheet_title')}</SheetTitle>
+ <SheetDescription>{t('admin.api_keys.create_sheet_description')}</SheetDescription>
+ </SheetHeader>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
+ {/* `flex-1 overflow-y-auto` keeps the footer pinned while the body
+ scrolls when the scope grid overflows. */}
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <FormErrorBanner message={form.formState.errors.root?.message} />
+ <ApiKeyNameField
+ id="api-key-name"
+ register={form.register}
+ error={form.formState.errors.name}
+ />
+
+ <Field>
+ <FieldLabel>{t('admin.fields.api_key.key_type.label')}</FieldLabel>
+ <Controller
+ name="key_type"
+ control={form.control}
+ render={({ field }) => (
+ <RadioGroup value={field.value} onValueChange={(value) => field.onChange(value)}>
+ <KeyTypeChoice
+ value="secret"
+ title={t('admin.api_keys.key_type.secret_title')}
+ description={t('admin.api_keys.key_type.secret_description')}
+ />
+ <KeyTypeChoice
+ value="publishable"
+ title={t('admin.api_keys.key_type.publishable_title')}
+ description={t('admin.api_keys.key_type.publishable_description')}
+ />
+ </RadioGroup>
+ )}
+ />
+ </Field>
+
+ {keyType === 'publishable' && (
+ <Field>
+ <FieldLabel htmlFor="api-key-channel">
+ {t('admin.fields.api_key.channel.label')}
+ </FieldLabel>
+ <Controller
+ name="channel_id"
+ control={form.control}
+ render={({ field }) => (
+ <ChannelBindingSelect
+ id="api-key-channel"
+ value={field.value}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t('admin.fields.api_key.channel.help')}
+ </p>
+ </Field>
+ )}
+
+ {keyType === 'secret' && (
+ <Field>
+ <FieldLabel>{t('admin.fields.api_key.scopes.label')}</FieldLabel>
+ <Controller
+ name="scopes"
+ control={form.control}
+ render={({ field }) => (
+ <ScopePicker value={field.value} onChange={field.onChange} />
+ )}
+ />
+ {form.formState.errors.scopes && (
+ <p className="text-sm text-destructive">{form.formState.errors.scopes.message}</p>
+ )}
+ </Field>
+ )}
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting
+ ? t('admin.actions.creating')
+ : t('admin.api_keys.create_key_cta')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-edit-sheet.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-edit-sheet.tsx
new file mode 100644
index 0000000000..83571b21ca
--- /dev/null
+++ b/packages/dashboard/src/components/spree/api-keys/api-key-edit-sheet.tsx
@@ -0,0 +1,115 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { type ApiKey, SpreeError } from '@spree/admin-sdk'
+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'
+import {
+ Button,
+ Field,
+ FieldLabel,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ toastManager,
+} from '@spree/dashboard-ui'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { z } from 'zod/v4'
+import { useUpdateApiKey } from '../../../hooks/use-api-keys'
+import { useOnSheetOpen } from '../../../hooks/use-on-sheet-open'
+import { ApiKeyNameField, FormErrorBanner } from './api-key-form-fields'
+import { ScopePicker } from './api-key-scope-picker'
+
+type EditFormValues = { name: string }
+
+// Lifted dialog (one instance per page, driven by `apiKey`) — mirrors
+// TokenRevealDialog. Only `name` is editable; secret keys show their scopes
+// disabled since scopes are fixed for the life of a key.
+export function EditApiKeyDialog({
+ apiKey,
+ onOpenChange,
+}: {
+ apiKey: ApiKey | null
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const updateMutation = useUpdateApiKey()
+
+ const form = useForm<EditFormValues>({
+ resolver: zodResolver(
+ z.object({ name: z.string().min(1, t('admin.fields.api_key.name.required')) }),
+ ),
+ defaultValues: { name: '' },
+ })
+
+ // Re-sync the form every time the sheet opens. `defaultValues` alone won't
+ // update across opens (the sheet is mounted once and reused), and keying on
+ // the key object would skip a re-open of the same cached row, leaving the
+ // previous unsaved name in the field.
+ useOnSheetOpen(!!apiKey, () => {
+ if (apiKey) form.reset({ name: apiKey.name })
+ })
+
+ async function onSubmit(values: EditFormValues) {
+ if (!apiKey) return
+ try {
+ await updateMutation.mutateAsync({ id: apiKey.id, params: { name: values.name } })
+ toastManager.add({ type: 'success', title: t('admin.messages.key_updated') })
+ onOpenChange(false)
+ } catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
+ toastManager.add({
+ type: 'error',
+ title: err instanceof Error ? err.message : t('admin.api_keys.errors.failed_to_update'),
+ })
+ }
+ }
+
+ return (
+ <Sheet open={!!apiKey} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.api_keys.edit_sheet_title')}</SheetTitle>
+ <SheetDescription>{t('admin.api_keys.edit_sheet_description')}</SheetDescription>
+ </SheetHeader>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <FormErrorBanner message={form.formState.errors.root?.message} />
+ <ApiKeyNameField
+ id="edit-api-key-name"
+ register={form.register}
+ error={form.formState.errors.name}
+ />
+
+ {apiKey?.key_type === 'secret' && apiKey.scopes.length > 0 && (
+ <Field>
+ <FieldLabel>{t('admin.fields.api_key.scopes.label')}</FieldLabel>
+ {/* Scopes are fixed for the life of a key — rendered disabled.
+ To change authority, create a new key and revoke this one. */}
+ <ScopePicker value={apiKey.scopes} disabled />
+ <p className="text-xs text-muted-foreground">
+ {t('admin.api_keys.scopes_immutable_help')}
+ </p>
+ </Field>
+ )}
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-form-fields.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-form-fields.tsx
new file mode 100644
index 0000000000..f72b6b8282
--- /dev/null
+++ b/packages/dashboard/src/components/spree/api-keys/api-key-form-fields.tsx
@@ -0,0 +1,130 @@
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldTitle,
+ Input,
+ RadioGroupItem,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@spree/dashboard-ui'
+import type { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useChannels } from '../../../hooks/use-channels'
+
+// The name field is identical across the create and edit sheets; both register
+// a `name` string field with the same label/placeholder/validation.
+export function ApiKeyNameField({
+ id,
+ register,
+ error,
+}: {
+ id: string
+ register: ReturnType<typeof useForm<{ name: string }>>['register']
+ error?: { message?: string }
+}) {
+ const { t } = useTranslation()
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{t('admin.fields.api_key.name.label')}</FieldLabel>
+ <Input
+ id={id}
+ autoFocus
+ placeholder={t('admin.fields.api_key.name.placeholder')}
+ aria-invalid={!!error || undefined}
+ {...register('name')}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )
+}
+
+export function FormErrorBanner({ message }: { message?: string }) {
+ if (!message) return null
+ return (
+ <p className="text-sm text-destructive" role="alert">
+ {message}
+ </p>
+ )
+}
+
+export function KeyTypeChoice({
+ value,
+ title,
+ description,
+}: {
+ value: 'publishable' | 'secret'
+ title: string
+ description: string
+}) {
+ return (
+ <FieldLabel>
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>{title}</FieldTitle>
+ <FieldDescription>{description}</FieldDescription>
+ </FieldContent>
+ <RadioGroupItem value={value} />
+ </Field>
+ </FieldLabel>
+ )
+}
+
+// Sentinel for the "All channels" (store-wide) option. Base UI's `<Select>`
+// treats an empty string value as "no selection" and shows the placeholder, so
+// the store-wide choice carries this non-empty value and is mapped back to `''`
+// (the schema's store-wide value) at the boundary.
+const ALL_CHANNELS = '__all__'
+
+// Channel binding picker for publishable keys. Unlike the shared
+// `<ChannelSelect>`, the first option is "All channels" (store-wide) so a key
+// can be left unbound, which is the default. Emits `''` for store-wide and a
+// prefixed `ch_…` for a bound channel.
+export function ChannelBindingSelect({
+ id,
+ value,
+ onChange,
+}: {
+ id: string
+ value: string
+ onChange: (channelId: string) => void
+}) {
+ const { t } = useTranslation()
+ const { data } = useChannels()
+ const channels = data?.data ?? []
+
+ const allChannelsLabel = t('admin.fields.api_key.channel.all_channels')
+
+ return (
+ <Select
+ value={value === '' ? ALL_CHANNELS : value}
+ onValueChange={(v) => onChange(v === ALL_CHANNELS ? '' : v)}
+ >
+ <SelectTrigger id={id}>
+ {/* Base UI's `<SelectValue>` renders the raw value (the prefixed ID);
+ the children render-prop resolves the channel name from the cached
+ list so the trigger matches the selected item. */}
+ <SelectValue>
+ {(v) =>
+ v === ALL_CHANNELS
+ ? allChannelsLabel
+ : (channels.find((c) => c.id === v)?.name ?? allChannelsLabel)
+ }
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={ALL_CHANNELS}>{allChannelsLabel}</SelectItem>
+ {channels.map((c) => (
+ <SelectItem key={c.id} value={c.id}>
+ {c.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-scope-picker.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-scope-picker.tsx
new file mode 100644
index 0000000000..3f7d6342ad
--- /dev/null
+++ b/packages/dashboard/src/components/spree/api-keys/api-key-scope-picker.tsx
@@ -0,0 +1,104 @@
+import { usePermissions } from '@spree/dashboard-core'
+import { Checkbox, cn, Skeleton } from '@spree/dashboard-ui'
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import { usePermissionCatalog } from '../../../hooks/use-roles'
+import { PermissionGrid } from '../permission-picker'
+
+// `disabled` renders the whole picker read-only — used when editing an existing
+// key, whose scopes are fixed for its lifetime (the server rejects scope edits).
+export function ScopePicker({
+ value,
+ onChange,
+ disabled = false,
+}: {
+ value: string[]
+ onChange?: (next: string[]) => void
+ disabled?: boolean
+}) {
+ const { t } = useTranslation()
+ const { data: catalog } = usePermissionCatalog()
+ const { permissionKeys } = usePermissions()
+ const hasWriteAll = value.includes('write_all')
+ const hasReadAll = value.includes('read_all')
+
+ // A staffer can only mint scopes within their own grant (the server's
+ // anti-amplification guard) — don't offer keys it would reject. A caller
+ // holding the whole catalog (admin) is unrestricted, including the aliases.
+ const blockedKeys = useMemo(() => {
+ if (!catalog) return undefined
+ const blocked = new Set(
+ catalog.data.filter((entry) => !permissionKeys.includes(entry.key)).map((entry) => entry.key),
+ )
+ return blocked.size > 0 ? blocked : undefined
+ }, [catalog, permissionKeys])
+ const writeAllBlocked = blockedKeys !== undefined
+ const readAllBlocked =
+ !!catalog &&
+ catalog.data.some((entry) => entry.kind === 'read' && !permissionKeys.includes(entry.key))
+
+ function setAllRead(checked: boolean) {
+ let next = value.filter((v) => v !== 'read_all' && !v.startsWith('read_'))
+ if (checked) next = [...next, 'read_all']
+ onChange?.(next)
+ }
+
+ function setAllWrite(checked: boolean) {
+ let next = value.filter((v) => v !== 'write_all' && !v.startsWith('write_'))
+ if (checked) next = [...next, 'write_all']
+ onChange?.(next)
+ }
+
+ return (
+ <div className={cn('flex flex-col gap-3', disabled && 'opacity-70')}>
+ {/* Quick access: write_all / read_all toggles. Selecting one blocks the
+ per-resource grid because the catch-all already covers it. */}
+ <div className="flex flex-col gap-2 rounded-md border border-border bg-muted/30 p-3">
+ <label htmlFor="scope-write-all" className="flex cursor-pointer items-center gap-2 text-sm">
+ <Checkbox
+ id="scope-write-all"
+ checked={hasWriteAll}
+ onCheckedChange={setAllWrite}
+ disabled={disabled || writeAllBlocked}
+ />
+ <span className="font-medium">{t('admin.api_keys.scope_picker.full_access_label')}</span>
+ <span className="text-xs text-muted-foreground">
+ {t('admin.api_keys.scope_picker.full_access_hint')}
+ </span>
+ </label>
+ <label htmlFor="scope-read-all" className="flex cursor-pointer items-center gap-2 text-sm">
+ <Checkbox
+ id="scope-read-all"
+ checked={hasReadAll}
+ onCheckedChange={setAllRead}
+ disabled={disabled || hasWriteAll || readAllBlocked}
+ />
+ <span className="font-medium">{t('admin.api_keys.scope_picker.read_all_label')}</span>
+ <span className="text-xs text-muted-foreground">
+ {t('admin.api_keys.scope_picker.read_all_hint')}
+ </span>
+ </label>
+ </div>
+
+ <div
+ className={cn(!disabled && (hasWriteAll || hasReadAll) && 'pointer-events-none opacity-50')}
+ >
+ {catalog ? (
+ <PermissionGrid
+ entries={catalog.data}
+ value={value}
+ onChange={(next) => onChange?.(next)}
+ disabled={disabled}
+ disabledKeys={blockedKeys}
+ />
+ ) : (
+ <div className="flex flex-col gap-2 p-3">
+ <Skeleton className="h-6 w-full" />
+ <Skeleton className="h-6 w-full" />
+ <Skeleton className="h-6 w-full" />
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx
new file mode 100644
index 0000000000..4a15229332
--- /dev/null
+++ b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx
@@ -0,0 +1,364 @@
+import type { ApiKey } from '@spree/admin-sdk'
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ cn,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyMedia,
+ EmptyTitle,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ RelativeTime,
+ RowActions,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ toastManager,
+ useConfirm,
+ useCopyToClipboard,
+} from '@spree/dashboard-ui'
+import { BanIcon, CheckIcon, CopyIcon, KeyRoundIcon, PencilIcon } from 'lucide-react'
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useDeleteApiKey, useRevokeApiKey } from '../../../hooks/use-api-keys'
+
+/**
+ * The two kinds of key are listed side by side but answer different questions:
+ * a publishable key is defined by the channel it is bound to, a secret key by
+ * the scopes it carries. Each has its own table below rather than one table
+ * with flags, so neither has to describe the other.
+ */
+
+type ApiKeyTableProps = {
+ keys: ApiKey[]
+ loading: boolean
+ onEdit: (key: ApiKey) => void
+}
+
+export function PublishableApiKeyTable({
+ channelName,
+ ...props
+}: ApiKeyTableProps & {
+ channelName: (channelId: string | null) => string | undefined
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <ApiKeyTableFrame
+ {...props}
+ title={t('admin.pages.settings.api_keys.publishable_section')}
+ description={t('admin.pages.settings.api_keys.publishable_help')}
+ emptyMessage={t('admin.pages.settings.api_keys.empty_publishable')}
+ column={<TableHead>{t('admin.pages.settings.api_keys.table.channel')}</TableHead>}
+ cell={(key) => <ChannelCell channelName={channelName(key.channel_id)} />}
+ />
+ )
+}
+
+export function SecretApiKeyTable(props: ApiKeyTableProps) {
+ const { t } = useTranslation()
+
+ return (
+ <ApiKeyTableFrame
+ {...props}
+ title={t('admin.pages.settings.api_keys.secret_section')}
+ description={t('admin.pages.settings.api_keys.secret_help')}
+ emptyMessage={t('admin.pages.settings.api_keys.empty_secret')}
+ column={<TableHead>{t('admin.pages.settings.api_keys.table.scopes')}</TableHead>}
+ cell={(key) => (
+ <TableCell>
+ <ScopeList scopes={key.scopes} />
+ </TableCell>
+ )}
+ />
+ )
+}
+
+/**
+ * The card, loading and empty states both tables share. `column` and `cell`
+ * carry the one column that differs; `cell` takes the row's key because it
+ * renders per row, which is what render props are for.
+ */
+function ApiKeyTableFrame({
+ title,
+ description,
+ keys,
+ loading,
+ emptyMessage,
+ onEdit,
+ column,
+ cell,
+}: ApiKeyTableProps & {
+ title: string
+ description: string
+ emptyMessage: string
+ column: ReactNode
+ cell: (key: ApiKey) => ReactNode
+}) {
+ const { t } = useTranslation()
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{title}</CardTitle>
+ <p className="text-sm text-muted-foreground">{description}</p>
+ </CardHeader>
+ <CardContent className="p-0">
+ {loading ? (
+ <div className="p-4">
+ <Skeleton className="h-10 w-full" />
+ </div>
+ ) : keys.length === 0 ? (
+ <Empty>
+ <EmptyHeader>
+ <EmptyMedia variant="icon">
+ <KeyRoundIcon />
+ </EmptyMedia>
+ <EmptyTitle>{emptyMessage}</EmptyTitle>
+ <EmptyDescription>{t('admin.api_keys.empty_description')}</EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <Table roundedBottom>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('admin.fields.name.label')}</TableHead>
+ <TableHead>{t('admin.pages.settings.api_keys.table.key')}</TableHead>
+ {column}
+ <TableHead>{t('admin.pages.settings.api_keys.table.last_used_at')}</TableHead>
+ <TableHead>{t('admin.fields.created_at.label')}</TableHead>
+ <TableHead className="w-12" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {keys.map((key) => (
+ <ApiKeyRow key={key.id} apiKey={key} onEdit={onEdit}>
+ {cell(key)}
+ </ApiKeyRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function ChannelCell({ channelName }: { channelName: string | undefined }) {
+ const { t } = useTranslation()
+ return (
+ <TableCell className="text-sm whitespace-nowrap">
+ {/* The name may not have loaded yet (channels query pending) — fall back
+ to the store-wide label rather than the raw ID. */}
+ {channelName ?? (
+ <span className="text-muted-foreground">
+ {t('admin.pages.settings.api_keys.table.all_channels')}
+ </span>
+ )}
+ </TableCell>
+ )
+}
+
+/** `children` is the table cell for whichever column its table declared. */
+function ApiKeyRow({
+ apiKey,
+ onEdit,
+ children,
+}: {
+ apiKey: ApiKey
+ onEdit: (key: ApiKey) => void
+ children: ReactNode
+}) {
+ const { t } = useTranslation()
+ const revokeMutation = useRevokeApiKey()
+ const deleteMutation = useDeleteApiKey()
+ const confirm = useConfirm()
+ const { copied, copy } = useCopyToClipboard()
+
+ const isRevoked = !!apiKey.revoked_at
+ // Publishable keys always carry their plaintext token (they're meant to be
+ // exposed); secret keys only return `token_prefix` after the one-shot
+ // create response.
+ const visibleToken = apiKey.plaintext_token ?? apiKey.token_prefix ?? ''
+
+ async function handleRevoke() {
+ const ok = await confirm({
+ title: t('admin.api_keys.revoke_confirm.title'),
+ message: t('admin.api_keys.revoke_confirm.message'),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.revoke'),
+ })
+ if (!ok) return
+
+ try {
+ await revokeMutation.mutateAsync(apiKey.id)
+ toastManager.add({ type: 'success', title: t('admin.messages.key_revoked') })
+ } catch (err) {
+ toastManager.add({
+ type: 'error',
+ title: err instanceof Error ? err.message : t('admin.errors.failed_to_revoke_key'),
+ })
+ }
+ }
+
+ async function handleDelete() {
+ const ok = await confirm({
+ title: t('admin.api_keys.delete_confirm.title'),
+ message: t('admin.api_keys.delete_confirm.message'),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return
+
+ try {
+ await deleteMutation.mutateAsync(apiKey.id)
+ toastManager.add({ type: 'success', title: t('admin.messages.key_deleted') })
+ } catch (err) {
+ toastManager.add({
+ type: 'error',
+ title: err instanceof Error ? err.message : t('admin.api_keys.errors.failed_to_delete'),
+ })
+ }
+ }
+
+ return (
+ <TableRow className={cn(isRevoked && 'opacity-60')}>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <span className="font-medium">{apiKey.name}</span>
+ {isRevoked && <Badge variant="destructive">{t('admin.api_keys.badge.revoked')}</Badge>}
+ </div>
+ </TableCell>
+ <TableCell>
+ <div className="flex items-center gap-1.5">
+ <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{visibleToken}…</code>
+ {apiKey.plaintext_token && (
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ onClick={() => copy(apiKey.plaintext_token ?? '')}
+ aria-label={t('admin.api_keys.dropdown.copy_token_aria')}
+ >
+ {copied ? <CheckIcon /> : <CopyIcon />}
+ </Button>
+ )}
+ </div>
+ </TableCell>
+ {children}
+ <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
+ {/* `last_used_at` is throttled to update at most hourly (see
+ ApiKeyAuthentication#touch_api_key_if_needed), so the timestamp
+ won't be perfectly fresh — but it's accurate enough for "is this
+ key still in use?" decisions. */}
+ <RelativeTime
+ iso={apiKey.last_used_at}
+ fallback={
+ <span className="text-muted-foreground/60">{t('admin.api_keys.badge.never_used')}</span>
+ }
+ />
+ </TableCell>
+ <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
+ <RelativeTime iso={apiKey.created_at} />
+ {apiKey.created_by_email && (
+ <div className="text-xs">
+ {t('admin.api_keys.by_email', { email: apiKey.created_by_email })}
+ </div>
+ )}
+ </TableCell>
+ <TableCell className="text-right">
+ <RowActions
+ actions={[
+ {
+ key: 'edit',
+ label: t('admin.actions.edit'),
+ icon: <PencilIcon className="size-4" />,
+ visible: !isRevoked,
+ onSelect: () => onEdit(apiKey),
+ },
+ {
+ key: 'revoke',
+ label: t('admin.api_keys.dropdown.revoke'),
+ icon: <BanIcon className="size-4" />,
+ visible: !isRevoked,
+ disabled: revokeMutation.isPending,
+ onSelect: handleRevoke,
+ },
+ {
+ key: 'delete',
+ destructive: true,
+ disabled: deleteMutation.isPending,
+ onSelect: handleDelete,
+ },
+ ]}
+ />
+ </TableCell>
+ </TableRow>
+ )
+}
+
+// Maximum number of scope chips rendered inline before collapsing the rest
+// into a `+N` popover. Chosen so a typical row stays under one line at the
+// usual table widths.
+const SCOPE_PREVIEW_COUNT = 3
+
+function ScopeList({ scopes }: { scopes: string[] }) {
+ const { t } = useTranslation()
+ if (scopes.includes('write_all')) {
+ return <Badge>{t('admin.pages.settings.api_keys.scope_badge.full_access')}</Badge>
+ }
+ if (scopes.includes('read_all')) {
+ return <Badge>{t('admin.pages.settings.api_keys.scope_badge.read_all')}</Badge>
+ }
+ if (scopes.length === 0) {
+ return <span className="text-sm text-muted-foreground">—</span>
+ }
+
+ const preview = scopes.slice(0, SCOPE_PREVIEW_COUNT)
+ const overflow = scopes.slice(SCOPE_PREVIEW_COUNT)
+
+ return (
+ <div className="flex max-w-xs flex-wrap items-center gap-1">
+ {preview.map((scope) => (
+ <Badge key={scope} className="font-mono text-[10px]">
+ {scope}
+ </Badge>
+ ))}
+ {overflow.length > 0 && (
+ <Popover>
+ {/* `asChild` so the Badge itself becomes the click target — no
+ extra button chrome around the chip. */}
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ className="cursor-pointer rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
+ aria-label={t('admin.api_keys.scope_picker.show_more_aria', {
+ count: overflow.length,
+ })}
+ >
+ <Badge className="font-mono text-[10px] hover:bg-accent">+{overflow.length}</Badge>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-auto max-w-sm p-2">
+ <div className="flex max-h-60 flex-col gap-1 overflow-y-auto">
+ {scopes.map((scope) => (
+ <Badge key={scope} className="self-start font-mono text-[10px]">
+ {scope}
+ </Badge>
+ ))}
+ </div>
+ </PopoverContent>
+ </Popover>
+ )}
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-token-reveal-dialog.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-token-reveal-dialog.tsx
new file mode 100644
index 0000000000..5b34523c7d
--- /dev/null
+++ b/packages/dashboard/src/components/spree/api-keys/api-key-token-reveal-dialog.tsx
@@ -0,0 +1,61 @@
+import type { ApiKey } from '@spree/admin-sdk'
+import {
+ Button,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ useCopyToClipboard,
+} from '@spree/dashboard-ui'
+import { AlertTriangleIcon, CheckIcon, CopyIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+/** One-shot reveal of a freshly created secret token. */
+export function TokenRevealDialog({
+ apiKey,
+ onOpenChange,
+}: {
+ apiKey: ApiKey | null
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { copied, copy } = useCopyToClipboard()
+
+ return (
+ <Dialog open={!!apiKey} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.pages.settings.api_keys.save_secret_title')}</DialogTitle>
+ <DialogDescription>
+ {t('admin.pages.settings.api_keys.save_secret_description')}
+ </DialogDescription>
+ </DialogHeader>
+ <DialogBody className="flex flex-col gap-3">
+ <div className="flex items-start gap-2 rounded-md border border-yellow-200 bg-yellow-50 p-3 text-sm text-yellow-900 dark:border-yellow-900/40 dark:bg-yellow-950/40 dark:text-yellow-200">
+ <AlertTriangleIcon className="size-4 shrink-0" />
+ <span>{t('admin.api_keys.warning_treat_like_password')}</span>
+ </div>
+ {apiKey?.plaintext_token && (
+ <div className="flex items-center gap-2 rounded-md border border-border bg-muted/40 p-3">
+ <code className="flex-1 truncate font-mono text-sm">{apiKey.plaintext_token}</code>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => copy(apiKey.plaintext_token ?? '')}
+ >
+ {copied ? <CheckIcon /> : <CopyIcon />}
+ {copied ? t('admin.actions.copied') : t('admin.actions.copy')}
+ </Button>
+ </div>
+ )}
+ </DialogBody>
+ <DialogFooter>
+ <Button onClick={() => onOpenChange(false)}>{t('admin.actions.done')}</Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-addresses-card.tsx b/packages/dashboard/src/components/spree/customers/customer-addresses-card.tsx
new file mode 100644
index 0000000000..05064942f4
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-addresses-card.tsx
@@ -0,0 +1,227 @@
+import type { Address, Customer } from '@spree/admin-sdk'
+import { AddressFormDialog, type AddressParams, useCountries } from '@spree/dashboard-core'
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { EllipsisVerticalIcon, PencilIcon, PlusIcon, TrashIcon } from 'lucide-react'
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ useCreateCustomerAddress,
+ useDeleteCustomerAddress,
+ useUpdateCustomerAddress,
+} from '../../../hooks/use-customers'
+
+export function CustomerAddressesCard({ customer }: { customer: Customer }) {
+ const { t } = useTranslation()
+ const [addOpen, setAddOpen] = useState(false)
+ const [editing, setEditing] = useState<Address | null>(null)
+ const confirm = useConfirm()
+ const addresses = useMemo(() => {
+ const isDefault = (a: Address) => a.is_default_billing || a.is_default_shipping
+ return [...(customer.addresses ?? [])].sort(
+ (a, b) => Number(isDefault(b)) - Number(isDefault(a)),
+ )
+ }, [customer.addresses])
+
+ const deleteMutation = useDeleteCustomerAddress(customer.id)
+
+ const updateMutation = useUpdateCustomerAddress(customer.id)
+ function setDefault(params: { id: string; kind: 'billing' | 'shipping' }) {
+ return updateMutation.mutate({
+ id: params.id,
+ params: {
+ [params.kind === 'billing' ? 'is_default_billing' : 'is_default_shipping']: true,
+ },
+ })
+ }
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ {t('admin.pages.customers.detail.section_addresses')}
+ {addresses.length > 0 && <Badge variant="outline">{addresses.length}</Badge>}
+ </CardTitle>
+ <CardAction>
+ <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>
+ <PlusIcon className="size-4" />
+ {t('admin.pages.customers.detail.add_address')}
+ </Button>
+ </CardAction>
+ </CardHeader>
+ {addresses.length === 0 ? (
+ <CardContent>
+ <p className="text-sm text-muted-foreground">
+ {t('admin.pages.customers.detail.addresses_empty')}
+ </p>
+ </CardContent>
+ ) : (
+ <CardContent className="flex flex-col gap-3">
+ {addresses.map((addr) => (
+ <div
+ key={addr.id}
+ className="flex items-start justify-between gap-2 rounded-md border p-3"
+ >
+ <div className="text-sm">
+ <div className="font-medium">
+ {addr.full_name ?? '—'}
+ <span className="ml-2 inline-flex gap-1">
+ {addr.is_default_billing && (
+ <Badge variant="outline">
+ {t('admin.customers.detail.address.default_billing')}
+ </Badge>
+ )}
+ {addr.is_default_shipping && (
+ <Badge variant="outline">
+ {t('admin.customers.detail.address.default_shipping')}
+ </Badge>
+ )}
+ </span>
+ </div>
+ <div className="text-muted-foreground">{addr.address1}</div>
+ {addr.address2 && <div className="text-muted-foreground">{addr.address2}</div>}
+ <div className="text-muted-foreground">
+ {[addr.city, addr.state_code, addr.postal_code].filter(Boolean).join(', ')} ·{' '}
+ {addr.country_code}
+ </div>
+ {addr.phone && <div className="text-muted-foreground">{addr.phone}</div>}
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ <span className="sr-only">{t('admin.actions.actions_menu')}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditing(addr)}>
+ <PencilIcon className="size-4" />
+ {t('admin.actions.edit')}
+ </DropdownMenuItem>
+ {!addr.is_default_billing && (
+ <DropdownMenuItem
+ onClick={() => setDefault({ id: addr.id, kind: 'billing' })}
+ >
+ {t('admin.customers.detail.address.set_default_billing')}
+ </DropdownMenuItem>
+ )}
+ {!addr.is_default_shipping && (
+ <DropdownMenuItem
+ onClick={() => setDefault({ id: addr.id, kind: 'shipping' })}
+ >
+ {t('admin.customers.detail.address.set_default_shipping')}
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ onClick={async () => {
+ if (
+ await confirm({
+ message: t('admin.customers.detail.address.delete_confirm_message'),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ ) {
+ deleteMutation.mutate(addr.id)
+ }
+ }}
+ >
+ <TrashIcon className="size-4" />
+ {t('admin.actions.delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ))}
+ </CardContent>
+ )}
+ </Card>
+
+ {addOpen && (
+ <CustomerAddressDialog
+ customer={customer}
+ address={newAddressTemplate(customer)}
+ onOpenChange={setAddOpen}
+ title={t('admin.pages.customers.detail.add_address')}
+ />
+ )}
+ {editing && (
+ <CustomerAddressDialog
+ customer={customer}
+ address={editing}
+ onOpenChange={(o) => {
+ if (!o) setEditing(null)
+ }}
+ title={t('admin.pages.customers.detail.edit_address')}
+ />
+ )}
+ </>
+ )
+}
+
+function newAddressTemplate(customer: Customer): Address {
+ return {
+ first_name: customer.first_name ?? '',
+ last_name: customer.last_name ?? '',
+ phone: customer.phone ?? '',
+ } as Address
+}
+
+function CustomerAddressDialog({
+ customer,
+ address,
+ onOpenChange,
+ title,
+}: {
+ customer: Customer
+ address: Address
+ onOpenChange: (open: boolean) => void
+ title: string
+}) {
+ const { isLoading: countriesLoading } = useCountries()
+ const isEdit = Boolean(address.id)
+ const createMutation = useCreateCustomerAddress(customer.id)
+ const updateMutation = useUpdateCustomerAddress(customer.id)
+ const mutation = isEdit ? updateMutation : createMutation
+
+ // Returns the promise so `AddressFormDialog` can map 422 errors onto fields.
+ // Closes the sheet only on success.
+ async function handleSave(params: AddressParams) {
+ if (isEdit) {
+ await updateMutation.mutateAsync({ id: address.id, params })
+ } else {
+ await createMutation.mutateAsync(params)
+ }
+ onOpenChange(false)
+ }
+
+ // Wait for countries before mounting so the country/state lazy initializer
+ // can resolve the address's country_code/state_code to a real option.
+ if (countriesLoading) return null
+
+ return (
+ <AddressFormDialog
+ address={address}
+ open
+ onOpenChange={onOpenChange}
+ onSave={handleSave}
+ title={title}
+ isPending={mutation.isPending}
+ showLabel
+ showDefaultFlags
+ />
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-groups-card.tsx b/packages/dashboard/src/components/spree/customers/customer-groups-card.tsx
new file mode 100644
index 0000000000..0157fb00be
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-groups-card.tsx
@@ -0,0 +1,162 @@
+import type { Customer } from '@spree/admin-sdk'
+import { ResourceMultiAutocomplete, useStore } from '@spree/dashboard-core'
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Field,
+ FieldLabel,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@spree/dashboard-ui'
+import { PencilIcon, UsersIcon } from 'lucide-react'
+import { useEffect, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+ customerGroupAutocompleteProps,
+ useCustomerGroups,
+} from '../../../hooks/use-customer-groups'
+import { useUpdateCustomerGroups } from '../../../hooks/use-customers'
+
+export function CustomerGroupsCard({ customer }: { customer: Customer }) {
+ const { t } = useTranslation()
+ const [editOpen, setEditOpen] = useState(false)
+ const groups = customer.customer_groups ?? []
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ {t('admin.customers.detail.groups.title')}
+ {groups.length > 0 && <Badge variant="outline">{groups.length}</Badge>}
+ </CardTitle>
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setEditOpen(true)}
+ aria-label={t('admin.actions.edit')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {groups.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {t('admin.customers.detail.groups.empty')}
+ </p>
+ ) : (
+ <div className="flex flex-wrap gap-1.5">
+ {groups.map((group) => (
+ <Badge key={group.id} variant="secondary" className="gap-1.5">
+ <UsersIcon className="size-3 text-muted-foreground" />
+ {group.name}
+ </Badge>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ <EditGroupsSheet customer={customer} open={editOpen} onOpenChange={setEditOpen} />
+ </>
+ )
+}
+
+function EditGroupsSheet({
+ customer,
+ open,
+ onOpenChange,
+}: {
+ customer: Customer
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { storeId } = useStore()
+ const currentIds = useMemo(() => customer.customer_group_ids ?? [], [customer.customer_group_ids])
+ const [groupIds, setGroupIds] = useState<string[]>(currentIds)
+ const [error, setError] = useState<string | null>(null)
+
+ // Surface the store's groups on focus (preloaded, 5-min cache) and re-seed
+ // the selection whenever the sheet re-opens so a prior cancelled edit or an
+ // external membership change is reflected.
+ //
+ // This tracks `currentIds` rather than only the open transition: the picker
+ // holds a selection, not typed text, and it has to pick up the membership a
+ // save just wrote before the sheet is opened again.
+ const { data: groupsData } = useCustomerGroups()
+ useEffect(() => {
+ if (open) {
+ setGroupIds(currentIds)
+ setError(null)
+ }
+ }, [open, currentIds])
+
+ // `customer_group_ids` is a collection setter on the customer: PATCH replaces
+ // the whole membership in one request, so no add/remove diffing needed.
+ const mutation = useUpdateCustomerGroups(customer.id)
+ const isPending = mutation.isPending
+
+ async function handleSave() {
+ setError(null)
+ try {
+ await mutation.mutateAsync(groupIds)
+ onOpenChange(false)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : t('admin.customers.detail.groups.save_failed'))
+ }
+ }
+
+ const dirty =
+ groupIds.length !== currentIds.length || groupIds.some((id) => !currentIds.includes(id))
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.customers.detail.groups.edit_title')}</SheetTitle>
+ <SheetDescription>{t('admin.customers.detail.groups.edit_description')}</SheetDescription>
+ </SheetHeader>
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {error && (
+ <p className="text-sm text-destructive" role="alert">
+ {error}
+ </p>
+ )}
+ <Field>
+ <FieldLabel>{t('admin.fields.customer.customer_groups.label')}</FieldLabel>
+ <ResourceMultiAutocomplete
+ {...customerGroupAutocompleteProps(`customer-detail-groups-picker-${storeId}`)}
+ initialItems={groupsData?.data}
+ value={groupIds}
+ onChange={setGroupIds}
+ />
+ </Field>
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={isPending}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="button" onClick={handleSave} disabled={isPending || !dirty}>
+ {isPending ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-internal-note-card.tsx b/packages/dashboard/src/components/spree/customers/customer-internal-note-card.tsx
new file mode 100644
index 0000000000..0f25939da1
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-internal-note-card.tsx
@@ -0,0 +1,94 @@
+import type { Customer } from '@spree/admin-sdk'
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ RichTextEditor,
+} from '@spree/dashboard-ui'
+import { PencilIcon } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useUpdateCustomer } from '../../../hooks/use-customers'
+
+export function CustomerInternalNoteCard({ customer }: { customer: Customer }) {
+ const { t } = useTranslation()
+ const [editing, setEditing] = useState(false)
+ const [note, setNote] = useState(customer.internal_note_html ?? '')
+ const serverNote = customer.internal_note_html ?? ''
+
+ // Track the server value only while the editor is closed, so a refetch from
+ // an unrelated mutation can't discard a note the user is part-way through.
+ useEffect(() => {
+ if (!editing) setNote(serverNote)
+ }, [editing, serverNote])
+
+ const mutation = useUpdateCustomer(customer.id)
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.customers.detail.section_internal_note')}</CardTitle>
+ {!editing && (
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setEditing(true)}
+ aria-label={t('admin.actions.edit')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ )}
+ </CardHeader>
+ <CardContent>
+ {editing ? (
+ <div className="flex flex-col gap-3">
+ <RichTextEditor
+ ariaLabel={t('admin.pages.customers.detail.section_internal_note')}
+ value={note}
+ onChange={setNote}
+ placeholder={t('admin.fields.customer.internal_note.placeholder')}
+ />
+ <div className="flex gap-2 justify-end">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ setEditing(false)
+ setNote(serverNote)
+ }}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ disabled={mutation.isPending}
+ onClick={() =>
+ mutation.mutate({ internal_note: note }, { onSuccess: () => setEditing(false) })
+ }
+ >
+ {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </div>
+ </div>
+ ) : customer.internal_note_html ? (
+ <div
+ className="text-sm prose-sm"
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is sanitized server-side via the rich-text pipeline
+ dangerouslySetInnerHTML={{ __html: customer.internal_note_html }}
+ />
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {t('admin.customers.detail.no_internal_notes')}
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-last-order-card.tsx b/packages/dashboard/src/components/spree/customers/customer-last-order-card.tsx
new file mode 100644
index 0000000000..4ace8fa8e8
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-last-order-card.tsx
@@ -0,0 +1,59 @@
+import type { Order } from '@spree/admin-sdk'
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ RelativeTime,
+ StatusBadge,
+ Thumbnail,
+} from '@spree/dashboard-ui'
+import { Link } from '@tanstack/react-router'
+import { useTranslation } from 'react-i18next'
+
+export function CustomerLastOrderCard({ order }: { order: Order }) {
+ const { t } = useTranslation()
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.customers.detail.last_order_placed')}</CardTitle>
+ </CardHeader>
+ <CardContent className="p-0">
+ <div className="border-t flex items-center justify-between px-6 py-3">
+ <div>
+ <Link
+ to={'/$storeId/orders/$orderId' as string}
+ params={{ orderId: order.id }}
+ className="font-medium text-foreground no-underline"
+ >
+ #{order.number}
+ </Link>
+ <span className="ml-2 inline-flex gap-2">
+ {order.payment_status && <StatusBadge status={order.payment_status} />}
+ {order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}
+ </span>
+ {order.completed_at && (
+ <div className="text-xs text-muted-foreground mt-1">
+ <RelativeTime iso={order.completed_at} />
+ </div>
+ )}
+ </div>
+ <div className="font-semibold">{order.display_total}</div>
+ </div>
+ {order.items?.slice(0, 5).map((item) => (
+ <div key={item.id} className="border-t flex items-center gap-3 px-6 py-3 text-sm">
+ <Thumbnail src={item.thumbnail_url} />
+ <div className="flex-1 min-w-0">
+ <div className="truncate">{item.name}</div>
+ {item.options_text && (
+ <div className="text-xs text-muted-foreground truncate">{item.options_text}</div>
+ )}
+ </div>
+ <div className="text-muted-foreground">×{item.quantity}</div>
+ <div className="font-medium tabular-nums">{item.display_total}</div>
+ </div>
+ ))}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx b/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx
new file mode 100644
index 0000000000..7d61844d22
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx
@@ -0,0 +1,56 @@
+import type { Customer } from '@spree/admin-sdk'
+import { useStore } from '@spree/dashboard-core'
+import { Card, CardContent, RelativeTime } from '@spree/dashboard-ui'
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useCurrencyLocale } from '../../../hooks/use-currency-locale'
+import { formatAmount } from '../../../lib/delivery-method-summary'
+
+export function CustomerLifetimeStatsCard({ customer }: { customer: Customer }) {
+ const { t, i18n } = useTranslation()
+ const { defaultCurrency } = useStore()
+ const localeForCurrency = useCurrencyLocale()
+ const orders = customer.orders_count ?? 0
+ const totalSpent = Number(customer.total_spent ?? '0')
+ // Format the average from the number rather than rewriting the digits inside
+ // `display_total_spent`: that string is already localized, so substituting a
+ // period-decimal figure into it mixes separators (`1.234,56 €` → `1234.57 €`).
+ const aovDisplay =
+ orders > 0 && totalSpent > 0
+ ? formatAmount(
+ totalSpent / orders,
+ defaultCurrency,
+ localeForCurrency(defaultCurrency) || i18n.language,
+ )
+ : '—'
+
+ return (
+ <Card>
+ <CardContent className="grid grid-cols-2 lg:grid-cols-5 gap-6 py-6">
+ <Stat
+ label={t('admin.pages.customers.detail.stat_total_spent')}
+ value={customer.display_total_spent ?? '—'}
+ />
+ <Stat label={t('admin.pages.customers.detail.stat_orders')} value={String(orders)} />
+ <Stat label={t('admin.pages.customers.detail.stat_avg_order_value')} value={aovDisplay} />
+ <Stat
+ label={t('admin.pages.customers.detail.section_store_credit')}
+ value={customer.display_available_store_credit_total ?? '—'}
+ />
+ <Stat
+ label={t('admin.customers.detail.customer_since')}
+ value={<RelativeTime iso={customer.created_at} />}
+ />
+ </CardContent>
+ </Card>
+ )
+}
+
+function Stat({ label, value }: { label: string; value: ReactNode }) {
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-sm text-muted-foreground">{label}</span>
+ <span className="text-lg font-semibold">{value}</span>
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-orders-card.tsx b/packages/dashboard/src/components/spree/customers/customer-orders-card.tsx
new file mode 100644
index 0000000000..529e7db7f7
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-orders-card.tsx
@@ -0,0 +1,119 @@
+import type { Customer, Order } from '@spree/admin-sdk'
+import {
+ Badge,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ RelativeTime,
+ StatusBadge,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@spree/dashboard-ui'
+import { Link } from '@tanstack/react-router'
+import { useTranslation } from 'react-i18next'
+
+export function CustomerOrdersCard({
+ customer,
+ orders,
+ totalCount,
+ isLoading,
+}: {
+ customer: Customer
+ orders: Order[]
+ totalCount: number
+ isLoading: boolean
+}) {
+ const { t } = useTranslation()
+ if (isLoading) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.customers.detail.section_orders')}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <p className="text-sm text-muted-foreground">{t('admin.common.loading')}</p>
+ </CardContent>
+ </Card>
+ )
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ {t('admin.pages.customers.detail.section_orders')}
+ {totalCount > 0 && <Badge variant="outline">{totalCount}</Badge>}
+ </CardTitle>
+ {totalCount > orders.length && (
+ <CardAction>
+ <Link
+ to={'/$storeId/orders' as string}
+ search={{
+ filters: [{ id: '1', field: 'user_id_eq', operator: 'eq', value: customer.id }],
+ }}
+ className="text-sm text-primary hover:underline"
+ >
+ {t('admin.actions.view_all')} →
+ </Link>
+ </CardAction>
+ )}
+ </CardHeader>
+ {orders.length === 0 ? (
+ <CardContent>
+ <p className="text-sm text-muted-foreground">
+ {t('admin.pages.customers.detail.orders_empty')}
+ </p>
+ </CardContent>
+ ) : (
+ <CardContent className="p-0">
+ <Table roundedBottom>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('admin.customers.detail.orders_table.order')}</TableHead>
+ <TableHead>{t('admin.customers.detail.orders_table.date')}</TableHead>
+ <TableHead>{t('admin.fields.status.label')}</TableHead>
+ <TableHead className="text-right">{t('admin.fields.total.label')}</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {orders.map((order: Order) => (
+ <TableRow key={order.id}>
+ <TableCell>
+ <Link
+ to={'/$storeId/orders/$orderId' as string}
+ params={{ orderId: order.id }}
+ className="font-medium text-foreground no-underline"
+ >
+ #{order.number}
+ </Link>
+ </TableCell>
+ <TableCell className="text-muted-foreground">
+ <RelativeTime iso={order.completed_at ?? order.created_at} />
+ </TableCell>
+ <TableCell>
+ <span className="inline-flex gap-1">
+ <StatusBadge status={order.status} />
+ {order.payment_status && <StatusBadge status={order.payment_status} />}
+ {order.fulfillment_status && (
+ <StatusBadge status={order.fulfillment_status} />
+ )}
+ </span>
+ </TableCell>
+ <TableCell className="text-right font-medium tabular-nums">
+ {order.display_total}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ )}
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-profile-card.tsx b/packages/dashboard/src/components/spree/customers/customer-profile-card.tsx
new file mode 100644
index 0000000000..d7805b5428
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-profile-card.tsx
@@ -0,0 +1,242 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { Customer } from '@spree/admin-sdk'
+import { mapSpreeErrorsToForm, Subject, TagCombobox } from '@spree/dashboard-core'
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Checkbox,
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ RelativeTime,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@spree/dashboard-ui'
+import { MailIcon, PencilIcon, PhoneIcon, StarIcon } from 'lucide-react'
+import { useState } from 'react'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useUpdateCustomer } from '../../../hooks/use-customers'
+import { useOnSheetOpen } from '../../../hooks/use-on-sheet-open'
+import {
+ type CustomerProfileFormValues,
+ customerProfileFormSchema,
+} from '../../../schemas/customer'
+
+export function CustomerProfileCard({ customer }: { customer: Customer }) {
+ const { t } = useTranslation()
+ const [editOpen, setEditOpen] = useState(false)
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.pages.customers.detail.section_profile')}</CardTitle>
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setEditOpen(true)}
+ aria-label={t('admin.actions.edit')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-3">
+ <div className="flex items-center gap-2 text-sm">
+ <MailIcon className="size-4 text-muted-foreground" />
+ <span>{customer.email}</span>
+ </div>
+ {customer.phone && (
+ <div className="flex items-center gap-2 text-sm">
+ <PhoneIcon className="size-4 text-muted-foreground" />
+ <span>{customer.phone}</span>
+ </div>
+ )}
+ <div className="flex items-center gap-2 text-sm">
+ <StarIcon className="size-4 text-muted-foreground" />
+ <span>
+ {customer.accepts_email_marketing
+ ? t('admin.customers.detail.subscribed_to_marketing')
+ : t('admin.customers.detail.not_subscribed_to_marketing')}
+ </span>
+ </div>
+ {customer.created_at && (
+ <div className="text-xs text-muted-foreground">
+ <RelativeTime
+ iso={customer.created_at}
+ prefix={t('admin.customers.detail.customer_since')}
+ />
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ <EditProfileSheet customer={customer} open={editOpen} onOpenChange={setEditOpen} />
+ </>
+ )
+}
+
+function EditProfileSheet({
+ customer,
+ open,
+ onOpenChange,
+}: {
+ customer: Customer
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const form = useForm<CustomerProfileFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(customerProfileFormSchema) as any,
+ defaultValues: {
+ email: customer.email,
+ first_name: customer.first_name ?? '',
+ last_name: customer.last_name ?? '',
+ phone: customer.phone ?? '',
+ tags: customer.tags ?? [],
+ accepts_email_marketing: customer.accepts_email_marketing,
+ },
+ })
+ const { errors } = form.formState
+ const mutation = useUpdateCustomer(customer.id)
+
+ // Re-seed from the latest server values each time the sheet opens, so stale
+ // edits from a previous session are discarded.
+ useOnSheetOpen(open, () => {
+ form.reset({
+ email: customer.email,
+ first_name: customer.first_name ?? '',
+ last_name: customer.last_name ?? '',
+ phone: customer.phone ?? '',
+ tags: customer.tags ?? [],
+ accepts_email_marketing: customer.accepts_email_marketing,
+ })
+ })
+
+ async function onSubmit(values: CustomerProfileFormValues) {
+ try {
+ await mutation.mutateAsync(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.pages.customers.edit_sheet_title')}</SheetTitle>
+ <SheetDescription>
+ {t('admin.customers.detail.edit_profile_description')}
+ </SheetDescription>
+ </SheetHeader>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="email">{t('admin.fields.email.label')}</FieldLabel>
+ <Input
+ id="email"
+ type="email"
+ aria-invalid={!!errors.email || undefined}
+ {...form.register('email')}
+ />
+ <FieldError errors={[errors.email]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="first_name">{t('admin.fields.first_name.label')}</FieldLabel>
+ <Input
+ id="first_name"
+ aria-invalid={!!errors.first_name || undefined}
+ {...form.register('first_name')}
+ />
+ <FieldError errors={[errors.first_name]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="last_name">{t('admin.fields.last_name.label')}</FieldLabel>
+ <Input
+ id="last_name"
+ aria-invalid={!!errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ <FieldError errors={[errors.last_name]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="phone">{t('admin.fields.phone.label')}</FieldLabel>
+ <Input
+ id="phone"
+ aria-invalid={!!errors.phone || undefined}
+ {...form.register('phone')}
+ />
+ <FieldError errors={[errors.phone]} />
+ </Field>
+ <Field>
+ <FieldLabel>{t('admin.fields.customer.tags.label')}</FieldLabel>
+ <Controller
+ name="tags"
+ control={form.control}
+ render={({ field }) => (
+ <TagCombobox
+ taggableType={Subject.Customer}
+ value={field.value}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </Field>
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <FieldLabel htmlFor="accepts_email_marketing" className="cursor-pointer">
+ {t('admin.fields.customer.accepts_email_marketing.label')}
+ </FieldLabel>
+ <Controller
+ name="accepts_email_marketing"
+ control={form.control}
+ render={({ field }) => (
+ <Checkbox
+ id="accepts_email_marketing"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
+ />
+ </div>
+ </Field>
+ </FieldGroup>
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={mutation.isPending}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-store-credits-card.tsx b/packages/dashboard/src/components/spree/customers/customer-store-credits-card.tsx
new file mode 100644
index 0000000000..d2a81481a5
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-store-credits-card.tsx
@@ -0,0 +1,446 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { Customer, StoreCredit } from '@spree/admin-sdk'
+import { CurrencySelect, mapSpreeErrorsToForm, useStore } from '@spree/dashboard-core'
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Field,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Textarea,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { EllipsisVerticalIcon, PencilIcon, PlusIcon, TrashIcon } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useCurrencyLocale } from '../../../hooks/use-currency-locale'
+import {
+ type StoreCreditUpdateParams,
+ useCreateCustomerStoreCredit,
+ useDeleteCustomerStoreCredit,
+ useUpdateCustomerStoreCredit,
+} from '../../../hooks/use-customer-store-credits'
+import {
+ type EditStoreCreditFormValues,
+ editStoreCreditFormSchema,
+ type IssueStoreCreditFormValues,
+ issueStoreCreditFormSchema,
+} from '../../../schemas/store-credit'
+import { currencyParts } from '../bulk-price-editor/currency-parts'
+import { normalizeMoneyInput } from '../bulk-price-editor/normalize-money'
+
+export function CustomerStoreCreditsCard({ customer }: { customer: Customer }) {
+ const { t } = useTranslation()
+ const [addOpen, setAddOpen] = useState(false)
+ const [editing, setEditing] = useState<StoreCredit | null>(null)
+ const confirm = useConfirm()
+ const credits = customer.store_credits ?? []
+
+ const deleteMutation = useDeleteCustomerStoreCredit(customer.id)
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ {t('admin.customers.detail.store_credit.title')}
+ {credits.length > 0 && <Badge>{credits.length}</Badge>}
+ </CardTitle>
+ <CardAction>
+ <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>
+ <PlusIcon className="size-4" />
+ {t('admin.pages.customers.detail.issue_credit')}
+ </Button>
+ </CardAction>
+ </CardHeader>
+ {credits.length === 0 ? (
+ <CardContent>
+ <p className="text-sm text-muted-foreground">
+ {t('admin.customers.detail.store_credit.empty')}
+ </p>
+ </CardContent>
+ ) : (
+ <CardContent className="p-0">
+ <Table roundedBottom>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('admin.fields.amount.label')}</TableHead>
+ <TableHead>{t('admin.customers.detail.store_credit.table.used')}</TableHead>
+ <TableHead>{t('admin.customers.detail.store_credit.table.remaining')}</TableHead>
+ <TableHead>{t('admin.customers.detail.store_credit.table.memo')}</TableHead>
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {credits.map((sc: StoreCredit) => (
+ <TableRow key={sc.id}>
+ <TableCell className="font-medium tabular-nums">
+ {sc.display_amount ?? sc.amount}
+ </TableCell>
+ <TableCell className="tabular-nums">
+ {sc.display_amount_used ?? sc.amount_used}
+ </TableCell>
+ <TableCell className="tabular-nums">
+ {sc.display_amount_remaining ?? sc.amount_remaining}
+ </TableCell>
+ <TableCell className="text-muted-foreground">{sc.memo ?? '—'}</TableCell>
+ <TableCell className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon-xs">
+ <EllipsisVerticalIcon className="size-4" />
+ <span className="sr-only">{t('admin.actions.actions_menu')}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditing(sc)}>
+ <PencilIcon className="size-4" />
+ {t('admin.actions.edit')}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="text-destructive focus:text-destructive"
+ onClick={async () => {
+ if (
+ await confirm({
+ message: t(
+ 'admin.customers.detail.store_credit.delete_confirm_message',
+ ),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ ) {
+ deleteMutation.mutate(sc.id)
+ }
+ }}
+ >
+ <TrashIcon className="size-4" />
+ {t('admin.actions.delete')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ )}
+ </Card>
+
+ <IssueStoreCreditDialog customerId={customer.id} open={addOpen} onOpenChange={setAddOpen} />
+ {editing && (
+ <EditStoreCreditDialog
+ customerId={customer.id}
+ credit={editing}
+ onOpenChange={(o) => {
+ if (!o) setEditing(null)
+ }}
+ />
+ )}
+ </>
+ )
+}
+
+function EditStoreCreditDialog({
+ customerId,
+ credit,
+ onOpenChange,
+}: {
+ customerId: string
+ credit: StoreCredit
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ // Server rejects amount changes once any of it has been used. Lock the
+ // field so the merchant doesn't submit a value that will only come back
+ // as a 422 store_credit_in_use.
+ const amountLocked = Number(credit.amount_used ?? 0) > 0
+
+ const localeForCurrency = useCurrencyLocale()
+ // Currency is locked on edit, so resolve its market locale once. The amount
+ // hydrates from the canonical API value (`"50.00"`) but is displayed/edited
+ // in that locale's format (`"50,00"` for EUR); on submit we normalize back to
+ // canonical. Displaying in the same locale we normalize from keeps an
+ // untouched amount from being mangled on save.
+ const creditLocale = localeForCurrency(credit.currency) || 'en'
+ const { decimal } = currencyParts(credit.currency, creditLocale)
+
+ const form = useForm<EditStoreCreditFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(editStoreCreditFormSchema) as any,
+ defaultValues: {
+ amount: credit.amount ? credit.amount.replace('.', decimal) : '',
+ memo: credit.memo ?? '',
+ },
+ })
+ const { errors } = form.formState
+
+ const mutation = useUpdateCustomerStoreCredit(customerId, credit.id)
+
+ async function onSubmit(values: EditStoreCreditFormValues) {
+ const params: StoreCreditUpdateParams = {}
+
+ if (!amountLocked) {
+ const amountValue = values.amount.toString().trim()
+ // Normalize from the credit's display locale to the canonical
+ // `"1234.56"` the API expects.
+ if (amountValue) {
+ params.amount = normalizeMoneyInput(amountValue, creditLocale)
+ }
+ }
+
+ params.memo = values.memo
+
+ try {
+ await mutation.mutateAsync(params)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.pages.customers.detail.edit_credit')}</DialogTitle>
+ <DialogDescription>
+ {t('admin.customers.detail.store_credit.edit_description')}
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <DialogBody>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <FieldGroup>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor="edit-sc-amount">
+ {t('admin.fields.store_credit.amount.label')}
+ </FieldLabel>
+ <Input
+ id="edit-sc-amount"
+ type="text"
+ inputMode="decimal"
+ disabled={amountLocked}
+ aria-invalid={!!errors.amount || undefined}
+ {...form.register('amount')}
+ />
+ <FieldError errors={[errors.amount]} />
+ </Field>
+ <Field>
+ {/* Currency is locked: the API doesn't accept `currency`
+ on update (changing it on a partially-used credit
+ would invalidate amount_used / amount_remaining). We
+ surface it disabled so the merchant always sees which
+ currency the credit is in. */}
+ <FieldLabel htmlFor="edit-sc-currency">
+ {t('admin.fields.store_credit.currency.label')}
+ </FieldLabel>
+ <CurrencySelect id="edit-sc-currency" value={credit.currency} disabled />
+ </Field>
+ </div>
+ <Field>
+ <FieldLabel htmlFor="edit-sc-memo">
+ {t('admin.fields.store_credit.memo.label')}
+ </FieldLabel>
+ <Textarea
+ id="edit-sc-memo"
+ rows={3}
+ placeholder={t('admin.fields.store_credit.memo.placeholder')}
+ aria-invalid={!!errors.memo || undefined}
+ {...form.register('memo')}
+ />
+ <FieldError errors={[errors.memo]} />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function IssueStoreCreditDialog({
+ customerId,
+ open,
+ onOpenChange,
+}: {
+ customerId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ // Seed `currency` with the store default so the merchant doesn't have to
+ // pick one explicitly — `CurrencySelect` displays it but no longer commits
+ // it via onChange, so the form value needs to start populated.
+ const { defaultCurrency } = useStore()
+ const form = useForm<IssueStoreCreditFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(issueStoreCreditFormSchema) as any,
+ defaultValues: { amount: '', currency: defaultCurrency, memo: '' },
+ })
+ const { errors } = form.formState
+
+ const mutation = useCreateCustomerStoreCredit(customerId)
+ const localeForCurrency = useCurrencyLocale()
+
+ // Clear any prior submission state when the dialog re-opens so a fresh form
+ // is presented (otherwise stale "Issue $20" values linger across opens).
+ useEffect(() => {
+ if (open) {
+ form.reset({ amount: '', currency: defaultCurrency, memo: '' })
+ }
+ }, [open, form, defaultCurrency])
+
+ // Switching currency re-displays the amount in the new currency's locale
+ // format, so the value the merchant sees always matches the locale it will be
+ // normalized under on submit. Without this, `25.00` typed under USD would be
+ // re-read under EUR's `de` locale (where `.` groups thousands) and persist as
+ // 2500. Canonicalize from the old locale, then swap to the new locale's
+ // decimal separator.
+ function handleCurrencyChange(
+ next: string,
+ field: { value: string; onChange: (v: string) => void },
+ ) {
+ const prev = field.value
+ field.onChange(next)
+ const raw = form.getValues('amount')?.trim()
+ if (!raw) return
+ const canonical = normalizeMoneyInput(raw, localeForCurrency(prev) || 'en')
+ const { decimal } = currencyParts(next, localeForCurrency(next) || 'en')
+ form.setValue('amount', decimal === '.' ? canonical : canonical.replace('.', decimal))
+ }
+
+ async function onSubmit(values: IssueStoreCreditFormValues) {
+ try {
+ await mutation.mutateAsync({
+ // Normalize the merchant's localized input (entered under the selected
+ // currency's market locale) to the canonical `"1234.56"` the API
+ // expects. The server never parses comma-vs-period.
+ amount: normalizeMoneyInput(values.amount, localeForCurrency(values.currency) || 'en'),
+ currency: values.currency,
+ memo: values.memo || undefined,
+ })
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.pages.customers.detail.issue_credit')}</DialogTitle>
+ <DialogDescription>
+ {t('admin.customers.detail.store_credit.add_description')}
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <DialogBody>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <FieldGroup>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor="sc-amount">
+ {t('admin.fields.store_credit.amount.label')}
+ </FieldLabel>
+ <Input
+ id="sc-amount"
+ type="text"
+ inputMode="decimal"
+ required
+ aria-invalid={!!errors.amount || undefined}
+ {...form.register('amount')}
+ />
+ <FieldError errors={[errors.amount]} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="sc-currency">
+ {t('admin.fields.store_credit.currency.label')}
+ </FieldLabel>
+ <Controller
+ name="currency"
+ control={form.control}
+ render={({ field }) => (
+ <CurrencySelect
+ id="sc-currency"
+ value={field.value || ''}
+ onChange={(next) => handleCurrencyChange(next, field)}
+ required
+ />
+ )}
+ />
+ </Field>
+ </div>
+ <Field>
+ <FieldLabel htmlFor="sc-memo">
+ {t('admin.fields.store_credit.memo.label')}
+ </FieldLabel>
+ <Textarea
+ id="sc-memo"
+ rows={3}
+ placeholder={t('admin.fields.store_credit.memo.placeholder')}
+ aria-invalid={!!errors.memo || undefined}
+ {...form.register('memo')}
+ />
+ <FieldError errors={[errors.memo]} />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending
+ ? t('admin.actions.saving')
+ : t('admin.pages.customers.detail.issue_credit')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/customers/customer-tax-identifiers-card.tsx b/packages/dashboard/src/components/spree/customers/customer-tax-identifiers-card.tsx
new file mode 100644
index 0000000000..7925fd686a
--- /dev/null
+++ b/packages/dashboard/src/components/spree/customers/customer-tax-identifiers-card.tsx
@@ -0,0 +1,34 @@
+import type { Customer } from '@spree/admin-sdk'
+import { Subject, usePermissions } from '@spree/dashboard-core'
+import {
+ useCreateCustomerTaxIdentifier,
+ useCustomerTaxIdentifiers,
+ useDeleteCustomerTaxIdentifier,
+ useUpdateCustomerTaxIdentifier,
+ useValidateCustomerTaxIdentifier,
+} from '../../../hooks/use-customers'
+import { TaxIdentifiersCard } from '../tax-identifiers-card'
+
+export function CustomerTaxIdentifiersCard({ customer }: { customer: Customer }) {
+ const { permissions } = usePermissions()
+ const { data, isLoading } = useCustomerTaxIdentifiers(customer.id)
+ const createMutation = useCreateCustomerTaxIdentifier(customer.id)
+ const updateMutation = useUpdateCustomerTaxIdentifier(customer.id)
+ const deleteMutation = useDeleteCustomerTaxIdentifier(customer.id)
+ const validateMutation = useValidateCustomerTaxIdentifier(customer.id)
+
+ return (
+ <TaxIdentifiersCard
+ identifiers={data?.data ?? []}
+ isLoading={isLoading}
+ canEdit={permissions.can('update', Subject.Customer)}
+ mutations={{
+ create: (params) => createMutation.mutateAsync(params),
+ update: (id, params) => updateMutation.mutateAsync({ id, params }),
+ remove: (id) => deleteMutation.mutateAsync(id),
+ validate: (id) => validateMutation.mutateAsync(id),
+ isValidating: validateMutation.isPending,
+ }}
+ />
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-at-a-glance-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-at-a-glance-card.tsx
new file mode 100644
index 0000000000..65a29beaf6
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-at-a-glance-card.tsx
@@ -0,0 +1,37 @@
+import type { Seller } from '@spree/admin-sdk'
+import { Card, CardContent, CardHeader, CardTitle, RelativeTime } from '@spree/dashboard-ui'
+import { PackageIcon, UsersIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { ReadRow } from './seller-read-row'
+
+/** The counts an operator scans for before opening anything else. */
+export function SellerAtAGlanceCard({ seller }: { seller: Seller }) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.sellers.detail.at_a_glance')}</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-3">
+ <div className="flex items-center justify-between text-sm">
+ <span className="flex items-center gap-2 text-muted-foreground">
+ <PackageIcon className="size-4" />
+ {t('admin.sellers.products_column')}
+ </span>
+ <span>{seller.products_count}</span>
+ </div>
+ <div className="flex items-center justify-between text-sm">
+ <span className="flex items-center gap-2 text-muted-foreground">
+ <UsersIcon className="size-4" />
+ {t('admin.sellers.team_column')}
+ </span>
+ <span>{seller.users_count}</span>
+ </div>
+ <ReadRow label={t('admin.fields.created_at.label')}>
+ <RelativeTime iso={seller.created_at} />
+ </ReadRow>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-brand-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-brand-card.tsx
new file mode 100644
index 0000000000..3c8c9e092d
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-brand-card.tsx
@@ -0,0 +1,83 @@
+import type { Seller } from '@spree/admin-sdk'
+import { Button, Card, CardContent } from '@spree/dashboard-ui'
+import { PencilIcon, StoreIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+/** Cover photo, logo and the seller's own description — the storefront face. */
+export function SellerBrandCard({
+ seller,
+ canEdit,
+ onEdit,
+}: {
+ seller: Seller
+ canEdit: boolean
+ onEdit: () => void
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Card className="overflow-hidden">
+ {/* A seller with no cover gets a slim band rather than a tall empty
+ block. It uses --accent rather than --muted: muted is a deliberate
+ "whisper" against white, which over a region this size disappears
+ entirely and leaves the logo looking unanchored. */}
+ <div className="relative">
+ {seller.cover_photo_url ? (
+ <img src={seller.cover_photo_url} alt="" className="h-40 w-full bg-accent object-cover" />
+ ) : (
+ <div className="h-20 w-full border-border border-b bg-muted" />
+ )}
+ {canEdit && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="absolute top-3 right-3 bg-background/80 backdrop-blur-sm hover:bg-background"
+ onClick={onEdit}
+ aria-label={t('admin.actions.edit')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ )}
+ </div>
+
+ {/* The logo straddles the band, so it needs more inset than CardContent's
+ own padding gives — otherwise an 80px tile pulled up over a slim band
+ reads as hanging off the card's corner. */}
+ <CardContent className="flex flex-col gap-4 px-5 pb-5">
+ {/* Positioned with its own z-index: the band above is `relative`, so a
+ plain sibling paints underneath it and the band's edge cuts across
+ the tile. The border belongs on the tile itself rather than a ring
+ outside it, which over the band reads as a halo. */}
+ <div className="-mt-10 relative z-10 flex size-20 items-center justify-center overflow-hidden rounded-xl border border-border bg-card shadow-sm">
+ {/* The square logo is the one cropped for a tile like this; the main
+ logo is the fallback, since a seller may have set only one. */}
+ {seller.square_logo_url || seller.logo_url ? (
+ <img
+ src={seller.square_logo_url ?? seller.logo_url ?? undefined}
+ alt=""
+ className="size-full object-cover"
+ />
+ ) : (
+ <StoreIcon className="size-7 text-muted-foreground" />
+ )}
+ </div>
+
+ {/* The name already sits in the page header; repeating it here would
+ just be the same words twice. The handle is what the header lacks. */}
+ <p className="text-muted-foreground text-sm">/{seller.slug}</p>
+
+ {seller.about_html ? (
+ // Server-sanitized on every write path (Spree::RichTextSanitizer),
+ // which is what makes rendering it here safe.
+ <div
+ className="prose prose-sm max-w-none dark:prose-invert"
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: sanitized server-side
+ dangerouslySetInnerHTML={{ __html: seller.about_html }}
+ />
+ ) : (
+ <p className="text-muted-foreground text-sm">{t('admin.sellers.detail.no_about')}</p>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-contact-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-contact-card.tsx
new file mode 100644
index 0000000000..b568bc7cb4
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-contact-card.tsx
@@ -0,0 +1,49 @@
+import type { Seller } from '@spree/admin-sdk'
+import { Button, Card, CardAction, CardContent, CardHeader, CardTitle } from '@spree/dashboard-ui'
+import { PencilIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { ReadRow } from './seller-read-row'
+
+export function SellerContactCard({
+ seller,
+ canEdit,
+ onEdit,
+}: {
+ seller: Seller
+ canEdit: boolean
+ onEdit: () => void
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.sellers.detail.contact')}</CardTitle>
+ {canEdit && (
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onEdit}
+ aria-label={t('admin.actions.edit')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ )}
+ </CardHeader>
+ <CardContent className="flex flex-col gap-3">
+ <ReadRow label={t('admin.fields.contact_email.label')}>
+ {seller.contact_email ? (
+ <a href={`mailto:${seller.contact_email}`}>{seller.contact_email}</a>
+ ) : null}
+ </ReadRow>
+ <ReadRow label={t('admin.fields.seller.billing_email.label')}>
+ {seller.billing_email ? (
+ <a href={`mailto:${seller.billing_email}`}>{seller.billing_email}</a>
+ ) : null}
+ </ReadRow>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-edit-profile-sheet.tsx b/packages/dashboard/src/components/spree/sellers/seller-edit-profile-sheet.tsx
new file mode 100644
index 0000000000..5f5f9ab4af
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-edit-profile-sheet.tsx
@@ -0,0 +1,223 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { Seller } from '@spree/admin-sdk'
+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'
+import {
+ Button,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ RichTextEditor,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@spree/dashboard-ui'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useOnSheetOpen } from '../../../hooks/use-on-sheet-open'
+import { useUpdateSeller } from '../../../hooks/use-sellers'
+import {
+ SELLER_DEFAULTS,
+ type SellerFormValues,
+ sellerFormSchema,
+ sellerImageParams,
+ sellerValuesToParams,
+} from '../../../schemas/seller'
+import { ResourceImageField } from '../resource-image-field'
+
+/** The profile the seller also maintains from their own panel. */
+export function SellerEditProfileSheet({
+ seller,
+ open,
+ onOpenChange,
+}: {
+ seller: Seller
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const updateMutation = useUpdateSeller(seller.id)
+
+ const form = useForm<SellerFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(sellerFormSchema) as any,
+ defaultValues: SELLER_DEFAULTS,
+ })
+
+ // Re-seed from the latest record each time the sheet opens.
+ //
+ // Images reset to the empty triple: the persisted ones are passed to the
+ // field as `serverUrl`, and the triple only carries what the operator
+ // changes this time round.
+ useOnSheetOpen(open, () => {
+ form.reset({
+ ...SELLER_DEFAULTS,
+ name: seller.name,
+ slug: seller.slug,
+ contact_email: seller.contact_email ?? '',
+ billing_email: seller.billing_email ?? '',
+ about: seller.about_html ?? '',
+ })
+ })
+
+ async function onSubmit(values: SellerFormValues) {
+ try {
+ // Only this sheet's own fields — the settlement sheet owns the rest, and
+ // sending them here would post this form's untouched defaults over them.
+ const params = sellerValuesToParams(values)
+ await updateMutation.mutateAsync({
+ ...sellerImageParams(values),
+ name: params.name,
+ slug: params.slug,
+ contact_email: params.contact_email,
+ billing_email: params.billing_email,
+ about: params.about,
+ })
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ const { errors } = form.formState
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.sellers.detail.edit_profile')}</SheetTitle>
+ <SheetDescription>{t('admin.sellers.detail.edit_profile_description')}</SheetDescription>
+ </SheetHeader>
+ <form
+ onSubmit={(event) => {
+ form.handleSubmit(onSubmit)(event)
+ event.stopPropagation()
+ }}
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <FieldGroup>
+ {errors.root?.message && (
+ <p className="text-destructive text-sm" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <ResourceImageField
+ form={form}
+ kind="logo"
+ serverUrl={seller.logo_url}
+ square
+ translationNamespace="admin.sellers"
+ labelKey="logo_label"
+ helpKey="logo_help"
+ />
+ <ResourceImageField
+ form={form}
+ kind="square_logo"
+ serverUrl={seller.square_logo_url}
+ square
+ translationNamespace="admin.sellers"
+ labelKey="square_logo_label"
+ helpKey="square_logo_help"
+ />
+ <ResourceImageField
+ form={form}
+ kind="cover_photo"
+ serverUrl={seller.cover_photo_url}
+ translationNamespace="admin.sellers"
+ labelKey="cover_photo_label"
+ helpKey="cover_photo_help"
+ />
+
+ <Field>
+ <FieldLabel htmlFor="seller-name">{t('admin.fields.name.label')}</FieldLabel>
+ <Input
+ id="seller-name"
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name')}
+ />
+ <FieldError errors={[errors.name]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="seller-slug">{t('admin.fields.slug.label')}</FieldLabel>
+ <Input
+ id="seller-slug"
+ aria-invalid={!!errors.slug || undefined}
+ {...form.register('slug')}
+ />
+ <FieldDescription>{t('admin.fields.seller.slug.help')}</FieldDescription>
+ <FieldError errors={[errors.slug]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="seller-contact-email">
+ {t('admin.fields.contact_email.label')}
+ </FieldLabel>
+ <Input
+ id="seller-contact-email"
+ type="email"
+ aria-invalid={!!errors.contact_email || undefined}
+ {...form.register('contact_email')}
+ />
+ <FieldDescription>{t('admin.fields.seller.contact_email.help')}</FieldDescription>
+ <FieldError errors={[errors.contact_email]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="seller-billing-email">
+ {t('admin.fields.seller.billing_email.label')}
+ </FieldLabel>
+ <Input
+ id="seller-billing-email"
+ type="email"
+ aria-invalid={!!errors.billing_email || undefined}
+ {...form.register('billing_email')}
+ />
+ <FieldDescription>{t('admin.fields.seller.billing_email.help')}</FieldDescription>
+ <FieldError errors={[errors.billing_email]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="seller-about">
+ {t('admin.fields.seller.about.label')}
+ </FieldLabel>
+ <Controller
+ control={form.control}
+ name="about"
+ render={({ field }) => (
+ <RichTextEditor
+ id="seller-about"
+ ariaLabel={t('admin.fields.seller.about.label')}
+ value={field.value ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ <FieldDescription>{t('admin.fields.seller.about.help')}</FieldDescription>
+ </Field>
+ </FieldGroup>
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-edit-settlement-sheet.tsx b/packages/dashboard/src/components/spree/sellers/seller-edit-settlement-sheet.tsx
new file mode 100644
index 0000000000..85ddbbec9e
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-edit-settlement-sheet.tsx
@@ -0,0 +1,236 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { Seller } from '@spree/admin-sdk'
+import { mapSpreeErrorsToForm, StoreDatePicker } from '@spree/dashboard-core'
+import {
+ Button,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@spree/dashboard-ui'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useOnSheetOpen } from '../../../hooks/use-on-sheet-open'
+import { useUpdateSeller } from '../../../hooks/use-sellers'
+import {
+ PAYOUT_INTERVALS,
+ SELLER_DEFAULTS,
+ type SellerFormValues,
+ sellerFormSchema,
+ sellerValuesToParams,
+ TAX_REMITTANCES,
+} from '../../../schemas/seller'
+
+export function SellerEditSettlementSheet({
+ seller,
+ open,
+ onOpenChange,
+}: {
+ seller: Seller
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const updateMutation = useUpdateSeller(seller.id)
+
+ const form = useForm<SellerFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(sellerFormSchema) as any,
+ defaultValues: SELLER_DEFAULTS,
+ })
+
+ useOnSheetOpen(open, () => {
+ form.reset({
+ ...SELLER_DEFAULTS,
+ // Carried so the schema's required `name` still validates; the submit
+ // below sends only this sheet's own fields.
+ name: seller.name,
+ tax_remittance: (seller.tax_remittance ?? 'seller') as SellerFormValues['tax_remittance'],
+ payouts_schedule_interval: (seller.payouts_schedule_interval ??
+ '') as SellerFormValues['payouts_schedule_interval'],
+ minimum_payout_amount: seller.minimum_payout_amount ?? '',
+ holiday_mode_until: seller.holiday_mode_until ?? '',
+ })
+ })
+
+ async function onSubmit(values: SellerFormValues) {
+ try {
+ const params = sellerValuesToParams(values)
+ await updateMutation.mutateAsync({
+ tax_remittance: params.tax_remittance,
+ payouts_schedule_interval: params.payouts_schedule_interval,
+ minimum_payout_amount: params.minimum_payout_amount,
+ holiday_mode_until: params.holiday_mode_until,
+ })
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ const { errors } = form.formState
+
+ const remittanceOptions = TAX_REMITTANCES.map((value) => ({
+ value,
+ label: t(`admin.sellers.tax_remittance.${value}`),
+ }))
+ const intervalOptions = [
+ { value: '', label: t('admin.sellers.payout_interval.inherit') },
+ ...PAYOUT_INTERVALS.map((value) => ({
+ value,
+ label: t(`admin.sellers.payout_interval.${value}`),
+ })),
+ ]
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.sellers.detail.edit_settlement')}</SheetTitle>
+ <SheetDescription>
+ {t('admin.sellers.detail.edit_settlement_description')}
+ </SheetDescription>
+ </SheetHeader>
+ <form
+ onSubmit={(event) => {
+ form.handleSubmit(onSubmit)(event)
+ event.stopPropagation()
+ }}
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <FieldGroup>
+ {errors.root?.message && (
+ <p className="text-destructive text-sm" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+
+ <Field>
+ <FieldLabel htmlFor="tax_remittance">
+ {t('admin.fields.seller.tax_remittance.label')}
+ </FieldLabel>
+ <Controller
+ name="tax_remittance"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ items={remittanceOptions}
+ value={field.value ?? 'seller'}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="tax_remittance" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {remittanceOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ <FieldDescription>{t('admin.fields.seller.tax_remittance.help')}</FieldDescription>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="payouts_schedule_interval">
+ {t('admin.fields.seller.payouts_schedule_interval.label')}
+ </FieldLabel>
+ <Controller
+ name="payouts_schedule_interval"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ items={intervalOptions}
+ value={field.value ?? ''}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="payouts_schedule_interval" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {intervalOptions.map((option) => (
+ <SelectItem key={option.value || 'inherit'} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ <FieldDescription>
+ {t('admin.fields.seller.payouts_schedule_interval.help')}
+ </FieldDescription>
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="minimum_payout_amount">
+ {t('admin.fields.seller.minimum_payout_amount.label')}
+ </FieldLabel>
+ <Input
+ id="minimum_payout_amount"
+ inputMode="decimal"
+ aria-invalid={!!errors.minimum_payout_amount || undefined}
+ {...form.register('minimum_payout_amount')}
+ />
+ <FieldDescription>
+ {t('admin.fields.seller.minimum_payout_amount.help')}
+ </FieldDescription>
+ <FieldError errors={[errors.minimum_payout_amount]} />
+ </Field>
+
+ <Field>
+ <FieldLabel>{t('admin.fields.seller.holiday_mode_until.label')}</FieldLabel>
+ <Controller
+ name="holiday_mode_until"
+ control={form.control}
+ render={({ field }) => (
+ <StoreDatePicker
+ value={field.value || null}
+ onChange={(next) => field.onChange(next ?? '')}
+ placeholder={t('admin.fields.seller.holiday_mode_until.placeholder')}
+ includeTime
+ inline
+ />
+ )}
+ />
+ <FieldDescription>
+ {t('admin.fields.seller.holiday_mode_until.help')}
+ </FieldDescription>
+ </Field>
+ </FieldGroup>
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-invite-sheet.tsx b/packages/dashboard/src/components/spree/sellers/seller-invite-sheet.tsx
new file mode 100644
index 0000000000..8091a7774b
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-invite-sheet.tsx
@@ -0,0 +1,108 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { Seller } from '@spree/admin-sdk'
+import { mapSpreeErrorsToForm } from '@spree/dashboard-core'
+import {
+ Button,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ Input,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@spree/dashboard-ui'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useInviteSeller } from '../../../hooks/use-sellers'
+import { type SellerInviteValues, sellerInviteSchema } from '../../../schemas/seller'
+
+export function SellerInviteSheet({
+ seller,
+ open,
+ onOpenChange,
+}: {
+ seller: Seller
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const inviteMutation = useInviteSeller(seller.id)
+ const form = useForm<SellerInviteValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(sellerInviteSchema) as any,
+ defaultValues: { email: seller.contact_email ?? '' },
+ })
+
+ async function onSubmit(values: SellerInviteValues) {
+ try {
+ await inviteMutation.mutateAsync(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ const { errors } = form.formState
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{t('admin.sellers.invite_sheet.title')}</SheetTitle>
+ <SheetDescription>{t('admin.sellers.invite_sheet.description')}</SheetDescription>
+ </SheetHeader>
+ <form
+ onSubmit={(event) => {
+ // This sheet renders inside the detail page's own tree; without
+ // stopping the bubble the browser would submit an outer form.
+ form.handleSubmit(onSubmit)(event)
+ event.stopPropagation()
+ }}
+ className="flex min-h-0 flex-1 flex-col"
+ >
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <FieldGroup>
+ {errors.root?.message && (
+ <p className="text-destructive text-sm" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <Field>
+ <FieldLabel htmlFor="invite-email">{t('admin.fields.email.label')}</FieldLabel>
+ <Input
+ id="invite-email"
+ type="email"
+ autoFocus
+ aria-invalid={!!errors.email || undefined}
+ {...form.register('email')}
+ />
+ <FieldDescription>{t('admin.sellers.invite_sheet.email_help')}</FieldDescription>
+ <FieldError errors={[errors.email]} />
+ </Field>
+ </FieldGroup>
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting
+ ? t('admin.actions.saving')
+ : t('admin.sellers.actions.send_invitation')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-read-row.tsx b/packages/dashboard/src/components/spree/sellers/seller-read-row.tsx
new file mode 100644
index 0000000000..da11651b8b
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-read-row.tsx
@@ -0,0 +1,17 @@
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+
+/** One labelled value in a sidebar card, with a placeholder when unset. */
+export function ReadRow({ label, children }: { label: string; children: ReactNode }) {
+ const { t } = useTranslation()
+ return (
+ <div className="flex items-start justify-between gap-3 text-sm">
+ <span className="text-muted-foreground">{label}</span>
+ <span className="text-right">
+ {children ?? (
+ <span className="text-muted-foreground">{t('admin.sellers.not_provided')}</span>
+ )}
+ </span>
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-settlement-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-settlement-card.tsx
new file mode 100644
index 0000000000..927d50a8a5
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-settlement-card.tsx
@@ -0,0 +1,64 @@
+import type { Seller } from '@spree/admin-sdk'
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ RelativeTime,
+} from '@spree/dashboard-ui'
+import { PencilIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { ReadRow } from './seller-read-row'
+
+/** Operator-only: how and when this seller gets paid, and who remits tax. */
+export function SellerSettlementCard({
+ seller,
+ canEdit,
+ onEdit,
+}: {
+ seller: Seller
+ canEdit: boolean
+ onEdit: () => void
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.sellers.detail.settlement')}</CardTitle>
+ {canEdit && (
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={onEdit}
+ aria-label={t('admin.actions.edit')}
+ >
+ <PencilIcon className="size-4" />
+ </Button>
+ </CardAction>
+ )}
+ </CardHeader>
+ <CardContent className="flex flex-col gap-3">
+ <ReadRow label={t('admin.fields.seller.tax_remittance.label')}>
+ {t(`admin.sellers.tax_remittance.${seller.tax_remittance}`, {
+ defaultValue: seller.tax_remittance,
+ })}
+ </ReadRow>
+ <ReadRow label={t('admin.fields.seller.payouts_schedule_interval.label')}>
+ {seller.payouts_schedule_interval
+ ? t(`admin.sellers.payout_interval.${seller.payouts_schedule_interval}`)
+ : t('admin.sellers.payout_interval.inherit')}
+ </ReadRow>
+ <ReadRow label={t('admin.fields.seller.minimum_payout_amount.label')}>
+ {seller.minimum_payout_amount}
+ </ReadRow>
+ <ReadRow label={t('admin.fields.seller.holiday_mode_until.label')}>
+ {seller.holiday_mode_until ? <RelativeTime iso={seller.holiday_mode_until} /> : null}
+ </ReadRow>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/sellers/seller-status-card.tsx b/packages/dashboard/src/components/spree/sellers/seller-status-card.tsx
new file mode 100644
index 0000000000..45a90210db
--- /dev/null
+++ b/packages/dashboard/src/components/spree/sellers/seller-status-card.tsx
@@ -0,0 +1,36 @@
+import type { Seller } from '@spree/admin-sdk'
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ StatusBadge,
+} from '@spree/dashboard-ui'
+import { useTranslation } from 'react-i18next'
+
+/** Where the seller is, and what that means in plain words. */
+export function SellerStatusCard({ seller }: { seller: Seller }) {
+ const { t } = useTranslation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.sellers.detail.status')}</CardTitle>
+ <CardAction>
+ <StatusBadge status={seller.status} label={t(`admin.sellers.status.${seller.status}`)} />
+ </CardAction>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-2">
+ <p className="text-muted-foreground text-sm">
+ {t(`admin.sellers.status_help.${seller.status}`, {
+ defaultValue: t('admin.sellers.status_help.pending'),
+ })}
+ </p>
+ {seller.on_holiday && (
+ <p className="text-muted-foreground text-sm">{t('admin.sellers.on_holiday_notice')}</p>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-digital-methods-card.tsx b/packages/dashboard/src/components/spree/shipping/delivery-digital-methods-card.tsx
new file mode 100644
index 0000000000..857af91b5a
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-digital-methods-card.tsx
@@ -0,0 +1,49 @@
+import type { DeliveryMethod } from '@spree/admin-sdk'
+import { Can, Subject } from '@spree/dashboard-core'
+import { Button, Card, CardContent, CardHeader, CardTitle } from '@spree/dashboard-ui'
+import { PlusIcon, ZapIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { DeliveryMethodList } from './delivery-method-list'
+import { useMethodSheetNavigation } from './use-method-sheet-navigation'
+
+/** Methods delivered without a destination of any kind. */
+export function DeliveryDigitalMethodsCard({ methods }: { methods: DeliveryMethod[] }) {
+ const { t } = useTranslation()
+ const { openNewMethod } = useMethodSheetNavigation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <ZapIcon className="size-4 text-muted-foreground" />
+ {t('admin.delivery_profiles.detail.digital_title')}
+ </CardTitle>
+ <span className="text-muted-foreground text-xs">
+ {t('admin.delivery_profiles.detail.digital_hint')}
+ </span>
+ </CardHeader>
+ <CardContent>
+ {methods.length > 0 ? (
+ <DeliveryMethodList methods={methods} icon={ZapIcon} />
+ ) : (
+ <div className="flex flex-col items-start gap-2">
+ <p className="text-muted-foreground text-sm">
+ {t('admin.delivery_profiles.detail.digital_empty')}
+ </p>
+ <Can I="create" a={Subject.DeliveryMethod}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => openNewMethod({ provider: 'digital' })}
+ >
+ <PlusIcon className="size-4" />
+ {t('admin.delivery_profiles.detail.add_digital_method')}
+ </Button>
+ </Can>
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx
new file mode 100644
index 0000000000..5d6835933b
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-list.tsx
@@ -0,0 +1,142 @@
+import type { DeliveryMethod } from '@spree/admin-sdk'
+import { Subject, usePermissions, useStore } from '@spree/dashboard-core'
+import {
+ Badge,
+ RowActions,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { TruckIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import {
+ useDeleteDeliveryMethod,
+ useDeliveryRateProviders,
+} from '../../../hooks/use-delivery-methods'
+import { flatAmount, formatAmount, summarizeRules } from '../../../lib/delivery-method-summary'
+import { useMethodSheetNavigation } from './use-method-sheet-navigation'
+
+export function DeliveryMethodList({
+ methods,
+ icon: Icon = TruckIcon,
+}: {
+ methods: DeliveryMethod[]
+ icon?: typeof TruckIcon
+}) {
+ const { t, i18n } = useTranslation()
+ const { store, defaultCurrency } = useStore()
+ const { openMethod } = useMethodSheetNavigation()
+ const confirm = useConfirm()
+ const deleteMutation = useDeleteDeliveryMethod()
+ const { permissions } = usePermissions()
+ const { data: rateProviders } = useDeliveryRateProviders()
+ const defaultRateProvider = rateProviders?.default ?? ''
+
+ async function handleDelete(method: DeliveryMethod) {
+ const ok = await confirm({
+ title: t('admin.delivery_methods.delete_confirm.title'),
+ message: t('admin.delivery_methods.delete_confirm.message', { name: method.name }),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return
+ await deleteMutation.mutateAsync(method.id).catch(() => undefined)
+ }
+
+ if (methods.length === 0) {
+ return (
+ <p className="text-muted-foreground text-sm">
+ {t('admin.delivery_profiles.detail.no_methods')}
+ </p>
+ )
+ }
+
+ return (
+ <div className="flex flex-col divide-y">
+ {methods.map((method) => {
+ const rateProvider = (rateProviders?.data ?? []).find(
+ (provider) => provider.type === method.rate_provider,
+ )
+ // A carrier quotes each shipment live, so this column answers what the
+ // price IS rather than naming the provider — which the method is
+ // usually named after anyway. Everything else is priced up front: an
+ // amount, or free when there is none.
+ //
+ // A method carrying a rate provider absent from the registry (an
+ // uninstalled gem, a disconnected integration) is still not
+ // calculator-priced, and calling it free would be a lie about money.
+ const carrierPriced = rateProvider
+ ? rateProvider.uses_calculator === false
+ : !!method.rate_provider && method.rate_provider !== defaultRateProvider
+ const amount = flatAmount(method.calculator_preferences)
+ const price = carrierPriced
+ ? t('admin.delivery_methods.carrier_rates')
+ : amount === null || amount === 0
+ ? t('admin.delivery_methods.free')
+ : formatAmount(amount, defaultCurrency, i18n.language)
+
+ const ruleSummary = summarizeRules(method.rules, {
+ t,
+ currency: defaultCurrency,
+ weightUnit: store?.preferred_weight_unit ?? 'lb',
+ locale: i18n.language,
+ })
+
+ return (
+ <div key={method.id} className="flex items-center justify-between gap-2 py-2">
+ <button
+ type="button"
+ className="flex flex-1 items-center gap-2 text-left"
+ onClick={() => openMethod(method.id)}
+ >
+ <Icon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="flex flex-col">
+ <span className="text-sm">{method.name}</span>
+ {ruleSummary && (
+ <span className="text-muted-foreground text-xs">{ruleSummary}</span>
+ )}
+ </span>
+ </button>
+ {!method.storefront_visible && (
+ <Badge variant="outline">{t('admin.delivery_profiles.detail.hidden_badge')}</Badge>
+ )}
+ {carrierPriced ? (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="shrink-0 cursor-default text-sm underline decoration-dotted underline-offset-2">
+ {price}
+ </span>
+ }
+ />
+ <TooltipContent className="max-w-xs">
+ {t('admin.delivery_methods.carrier_rates_hint', {
+ name: rateProvider?.name ?? method.name,
+ })}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <span className="shrink-0 text-sm tabular-nums">{price}</span>
+ )}
+ <RowActions
+ actions={[
+ {
+ key: 'edit',
+ onSelect: () => openMethod(method.id),
+ },
+ {
+ key: 'delete',
+ destructive: true,
+ visible: permissions.can('destroy', Subject.DeliveryMethod),
+ disabled: deleteMutation.isPending,
+ onSelect: () => handleDelete(method),
+ },
+ ]}
+ />
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-origin-group-section.tsx b/packages/dashboard/src/components/spree/shipping/delivery-origin-group-section.tsx
new file mode 100644
index 0000000000..c8377cb210
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-origin-group-section.tsx
@@ -0,0 +1,130 @@
+import type {
+ DeliveryMethod,
+ DeliveryOriginGroup,
+ DeliveryProfile,
+ DeliveryZone,
+} from '@spree/admin-sdk'
+import { Can, Subject, usePermissions } from '@spree/dashboard-core'
+import { Button, RowActions, useConfirm } from '@spree/dashboard-ui'
+import { PlusIcon, WarehouseIcon } from 'lucide-react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useDeleteDeliveryOriginGroup } from '../../../hooks/use-delivery-origin-groups'
+import { useStockLocations } from '../../../hooks/use-stock-locations'
+import { DeliveryOriginGroupDialog } from './delivery-origin-group-dialog'
+import { DeliveryZoneCard, UnrestrictedMethodsCard } from './delivery-zone-card'
+
+/**
+ * One origin group of a split profile: the warehouses it ships from, and the
+ * zones and methods priced from them. Same cards as the flat rendering, under
+ * a header that names the origin.
+ */
+export function DeliveryOriginGroupSection({
+ profile,
+ group,
+ zones,
+ methods,
+ onAddZone,
+ onEditZone,
+}: {
+ profile: DeliveryProfile
+ group: DeliveryProfile['origin_groups'][number]
+ zones: DeliveryZone[]
+ methods: DeliveryMethod[]
+ onAddZone: () => void
+ onEditZone: (zoneId: string) => void
+}) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ const { permissions } = usePermissions()
+ const { data: stockLocations } = useStockLocations()
+ const deleteMutation = useDeleteDeliveryOriginGroup(profile.id)
+ const [editing, setEditing] = useState(false)
+
+ const unrestricted = methods.filter((method) => !method.delivery_zone_id)
+ const locationNames = (stockLocations?.data ?? [])
+ .filter((location) => group.stock_location_ids.includes(location.id))
+ .map((location) => location.name)
+
+ async function handleDelete() {
+ const ok = await confirm({
+ title: t('admin.delivery_origin_groups.delete_confirm.title'),
+ message: t('admin.delivery_origin_groups.delete_confirm.message', {
+ name: group.name ?? t('admin.delivery_profiles.all_locations'),
+ }),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return
+ // Deleting cascades to the group's zones and methods — the confirm says
+ // so. Only the profile's last group is refused (422, surfaced as a toast).
+ await deleteMutation.mutateAsync(group.id).catch(() => undefined)
+ }
+
+ return (
+ <section className="flex flex-col gap-4 rounded-lg border p-4">
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-2">
+ <WarehouseIcon className="size-4 text-muted-foreground" />
+ <span className="font-medium text-sm">
+ {group.name || t('admin.delivery_profiles.all_locations')}
+ </span>
+ </div>
+ <span className="text-muted-foreground text-xs">
+ {locationNames.length > 0
+ ? t('admin.delivery_origin_groups.ships_from', {
+ locations: locationNames.join(', '),
+ })
+ : t('admin.delivery_origin_groups.ships_from_all')}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ <Can I="create" a={Subject.DeliveryZone}>
+ <Button type="button" variant="outline" size="sm" onClick={onAddZone}>
+ <PlusIcon className="size-4" />
+ {t('admin.delivery_zones.add_cta')}
+ </Button>
+ </Can>
+ <RowActions
+ actions={[
+ {
+ key: 'edit',
+ visible: permissions.can('update', Subject.DeliveryProfile),
+ onSelect: () => setEditing(true),
+ },
+ {
+ key: 'delete',
+ destructive: true,
+ visible: permissions.can('update', Subject.DeliveryProfile),
+ disabled: deleteMutation.isPending,
+ onSelect: handleDelete,
+ },
+ ]}
+ />
+ </div>
+ </div>
+
+ {zones.map((zone) => (
+ <DeliveryZoneCard
+ key={zone.id}
+ zone={zone}
+ methods={methods.filter((method) => method.delivery_zone_id === zone.id)}
+ onEdit={() => onEditZone(zone.id)}
+ originGroupId={group.id}
+ />
+ ))}
+
+ <UnrestrictedMethodsCard methods={unrestricted} originGroupId={group.id} />
+
+ {editing && (
+ <DeliveryOriginGroupDialog
+ deliveryProfileId={profile.id}
+ group={group as DeliveryOriginGroup}
+ open
+ onOpenChange={(open) => !open && setEditing(false)}
+ />
+ )}
+ </section>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-pickup-card.tsx b/packages/dashboard/src/components/spree/shipping/delivery-pickup-card.tsx
new file mode 100644
index 0000000000..e93b5be355
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-pickup-card.tsx
@@ -0,0 +1,112 @@
+import type { DeliveryMethod } from '@spree/admin-sdk'
+import { Can, Subject } from '@spree/dashboard-core'
+import { Button, Card, CardContent, CardHeader, CardTitle, Checkbox } from '@spree/dashboard-ui'
+import { PlusIcon, StoreIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { useStockLocations, useUpdateStockLocationById } from '../../../hooks/use-stock-locations'
+import { DeliveryMethodList } from './delivery-method-list'
+import { useMethodSheetNavigation } from './use-method-sheet-navigation'
+
+/**
+ * The methods customers collect in person, and which counters they can
+ * collect from.
+ */
+export function DeliveryPickupCard({ methods }: { methods: DeliveryMethod[] }) {
+ const { t } = useTranslation()
+ const { openNewMethod } = useMethodSheetNavigation()
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="flex items-center gap-2">
+ <StoreIcon className="size-4 text-muted-foreground" />
+ {t('admin.delivery_profiles.detail.pickup_title')}
+ </CardTitle>
+ <span className="text-muted-foreground text-xs">
+ {t('admin.delivery_profiles.detail.pickup_hint')}
+ </span>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ {methods.length > 0 ? (
+ <DeliveryMethodList methods={methods} icon={StoreIcon} />
+ ) : (
+ <div className="flex flex-col items-start gap-2">
+ <p className="text-muted-foreground text-sm">
+ {t('admin.delivery_profiles.detail.pickup_empty')}
+ </p>
+ <Can I="create" a={Subject.DeliveryMethod}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => openNewMethod({ provider: 'pickup' })}
+ >
+ <PlusIcon className="size-4" />
+ {t('admin.delivery_profiles.detail.offer_pickup')}
+ </Button>
+ </Can>
+ </div>
+ )}
+
+ <PickupLocationsBlock />
+ </CardContent>
+ </Card>
+ )
+}
+
+/**
+ * Every stock location of the store, each a counter customers can collect
+ * from. Toggling writes straight through — the surrounding page is a set of
+ * saved forms, so the helper line says these changes are immediate.
+ */
+function PickupLocationsBlock() {
+ const { t } = useTranslation()
+ const { data: stockLocations, isLoading } = useStockLocations()
+ const updateMutation = useUpdateStockLocationById()
+
+ const locations = stockLocations?.data ?? []
+
+ return (
+ <div className="flex flex-col gap-2 border-t pt-4">
+ <span className="font-medium text-sm">
+ {t('admin.delivery_profiles.detail.collect_from')}
+ </span>
+ <span className="text-muted-foreground text-xs">
+ {t('admin.delivery_profiles.detail.collect_from_hint')}
+ </span>
+
+ {isLoading ? (
+ <p className="text-muted-foreground text-sm">{t('admin.common.loading')}</p>
+ ) : locations.length === 0 ? (
+ <p className="text-muted-foreground text-sm">
+ {t('admin.delivery_profiles.detail.no_stock_locations')}
+ </p>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {locations.map((location) => (
+ <label
+ key={location.id}
+ htmlFor={`pickup-location-${location.id}`}
+ className="flex items-center gap-2 text-sm"
+ >
+ <Checkbox
+ id={`pickup-location-${location.id}`}
+ checked={location.pickup_enabled}
+ disabled={updateMutation.isPending}
+ onCheckedChange={(next) =>
+ updateMutation
+ .mutateAsync({
+ id: location.id,
+ params: { pickup_enabled: !!next },
+ })
+ .catch(() => undefined)
+ }
+ />
+ {location.name}
+ </label>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-profile-general-card.tsx b/packages/dashboard/src/components/spree/shipping/delivery-profile-general-card.tsx
new file mode 100644
index 0000000000..b73a50c732
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-profile-general-card.tsx
@@ -0,0 +1,130 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { DeliveryProfile } from '@spree/admin-sdk'
+import { Can, mapSpreeErrorsToForm, Subject } from '@spree/dashboard-core'
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Field,
+ FieldError,
+ FieldLabel,
+ Input,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useUpdateDeliveryProfile } from '../../../hooks/use-delivery-profiles'
+import {
+ type DeliveryProfileGeneralValues,
+ deliveryProfileGeneralSchema,
+} from '../../../schemas/delivery-profile'
+
+/** Name, kind, and promotion to store default. */
+export function DeliveryProfileGeneralCard({ profile }: { profile: DeliveryProfile }) {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ const updateMutation = useUpdateDeliveryProfile(profile.id)
+
+ const form = useForm<DeliveryProfileGeneralValues>({
+ resolver: zodResolver(deliveryProfileGeneralSchema),
+ defaultValues: { name: profile.name },
+ values: { name: profile.name },
+ resetOptions: { keepDirtyValues: true },
+ })
+
+ async function onSubmit(values: DeliveryProfileGeneralValues) {
+ try {
+ await updateMutation.mutateAsync({ name: values.name })
+ form.reset(values)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ async function handleMakeDefault() {
+ const ok = await confirm({
+ title: t('admin.delivery_profiles.default_confirm.title'),
+ message: t('admin.delivery_profiles.default_confirm.message', { name: profile.name }),
+ confirmLabel: t('admin.delivery_profiles.make_default'),
+ })
+ if (!ok) return
+ await updateMutation.mutateAsync({ default: true }).catch(() => undefined)
+ }
+
+ const { errors } = form.formState
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.delivery_profiles.detail.general_title')}</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+ <Field>
+ <FieldLabel htmlFor="profile-name">{t('admin.fields.name.label')}</FieldLabel>
+ <Input
+ id="profile-name"
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name')}
+ />
+ <FieldError errors={[errors.name]} />
+ </Field>
+
+ <Field>
+ <FieldLabel>{t('admin.fields.delivery_profile.kind.label')}</FieldLabel>
+ <div>
+ <Badge variant="outline">
+ {t(`admin.delivery_profiles.kinds.${profile.kind}`, {
+ defaultValue: profile.kind,
+ })}
+ </Badge>
+ </div>
+ <span className="text-muted-foreground text-xs">
+ {t('admin.delivery_profiles.kind_immutable_hint')}
+ </span>
+ </Field>
+
+ <Field>
+ <FieldLabel>{t('admin.delivery_profiles.default_badge')}</FieldLabel>
+ {profile.default ? (
+ <span className="text-muted-foreground text-xs">
+ {t('admin.delivery_profiles.is_default_hint')}
+ </span>
+ ) : (
+ <Can I="update" a={Subject.DeliveryProfile}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="self-start"
+ onClick={handleMakeDefault}
+ disabled={updateMutation.isPending}
+ >
+ {t('admin.delivery_profiles.make_default')}
+ </Button>
+ </Can>
+ )}
+ </Field>
+
+ <Can I="update" a={Subject.DeliveryProfile}>
+ <Button
+ type="button"
+ size="sm"
+ className="self-start"
+ onClick={form.handleSubmit(onSubmit)}
+ disabled={form.formState.isSubmitting || !form.formState.isDirty}
+ >
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </Can>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-profile-origins-card.tsx b/packages/dashboard/src/components/spree/shipping/delivery-profile-origins-card.tsx
new file mode 100644
index 0000000000..26795c12da
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-profile-origins-card.tsx
@@ -0,0 +1,86 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { DeliveryProfile } from '@spree/admin-sdk'
+import { Can, mapSpreeErrorsToForm, Subject } from '@spree/dashboard-core'
+import { Button, Card, CardContent, CardHeader, CardTitle } from '@spree/dashboard-ui'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useUpdateDeliveryProfile } from '../../../hooks/use-delivery-profiles'
+import { useStockLocations } from '../../../hooks/use-stock-locations'
+import {
+ type DeliveryProfileLocationsValues,
+ deliveryProfileLocationsSchema,
+ deliveryProfileLocationsToParams,
+} from '../../../schemas/delivery-profile'
+import { StockLocationScopeField } from './stock-location-scope-field'
+
+/** Which stock locations this profile ships from. */
+export function DeliveryProfileOriginsCard({ profile }: { profile: DeliveryProfile }) {
+ const { t } = useTranslation()
+ const updateMutation = useUpdateDeliveryProfile(profile.id)
+ const { data: stockLocations } = useStockLocations()
+
+ const initial: DeliveryProfileLocationsValues = {
+ scope: profile.stock_location_ids.length === 0 ? 'all' : 'selected',
+ stock_location_ids: profile.stock_location_ids,
+ }
+
+ const form = useForm<DeliveryProfileLocationsValues>({
+ resolver: zodResolver(deliveryProfileLocationsSchema),
+ defaultValues: initial,
+ values: initial,
+ resetOptions: { keepDirtyValues: true },
+ })
+
+ const scope = form.watch('scope')
+
+ async function onSubmit(values: DeliveryProfileLocationsValues) {
+ try {
+ await updateMutation.mutateAsync(deliveryProfileLocationsToParams(values))
+ form.reset(values)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('admin.delivery_profiles.detail.origins_title')}</CardTitle>
+ </CardHeader>
+ <CardContent className="flex flex-col gap-4">
+ <Controller
+ name="stock_location_ids"
+ control={form.control}
+ render={({ field }) => (
+ <StockLocationScopeField
+ idPrefix="origins"
+ scope={scope}
+ onScopeChange={(next) => {
+ form.setValue('scope', next, { shouldDirty: true })
+ if (next === 'all') field.onChange([])
+ }}
+ locations={stockLocations?.data ?? []}
+ selectedIds={field.value}
+ onSelectedIdsChange={field.onChange}
+ allLabel={t('admin.delivery_profiles.all_locations')}
+ selectedLabel={t('admin.delivery_profiles.selected_locations')}
+ emptyLabel={t('admin.delivery_profiles.detail.no_stock_locations')}
+ />
+ )}
+ />
+
+ <Can I="update" a={Subject.DeliveryProfile}>
+ <Button
+ type="button"
+ size="sm"
+ className="self-start"
+ onClick={form.handleSubmit(onSubmit)}
+ disabled={form.formState.isSubmitting || !form.formState.isDirty}
+ >
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </Can>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-zone-card.tsx b/packages/dashboard/src/components/spree/shipping/delivery-zone-card.tsx
new file mode 100644
index 0000000000..c5ed91e9c1
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-zone-card.tsx
@@ -0,0 +1,194 @@
+import type { DeliveryMethod, DeliveryZone, DeliveryZoneMember } from '@spree/admin-sdk'
+import { Can, Subject, usePermissions } from '@spree/dashboard-core'
+import {
+ Button,
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ RowActions,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ useConfirm,
+} from '@spree/dashboard-ui'
+import { GlobeIcon, MapIcon, PlusIcon } from 'lucide-react'
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useDeleteDeliveryZone } from '../../../hooks/use-delivery-zones'
+import { DeliveryMethodList } from './delivery-method-list'
+import { useMethodSheetNavigation } from './use-method-sheet-navigation'
+
+export function DeliveryZoneCard({
+ zone,
+ methods,
+ onEdit,
+ originGroupId,
+}: {
+ zone: DeliveryZone
+ methods: DeliveryMethod[]
+ onEdit: () => void
+ /** Set only on a split profile, so a new method lands in the right group. */
+ originGroupId?: string
+}) {
+ const { t } = useTranslation()
+ const { openNewMethod } = useMethodSheetNavigation()
+ const confirm = useConfirm()
+ const deleteMutation = useDeleteDeliveryZone()
+ const { permissions } = usePermissions()
+
+ async function handleDelete() {
+ const ok = await confirm({
+ title: t('admin.delivery_zones.delete_confirm.title'),
+ message: t('admin.delivery_zones.delete_confirm.message', { name: zone.name }),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return
+ await deleteMutation.mutateAsync(zone.id).catch(() => undefined)
+ }
+
+ return (
+ <Card>
+ <CardHeader className="flex flex-row items-start justify-between gap-2">
+ <div className="flex flex-col gap-1">
+ <CardTitle className="flex items-center gap-2">
+ <MapIcon className="size-4 text-muted-foreground" />
+ {zone.name}
+ </CardTitle>
+ <ZoneMembersSummary zone={zone} />
+ </div>
+ <div className="flex items-center gap-2">
+ <Can I="create" a={Subject.DeliveryMethod}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => openNewMethod({ zone: zone.id, group: originGroupId })}
+ >
+ <PlusIcon className="size-4" />
+ {t('admin.delivery_profiles.detail.add_method')}
+ </Button>
+ </Can>
+ <RowActions
+ actions={[
+ { key: 'edit', onSelect: onEdit },
+ {
+ key: 'delete',
+ destructive: true,
+ visible: permissions.can('destroy', Subject.DeliveryZone),
+ disabled: deleteMutation.isPending,
+ onSelect: handleDelete,
+ },
+ ]}
+ />
+ </div>
+ </CardHeader>
+ <CardContent>
+ <DeliveryMethodList methods={methods} />
+ </CardContent>
+ </Card>
+ )
+}
+
+/**
+ * Methods offered wherever the profile reaches. Always rendered, even empty:
+ * a profile with no zones would otherwise have nowhere to add a method from,
+ * and a carrier method that quotes worldwide never wants a zone at all.
+ */
+export function UnrestrictedMethodsCard({
+ methods,
+ originGroupId,
+}: {
+ methods: DeliveryMethod[]
+ originGroupId?: string
+}) {
+ const { t } = useTranslation()
+ const { openNewMethod } = useMethodSheetNavigation()
+
+ return (
+ <Card>
+ <CardHeader className="flex flex-row items-start justify-between gap-2">
+ <div className="flex flex-col gap-1">
+ <CardTitle className="flex items-center gap-2">
+ <GlobeIcon className="size-4 text-muted-foreground" />
+ {t('admin.delivery_profiles.detail.no_zone_title')}
+ </CardTitle>
+ <span className="text-muted-foreground text-xs">
+ {t('admin.delivery_profiles.detail.no_zone_hint')}
+ </span>
+ </div>
+ <Can I="create" a={Subject.DeliveryMethod}>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => openNewMethod({ group: originGroupId })}
+ >
+ <PlusIcon className="size-4" />
+ {t('admin.delivery_profiles.detail.add_method')}
+ </Button>
+ </Can>
+ </CardHeader>
+ {methods.length > 0 && (
+ <CardContent>
+ <DeliveryMethodList methods={methods} />
+ </CardContent>
+ )}
+ </Card>
+ )
+}
+
+/**
+ * Names the places a zone covers: the first few members, then the rest behind
+ * a tooltip. Countries come first because they are how merchants think about
+ * a zone; states and postal-code rules follow when a zone is finer-grained.
+ */
+function ZoneMembersSummary({ zone }: { zone: DeliveryZone }) {
+ const { t } = useTranslation()
+
+ const names = useMemo(() => {
+ const members = zone.members ?? []
+ const label = (member: DeliveryZoneMember): string | null => {
+ if (member.member_type === 'country') return member.country_name ?? member.country_code
+ if (member.member_type === 'state') return member.state_name ?? member.state_code
+ if (member.postal_code_prefix) return `${member.postal_code_prefix}*`
+ if (member.postal_code_from && member.postal_code_to) {
+ return `${member.postal_code_from}–${member.postal_code_to}`
+ }
+ return member.postal_code_from ?? member.postal_code_to
+ }
+
+ const order = { country: 0, state: 1 } as Record<string, number>
+ return [...members]
+ .sort((a, b) => (order[a.member_type] ?? 2) - (order[b.member_type] ?? 2))
+ .map(label)
+ .filter((name): name is string => !!name)
+ }, [zone.members])
+
+ if (names.length === 0) return null
+
+ const shown = names.slice(0, 3)
+ const remaining = names.slice(3)
+
+ return (
+ <span className="text-muted-foreground text-xs">
+ {shown.join(t('admin.delivery_zones.member_separator'))}
+ {remaining.length > 0 && (
+ <>
+ {t('admin.delivery_zones.member_separator')}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button type="button" className="underline decoration-dotted underline-offset-2">
+ {t('admin.delivery_zones.members_more', { count: remaining.length })}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ {remaining.join(t('admin.delivery_zones.member_separator'))}
+ </TooltipContent>
+ </Tooltip>
+ </>
+ )}
+ </span>
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-zones-and-methods-section.tsx b/packages/dashboard/src/components/spree/shipping/delivery-zones-and-methods-section.tsx
new file mode 100644
index 0000000000..9842c8b52b
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/delivery-zones-and-methods-section.tsx
@@ -0,0 +1,213 @@
+import type { DeliveryMethod, DeliveryProfile, DeliveryZone } from '@spree/admin-sdk'
+import { Can, Subject } from '@spree/dashboard-core'
+import { Button } from '@spree/dashboard-ui'
+import { PlusIcon, SplitIcon } from 'lucide-react'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useAllDeliveryMethods } from '../../../hooks/use-delivery-methods'
+import { useProfileDeliveryZones } from '../../../hooks/use-delivery-zones'
+import { DeliveryDigitalMethodsCard } from './delivery-digital-methods-card'
+import { DeliveryMethodSheet } from './delivery-method-sheet'
+import { DeliveryOriginGroupDialog } from './delivery-origin-group-dialog'
+import { DeliveryOriginGroupSection } from './delivery-origin-group-section'
+import { DeliveryPickupCard } from './delivery-pickup-card'
+import { DeliveryZoneCard, UnrestrictedMethodsCard } from './delivery-zone-card'
+import { DeliveryZoneSheet } from './delivery-zone-sheet'
+import { useMethodSheetNavigation } from './use-method-sheet-navigation'
+
+/** What the URL carries about the method sheet on the profile detail page. */
+export type MethodSheetSearch = {
+ method?: string
+ zone?: string
+ group?: string
+ provider?: 'pickup' | 'digital'
+}
+
+/**
+ * Methods, split by how they reach the customer. Zones are a destination
+ * concept, so only address-shipping methods are filed under them; pickup and
+ * digital methods get their own cards, with no zone language at all.
+ */
+export function DeliveryZonesAndMethodsSection({
+ profile,
+ search,
+}: {
+ profile: DeliveryProfile
+ search: MethodSheetSearch
+}) {
+ const { t } = useTranslation()
+ const { data: zones, isLoading: zonesLoading } = useProfileDeliveryZones(profile.id)
+ const { data: allMethods, isLoading: methodsLoading } = useAllDeliveryMethods()
+ const [zoneSheet, setZoneSheet] = useState<{ zoneId?: string; groupId?: string } | null>(null)
+ const [splitting, setSplitting] = useState(false)
+
+ const methods = (allMethods ?? []).filter((method) => method.delivery_profile_id === profile.id)
+ const pickupMethods = methods.filter((method) => method.pickup || method.pickup_point)
+ const digitalMethods = methods.filter((method) => method.digital)
+ const shippingMethods = methods.filter(
+ (method) => !method.digital && !method.pickup && !method.pickup_point,
+ )
+
+ const groups = [...(profile.origin_groups ?? [])].sort(
+ (a, b) => (a.position ?? 0) - (b.position ?? 0),
+ )
+ // Until a profile is split, the origin-group layer is invisible: one group
+ // means one flat list of zones, exactly as before groups existed.
+ const split = groups.length > 1
+
+ if (zonesLoading || methodsLoading) {
+ return <p className="text-muted-foreground">{t('admin.common.loading')}</p>
+ }
+
+ // A digital profile has no destination and no counter, so zones would be
+ // meaningless there — it gets the digital card alone. The method sheet still
+ // rides along, since digital methods are edited through it too.
+ if (profile.digital) {
+ return (
+ <>
+ <DeliveryDigitalMethodsCard methods={digitalMethods} />
+ <MethodSheetOutlet profile={profile} zones={zones ?? []} search={search} />
+ </>
+ )
+ }
+
+ return (
+ <>
+ <div className="flex items-center justify-between">
+ <h2 className="font-medium text-base">{t('admin.delivery_profiles.detail.zones_title')}</h2>
+ <div className="flex items-center gap-2">
+ <Can I="update" a={Subject.DeliveryProfile}>
+ <Button type="button" variant="ghost" size="sm" onClick={() => setSplitting(true)}>
+ <SplitIcon className="size-4" />
+ {t('admin.delivery_origin_groups.split_cta')}
+ </Button>
+ </Can>
+ {!split && (
+ <Can I="create" a={Subject.DeliveryZone}>
+ <Button type="button" variant="outline" size="sm" onClick={() => setZoneSheet({})}>
+ <PlusIcon className="size-4" />
+ {t('admin.delivery_zones.add_cta')}
+ </Button>
+ </Can>
+ )}
+ </div>
+ </div>
+
+ {split ? (
+ groups.map((group) => (
+ <DeliveryOriginGroupSection
+ key={group.id}
+ profile={profile}
+ group={group}
+ zones={(zones ?? []).filter((zone) => zone.delivery_origin_group_id === group.id)}
+ methods={shippingMethods.filter(
+ (method) => method.delivery_origin_group_id === group.id,
+ )}
+ onAddZone={() => setZoneSheet({ groupId: group.id })}
+ onEditZone={(zoneId) => setZoneSheet({ zoneId })}
+ />
+ ))
+ ) : (
+ <FlatZoneList
+ zones={zones ?? []}
+ methods={shippingMethods}
+ onEditZone={(zoneId) => setZoneSheet({ zoneId })}
+ />
+ )}
+
+ <DeliveryPickupCard methods={pickupMethods} />
+
+ {digitalMethods.length > 0 && <DeliveryDigitalMethodsCard methods={digitalMethods} />}
+
+ {zoneSheet && (
+ <DeliveryZoneSheet
+ deliveryProfileId={profile.id}
+ deliveryOriginGroupId={zoneSheet.groupId}
+ zoneId={zoneSheet.zoneId}
+ siblingZones={zones ?? []}
+ open
+ onOpenChange={(open) => !open && setZoneSheet(null)}
+ />
+ )}
+
+ {splitting && (
+ <DeliveryOriginGroupDialog
+ deliveryProfileId={profile.id}
+ open
+ onOpenChange={(open) => !open && setSplitting(false)}
+ />
+ )}
+
+ <MethodSheetOutlet profile={profile} zones={zones ?? []} search={search} />
+ </>
+ )
+}
+
+/**
+ * The zones of one profile with no origin-group framing at all — what a
+ * merchant who never split their origins sees, and what they return to after
+ * deleting the second group.
+ */
+function FlatZoneList({
+ zones,
+ methods,
+ onEditZone,
+}: {
+ zones: DeliveryZone[]
+ methods: DeliveryMethod[]
+ onEditZone: (zoneId: string) => void
+}) {
+ const unrestricted = methods.filter((method) => !method.delivery_zone_id)
+
+ return (
+ <>
+ {zones.map((zone) => (
+ <DeliveryZoneCard
+ key={zone.id}
+ zone={zone}
+ methods={methods.filter((method) => method.delivery_zone_id === zone.id)}
+ onEdit={() => onEditZone(zone.id)}
+ />
+ ))}
+
+ <UnrestrictedMethodsCard methods={unrestricted} />
+ </>
+ )
+}
+
+/**
+ * Renders the method sheet whenever the URL asks for one. Kept apart from the
+ * page body so the profile stays mounted underneath: opening a method is a
+ * search-param change, not a navigation away.
+ */
+function MethodSheetOutlet({
+ profile,
+ zones,
+ search,
+}: {
+ profile: DeliveryProfile
+ zones: DeliveryZone[]
+ search: MethodSheetSearch
+}) {
+ const { closeMethodSheet } = useMethodSheetNavigation()
+
+ if (!search.method) return null
+
+ const creating = search.method === 'new'
+
+ return (
+ <DeliveryMethodSheet
+ // Remounting on the method being edited drops the previous record's
+ // form state, which a shared instance would otherwise carry over.
+ key={search.method}
+ profile={profile}
+ zones={zones}
+ methodId={creating ? undefined : search.method}
+ zoneId={creating ? search.zone : undefined}
+ originGroupId={creating ? search.group : undefined}
+ provider={creating ? search.provider : undefined}
+ open
+ onOpenChange={(open) => !open && closeMethodSheet()}
+ />
+ )
+}
diff --git a/packages/dashboard/src/components/spree/shipping/use-method-sheet-navigation.ts b/packages/dashboard/src/components/spree/shipping/use-method-sheet-navigation.ts
new file mode 100644
index 0000000000..365885dadc
--- /dev/null
+++ b/packages/dashboard/src/components/spree/shipping/use-method-sheet-navigation.ts
@@ -0,0 +1,47 @@
+import { useNavigate } from '@tanstack/react-router'
+
+/**
+ * Opens the method sheet for an existing method, or for a new one.
+ *
+ * Every move replaces the history entry rather than pushing one. The sheet
+ * lives in the URL so a deep link reopens it, but opening and closing one is
+ * not a place a merchant navigated to — pushing would leave the page's back
+ * arrow walking through sheets they already dismissed instead of returning to
+ * the profile list.
+ */
+export function useMethodSheetNavigation() {
+ const navigate = useNavigate()
+
+ const openMethod = (methodId: string) =>
+ navigate({
+ replace: true,
+ search: (prev: Record<string, unknown>) => {
+ const { zone: _z, group: _g, provider: _p, ...rest } = prev
+ return { ...rest, method: methodId } as never
+ },
+ })
+
+ const openNewMethod = (options: { zone?: string; group?: string; provider?: string } = {}) =>
+ navigate({
+ replace: true,
+ search: (prev: Record<string, unknown>) =>
+ ({
+ ...prev,
+ method: 'new',
+ ...(options.zone ? { zone: options.zone } : { zone: undefined }),
+ ...(options.group ? { group: options.group } : { group: undefined }),
+ ...(options.provider ? { provider: options.provider } : { provider: undefined }),
+ }) as never,
+ })
+
+ const closeMethodSheet = () =>
+ navigate({
+ replace: true,
+ search: (prev: Record<string, unknown>) => {
+ const { method: _m, zone: _z, group: _g, provider: _p, ...rest } = prev
+ return rest as never
+ },
+ })
+
+ return { openMethod, openNewMethod, closeMethodSheet }
+}
diff --git a/packages/dashboard/src/hooks/use-on-sheet-open.ts b/packages/dashboard/src/hooks/use-on-sheet-open.ts
new file mode 100644
index 0000000000..37259eb8db
--- /dev/null
+++ b/packages/dashboard/src/hooks/use-on-sheet-open.ts
@@ -0,0 +1,24 @@
+import { useEffect, useRef } from 'react'
+
+/**
+ * Runs `seed` when a sheet or dialog goes from closed to open.
+ *
+ * Sheets stay mounted between opens, so their forms have to be reseeded from
+ * the record each time one is opened. Depending on the record itself does that
+ * too often: it is a new object on every refetch, and a background refetch
+ * while the sheet is open would overwrite what the operator has typed. Keying
+ * on the open transition reseeds exactly once per open.
+ *
+ * `seed` is read through a ref, so it does not need to be memoized by callers.
+ */
+export function useOnSheetOpen(open: boolean, seed: () => void) {
+ const seedRef = useRef(seed)
+ seedRef.current = seed
+
+ const wasOpen = useRef(false)
+
+ useEffect(() => {
+ if (open && !wasOpen.current) seedRef.current()
+ wasOpen.current = open
+ }, [open])
+}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx
index 7d850670db..abebbb9880 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/customers/$customerId.tsx
@@ -1,125 +1,24 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import type { Address, Customer, Order, StoreCredit } from '@spree/admin-sdk'
-import {
- AddressFormDialog,
- type AddressParams,
- CurrencySelect,
- mapSpreeErrorsToForm,
- PageHeader,
- ResourceMultiAutocomplete,
- Slot,
- Subject,
- TagCombobox,
- useCountries,
- usePermissions,
- useStore,
-} from '@spree/dashboard-core'
-import {
- Badge,
- Button,
- Card,
- CardAction,
- CardContent,
- CardHeader,
- CardTitle,
- Checkbox,
- Dialog,
- DialogBody,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- ErrorState,
- Field,
- FieldError,
- FieldGroup,
- FieldLabel,
- Input,
- MetadataCard,
- RelativeTime,
- ResourceLayout,
- RichTextEditor,
- Sheet,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
- StatusBadge,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- Textarea,
- Thumbnail,
- useConfirm,
-} from '@spree/dashboard-ui'
-import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
-import {
- EllipsisVerticalIcon,
- MailIcon,
- PencilIcon,
- PhoneIcon,
- PlusIcon,
- StarIcon,
- TrashIcon,
- UsersIcon,
-} from 'lucide-react'
-import { type ReactNode, useEffect, useMemo, useState } from 'react'
-import { Controller, useForm } from 'react-hook-form'
+import type { Customer } from '@spree/admin-sdk'
+import { PageHeader, Slot, Subject } from '@spree/dashboard-core'
+import { Badge, ErrorState, MetadataCard, ResourceLayout } from '@spree/dashboard-ui'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
-import { currencyParts } from '../../../../components/spree/bulk-price-editor/currency-parts'
-import { normalizeMoneyInput } from '../../../../components/spree/bulk-price-editor/normalize-money'
import {
CustomFieldsInlineCard,
EditableApiCustomFieldsProvider,
} from '../../../../components/spree/custom-fields/custom-fields-inline'
+import { CustomerAddressesCard } from '../../../../components/spree/customers/customer-addresses-card'
+import { CustomerGroupsCard } from '../../../../components/spree/customers/customer-groups-card'
+import { CustomerInternalNoteCard } from '../../../../components/spree/customers/customer-internal-note-card'
+import { CustomerLastOrderCard } from '../../../../components/spree/customers/customer-last-order-card'
+import { CustomerLifetimeStatsCard } from '../../../../components/spree/customers/customer-lifetime-stats-card'
+import { CustomerOrdersCard } from '../../../../components/spree/customers/customer-orders-card'
+import { CustomerProfileCard } from '../../../../components/spree/customers/customer-profile-card'
+import { CustomerStoreCreditsCard } from '../../../../components/spree/customers/customer-store-credits-card'
+import { CustomerTaxIdentifiersCard } from '../../../../components/spree/customers/customer-tax-identifiers-card'
import { ResourceDetailSkeleton } from '../../../../components/spree/route-pending'
-import { TaxIdentifiersCard } from '../../../../components/spree/tax-identifiers-card'
-import { useCurrencyLocale } from '../../../../hooks/use-currency-locale'
-import {
- customerGroupAutocompleteProps,
- useCustomerGroups,
-} from '../../../../hooks/use-customer-groups'
-import {
- type StoreCreditUpdateParams,
- useCreateCustomerStoreCredit,
- useDeleteCustomerStoreCredit,
- useUpdateCustomerStoreCredit,
-} from '../../../../hooks/use-customer-store-credits'
-import {
- useCreateCustomerAddress,
- useCreateCustomerTaxIdentifier,
- useCustomer,
- useCustomerOrders,
- useCustomerTaxIdentifiers,
- useDeleteCustomer,
- useDeleteCustomerAddress,
- useDeleteCustomerTaxIdentifier,
- useUpdateCustomer,
- useUpdateCustomerAddress,
- useUpdateCustomerGroups,
- useUpdateCustomerTaxIdentifier,
- useValidateCustomerTaxIdentifier,
-} from '../../../../hooks/use-customers'
+import { useCustomer, useCustomerOrders, useDeleteCustomer } from '../../../../hooks/use-customers'
import { spreeJsonLinkResolver } from '../../../../lib/json-link-resolver'
-import {
- type CustomerProfileFormValues,
- customerProfileFormSchema,
-} from '../../../../schemas/customer'
-import {
- type EditStoreCreditFormValues,
- editStoreCreditFormSchema,
- type IssueStoreCreditFormValues,
- issueStoreCreditFormSchema,
-} from '../../../../schemas/store-credit'
export const Route = createFileRoute('/_authenticated/$storeId/customers/$customerId')({
component: CustomerDetailPage,
@@ -190,19 +89,19 @@ function CustomerBody({ customer }: { customer: Customer }) {
{deleteMutation.error && (
<p className="text-sm text-destructive">{(deleteMutation.error as Error).message}</p>
)}
- <LifetimeStatsCard customer={customer} />
+ <CustomerLifetimeStatsCard customer={customer} />
</>
}
main={
<>
- {lastCompletedOrder && <LastOrderCard order={lastCompletedOrder} />}
- <OrdersCard
+ {lastCompletedOrder && <CustomerLastOrderCard order={lastCompletedOrder} />}
+ <CustomerOrdersCard
customer={customer}
orders={orders}
totalCount={totalCount}
isLoading={isLoading}
/>
- <StoreCreditsCard customer={customer} />
+ <CustomerStoreCreditsCard customer={customer} />
<EditableApiCustomFieldsProvider
ownerType={Subject.Customer}
ownerId={customer.id}
@@ -221,1281 +120,14 @@ function CustomerBody({ customer }: { customer: Customer }) {
}
sidebar={
<>
- <ProfileCard customer={customer} />
+ <CustomerProfileCard customer={customer} />
<CustomerGroupsCard customer={customer} />
- <AddressesCard customer={customer} />
+ <CustomerAddressesCard customer={customer} />
<CustomerTaxIdentifiersCard customer={customer} />
- <InternalNoteCard customer={customer} />
+ <CustomerInternalNoteCard customer={customer} />
<Slot name="customer.form_sidebar" context={{ customer }} />
</>
}
/>
)
}
-
-// ---------------------------------------------------------------------------
-// Profile
-// ---------------------------------------------------------------------------
-
-function ProfileCard({ customer }: { customer: Customer }) {
- const { t } = useTranslation()
- const [editOpen, setEditOpen] = useState(false)
-
- return (
- <>
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.pages.customers.detail.section_profile')}</CardTitle>
- <CardAction>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setEditOpen(true)}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- </CardAction>
- </CardHeader>
- <CardContent className="flex flex-col gap-3">
- <div className="flex items-center gap-2 text-sm">
- <MailIcon className="size-4 text-muted-foreground" />
- <span>{customer.email}</span>
- </div>
- {customer.phone && (
- <div className="flex items-center gap-2 text-sm">
- <PhoneIcon className="size-4 text-muted-foreground" />
- <span>{customer.phone}</span>
- </div>
- )}
- <div className="flex items-center gap-2 text-sm">
- <StarIcon className="size-4 text-muted-foreground" />
- <span>
- {customer.accepts_email_marketing
- ? t('admin.customers.detail.subscribed_to_marketing')
- : t('admin.customers.detail.not_subscribed_to_marketing')}
- </span>
- </div>
- {customer.created_at && (
- <div className="text-xs text-muted-foreground">
- <RelativeTime
- iso={customer.created_at}
- prefix={t('admin.customers.detail.customer_since')}
- />
- </div>
- )}
- </CardContent>
- </Card>
- <EditProfileSheet customer={customer} open={editOpen} onOpenChange={setEditOpen} />
- </>
- )
-}
-
-function EditProfileSheet({
- customer,
- open,
- onOpenChange,
-}: {
- customer: Customer
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const form = useForm<CustomerProfileFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(customerProfileFormSchema) as any,
- defaultValues: {
- email: customer.email,
- first_name: customer.first_name ?? '',
- last_name: customer.last_name ?? '',
- phone: customer.phone ?? '',
- tags: customer.tags ?? [],
- accepts_email_marketing: customer.accepts_email_marketing,
- },
- })
- const { errors } = form.formState
- const mutation = useUpdateCustomer(customer.id)
-
- // Sheet stays mounted across opens; re-seed form with the latest server
- // values whenever the dialog re-opens or the underlying record refreshes,
- // so stale edits from a previous session are discarded.
- useEffect(() => {
- if (open) {
- form.reset({
- email: customer.email,
- first_name: customer.first_name ?? '',
- last_name: customer.last_name ?? '',
- phone: customer.phone ?? '',
- tags: customer.tags ?? [],
- accepts_email_marketing: customer.accepts_email_marketing,
- })
- }
- }, [open, customer, form])
-
- async function onSubmit(values: CustomerProfileFormValues) {
- try {
- await mutation.mutateAsync(values)
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.pages.customers.edit_sheet_title')}</SheetTitle>
- <SheetDescription>
- {t('admin.customers.detail.edit_profile_description')}
- </SheetDescription>
- </SheetHeader>
- <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- {errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {errors.root.message}
- </p>
- )}
- <FieldGroup>
- <Field>
- <FieldLabel htmlFor="email">{t('admin.fields.email.label')}</FieldLabel>
- <Input
- id="email"
- type="email"
- aria-invalid={!!errors.email || undefined}
- {...form.register('email')}
- />
- <FieldError errors={[errors.email]} />
- </Field>
- <Field>
- <FieldLabel htmlFor="first_name">{t('admin.fields.first_name.label')}</FieldLabel>
- <Input
- id="first_name"
- aria-invalid={!!errors.first_name || undefined}
- {...form.register('first_name')}
- />
- <FieldError errors={[errors.first_name]} />
- </Field>
- <Field>
- <FieldLabel htmlFor="last_name">{t('admin.fields.last_name.label')}</FieldLabel>
- <Input
- id="last_name"
- aria-invalid={!!errors.last_name || undefined}
- {...form.register('last_name')}
- />
- <FieldError errors={[errors.last_name]} />
- </Field>
- <Field>
- <FieldLabel htmlFor="phone">{t('admin.fields.phone.label')}</FieldLabel>
- <Input
- id="phone"
- aria-invalid={!!errors.phone || undefined}
- {...form.register('phone')}
- />
- <FieldError errors={[errors.phone]} />
- </Field>
- <Field>
- <FieldLabel>{t('admin.fields.customer.tags.label')}</FieldLabel>
- <Controller
- name="tags"
- control={form.control}
- render={({ field }) => (
- <TagCombobox
- taggableType={Subject.Customer}
- value={field.value}
- onChange={field.onChange}
- />
- )}
- />
- </Field>
- <Field>
- <div className="flex items-start justify-between gap-4">
- <FieldLabel htmlFor="accepts_email_marketing" className="cursor-pointer">
- {t('admin.fields.customer.accepts_email_marketing.label')}
- </FieldLabel>
- <Controller
- name="accepts_email_marketing"
- control={form.control}
- render={({ field }) => (
- <Checkbox
- id="accepts_email_marketing"
- checked={!!field.value}
- onCheckedChange={field.onChange}
- />
- )}
- />
- </div>
- </Field>
- </FieldGroup>
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={mutation.isPending}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={mutation.isPending}>
- {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Customer Groups
-// ---------------------------------------------------------------------------
-
-function CustomerGroupsCard({ customer }: { customer: Customer }) {
- const { t } = useTranslation()
- const [editOpen, setEditOpen] = useState(false)
- const groups = customer.customer_groups ?? []
-
- return (
- <>
- <Card>
- <CardHeader>
- <CardTitle>
- {t('admin.customers.detail.groups.title')}
- {groups.length > 0 && <Badge variant="outline">{groups.length}</Badge>}
- </CardTitle>
- <CardAction>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setEditOpen(true)}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- </CardAction>
- </CardHeader>
- <CardContent>
- {groups.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- {t('admin.customers.detail.groups.empty')}
- </p>
- ) : (
- <div className="flex flex-wrap gap-1.5">
- {groups.map((group) => (
- <Badge key={group.id} variant="secondary" className="gap-1.5">
- <UsersIcon className="size-3 text-muted-foreground" />
- {group.name}
- </Badge>
- ))}
- </div>
- )}
- </CardContent>
- </Card>
- <EditGroupsSheet customer={customer} open={editOpen} onOpenChange={setEditOpen} />
- </>
- )
-}
-
-function EditGroupsSheet({
- customer,
- open,
- onOpenChange,
-}: {
- customer: Customer
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const { storeId } = useStore()
- const currentIds = useMemo(() => customer.customer_group_ids ?? [], [customer.customer_group_ids])
- const [groupIds, setGroupIds] = useState<string[]>(currentIds)
- const [error, setError] = useState<string | null>(null)
-
- // Surface the store's groups on focus (preloaded, 5-min cache) and re-seed
- // the selection whenever the sheet re-opens so a prior cancelled edit or an
- // external membership change is reflected.
- const { data: groupsData } = useCustomerGroups()
- useEffect(() => {
- if (open) {
- setGroupIds(currentIds)
- setError(null)
- }
- }, [open, currentIds])
-
- // `customer_group_ids` is a collection setter on the customer: PATCH replaces
- // the whole membership in one request, so no add/remove diffing needed.
- const mutation = useUpdateCustomerGroups(customer.id)
- const isPending = mutation.isPending
-
- async function handleSave() {
- setError(null)
- try {
- await mutation.mutateAsync(groupIds)
- onOpenChange(false)
- } catch (err) {
- setError(err instanceof Error ? err.message : t('admin.customers.detail.groups.save_failed'))
- }
- }
-
- const dirty =
- groupIds.length !== currentIds.length || groupIds.some((id) => !currentIds.includes(id))
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.customers.detail.groups.edit_title')}</SheetTitle>
- <SheetDescription>{t('admin.customers.detail.groups.edit_description')}</SheetDescription>
- </SheetHeader>
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- {error && (
- <p className="text-sm text-destructive" role="alert">
- {error}
- </p>
- )}
- <Field>
- <FieldLabel>{t('admin.fields.customer.customer_groups.label')}</FieldLabel>
- <ResourceMultiAutocomplete
- {...customerGroupAutocompleteProps(`customer-detail-groups-picker-${storeId}`)}
- initialItems={groupsData?.data}
- value={groupIds}
- onChange={setGroupIds}
- />
- </Field>
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={isPending}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="button" onClick={handleSave} disabled={isPending || !dirty}>
- {isPending ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </SheetFooter>
- </SheetContent>
- </Sheet>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Lifetime Stats
-// ---------------------------------------------------------------------------
-
-function LifetimeStatsCard({ customer }: { customer: Customer }) {
- const { t } = useTranslation()
- const orders = customer.orders_count ?? 0
- const totalSpent = Number(customer.total_spent ?? '0')
- const aov = orders > 0 ? totalSpent / orders : 0
- const aovDisplay =
- orders > 0 && totalSpent > 0
- ? customer.display_total_spent?.replace(/[\d.,]+/, aov.toFixed(2))
- : '—'
-
- return (
- <Card>
- <CardContent className="grid grid-cols-2 lg:grid-cols-5 gap-6 py-6">
- <Stat
- label={t('admin.pages.customers.detail.stat_total_spent')}
- value={customer.display_total_spent ?? '—'}
- />
- <Stat label={t('admin.pages.customers.detail.stat_orders')} value={String(orders)} />
- <Stat
- label={t('admin.pages.customers.detail.stat_avg_order_value')}
- value={aovDisplay ?? '—'}
- />
- <Stat
- label={t('admin.pages.customers.detail.section_store_credit')}
- value={customer.display_available_store_credit_total ?? '—'}
- />
- <Stat
- label={t('admin.customers.detail.customer_since')}
- value={<RelativeTime iso={customer.created_at} />}
- />
- </CardContent>
- </Card>
- )
-}
-
-function Stat({ label, value }: { label: string; value: ReactNode }) {
- return (
- <div className="flex flex-col gap-1">
- <span className="text-sm text-muted-foreground">{label}</span>
- <span className="text-lg font-semibold">{value}</span>
- </div>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Last Order
-// ---------------------------------------------------------------------------
-
-function LastOrderCard({ order }: { order: Order }) {
- const { t } = useTranslation()
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.customers.detail.last_order_placed')}</CardTitle>
- </CardHeader>
- <CardContent className="p-0">
- <div className="border-t flex items-center justify-between px-6 py-3">
- <div>
- <Link
- to={'/$storeId/orders/$orderId' as string}
- params={{ orderId: order.id }}
- className="font-medium text-foreground no-underline"
- >
- #{order.number}
- </Link>
- <span className="ml-2 inline-flex gap-2">
- {order.payment_status && <StatusBadge status={order.payment_status} />}
- {order.fulfillment_status && <StatusBadge status={order.fulfillment_status} />}
- </span>
- {order.completed_at && (
- <div className="text-xs text-muted-foreground mt-1">
- <RelativeTime iso={order.completed_at} />
- </div>
- )}
- </div>
- <div className="font-semibold">{order.display_total}</div>
- </div>
- {order.items?.slice(0, 5).map((item) => (
- <div key={item.id} className="border-t flex items-center gap-3 px-6 py-3 text-sm">
- <Thumbnail src={item.thumbnail_url} />
- <div className="flex-1 min-w-0">
- <div className="truncate">{item.name}</div>
- {item.options_text && (
- <div className="text-xs text-muted-foreground truncate">{item.options_text}</div>
- )}
- </div>
- <div className="text-muted-foreground">×{item.quantity}</div>
- <div className="font-medium tabular-nums">{item.display_total}</div>
- </div>
- ))}
- </CardContent>
- </Card>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Orders
-// ---------------------------------------------------------------------------
-
-function OrdersCard({
- customer,
- orders,
- totalCount,
- isLoading,
-}: {
- customer: Customer
- orders: Order[]
- totalCount: number
- isLoading: boolean
-}) {
- const { t } = useTranslation()
- if (isLoading) {
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.pages.customers.detail.section_orders')}</CardTitle>
- </CardHeader>
- <CardContent>
- <p className="text-sm text-muted-foreground">{t('admin.common.loading')}</p>
- </CardContent>
- </Card>
- )
- }
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>
- {t('admin.pages.customers.detail.section_orders')}
- {totalCount > 0 && <Badge variant="outline">{totalCount}</Badge>}
- </CardTitle>
- {totalCount > orders.length && (
- <CardAction>
- <Link
- to={'/$storeId/orders' as string}
- search={{
- filters: [{ id: '1', field: 'user_id_eq', operator: 'eq', value: customer.id }],
- }}
- className="text-sm text-primary hover:underline"
- >
- {t('admin.actions.view_all')} →
- </Link>
- </CardAction>
- )}
- </CardHeader>
- {orders.length === 0 ? (
- <CardContent>
- <p className="text-sm text-muted-foreground">
- {t('admin.pages.customers.detail.orders_empty')}
- </p>
- </CardContent>
- ) : (
- <CardContent className="p-0">
- <Table roundedBottom>
- <TableHeader>
- <TableRow>
- <TableHead>{t('admin.customers.detail.orders_table.order')}</TableHead>
- <TableHead>{t('admin.customers.detail.orders_table.date')}</TableHead>
- <TableHead>{t('admin.fields.status.label')}</TableHead>
- <TableHead className="text-right">{t('admin.fields.total.label')}</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {orders.map((order: Order) => (
- <TableRow key={order.id}>
- <TableCell>
- <Link
- to={'/$storeId/orders/$orderId' as string}
- params={{ orderId: order.id }}
- className="font-medium text-foreground no-underline"
- >
- #{order.number}
- </Link>
- </TableCell>
- <TableCell className="text-muted-foreground">
- <RelativeTime iso={order.completed_at ?? order.created_at} />
- </TableCell>
- <TableCell>
- <span className="inline-flex gap-1">
- <StatusBadge status={order.status} />
- {order.payment_status && <StatusBadge status={order.payment_status} />}
- {order.fulfillment_status && (
- <StatusBadge status={order.fulfillment_status} />
- )}
- </span>
- </TableCell>
- <TableCell className="text-right font-medium tabular-nums">
- {order.display_total}
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </CardContent>
- )}
- </Card>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Internal Note
-// ---------------------------------------------------------------------------
-
-function InternalNoteCard({ customer }: { customer: Customer }) {
- const { t } = useTranslation()
- const [editing, setEditing] = useState(false)
- const [note, setNote] = useState(customer.internal_note_html ?? '')
- const serverNote = customer.internal_note_html ?? ''
-
- // Track the server value only while the editor is closed, so a refetch from
- // an unrelated mutation can't discard a note the user is part-way through.
- useEffect(() => {
- if (!editing) setNote(serverNote)
- }, [editing, serverNote])
-
- const mutation = useUpdateCustomer(customer.id)
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.pages.customers.detail.section_internal_note')}</CardTitle>
- {!editing && (
- <CardAction>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={() => setEditing(true)}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- </CardAction>
- )}
- </CardHeader>
- <CardContent>
- {editing ? (
- <div className="flex flex-col gap-3">
- <RichTextEditor
- ariaLabel={t('admin.pages.customers.detail.section_internal_note')}
- value={note}
- onChange={setNote}
- placeholder={t('admin.fields.customer.internal_note.placeholder')}
- />
- <div className="flex gap-2 justify-end">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => {
- setEditing(false)
- setNote(serverNote)
- }}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button
- type="button"
- size="sm"
- disabled={mutation.isPending}
- onClick={() =>
- mutation.mutate({ internal_note: note }, { onSuccess: () => setEditing(false) })
- }
- >
- {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </div>
- </div>
- ) : customer.internal_note_html ? (
- <div
- className="text-sm prose-sm"
- // biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is sanitized server-side via the rich-text pipeline
- dangerouslySetInnerHTML={{ __html: customer.internal_note_html }}
- />
- ) : (
- <p className="text-sm text-muted-foreground">
- {t('admin.customers.detail.no_internal_notes')}
- </p>
- )}
- </CardContent>
- </Card>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Tax identifiers
-// ---------------------------------------------------------------------------
-
-function CustomerTaxIdentifiersCard({ customer }: { customer: Customer }) {
- const { permissions } = usePermissions()
- const { data, isLoading } = useCustomerTaxIdentifiers(customer.id)
- const createMutation = useCreateCustomerTaxIdentifier(customer.id)
- const updateMutation = useUpdateCustomerTaxIdentifier(customer.id)
- const deleteMutation = useDeleteCustomerTaxIdentifier(customer.id)
- const validateMutation = useValidateCustomerTaxIdentifier(customer.id)
-
- return (
- <TaxIdentifiersCard
- identifiers={data?.data ?? []}
- isLoading={isLoading}
- canEdit={permissions.can('update', Subject.Customer)}
- mutations={{
- create: (params) => createMutation.mutateAsync(params),
- update: (id, params) => updateMutation.mutateAsync({ id, params }),
- remove: (id) => deleteMutation.mutateAsync(id),
- validate: (id) => validateMutation.mutateAsync(id),
- isValidating: validateMutation.isPending,
- }}
- />
- )
-}
-
-// ---------------------------------------------------------------------------
-// Addresses
-// ---------------------------------------------------------------------------
-
-function AddressesCard({ customer }: { customer: Customer }) {
- const { t } = useTranslation()
- const [addOpen, setAddOpen] = useState(false)
- const [editing, setEditing] = useState<Address | null>(null)
- const confirm = useConfirm()
- const addresses = useMemo(() => {
- const isDefault = (a: Address) => a.is_default_billing || a.is_default_shipping
- return [...(customer.addresses ?? [])].sort(
- (a, b) => Number(isDefault(b)) - Number(isDefault(a)),
- )
- }, [customer.addresses])
-
- const deleteMutation = useDeleteCustomerAddress(customer.id)
-
- const updateMutation = useUpdateCustomerAddress(customer.id)
- function setDefault(params: { id: string; kind: 'billing' | 'shipping' }) {
- return updateMutation.mutate({
- id: params.id,
- params: {
- [params.kind === 'billing' ? 'is_default_billing' : 'is_default_shipping']: true,
- },
- })
- }
-
- return (
- <>
- <Card>
- <CardHeader>
- <CardTitle>
- {t('admin.pages.customers.detail.section_addresses')}
- {addresses.length > 0 && <Badge variant="outline">{addresses.length}</Badge>}
- </CardTitle>
- <CardAction>
- <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>
- <PlusIcon className="size-4" />
- {t('admin.pages.customers.detail.add_address')}
- </Button>
- </CardAction>
- </CardHeader>
- {addresses.length === 0 ? (
- <CardContent>
- <p className="text-sm text-muted-foreground">
- {t('admin.pages.customers.detail.addresses_empty')}
- </p>
- </CardContent>
- ) : (
- <CardContent className="flex flex-col gap-3">
- {addresses.map((addr) => (
- <div
- key={addr.id}
- className="flex items-start justify-between gap-2 rounded-md border p-3"
- >
- <div className="text-sm">
- <div className="font-medium">
- {addr.full_name ?? '—'}
- <span className="ml-2 inline-flex gap-1">
- {addr.is_default_billing && (
- <Badge variant="outline">
- {t('admin.customers.detail.address.default_billing')}
- </Badge>
- )}
- {addr.is_default_shipping && (
- <Badge variant="outline">
- {t('admin.customers.detail.address.default_shipping')}
- </Badge>
- )}
- </span>
- </div>
- <div className="text-muted-foreground">{addr.address1}</div>
- {addr.address2 && <div className="text-muted-foreground">{addr.address2}</div>}
- <div className="text-muted-foreground">
- {[addr.city, addr.state_code, addr.postal_code].filter(Boolean).join(', ')} ·{' '}
- {addr.country_code}
- </div>
- {addr.phone && <div className="text-muted-foreground">{addr.phone}</div>}
- </div>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon-xs">
- <EllipsisVerticalIcon className="size-4" />
- <span className="sr-only">{t('admin.actions.actions_menu')}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => setEditing(addr)}>
- <PencilIcon className="size-4" />
- {t('admin.actions.edit')}
- </DropdownMenuItem>
- {!addr.is_default_billing && (
- <DropdownMenuItem
- onClick={() => setDefault({ id: addr.id, kind: 'billing' })}
- >
- {t('admin.customers.detail.address.set_default_billing')}
- </DropdownMenuItem>
- )}
- {!addr.is_default_shipping && (
- <DropdownMenuItem
- onClick={() => setDefault({ id: addr.id, kind: 'shipping' })}
- >
- {t('admin.customers.detail.address.set_default_shipping')}
- </DropdownMenuItem>
- )}
- <DropdownMenuItem
- className="text-destructive focus:text-destructive"
- onClick={async () => {
- if (
- await confirm({
- message: t('admin.customers.detail.address.delete_confirm_message'),
- variant: 'destructive',
- confirmLabel: t('admin.actions.delete'),
- })
- ) {
- deleteMutation.mutate(addr.id)
- }
- }}
- >
- <TrashIcon className="size-4" />
- {t('admin.actions.delete')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- ))}
- </CardContent>
- )}
- </Card>
-
- {addOpen && (
- <CustomerAddressDialog
- customer={customer}
- address={newAddressTemplate(customer)}
- onOpenChange={setAddOpen}
- title={t('admin.pages.customers.detail.add_address')}
- />
- )}
- {editing && (
- <CustomerAddressDialog
- customer={customer}
- address={editing}
- onOpenChange={(o) => {
- if (!o) setEditing(null)
- }}
- title={t('admin.pages.customers.detail.edit_address')}
- />
- )}
- </>
- )
-}
-
-function newAddressTemplate(customer: Customer): Address {
- return {
- first_name: customer.first_name ?? '',
- last_name: customer.last_name ?? '',
- phone: customer.phone ?? '',
- } as Address
-}
-
-function CustomerAddressDialog({
- customer,
- address,
- onOpenChange,
- title,
-}: {
- customer: Customer
- address: Address
- onOpenChange: (open: boolean) => void
- title: string
-}) {
- const { isLoading: countriesLoading } = useCountries()
- const isEdit = Boolean(address.id)
- const createMutation = useCreateCustomerAddress(customer.id)
- const updateMutation = useUpdateCustomerAddress(customer.id)
- const mutation = isEdit ? updateMutation : createMutation
-
- // Returns the promise so `AddressFormDialog` can map 422 errors onto fields.
- // Closes the sheet only on success.
- async function handleSave(params: AddressParams) {
- if (isEdit) {
- await updateMutation.mutateAsync({ id: address.id, params })
- } else {
- await createMutation.mutateAsync(params)
- }
- onOpenChange(false)
- }
-
- // Wait for countries before mounting so the country/state lazy initializer
- // can resolve the address's country_code/state_code to a real option.
- if (countriesLoading) return null
-
- return (
- <AddressFormDialog
- address={address}
- open
- onOpenChange={onOpenChange}
- onSave={handleSave}
- title={title}
- isPending={mutation.isPending}
- showLabel
- showDefaultFlags
- />
- )
-}
-
-// ---------------------------------------------------------------------------
-// Store Credits
-// ---------------------------------------------------------------------------
-
-function StoreCreditsCard({ customer }: { customer: Customer }) {
- const { t } = useTranslation()
- const [addOpen, setAddOpen] = useState(false)
- const [editing, setEditing] = useState<StoreCredit | null>(null)
- const confirm = useConfirm()
- const credits = customer.store_credits ?? []
-
- const deleteMutation = useDeleteCustomerStoreCredit(customer.id)
-
- return (
- <>
- <Card>
- <CardHeader>
- <CardTitle>
- {t('admin.customers.detail.store_credit.title')}
- {credits.length > 0 && <Badge>{credits.length}</Badge>}
- </CardTitle>
- <CardAction>
- <Button size="sm" variant="outline" onClick={() => setAddOpen(true)}>
- <PlusIcon className="size-4" />
- {t('admin.pages.customers.detail.issue_credit')}
- </Button>
- </CardAction>
- </CardHeader>
- {credits.length === 0 ? (
- <CardContent>
- <p className="text-sm text-muted-foreground">
- {t('admin.customers.detail.store_credit.empty')}
- </p>
- </CardContent>
- ) : (
- <CardContent className="p-0">
- <Table roundedBottom>
- <TableHeader>
- <TableRow>
- <TableHead>{t('admin.fields.amount.label')}</TableHead>
- <TableHead>{t('admin.customers.detail.store_credit.table.used')}</TableHead>
- <TableHead>{t('admin.customers.detail.store_credit.table.remaining')}</TableHead>
- <TableHead>{t('admin.customers.detail.store_credit.table.memo')}</TableHead>
- <TableHead className="w-10" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {credits.map((sc: StoreCredit) => (
- <TableRow key={sc.id}>
- <TableCell className="font-medium tabular-nums">
- {sc.display_amount ?? sc.amount}
- </TableCell>
- <TableCell className="tabular-nums">
- {sc.display_amount_used ?? sc.amount_used}
- </TableCell>
- <TableCell className="tabular-nums">
- {sc.display_amount_remaining ?? sc.amount_remaining}
- </TableCell>
- <TableCell className="text-muted-foreground">{sc.memo ?? '—'}</TableCell>
- <TableCell className="text-right">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="icon-xs">
- <EllipsisVerticalIcon className="size-4" />
- <span className="sr-only">{t('admin.actions.actions_menu')}</span>
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => setEditing(sc)}>
- <PencilIcon className="size-4" />
- {t('admin.actions.edit')}
- </DropdownMenuItem>
- <DropdownMenuItem
- className="text-destructive focus:text-destructive"
- onClick={async () => {
- if (
- await confirm({
- message: t(
- 'admin.customers.detail.store_credit.delete_confirm_message',
- ),
- variant: 'destructive',
- confirmLabel: t('admin.actions.delete'),
- })
- ) {
- deleteMutation.mutate(sc.id)
- }
- }}
- >
- <TrashIcon className="size-4" />
- {t('admin.actions.delete')}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </TableCell>
- </TableRow>
- ))}
- </TableBody>
- </Table>
- </CardContent>
- )}
- </Card>
-
- <IssueStoreCreditDialog customerId={customer.id} open={addOpen} onOpenChange={setAddOpen} />
- {editing && (
- <EditStoreCreditDialog
- customerId={customer.id}
- credit={editing}
- onOpenChange={(o) => {
- if (!o) setEditing(null)
- }}
- />
- )}
- </>
- )
-}
-
-function EditStoreCreditDialog({
- customerId,
- credit,
- onOpenChange,
-}: {
- customerId: string
- credit: StoreCredit
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- // Server rejects amount changes once any of it has been used. Lock the
- // field so the merchant doesn't submit a value that will only come back
- // as a 422 store_credit_in_use.
- const amountLocked = Number(credit.amount_used ?? 0) > 0
-
- const localeForCurrency = useCurrencyLocale()
- // Currency is locked on edit, so resolve its market locale once. The amount
- // hydrates from the canonical API value (`"50.00"`) but is displayed/edited
- // in that locale's format (`"50,00"` for EUR); on submit we normalize back to
- // canonical. Displaying in the same locale we normalize from keeps an
- // untouched amount from being mangled on save.
- const creditLocale = localeForCurrency(credit.currency) || 'en'
- const { decimal } = currencyParts(credit.currency, creditLocale)
-
- const form = useForm<EditStoreCreditFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(editStoreCreditFormSchema) as any,
- defaultValues: {
- amount: credit.amount ? credit.amount.replace('.', decimal) : '',
- memo: credit.memo ?? '',
- },
- })
- const { errors } = form.formState
-
- const mutation = useUpdateCustomerStoreCredit(customerId, credit.id)
-
- async function onSubmit(values: EditStoreCreditFormValues) {
- const params: StoreCreditUpdateParams = {}
-
- if (!amountLocked) {
- const amountValue = values.amount.toString().trim()
- // Normalize from the credit's display locale to the canonical
- // `"1234.56"` the API expects.
- if (amountValue) {
- params.amount = normalizeMoneyInput(amountValue, creditLocale)
- }
- }
-
- params.memo = values.memo
-
- try {
- await mutation.mutateAsync(params)
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- return (
- <Dialog open onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('admin.pages.customers.detail.edit_credit')}</DialogTitle>
- <DialogDescription>
- {t('admin.customers.detail.store_credit.edit_description')}
- </DialogDescription>
- </DialogHeader>
- <form onSubmit={form.handleSubmit(onSubmit)}>
- <DialogBody>
- {errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {errors.root.message}
- </p>
- )}
- <FieldGroup>
- <div className="grid grid-cols-2 gap-3">
- <Field>
- <FieldLabel htmlFor="edit-sc-amount">
- {t('admin.fields.store_credit.amount.label')}
- </FieldLabel>
- <Input
- id="edit-sc-amount"
- type="text"
- inputMode="decimal"
- disabled={amountLocked}
- aria-invalid={!!errors.amount || undefined}
- {...form.register('amount')}
- />
- <FieldError errors={[errors.amount]} />
- </Field>
- <Field>
- {/* Currency is locked: the API doesn't accept `currency`
- on update (changing it on a partially-used credit
- would invalidate amount_used / amount_remaining). We
- surface it disabled so the merchant always sees which
- currency the credit is in. */}
- <FieldLabel htmlFor="edit-sc-currency">
- {t('admin.fields.store_credit.currency.label')}
- </FieldLabel>
- <CurrencySelect id="edit-sc-currency" value={credit.currency} disabled />
- </Field>
- </div>
- <Field>
- <FieldLabel htmlFor="edit-sc-memo">
- {t('admin.fields.store_credit.memo.label')}
- </FieldLabel>
- <Textarea
- id="edit-sc-memo"
- rows={3}
- placeholder={t('admin.fields.store_credit.memo.placeholder')}
- aria-invalid={!!errors.memo || undefined}
- {...form.register('memo')}
- />
- <FieldError errors={[errors.memo]} />
- </Field>
- </FieldGroup>
- </DialogBody>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={mutation.isPending}>
- {mutation.isPending ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- )
-}
-
-function IssueStoreCreditDialog({
- customerId,
- open,
- onOpenChange,
-}: {
- customerId: string
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- // Seed `currency` with the store default so the merchant doesn't have to
- // pick one explicitly — `CurrencySelect` displays it but no longer commits
- // it via onChange, so the form value needs to start populated.
- const { defaultCurrency } = useStore()
- const form = useForm<IssueStoreCreditFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(issueStoreCreditFormSchema) as any,
- defaultValues: { amount: '', currency: defaultCurrency, memo: '' },
- })
- const { errors } = form.formState
-
- const mutation = useCreateCustomerStoreCredit(customerId)
- const localeForCurrency = useCurrencyLocale()
-
- // Clear any prior submission state when the dialog re-opens so a fresh form
- // is presented (otherwise stale "Issue $20" values linger across opens).
- useEffect(() => {
- if (open) {
- form.reset({ amount: '', currency: defaultCurrency, memo: '' })
- }
- }, [open, form, defaultCurrency])
-
- // Switching currency re-displays the amount in the new currency's locale
- // format, so the value the merchant sees always matches the locale it will be
- // normalized under on submit. Without this, `25.00` typed under USD would be
- // re-read under EUR's `de` locale (where `.` groups thousands) and persist as
- // 2500. Canonicalize from the old locale, then swap to the new locale's
- // decimal separator.
- function handleCurrencyChange(
- next: string,
- field: { value: string; onChange: (v: string) => void },
- ) {
- const prev = field.value
- field.onChange(next)
- const raw = form.getValues('amount')?.trim()
- if (!raw) return
- const canonical = normalizeMoneyInput(raw, localeForCurrency(prev) || 'en')
- const { decimal } = currencyParts(next, localeForCurrency(next) || 'en')
- form.setValue('amount', decimal === '.' ? canonical : canonical.replace('.', decimal))
- }
-
- async function onSubmit(values: IssueStoreCreditFormValues) {
- try {
- await mutation.mutateAsync({
- // Normalize the merchant's localized input (entered under the selected
- // currency's market locale) to the canonical `"1234.56"` the API
- // expects. The server never parses comma-vs-period.
- amount: normalizeMoneyInput(values.amount, localeForCurrency(values.currency) || 'en'),
- currency: values.currency,
- memo: values.memo || undefined,
- })
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('admin.pages.customers.detail.issue_credit')}</DialogTitle>
- <DialogDescription>
- {t('admin.customers.detail.store_credit.add_description')}
- </DialogDescription>
- </DialogHeader>
- <form onSubmit={form.handleSubmit(onSubmit)}>
- <DialogBody>
- {errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {errors.root.message}
- </p>
- )}
- <FieldGroup>
- <div className="grid grid-cols-2 gap-3">
- <Field>
- <FieldLabel htmlFor="sc-amount">
- {t('admin.fields.store_credit.amount.label')}
- </FieldLabel>
- <Input
- id="sc-amount"
- type="text"
- inputMode="decimal"
- required
- aria-invalid={!!errors.amount || undefined}
- {...form.register('amount')}
- />
- <FieldError errors={[errors.amount]} />
- </Field>
- <Field>
- <FieldLabel htmlFor="sc-currency">
- {t('admin.fields.store_credit.currency.label')}
- </FieldLabel>
- <Controller
- name="currency"
- control={form.control}
- render={({ field }) => (
- <CurrencySelect
- id="sc-currency"
- value={field.value || ''}
- onChange={(next) => handleCurrencyChange(next, field)}
- required
- />
- )}
- />
- </Field>
- </div>
- <Field>
- <FieldLabel htmlFor="sc-memo">
- {t('admin.fields.store_credit.memo.label')}
- </FieldLabel>
- <Textarea
- id="sc-memo"
- rows={3}
- placeholder={t('admin.fields.store_credit.memo.placeholder')}
- aria-invalid={!!errors.memo || undefined}
- {...form.register('memo')}
- />
- <FieldError errors={[errors.memo]} />
- </Field>
- </FieldGroup>
- </DialogBody>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={mutation.isPending}>
- {mutation.isPending
- ? t('admin.actions.saving')
- : t('admin.pages.customers.detail.issue_credit')}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsx
index 41de04bcbc..a72d856798 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/sellers/$sellerId.tsx
@@ -1,88 +1,39 @@
-import { zodResolver } from '@hookform/resolvers/zod'
import type { Seller } from '@spree/admin-sdk'
-import {
- adminClient,
- mapSpreeErrorsToForm,
- PageHeader,
- Slot,
- StoreDatePicker,
- Subject,
- usePermissions,
-} from '@spree/dashboard-core'
+import { adminClient, PageHeader, Slot, Subject, usePermissions } from '@spree/dashboard-core'
import {
Badge,
Button,
- Card,
- CardAction,
- CardContent,
- CardHeader,
- CardTitle,
DropdownMenuItem,
ErrorState,
- Field,
- FieldDescription,
- FieldError,
- FieldGroup,
- FieldLabel,
- Input,
- RelativeTime,
ResourceLayout,
- RichTextEditor,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Sheet,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
StatusBadge,
useConfirm,
} from '@spree/dashboard-ui'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import {
- BanIcon,
- MailIcon,
- PackageIcon,
- PauseIcon,
- PencilIcon,
- StoreIcon,
- UndoIcon,
- UsersIcon,
-} from 'lucide-react'
-import { type ReactNode, useEffect, useState } from 'react'
-import { Controller, useForm } from 'react-hook-form'
+import { BanIcon, MailIcon, PauseIcon, UndoIcon } from 'lucide-react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { ResourceImageField } from '../../../../components/spree/resource-image-field'
import { ResourceDetailSkeleton } from '../../../../components/spree/route-pending'
import { SellerAddressCard } from '../../../../components/spree/sellers/seller-address-card'
+import { SellerAtAGlanceCard } from '../../../../components/spree/sellers/seller-at-a-glance-card'
+import { SellerBrandCard } from '../../../../components/spree/sellers/seller-brand-card'
+import { SellerContactCard } from '../../../../components/spree/sellers/seller-contact-card'
+import { SellerEditProfileSheet } from '../../../../components/spree/sellers/seller-edit-profile-sheet'
+import { SellerEditSettlementSheet } from '../../../../components/spree/sellers/seller-edit-settlement-sheet'
+import { SellerInviteSheet } from '../../../../components/spree/sellers/seller-invite-sheet'
import { SellerOnboardingCard } from '../../../../components/spree/sellers/seller-onboarding-card'
+import { SellerSettlementCard } from '../../../../components/spree/sellers/seller-settlement-card'
+import { SellerStatusCard } from '../../../../components/spree/sellers/seller-status-card'
import { useSellerOnboarding } from '../../../../hooks/use-seller-requirements'
import {
useApproveSeller,
useDeleteSeller,
- useInviteSeller,
useRejectSeller,
useReopenSellerOnboarding,
useSeller,
useSuspendSeller,
- useUpdateSeller,
} from '../../../../hooks/use-sellers'
import { spreeJsonLinkResolver } from '../../../../lib/json-link-resolver'
-import {
- PAYOUT_INTERVALS,
- SELLER_DEFAULTS,
- type SellerFormValues,
- type SellerInviteValues,
- sellerFormSchema,
- sellerImageParams,
- sellerInviteSchema,
- sellerValuesToParams,
- TAX_REMITTANCES,
-} from '../../../../schemas/seller'
export const Route = createFileRoute('/_authenticated/$storeId/sellers/$sellerId')({
component: SellerDetailPage,
@@ -333,743 +284,17 @@ function SellerBody({ seller }: { seller: Seller }) {
}
/>
- <EditProfileSheet seller={seller} open={editingProfile} onOpenChange={setEditingProfile} />
- <EditSettlementSheet
+ <SellerEditProfileSheet
+ seller={seller}
+ open={editingProfile}
+ onOpenChange={setEditingProfile}
+ />
+ <SellerEditSettlementSheet
seller={seller}
open={editingSettlement}
onOpenChange={setEditingSettlement}
/>
- {inviting && <InviteSellerSheet seller={seller} open onOpenChange={setInviting} />}
+ {inviting && <SellerInviteSheet seller={seller} open onOpenChange={setInviting} />}
</>
)
}
-
-/** One labelled value in a sidebar card, with a placeholder when unset. */
-function ReadRow({ label, children }: { label: string; children: ReactNode }) {
- const { t } = useTranslation()
- return (
- <div className="flex items-start justify-between gap-3 text-sm">
- <span className="text-muted-foreground">{label}</span>
- <span className="text-right">
- {children ?? (
- <span className="text-muted-foreground">{t('admin.sellers.not_provided')}</span>
- )}
- </span>
- </div>
- )
-}
-
-/** Cover photo, logo and the seller's own description — the storefront face. */
-function SellerBrandCard({
- seller,
- canEdit,
- onEdit,
-}: {
- seller: Seller
- canEdit: boolean
- onEdit: () => void
-}) {
- const { t } = useTranslation()
-
- return (
- <Card className="overflow-hidden">
- {/* A seller with no cover gets a slim band rather than a tall empty
- block. It uses --accent rather than --muted: muted is a deliberate
- "whisper" against white, which over a region this size disappears
- entirely and leaves the logo looking unanchored. */}
- <div className="relative">
- {seller.cover_photo_url ? (
- <img src={seller.cover_photo_url} alt="" className="h-40 w-full bg-accent object-cover" />
- ) : (
- <div className="h-20 w-full border-border border-b bg-muted" />
- )}
- {canEdit && (
- <Button
- variant="ghost"
- size="icon-sm"
- className="absolute top-3 right-3 bg-background/80 backdrop-blur-sm hover:bg-background"
- onClick={onEdit}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- )}
- </div>
-
- {/* The logo straddles the band, so it needs more inset than CardContent's
- own padding gives — otherwise an 80px tile pulled up over a slim band
- reads as hanging off the card's corner. */}
- <CardContent className="flex flex-col gap-4 px-5 pb-5">
- {/* Positioned with its own z-index: the band above is `relative`, so a
- plain sibling paints underneath it and the band's edge cuts across
- the tile. The border belongs on the tile itself rather than a ring
- outside it, which over the band reads as a halo. */}
- <div className="-mt-10 relative z-10 flex size-20 items-center justify-center overflow-hidden rounded-xl border border-border bg-card shadow-sm">
- {/* The square logo is the one cropped for a tile like this; the main
- logo is the fallback, since a seller may have set only one. */}
- {seller.square_logo_url || seller.logo_url ? (
- <img
- src={seller.square_logo_url ?? seller.logo_url ?? undefined}
- alt=""
- className="size-full object-cover"
- />
- ) : (
- <StoreIcon className="size-7 text-muted-foreground" />
- )}
- </div>
-
- {/* The name already sits in the page header; repeating it here would
- just be the same words twice. The handle is what the header lacks. */}
- <p className="text-muted-foreground text-sm">/{seller.slug}</p>
-
- {seller.about_html ? (
- // Server-sanitized on every write path (Spree::RichTextSanitizer),
- // which is what makes rendering it here safe.
- <div
- className="prose prose-sm max-w-none dark:prose-invert"
- // biome-ignore lint/security/noDangerouslySetInnerHtml: sanitized server-side
- dangerouslySetInnerHTML={{ __html: seller.about_html }}
- />
- ) : (
- <p className="text-muted-foreground text-sm">{t('admin.sellers.detail.no_about')}</p>
- )}
- </CardContent>
- </Card>
- )
-}
-
-/** Where the seller is, and what that means in plain words. */
-function SellerStatusCard({ seller }: { seller: Seller }) {
- const { t } = useTranslation()
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.sellers.detail.status')}</CardTitle>
- <CardAction>
- <StatusBadge status={seller.status} label={t(`admin.sellers.status.${seller.status}`)} />
- </CardAction>
- </CardHeader>
- <CardContent className="flex flex-col gap-2">
- <p className="text-muted-foreground text-sm">
- {t(`admin.sellers.status_help.${seller.status}`, {
- defaultValue: t('admin.sellers.status_help.pending'),
- })}
- </p>
- {seller.on_holiday && (
- <p className="text-muted-foreground text-sm">{t('admin.sellers.on_holiday_notice')}</p>
- )}
- </CardContent>
- </Card>
- )
-}
-
-/** The counts an operator scans for before opening anything else. */
-function SellerAtAGlanceCard({ seller }: { seller: Seller }) {
- const { t } = useTranslation()
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.sellers.detail.at_a_glance')}</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-col gap-3">
- <div className="flex items-center justify-between text-sm">
- <span className="flex items-center gap-2 text-muted-foreground">
- <PackageIcon className="size-4" />
- {t('admin.sellers.products_column')}
- </span>
- <span>{seller.products_count}</span>
- </div>
- <div className="flex items-center justify-between text-sm">
- <span className="flex items-center gap-2 text-muted-foreground">
- <UsersIcon className="size-4" />
- {t('admin.sellers.team_column')}
- </span>
- <span>{seller.users_count}</span>
- </div>
- <ReadRow label={t('admin.fields.created_at.label')}>
- <RelativeTime iso={seller.created_at} />
- </ReadRow>
- </CardContent>
- </Card>
- )
-}
-
-function SellerContactCard({
- seller,
- canEdit,
- onEdit,
-}: {
- seller: Seller
- canEdit: boolean
- onEdit: () => void
-}) {
- const { t } = useTranslation()
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.sellers.detail.contact')}</CardTitle>
- {canEdit && (
- <CardAction>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={onEdit}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- </CardAction>
- )}
- </CardHeader>
- <CardContent className="flex flex-col gap-3">
- <ReadRow label={t('admin.fields.contact_email.label')}>
- {seller.contact_email ? (
- <a href={`mailto:${seller.contact_email}`}>{seller.contact_email}</a>
- ) : null}
- </ReadRow>
- <ReadRow label={t('admin.fields.seller.billing_email.label')}>
- {seller.billing_email ? (
- <a href={`mailto:${seller.billing_email}`}>{seller.billing_email}</a>
- ) : null}
- </ReadRow>
- </CardContent>
- </Card>
- )
-}
-
-/** Operator-only: how and when this seller gets paid, and who remits tax. */
-function SellerSettlementCard({
- seller,
- canEdit,
- onEdit,
-}: {
- seller: Seller
- canEdit: boolean
- onEdit: () => void
-}) {
- const { t } = useTranslation()
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.sellers.detail.settlement')}</CardTitle>
- {canEdit && (
- <CardAction>
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={onEdit}
- aria-label={t('admin.actions.edit')}
- >
- <PencilIcon className="size-4" />
- </Button>
- </CardAction>
- )}
- </CardHeader>
- <CardContent className="flex flex-col gap-3">
- <ReadRow label={t('admin.fields.seller.tax_remittance.label')}>
- {t(`admin.sellers.tax_remittance.${seller.tax_remittance}`, {
- defaultValue: seller.tax_remittance,
- })}
- </ReadRow>
- <ReadRow label={t('admin.fields.seller.payouts_schedule_interval.label')}>
- {seller.payouts_schedule_interval
- ? t(`admin.sellers.payout_interval.${seller.payouts_schedule_interval}`)
- : t('admin.sellers.payout_interval.inherit')}
- </ReadRow>
- <ReadRow label={t('admin.fields.seller.minimum_payout_amount.label')}>
- {seller.minimum_payout_amount}
- </ReadRow>
- <ReadRow label={t('admin.fields.seller.holiday_mode_until.label')}>
- {seller.holiday_mode_until ? <RelativeTime iso={seller.holiday_mode_until} /> : null}
- </ReadRow>
- </CardContent>
- </Card>
- )
-}
-
-/** The profile the seller also maintains from their own panel. */
-function EditProfileSheet({
- seller,
- open,
- onOpenChange,
-}: {
- seller: Seller
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const updateMutation = useUpdateSeller(seller.id)
-
- const form = useForm<SellerFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(sellerFormSchema) as any,
- defaultValues: SELLER_DEFAULTS,
- })
-
- // The sheet stays mounted across opens, so re-seed from the latest record
- // each time it opens rather than only on first mount.
- useEffect(() => {
- if (!open) return
-
- // Images reset to the empty triple: the persisted ones are passed to the
- // field as `serverUrl`, and the triple only carries what the operator
- // changes this time round.
- form.reset({
- ...SELLER_DEFAULTS,
- name: seller.name,
- slug: seller.slug,
- contact_email: seller.contact_email ?? '',
- billing_email: seller.billing_email ?? '',
- about: seller.about_html ?? '',
- })
- }, [open, seller, form])
-
- async function onSubmit(values: SellerFormValues) {
- try {
- // Only this sheet's own fields — the settlement sheet owns the rest, and
- // sending them here would post this form's untouched defaults over them.
- const params = sellerValuesToParams(values)
- await updateMutation.mutateAsync({
- ...sellerImageParams(values),
- name: params.name,
- slug: params.slug,
- contact_email: params.contact_email,
- billing_email: params.billing_email,
- about: params.about,
- })
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- const { errors } = form.formState
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.sellers.detail.edit_profile')}</SheetTitle>
- <SheetDescription>{t('admin.sellers.detail.edit_profile_description')}</SheetDescription>
- </SheetHeader>
- <form
- onSubmit={(event) => {
- form.handleSubmit(onSubmit)(event)
- event.stopPropagation()
- }}
- className="flex min-h-0 flex-1 flex-col"
- >
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- <FieldGroup>
- {errors.root?.message && (
- <p className="text-destructive text-sm" role="alert">
- {errors.root.message}
- </p>
- )}
- <ResourceImageField
- form={form}
- kind="logo"
- serverUrl={seller.logo_url}
- square
- translationNamespace="admin.sellers"
- labelKey="logo_label"
- helpKey="logo_help"
- />
- <ResourceImageField
- form={form}
- kind="square_logo"
- serverUrl={seller.square_logo_url}
- square
- translationNamespace="admin.sellers"
- labelKey="square_logo_label"
- helpKey="square_logo_help"
- />
- <ResourceImageField
- form={form}
- kind="cover_photo"
- serverUrl={seller.cover_photo_url}
- translationNamespace="admin.sellers"
- labelKey="cover_photo_label"
- helpKey="cover_photo_help"
- />
-
- <Field>
- <FieldLabel htmlFor="seller-name">{t('admin.fields.name.label')}</FieldLabel>
- <Input
- id="seller-name"
- aria-invalid={!!errors.name || undefined}
- {...form.register('name')}
- />
- <FieldError errors={[errors.name]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="seller-slug">{t('admin.fields.slug.label')}</FieldLabel>
- <Input
- id="seller-slug"
- aria-invalid={!!errors.slug || undefined}
- {...form.register('slug')}
- />
- <FieldDescription>{t('admin.fields.seller.slug.help')}</FieldDescription>
- <FieldError errors={[errors.slug]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="seller-contact-email">
- {t('admin.fields.contact_email.label')}
- </FieldLabel>
- <Input
- id="seller-contact-email"
- type="email"
- aria-invalid={!!errors.contact_email || undefined}
- {...form.register('contact_email')}
- />
- <FieldDescription>{t('admin.fields.seller.contact_email.help')}</FieldDescription>
- <FieldError errors={[errors.contact_email]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="seller-billing-email">
- {t('admin.fields.seller.billing_email.label')}
- </FieldLabel>
- <Input
- id="seller-billing-email"
- type="email"
- aria-invalid={!!errors.billing_email || undefined}
- {...form.register('billing_email')}
- />
- <FieldDescription>{t('admin.fields.seller.billing_email.help')}</FieldDescription>
- <FieldError errors={[errors.billing_email]} />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="seller-about">
- {t('admin.fields.seller.about.label')}
- </FieldLabel>
- <Controller
- control={form.control}
- name="about"
- render={({ field }) => (
- <RichTextEditor
- id="seller-about"
- ariaLabel={t('admin.fields.seller.about.label')}
- value={field.value ?? ''}
- onChange={field.onChange}
- />
- )}
- />
- <FieldDescription>{t('admin.fields.seller.about.help')}</FieldDescription>
- </Field>
- </FieldGroup>
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={form.formState.isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={form.formState.isSubmitting}>
- {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
- )
-}
-
-function EditSettlementSheet({
- seller,
- open,
- onOpenChange,
-}: {
- seller: Seller
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const updateMutation = useUpdateSeller(seller.id)
-
- const form = useForm<SellerFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(sellerFormSchema) as any,
- defaultValues: SELLER_DEFAULTS,
- })
-
- useEffect(() => {
- if (!open) return
-
- form.reset({
- ...SELLER_DEFAULTS,
- // Carried so the schema's required `name` still validates; the submit
- // below sends only this sheet's own fields.
- name: seller.name,
- tax_remittance: (seller.tax_remittance ?? 'seller') as SellerFormValues['tax_remittance'],
- payouts_schedule_interval: (seller.payouts_schedule_interval ??
- '') as SellerFormValues['payouts_schedule_interval'],
- minimum_payout_amount: seller.minimum_payout_amount ?? '',
- holiday_mode_until: seller.holiday_mode_until ?? '',
- })
- }, [open, seller, form])
-
- async function onSubmit(values: SellerFormValues) {
- try {
- const params = sellerValuesToParams(values)
- await updateMutation.mutateAsync({
- tax_remittance: params.tax_remittance,
- payouts_schedule_interval: params.payouts_schedule_interval,
- minimum_payout_amount: params.minimum_payout_amount,
- holiday_mode_until: params.holiday_mode_until,
- })
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- const { errors } = form.formState
-
- const remittanceOptions = TAX_REMITTANCES.map((value) => ({
- value,
- label: t(`admin.sellers.tax_remittance.${value}`),
- }))
- const intervalOptions = [
- { value: '', label: t('admin.sellers.payout_interval.inherit') },
- ...PAYOUT_INTERVALS.map((value) => ({
- value,
- label: t(`admin.sellers.payout_interval.${value}`),
- })),
- ]
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.sellers.detail.edit_settlement')}</SheetTitle>
- <SheetDescription>
- {t('admin.sellers.detail.edit_settlement_description')}
- </SheetDescription>
- </SheetHeader>
- <form
- onSubmit={(event) => {
- form.handleSubmit(onSubmit)(event)
- event.stopPropagation()
- }}
- className="flex min-h-0 flex-1 flex-col"
- >
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- <FieldGroup>
- {errors.root?.message && (
- <p className="text-destructive text-sm" role="alert">
- {errors.root.message}
- </p>
- )}
-
- <Field>
- <FieldLabel htmlFor="tax_remittance">
- {t('admin.fields.seller.tax_remittance.label')}
- </FieldLabel>
- <Controller
- name="tax_remittance"
- control={form.control}
- render={({ field }) => (
- <Select
- items={remittanceOptions}
- value={field.value ?? 'seller'}
- onValueChange={field.onChange}
- >
- <SelectTrigger id="tax_remittance" className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {remittanceOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- <FieldDescription>{t('admin.fields.seller.tax_remittance.help')}</FieldDescription>
- </Field>
-
- <Field>
- <FieldLabel htmlFor="payouts_schedule_interval">
- {t('admin.fields.seller.payouts_schedule_interval.label')}
- </FieldLabel>
- <Controller
- name="payouts_schedule_interval"
- control={form.control}
- render={({ field }) => (
- <Select
- items={intervalOptions}
- value={field.value ?? ''}
- onValueChange={field.onChange}
- >
- <SelectTrigger id="payouts_schedule_interval" className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {intervalOptions.map((option) => (
- <SelectItem key={option.value || 'inherit'} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- <FieldDescription>
- {t('admin.fields.seller.payouts_schedule_interval.help')}
- </FieldDescription>
- </Field>
-
- <Field>
- <FieldLabel htmlFor="minimum_payout_amount">
- {t('admin.fields.seller.minimum_payout_amount.label')}
- </FieldLabel>
- <Input
- id="minimum_payout_amount"
- inputMode="decimal"
- aria-invalid={!!errors.minimum_payout_amount || undefined}
- {...form.register('minimum_payout_amount')}
- />
- <FieldDescription>
- {t('admin.fields.seller.minimum_payout_amount.help')}
- </FieldDescription>
- <FieldError errors={[errors.minimum_payout_amount]} />
- </Field>
-
- <Field>
- <FieldLabel>{t('admin.fields.seller.holiday_mode_until.label')}</FieldLabel>
- <Controller
- name="holiday_mode_until"
- control={form.control}
- render={({ field }) => (
- <StoreDatePicker
- value={field.value || null}
- onChange={(next) => field.onChange(next ?? '')}
- placeholder={t('admin.fields.seller.holiday_mode_until.placeholder')}
- includeTime
- inline
- />
- )}
- />
- <FieldDescription>
- {t('admin.fields.seller.holiday_mode_until.help')}
- </FieldDescription>
- </Field>
- </FieldGroup>
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={form.formState.isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={form.formState.isSubmitting}>
- {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
- )
-}
-
-function InviteSellerSheet({
- seller,
- open,
- onOpenChange,
-}: {
- seller: Seller
- open: boolean
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const inviteMutation = useInviteSeller(seller.id)
- const form = useForm<SellerInviteValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(sellerInviteSchema) as any,
- defaultValues: { email: seller.contact_email ?? '' },
- })
-
- async function onSubmit(values: SellerInviteValues) {
- try {
- await inviteMutation.mutateAsync(values)
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- const { errors } = form.formState
-
- return (
- <Sheet open={open} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.sellers.invite_sheet.title')}</SheetTitle>
- <SheetDescription>{t('admin.sellers.invite_sheet.description')}</SheetDescription>
- </SheetHeader>
- <form
- onSubmit={(event) => {
- // This sheet renders inside the detail page's own tree; without
- // stopping the bubble the browser would submit an outer form.
- form.handleSubmit(onSubmit)(event)
- event.stopPropagation()
- }}
- className="flex min-h-0 flex-1 flex-col"
- >
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- <FieldGroup>
- {errors.root?.message && (
- <p className="text-destructive text-sm" role="alert">
- {errors.root.message}
- </p>
- )}
- <Field>
- <FieldLabel htmlFor="invite-email">{t('admin.fields.email.label')}</FieldLabel>
- <Input
- id="invite-email"
- type="email"
- autoFocus
- aria-invalid={!!errors.email || undefined}
- {...form.register('email')}
- />
- <FieldDescription>{t('admin.sellers.invite_sheet.email_help')}</FieldDescription>
- <FieldError errors={[errors.email]} />
- </Field>
- </FieldGroup>
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={form.formState.isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={form.formState.isSubmitting}>
- {form.formState.isSubmitting
- ? t('admin.actions.saving')
- : t('admin.sellers.actions.send_invitation')}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
- )
-}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsx
index ccdaa57054..2efb603ac7 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/api-keys.tsx
@@ -1,97 +1,24 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import { type ApiKey, type ApiKeyCreateParams, SpreeError } from '@spree/admin-sdk'
-import { mapSpreeErrorsToForm, PageHeader, usePermissions } from '@spree/dashboard-core'
-import {
- Badge,
- Button,
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- Checkbox,
- cn,
- Dialog,
- DialogBody,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- Empty,
- EmptyDescription,
- EmptyHeader,
- EmptyMedia,
- EmptyTitle,
- Field,
- FieldContent,
- FieldDescription,
- FieldError,
- FieldLabel,
- FieldTitle,
- Input,
- Popover,
- PopoverContent,
- PopoverTrigger,
- RadioGroup,
- RadioGroupItem,
- RelativeTime,
- RowActions,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Sheet,
- SheetContent,
- SheetDescription,
- SheetFooter,
- SheetHeader,
- SheetTitle,
- Skeleton,
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
- toastManager,
- useConfirm,
- useCopyToClipboard,
-} from '@spree/dashboard-ui'
+import type { ApiKey } from '@spree/admin-sdk'
+import { PageHeader } from '@spree/dashboard-core'
+import { Button } from '@spree/dashboard-ui'
import { createFileRoute } from '@tanstack/react-router'
-import type { TFunction } from 'i18next'
-import {
- AlertTriangleIcon,
- BanIcon,
- CheckIcon,
- CopyIcon,
- KeyRoundIcon,
- PencilIcon,
- PlusIcon,
-} from 'lucide-react'
-import { useEffect, useMemo, useState } from 'react'
-import { Controller, useForm } from 'react-hook-form'
+import { PlusIcon } from 'lucide-react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { z } from 'zod/v4'
-import { PermissionGrid } from '../../../../components/spree/permission-picker'
+import { CreateApiKeyDialog } from '../../../../components/spree/api-keys/api-key-create-sheet'
+import { EditApiKeyDialog } from '../../../../components/spree/api-keys/api-key-edit-sheet'
import {
- useApiKeys,
- useCreateApiKey,
- useDeleteApiKey,
- useRevokeApiKey,
- useUpdateApiKey,
-} from '../../../../hooks/use-api-keys'
+ PublishableApiKeyTable,
+ SecretApiKeyTable,
+} from '../../../../components/spree/api-keys/api-key-table'
+import { TokenRevealDialog } from '../../../../components/spree/api-keys/api-key-token-reveal-dialog'
+import { useApiKeys } from '../../../../hooks/use-api-keys'
import { useChannels } from '../../../../hooks/use-channels'
-import { usePermissionCatalog } from '../../../../hooks/use-roles'
export const Route = createFileRoute('/_authenticated/$storeId/settings/api-keys')({
component: ApiKeysSettingsPage,
})
-// ---------------------------------------------------------------------------
-// Page
-// ---------------------------------------------------------------------------
-
function ApiKeysSettingsPage() {
const { t } = useTranslation()
const { data, isLoading } = useApiKeys()
@@ -123,27 +50,14 @@ function ApiKeysSettingsPage() {
}
/>
- <ApiKeyTable
- title={t('admin.pages.settings.api_keys.publishable_section')}
- description={t('admin.pages.settings.api_keys.publishable_help')}
+ <PublishableApiKeyTable
keys={publishable}
loading={isLoading}
- showScopes={false}
- showChannel
- emptyMessage={t('admin.pages.settings.api_keys.empty_publishable')}
onEdit={setEditKey}
channelName={channelName}
/>
- <ApiKeyTable
- title={t('admin.pages.settings.api_keys.secret_section')}
- description={t('admin.pages.settings.api_keys.secret_help')}
- keys={secret}
- loading={isLoading}
- showScopes
- emptyMessage={t('admin.pages.settings.api_keys.empty_secret')}
- onEdit={setEditKey}
- />
+ <SecretApiKeyTable keys={secret} loading={isLoading} onEdit={setEditKey} />
<CreateApiKeyDialog
open={createOpen}
@@ -175,834 +89,3 @@ function ApiKeysSettingsPage() {
</div>
)
}
-
-// ---------------------------------------------------------------------------
-// Table
-// ---------------------------------------------------------------------------
-
-function ApiKeyTable({
- title,
- description,
- keys,
- loading,
- showScopes,
- showChannel = false,
- emptyMessage,
- onEdit,
- channelName,
-}: {
- title: string
- description: string
- keys: ApiKey[]
- loading: boolean
- showScopes: boolean
- showChannel?: boolean
- emptyMessage: string
- onEdit: (key: ApiKey) => void
- channelName?: (channelId: string | null) => string | undefined
-}) {
- const { t } = useTranslation()
- return (
- <Card>
- <CardHeader>
- <CardTitle>{title}</CardTitle>
- <p className="text-sm text-muted-foreground">{description}</p>
- </CardHeader>
- <CardContent className="p-0">
- {loading ? (
- <div className="p-4">
- <Skeleton className="h-10 w-full" />
- </div>
- ) : keys.length === 0 ? (
- <Empty>
- <EmptyHeader>
- <EmptyMedia variant="icon">
- <KeyRoundIcon />
- </EmptyMedia>
- <EmptyTitle>{emptyMessage}</EmptyTitle>
- <EmptyDescription>{t('admin.api_keys.empty_description')}</EmptyDescription>
- </EmptyHeader>
- </Empty>
- ) : (
- <Table roundedBottom>
- <TableHeader>
- <TableRow>
- <TableHead>{t('admin.fields.name.label')}</TableHead>
- <TableHead>{t('admin.pages.settings.api_keys.table.key')}</TableHead>
- {showScopes && (
- <TableHead>{t('admin.pages.settings.api_keys.table.scopes')}</TableHead>
- )}
- {showChannel && (
- <TableHead>{t('admin.pages.settings.api_keys.table.channel')}</TableHead>
- )}
- <TableHead>{t('admin.pages.settings.api_keys.table.last_used_at')}</TableHead>
- <TableHead>{t('admin.fields.created_at.label')}</TableHead>
- <TableHead className="w-12" />
- </TableRow>
- </TableHeader>
- <TableBody>
- {keys.map((key) => (
- <ApiKeyRow
- key={key.id}
- apiKey={key}
- showScopes={showScopes}
- showChannel={showChannel}
- onEdit={onEdit}
- channelName={channelName}
- />
- ))}
- </TableBody>
- </Table>
- )}
- </CardContent>
- </Card>
- )
-}
-
-function ApiKeyRow({
- apiKey,
- showScopes,
- onEdit,
- showChannel,
- channelName,
-}: {
- apiKey: ApiKey
- showScopes: boolean
- showChannel: boolean
- onEdit: (key: ApiKey) => void
- channelName?: (channelId: string | null) => string | undefined
-}) {
- const { t } = useTranslation()
- const revokeMutation = useRevokeApiKey()
- const deleteMutation = useDeleteApiKey()
- const confirm = useConfirm()
- const { copied, copy } = useCopyToClipboard()
-
- const isRevoked = !!apiKey.revoked_at
- // Publishable keys always carry their plaintext token (they're meant to be
- // exposed); secret keys only return `token_prefix` after the one-shot
- // create response.
- const visibleToken = apiKey.plaintext_token ?? apiKey.token_prefix ?? ''
- // Bound publishable keys show their channel; the name may not have loaded yet
- // (channels query pending) — fall back to nothing rather than the raw ID.
- const boundChannelName = channelName?.(apiKey.channel_id)
-
- async function handleRevoke() {
- const ok = await confirm({
- title: t('admin.api_keys.revoke_confirm.title'),
- message: t('admin.api_keys.revoke_confirm.message'),
- variant: 'destructive',
- confirmLabel: t('admin.actions.revoke'),
- })
- if (!ok) return
-
- try {
- await revokeMutation.mutateAsync(apiKey.id)
- toastManager.add({ type: 'success', title: t('admin.messages.key_revoked') })
- } catch (err) {
- toastManager.add({
- type: 'error',
- title: err instanceof Error ? err.message : t('admin.errors.failed_to_revoke_key'),
- })
- }
- }
-
- async function handleDelete() {
- const ok = await confirm({
- title: t('admin.api_keys.delete_confirm.title'),
- message: t('admin.api_keys.delete_confirm.message'),
- variant: 'destructive',
- confirmLabel: t('admin.actions.delete'),
- })
- if (!ok) return
-
- try {
- await deleteMutation.mutateAsync(apiKey.id)
- toastManager.add({ type: 'success', title: t('admin.messages.key_deleted') })
- } catch (err) {
- toastManager.add({
- type: 'error',
- title: err instanceof Error ? err.message : t('admin.api_keys.errors.failed_to_delete'),
- })
- }
- }
-
- return (
- <TableRow className={cn(isRevoked && 'opacity-60')}>
- <TableCell>
- <div className="flex items-center gap-2">
- <span className="font-medium">{apiKey.name}</span>
- {isRevoked && <Badge variant="destructive">{t('admin.api_keys.badge.revoked')}</Badge>}
- </div>
- </TableCell>
- <TableCell>
- <div className="flex items-center gap-1.5">
- <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{visibleToken}…</code>
- {apiKey.plaintext_token && (
- <Button
- size="icon-xs"
- variant="ghost"
- onClick={() => copy(apiKey.plaintext_token ?? '')}
- aria-label={t('admin.api_keys.dropdown.copy_token_aria')}
- >
- {copied ? <CheckIcon /> : <CopyIcon />}
- </Button>
- )}
- </div>
- </TableCell>
- {showScopes && (
- <TableCell>
- <ScopeList scopes={apiKey.scopes} />
- </TableCell>
- )}
- {showChannel && (
- <TableCell className="text-sm whitespace-nowrap">
- {boundChannelName ?? (
- <span className="text-muted-foreground">
- {t('admin.pages.settings.api_keys.table.all_channels')}
- </span>
- )}
- </TableCell>
- )}
- <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
- {/* `last_used_at` is throttled to update at most hourly (see
- ApiKeyAuthentication#touch_api_key_if_needed), so the timestamp
- won't be perfectly fresh — but it's accurate enough for "is this
- key still in use?" decisions. */}
- <RelativeTime
- iso={apiKey.last_used_at}
- fallback={
- <span className="text-muted-foreground/60">{t('admin.api_keys.badge.never_used')}</span>
- }
- />
- </TableCell>
- <TableCell className="text-sm text-muted-foreground whitespace-nowrap">
- <RelativeTime iso={apiKey.created_at} />
- {apiKey.created_by_email && (
- <div className="text-xs">
- {t('admin.api_keys.by_email', { email: apiKey.created_by_email })}
- </div>
- )}
- </TableCell>
- <TableCell className="text-right">
- <RowActions
- actions={[
- {
- key: 'edit',
- label: t('admin.actions.edit'),
- icon: <PencilIcon className="size-4" />,
- visible: !isRevoked,
- onSelect: () => onEdit(apiKey),
- },
- {
- key: 'revoke',
- label: t('admin.api_keys.dropdown.revoke'),
- icon: <BanIcon className="size-4" />,
- visible: !isRevoked,
- disabled: revokeMutation.isPending,
- onSelect: handleRevoke,
- },
- {
- key: 'delete',
- destructive: true,
- disabled: deleteMutation.isPending,
- onSelect: handleDelete,
- },
- ]}
- />
- </TableCell>
- </TableRow>
- )
-}
-
-// Maximum number of scope chips rendered inline before collapsing the rest
-// into a `+N` popover. Chosen so a typical row stays under one line at the
-// usual table widths.
-const SCOPE_PREVIEW_COUNT = 3
-
-function ScopeList({ scopes }: { scopes: string[] }) {
- const { t } = useTranslation()
- if (scopes.includes('write_all')) {
- return <Badge>{t('admin.pages.settings.api_keys.scope_badge.full_access')}</Badge>
- }
- if (scopes.includes('read_all')) {
- return <Badge>{t('admin.pages.settings.api_keys.scope_badge.read_all')}</Badge>
- }
- if (scopes.length === 0) {
- return <span className="text-sm text-muted-foreground">—</span>
- }
-
- const preview = scopes.slice(0, SCOPE_PREVIEW_COUNT)
- const overflow = scopes.slice(SCOPE_PREVIEW_COUNT)
-
- return (
- <div className="flex max-w-xs flex-wrap items-center gap-1">
- {preview.map((scope) => (
- <Badge key={scope} className="font-mono text-[10px]">
- {scope}
- </Badge>
- ))}
- {overflow.length > 0 && (
- <Popover>
- {/* `asChild` so the Badge itself becomes the click target — no
- extra button chrome around the chip. */}
- <PopoverTrigger asChild>
- <button
- type="button"
- className="cursor-pointer rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
- aria-label={t('admin.api_keys.scope_picker.show_more_aria', {
- count: overflow.length,
- })}
- >
- <Badge className="font-mono text-[10px] hover:bg-accent">+{overflow.length}</Badge>
- </button>
- </PopoverTrigger>
- <PopoverContent align="start" className="w-auto max-w-sm p-2">
- <div className="flex max-h-60 flex-col gap-1 overflow-y-auto">
- {scopes.map((scope) => (
- <Badge key={scope} className="self-start font-mono text-[10px]">
- {scope}
- </Badge>
- ))}
- </div>
- </PopoverContent>
- </Popover>
- )}
- </div>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Shared form pieces (create + edit sheets)
-// ---------------------------------------------------------------------------
-
-// The name field is identical across the create and edit sheets; both register
-// a `name` string field with the same label/placeholder/validation.
-function ApiKeyNameField({
- id,
- register,
- error,
-}: {
- id: string
- register: ReturnType<typeof useForm<{ name: string }>>['register']
- error?: { message?: string }
-}) {
- const { t } = useTranslation()
- return (
- <Field>
- <FieldLabel htmlFor={id}>{t('admin.fields.api_key.name.label')}</FieldLabel>
- <Input
- id={id}
- autoFocus
- placeholder={t('admin.fields.api_key.name.placeholder')}
- aria-invalid={!!error || undefined}
- {...register('name')}
- />
- <FieldError errors={[error]} />
- </Field>
- )
-}
-
-function FormErrorBanner({ message }: { message?: string }) {
- if (!message) return null
- return (
- <p className="text-sm text-destructive" role="alert">
- {message}
- </p>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Create dialog
-// ---------------------------------------------------------------------------
-
-// `channel_id` holds the raw channel selection: `''` means "All channels"
-// (store-wide) and is dropped on submit; a prefixed `ch_…` binds a publishable
-// key to that channel. Only publishable keys can bind — the value is ignored
-// (and never sent) for secret keys.
-const buildCreateSchema = (t: TFunction) =>
- z
- .object({
- name: z.string().min(1, t('admin.fields.api_key.name.required')),
- key_type: z.enum(['publishable', 'secret']),
- scopes: z.array(z.string()),
- channel_id: z.string(),
- })
- .refine((v) => v.key_type !== 'secret' || v.scopes.length > 0, {
- message: t('admin.api_keys.validation.scope_required'),
- path: ['scopes'],
- })
-
-type CreateFormValues = z.infer<ReturnType<typeof buildCreateSchema>>
-
-// Create UX is a side Sheet (not a Dialog) because the scope grid makes the
-// form taller than most viewports — Sheet handles overflow with internal
-// scroll and avoids the centered-modal "content cut off" problem.
-function CreateApiKeyDialog({
- open,
- onOpenChange,
- onCreated,
-}: {
- open: boolean
- onOpenChange: (open: boolean) => void
- onCreated: (key: ApiKey) => void
-}) {
- const { t } = useTranslation()
- const createMutation = useCreateApiKey()
-
- const form = useForm<CreateFormValues>({
- resolver: zodResolver(buildCreateSchema(t)),
- defaultValues: { name: '', key_type: 'secret', scopes: [], channel_id: '' },
- })
-
- const keyType = form.watch('key_type')
-
- async function onSubmit(values: CreateFormValues) {
- const isPublishable = values.key_type === 'publishable'
- const params: ApiKeyCreateParams = {
- name: values.name,
- key_type: values.key_type,
- scopes: isPublishable ? undefined : values.scopes,
- // Channel binding is publishable-only; omit for secret keys and for the
- // "All channels" default (empty string) so the key stays store-wide.
- channel_id: isPublishable && values.channel_id ? values.channel_id : undefined,
- }
- try {
- const key = await createMutation.mutateAsync(params)
- toastManager.add({ type: 'success', title: t('admin.messages.key_created') })
- form.reset({ name: '', key_type: 'secret', scopes: [], channel_id: '' })
- onCreated(key)
- } catch (err) {
- if (mapSpreeErrorsToForm(err, form.setError)) return
- if (err instanceof SpreeError) throw err
- toastManager.add({
- type: 'error',
- title: err instanceof Error ? err.message : t('admin.api_keys.errors.failed_to_create'),
- })
- }
- }
-
- return (
- <Sheet
- open={open}
- onOpenChange={(next) => {
- if (!next) form.reset({ name: '', key_type: 'secret', scopes: [], channel_id: '' })
- onOpenChange(next)
- }}
- >
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.api_keys.create_sheet_title')}</SheetTitle>
- <SheetDescription>{t('admin.api_keys.create_sheet_description')}</SheetDescription>
- </SheetHeader>
- <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
- {/* `flex-1 overflow-y-auto` keeps the footer pinned while the body
- scrolls when the scope grid overflows. */}
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- <FormErrorBanner message={form.formState.errors.root?.message} />
- <ApiKeyNameField
- id="api-key-name"
- register={form.register}
- error={form.formState.errors.name}
- />
-
- <Field>
- <FieldLabel>{t('admin.fields.api_key.key_type.label')}</FieldLabel>
- <Controller
- name="key_type"
- control={form.control}
- render={({ field }) => (
- <RadioGroup value={field.value} onValueChange={(value) => field.onChange(value)}>
- <KeyTypeChoice
- value="secret"
- title={t('admin.api_keys.key_type.secret_title')}
- description={t('admin.api_keys.key_type.secret_description')}
- />
- <KeyTypeChoice
- value="publishable"
- title={t('admin.api_keys.key_type.publishable_title')}
- description={t('admin.api_keys.key_type.publishable_description')}
- />
- </RadioGroup>
- )}
- />
- </Field>
-
- {keyType === 'publishable' && (
- <Field>
- <FieldLabel htmlFor="api-key-channel">
- {t('admin.fields.api_key.channel.label')}
- </FieldLabel>
- <Controller
- name="channel_id"
- control={form.control}
- render={({ field }) => (
- <ChannelBindingSelect
- id="api-key-channel"
- value={field.value}
- onChange={field.onChange}
- />
- )}
- />
- <p className="text-xs text-muted-foreground">
- {t('admin.fields.api_key.channel.help')}
- </p>
- </Field>
- )}
-
- {keyType === 'secret' && (
- <Field>
- <FieldLabel>{t('admin.fields.api_key.scopes.label')}</FieldLabel>
- <Controller
- name="scopes"
- control={form.control}
- render={({ field }) => (
- <ScopePicker value={field.value} onChange={field.onChange} />
- )}
- />
- {form.formState.errors.scopes && (
- <p className="text-sm text-destructive">{form.formState.errors.scopes.message}</p>
- )}
- </Field>
- )}
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={form.formState.isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={form.formState.isSubmitting}>
- {form.formState.isSubmitting
- ? t('admin.actions.creating')
- : t('admin.api_keys.create_key_cta')}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Edit sheet (name only — scopes are fixed for the life of a key)
-// ---------------------------------------------------------------------------
-
-type EditFormValues = { name: string }
-
-// Lifted dialog (one instance per page, driven by `apiKey`) — mirrors
-// TokenRevealDialog. Only `name` is editable; secret keys show their scopes
-// disabled since scopes are fixed for the life of a key.
-function EditApiKeyDialog({
- apiKey,
- onOpenChange,
-}: {
- apiKey: ApiKey | null
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const updateMutation = useUpdateApiKey()
-
- const form = useForm<EditFormValues>({
- resolver: zodResolver(
- z.object({ name: z.string().min(1, t('admin.fields.api_key.name.required')) }),
- ),
- defaultValues: { name: '' },
- })
-
- // Re-sync the form when a different key is opened. `defaultValues` alone won't
- // update across opens (the dialog is mounted once and reused), so reset
- // explicitly when the key changes.
- useEffect(() => {
- if (apiKey) form.reset({ name: apiKey.name })
- }, [apiKey, form])
-
- async function onSubmit(values: EditFormValues) {
- if (!apiKey) return
- try {
- await updateMutation.mutateAsync({ id: apiKey.id, params: { name: values.name } })
- toastManager.add({ type: 'success', title: t('admin.messages.key_updated') })
- onOpenChange(false)
- } catch (err) {
- if (mapSpreeErrorsToForm(err, form.setError)) return
- if (err instanceof SpreeError) throw err
- toastManager.add({
- type: 'error',
- title: err instanceof Error ? err.message : t('admin.api_keys.errors.failed_to_update'),
- })
- }
- }
-
- return (
- <Sheet open={!!apiKey} onOpenChange={onOpenChange}>
- <SheetContent>
- <SheetHeader>
- <SheetTitle>{t('admin.api_keys.edit_sheet_title')}</SheetTitle>
- <SheetDescription>{t('admin.api_keys.edit_sheet_description')}</SheetDescription>
- </SheetHeader>
- <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- <FormErrorBanner message={form.formState.errors.root?.message} />
- <ApiKeyNameField
- id="edit-api-key-name"
- register={form.register}
- error={form.formState.errors.name}
- />
-
- {apiKey?.key_type === 'secret' && apiKey.scopes.length > 0 && (
- <Field>
- <FieldLabel>{t('admin.fields.api_key.scopes.label')}</FieldLabel>
- {/* Scopes are fixed for the life of a key — rendered disabled.
- To change authority, create a new key and revoke this one. */}
- <ScopePicker value={apiKey.scopes} disabled />
- <p className="text-xs text-muted-foreground">
- {t('admin.api_keys.scopes_immutable_help')}
- </p>
- </Field>
- )}
- </div>
- <SheetFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => onOpenChange(false)}
- disabled={form.formState.isSubmitting}
- >
- {t('admin.actions.cancel')}
- </Button>
- <Button type="submit" disabled={form.formState.isSubmitting}>
- {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
- )
-}
-
-// Sentinel for the "All channels" (store-wide) option. Base UI's `<Select>`
-// treats an empty string value as "no selection" and shows the placeholder, so
-// the store-wide choice carries this non-empty value and is mapped back to `''`
-// (the schema's store-wide value) at the boundary.
-const ALL_CHANNELS = '__all__'
-
-// Channel binding picker for publishable keys. Unlike the shared
-// `<ChannelSelect>`, the first option is "All channels" (store-wide) so a key
-// can be left unbound, which is the default. Emits `''` for store-wide and a
-// prefixed `ch_…` for a bound channel.
-function ChannelBindingSelect({
- id,
- value,
- onChange,
-}: {
- id: string
- value: string
- onChange: (channelId: string) => void
-}) {
- const { t } = useTranslation()
- const { data } = useChannels()
- const channels = data?.data ?? []
-
- const allChannelsLabel = t('admin.fields.api_key.channel.all_channels')
-
- return (
- <Select
- value={value === '' ? ALL_CHANNELS : value}
- onValueChange={(v) => onChange(v === ALL_CHANNELS ? '' : v)}
- >
- <SelectTrigger id={id}>
- {/* Base UI's `<SelectValue>` renders the raw value (the prefixed ID);
- the children render-prop resolves the channel name from the cached
- list so the trigger matches the selected item. */}
- <SelectValue>
- {(v) =>
- v === ALL_CHANNELS
- ? allChannelsLabel
- : (channels.find((c) => c.id === v)?.name ?? allChannelsLabel)
- }
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={ALL_CHANNELS}>{allChannelsLabel}</SelectItem>
- {channels.map((c) => (
- <SelectItem key={c.id} value={c.id}>
- {c.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )
-}
-
-function KeyTypeChoice({
- value,
- title,
- description,
-}: {
- value: 'publishable' | 'secret'
- title: string
- description: string
-}) {
- return (
- <FieldLabel>
- <Field orientation="horizontal">
- <FieldContent>
- <FieldTitle>{title}</FieldTitle>
- <FieldDescription>{description}</FieldDescription>
- </FieldContent>
- <RadioGroupItem value={value} />
- </Field>
- </FieldLabel>
- )
-}
-
-// `disabled` renders the whole picker read-only — used when editing an existing
-// key, whose scopes are fixed for its lifetime (the server rejects scope edits).
-function ScopePicker({
- value,
- onChange,
- disabled = false,
-}: {
- value: string[]
- onChange?: (next: string[]) => void
- disabled?: boolean
-}) {
- const { t } = useTranslation()
- const { data: catalog } = usePermissionCatalog()
- const { permissionKeys } = usePermissions()
- const hasWriteAll = value.includes('write_all')
- const hasReadAll = value.includes('read_all')
-
- // A staffer can only mint scopes within their own grant (the server's
- // anti-amplification guard) — don't offer keys it would reject. A caller
- // holding the whole catalog (admin) is unrestricted, including the aliases.
- const blockedKeys = useMemo(() => {
- if (!catalog) return undefined
- const blocked = new Set(
- catalog.data.filter((entry) => !permissionKeys.includes(entry.key)).map((entry) => entry.key),
- )
- return blocked.size > 0 ? blocked : undefined
- }, [catalog, permissionKeys])
- const writeAllBlocked = blockedKeys !== undefined
- const readAllBlocked =
- !!catalog &&
- catalog.data.some((entry) => entry.kind === 'read' && !permissionKeys.includes(entry.key))
-
- function setAllRead(checked: boolean) {
- let next = value.filter((v) => v !== 'read_all' && !v.startsWith('read_'))
- if (checked) next = [...next, 'read_all']
- onChange?.(next)
- }
-
- function setAllWrite(checked: boolean) {
- let next = value.filter((v) => v !== 'write_all' && !v.startsWith('write_'))
- if (checked) next = [...next, 'write_all']
- onChange?.(next)
- }
-
- return (
- <div className={cn('flex flex-col gap-3', disabled && 'opacity-70')}>
- {/* Quick access: write_all / read_all toggles. Selecting one blocks the
- per-resource grid because the catch-all already covers it. */}
- <div className="flex flex-col gap-2 rounded-md border border-border bg-muted/30 p-3">
- <label htmlFor="scope-write-all" className="flex cursor-pointer items-center gap-2 text-sm">
- <Checkbox
- id="scope-write-all"
- checked={hasWriteAll}
- onCheckedChange={setAllWrite}
- disabled={disabled || writeAllBlocked}
- />
- <span className="font-medium">{t('admin.api_keys.scope_picker.full_access_label')}</span>
- <span className="text-xs text-muted-foreground">
- {t('admin.api_keys.scope_picker.full_access_hint')}
- </span>
- </label>
- <label htmlFor="scope-read-all" className="flex cursor-pointer items-center gap-2 text-sm">
- <Checkbox
- id="scope-read-all"
- checked={hasReadAll}
- onCheckedChange={setAllRead}
- disabled={disabled || hasWriteAll || readAllBlocked}
- />
- <span className="font-medium">{t('admin.api_keys.scope_picker.read_all_label')}</span>
- <span className="text-xs text-muted-foreground">
- {t('admin.api_keys.scope_picker.read_all_hint')}
- </span>
- </label>
- </div>
-
- <div
- className={cn(!disabled && (hasWriteAll || hasReadAll) && 'pointer-events-none opacity-50')}
- >
- {catalog ? (
- <PermissionGrid
- entries={catalog.data}
- value={value}
- onChange={(next) => onChange?.(next)}
- disabled={disabled}
- disabledKeys={blockedKeys}
- />
- ) : (
- <div className="flex flex-col gap-2 p-3">
- <Skeleton className="h-6 w-full" />
- <Skeleton className="h-6 w-full" />
- <Skeleton className="h-6 w-full" />
- </div>
- )}
- </div>
- </div>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Token reveal dialog (one-shot, on create)
-// ---------------------------------------------------------------------------
-
-function TokenRevealDialog({
- apiKey,
- onOpenChange,
-}: {
- apiKey: ApiKey | null
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- const { copied, copy } = useCopyToClipboard()
-
- return (
- <Dialog open={!!apiKey} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('admin.pages.settings.api_keys.save_secret_title')}</DialogTitle>
- <DialogDescription>
- {t('admin.pages.settings.api_keys.save_secret_description')}
- </DialogDescription>
- </DialogHeader>
- <DialogBody className="flex flex-col gap-3">
- <div className="flex items-start gap-2 rounded-md border border-yellow-200 bg-yellow-50 p-3 text-sm text-yellow-900 dark:border-yellow-900/40 dark:bg-yellow-950/40 dark:text-yellow-200">
- <AlertTriangleIcon className="size-4 shrink-0" />
- <span>{t('admin.api_keys.warning_treat_like_password')}</span>
- </div>
- {apiKey?.plaintext_token && (
- <div className="flex items-center gap-2 rounded-md border border-border bg-muted/40 p-3">
- <code className="flex-1 truncate font-mono text-sm">{apiKey.plaintext_token}</code>
- <Button
- size="sm"
- variant="outline"
- onClick={() => copy(apiKey.plaintext_token ?? '')}
- >
- {copied ? <CheckIcon /> : <CopyIcon />}
- {copied ? t('admin.actions.copied') : t('admin.actions.copy')}
- </Button>
- </div>
- )}
- </DialogBody>
- <DialogFooter>
- <Button onClick={() => onOpenChange(false)}>{t('admin.actions.done')}</Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsx
index 13d4f23312..42cb86341a 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-profiles/$profileId/index.tsx
@@ -1,91 +1,17 @@
-import { zodResolver } from '@hookform/resolvers/zod'
-import type {
- DeliveryMethod,
- DeliveryOriginGroup,
- DeliveryProfile,
- DeliveryZone,
- DeliveryZoneMember,
-} from '@spree/admin-sdk'
-import {
- adminClient,
- Can,
- mapSpreeErrorsToForm,
- PageHeader,
- Subject,
- usePermissions,
- useStore,
-} from '@spree/dashboard-core'
-import {
- Badge,
- Button,
- Card,
- CardContent,
- CardHeader,
- CardTitle,
- Checkbox,
- ErrorState,
- Field,
- FieldError,
- FieldLabel,
- Input,
- ResourceLayout,
- RowActions,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
- useConfirm,
-} from '@spree/dashboard-ui'
+import type { DeliveryProfile } from '@spree/admin-sdk'
+import { adminClient, PageHeader } from '@spree/dashboard-core'
+import { ErrorState, ResourceLayout, useConfirm } from '@spree/dashboard-ui'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import {
- GlobeIcon,
- MapIcon,
- PlusIcon,
- SplitIcon,
- StoreIcon,
- TruckIcon,
- WarehouseIcon,
- ZapIcon,
-} from 'lucide-react'
-import { useMemo, useState } from 'react'
-import { Controller, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
-import { DeliveryMethodSheet } from '../../../../../../components/spree/shipping/delivery-method-sheet'
-import { DeliveryOriginGroupDialog } from '../../../../../../components/spree/shipping/delivery-origin-group-dialog'
-import { DeliveryZoneSheet } from '../../../../../../components/spree/shipping/delivery-zone-sheet'
-import { StockLocationScopeField } from '../../../../../../components/spree/shipping/stock-location-scope-field'
-import {
- useAllDeliveryMethods,
- useDeleteDeliveryMethod,
- useDeliveryRateProviders,
-} from '../../../../../../hooks/use-delivery-methods'
-import { useDeleteDeliveryOriginGroup } from '../../../../../../hooks/use-delivery-origin-groups'
+import { DeliveryProfileGeneralCard } from '../../../../../../components/spree/shipping/delivery-profile-general-card'
+import { DeliveryProfileOriginsCard } from '../../../../../../components/spree/shipping/delivery-profile-origins-card'
+import { DeliveryZonesAndMethodsSection } from '../../../../../../components/spree/shipping/delivery-zones-and-methods-section'
import {
useDeleteDeliveryProfile,
useDeliveryProfile,
- useUpdateDeliveryProfile,
} from '../../../../../../hooks/use-delivery-profiles'
-import {
- useDeleteDeliveryZone,
- useProfileDeliveryZones,
-} from '../../../../../../hooks/use-delivery-zones'
-import {
- useStockLocations,
- useUpdateStockLocationById,
-} from '../../../../../../hooks/use-stock-locations'
-import {
- flatAmount,
- formatAmount,
- summarizeRules,
-} from '../../../../../../lib/delivery-method-summary'
import { spreeJsonLinkResolver } from '../../../../../../lib/json-link-resolver'
-import {
- type DeliveryProfileGeneralValues,
- type DeliveryProfileLocationsValues,
- deliveryProfileGeneralSchema,
- deliveryProfileLocationsSchema,
- deliveryProfileLocationsToParams,
-} from '../../../../../../schemas/delivery-profile'
/**
* The method sheet is driven from the URL so a deep link opens it over a live
@@ -99,8 +25,6 @@ const profileDetailSearchSchema = z.object({
provider: z.enum(['pickup', 'digital']).optional(),
})
-type ProfileDetailSearch = z.infer<typeof profileDetailSearchSchema>
-
export const Route = createFileRoute(
'/_authenticated/$storeId/settings/delivery-profiles/$profileId/',
)({
@@ -108,52 +32,6 @@ export const Route = createFileRoute(
component: DeliveryProfileDetailPage,
})
-/**
- * Opens the method sheet for an existing method, or for a new one.
- *
- * Every move replaces the history entry rather than pushing one. The sheet
- * lives in the URL so a deep link reopens it, but opening and closing one is
- * not a place a merchant navigated to — pushing would leave the page's back
- * arrow walking through sheets they already dismissed instead of returning to
- * the profile list.
- */
-function useMethodSheetNavigation() {
- const navigate = useNavigate()
-
- const openMethod = (methodId: string) =>
- navigate({
- replace: true,
- search: (prev: Record<string, unknown>) => {
- const { zone: _z, group: _g, provider: _p, ...rest } = prev
- return { ...rest, method: methodId } as never
- },
- })
-
- const openNewMethod = (options: { zone?: string; group?: string; provider?: string } = {}) =>
- navigate({
- replace: true,
- search: (prev: Record<string, unknown>) =>
- ({
- ...prev,
- method: 'new',
- ...(options.zone ? { zone: options.zone } : { zone: undefined }),
- ...(options.group ? { group: options.group } : { group: undefined }),
- ...(options.provider ? { provider: options.provider } : { provider: undefined }),
- }) as never,
- })
-
- const closeMethodSheet = () =>
- navigate({
- replace: true,
- search: (prev: Record<string, unknown>) => {
- const { method: _m, zone: _z, group: _g, provider: _p, ...rest } = prev
- return rest as never
- },
- })
-
- return { openMethod, openNewMethod, closeMethodSheet }
-}
-
function DeliveryProfileDetailPage() {
const { t } = useTranslation()
const { profileId } = Route.useParams()
@@ -177,6 +55,7 @@ function DeliveryProfileDetailPage() {
function DeliveryProfileDetailBody({ profile }: { profile: DeliveryProfile }) {
const { t } = useTranslation()
const { storeId } = Route.useParams()
+ const search = Route.useSearch()
const navigate = useNavigate()
const confirm = useConfirm()
const deleteMutation = useDeleteDeliveryProfile()
@@ -210,944 +89,13 @@ function DeliveryProfileDetailBody({ profile }: { profile: DeliveryProfile }) {
deleteLabel={t('admin.delivery_profiles.detail.delete_label')}
/>
}
- main={<ZonesAndMethodsSection profile={profile} />}
+ main={<DeliveryZonesAndMethodsSection profile={profile} search={search} />}
sidebar={
<>
- <GeneralCard profile={profile} />
- <OriginsCard profile={profile} />
+ <DeliveryProfileGeneralCard profile={profile} />
+ <DeliveryProfileOriginsCard profile={profile} />
</>
}
/>
)
}
-
-// ---------------------------------------------------------------------------
-// General — name, kind, and promotion to store default
-// ---------------------------------------------------------------------------
-
-function GeneralCard({ profile }: { profile: DeliveryProfile }) {
- const { t } = useTranslation()
- const confirm = useConfirm()
- const updateMutation = useUpdateDeliveryProfile(profile.id)
-
- const form = useForm<DeliveryProfileGeneralValues>({
- resolver: zodResolver(deliveryProfileGeneralSchema),
- defaultValues: { name: profile.name },
- values: { name: profile.name },
- resetOptions: { keepDirtyValues: true },
- })
-
- async function onSubmit(values: DeliveryProfileGeneralValues) {
- try {
- await updateMutation.mutateAsync({ name: values.name })
- form.reset(values)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- async function handleMakeDefault() {
- const ok = await confirm({
- title: t('admin.delivery_profiles.default_confirm.title'),
- message: t('admin.delivery_profiles.default_confirm.message', { name: profile.name }),
- confirmLabel: t('admin.delivery_profiles.make_default'),
- })
- if (!ok) return
- await updateMutation.mutateAsync({ default: true }).catch(() => undefined)
- }
-
- const { errors } = form.formState
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.delivery_profiles.detail.general_title')}</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-col gap-4">
- {errors.root?.message && (
- <p className="text-sm text-destructive" role="alert">
- {errors.root.message}
- </p>
- )}
- <Field>
- <FieldLabel htmlFor="profile-name">{t('admin.fields.name.label')}</FieldLabel>
- <Input
- id="profile-name"
- aria-invalid={!!errors.name || undefined}
- {...form.register('name')}
- />
- <FieldError errors={[errors.name]} />
- </Field>
-
- <Field>
- <FieldLabel>{t('admin.fields.delivery_profile.kind.label')}</FieldLabel>
- <div>
- <Badge variant="outline">
- {t(`admin.delivery_profiles.kinds.${profile.kind}`, {
- defaultValue: profile.kind,
- })}
- </Badge>
- </div>
- <span className="text-muted-foreground text-xs">
- {t('admin.delivery_profiles.kind_immutable_hint')}
- </span>
- </Field>
-
- <Field>
- <FieldLabel>{t('admin.delivery_profiles.default_badge')}</FieldLabel>
- {profile.default ? (
- <span className="text-muted-foreground text-xs">
- {t('admin.delivery_profiles.is_default_hint')}
- </span>
- ) : (
- <Can I="update" a={Subject.DeliveryProfile}>
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="self-start"
- onClick={handleMakeDefault}
- disabled={updateMutation.isPending}
- >
- {t('admin.delivery_profiles.make_default')}
- </Button>
- </Can>
- )}
- </Field>
-
- <Can I="update" a={Subject.DeliveryProfile}>
- <Button
- type="button"
- size="sm"
- className="self-start"
- onClick={form.handleSubmit(onSubmit)}
- disabled={form.formState.isSubmitting || !form.formState.isDirty}
- >
- {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </Can>
- </CardContent>
- </Card>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Origins — which stock locations this profile ships from
-// ---------------------------------------------------------------------------
-
-function OriginsCard({ profile }: { profile: DeliveryProfile }) {
- const { t } = useTranslation()
- const updateMutation = useUpdateDeliveryProfile(profile.id)
- const { data: stockLocations } = useStockLocations()
-
- const initial: DeliveryProfileLocationsValues = {
- scope: profile.stock_location_ids.length === 0 ? 'all' : 'selected',
- stock_location_ids: profile.stock_location_ids,
- }
-
- const form = useForm<DeliveryProfileLocationsValues>({
- resolver: zodResolver(deliveryProfileLocationsSchema),
- defaultValues: initial,
- values: initial,
- resetOptions: { keepDirtyValues: true },
- })
-
- const scope = form.watch('scope')
-
- async function onSubmit(values: DeliveryProfileLocationsValues) {
- try {
- await updateMutation.mutateAsync(deliveryProfileLocationsToParams(values))
- form.reset(values)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- return (
- <Card>
- <CardHeader>
- <CardTitle>{t('admin.delivery_profiles.detail.origins_title')}</CardTitle>
- </CardHeader>
- <CardContent className="flex flex-col gap-4">
- <Controller
- name="stock_location_ids"
- control={form.control}
- render={({ field }) => (
- <StockLocationScopeField
- idPrefix="origins"
- scope={scope}
- onScopeChange={(next) => {
- form.setValue('scope', next, { shouldDirty: true })
- if (next === 'all') field.onChange([])
- }}
- locations={stockLocations?.data ?? []}
- selectedIds={field.value}
- onSelectedIdsChange={field.onChange}
- allLabel={t('admin.delivery_profiles.all_locations')}
- selectedLabel={t('admin.delivery_profiles.selected_locations')}
- emptyLabel={t('admin.delivery_profiles.detail.no_stock_locations')}
- />
- )}
- />
-
- <Can I="update" a={Subject.DeliveryProfile}>
- <Button
- type="button"
- size="sm"
- className="self-start"
- onClick={form.handleSubmit(onSubmit)}
- disabled={form.formState.isSubmitting || !form.formState.isDirty}
- >
- {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
- </Can>
- </CardContent>
- </Card>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Methods, split by how they reach the customer. Zones are a destination
-// concept, so only address-shipping methods are filed under them; pickup and
-// digital methods get their own cards, with no zone language at all.
-// ---------------------------------------------------------------------------
-
-function ZonesAndMethodsSection({ profile }: { profile: DeliveryProfile }) {
- const { t } = useTranslation()
- const { data: zones, isLoading: zonesLoading } = useProfileDeliveryZones(profile.id)
- const { data: allMethods, isLoading: methodsLoading } = useAllDeliveryMethods()
- const [zoneSheet, setZoneSheet] = useState<{ zoneId?: string; groupId?: string } | null>(null)
- const [splitting, setSplitting] = useState(false)
-
- const methods = (allMethods ?? []).filter((method) => method.delivery_profile_id === profile.id)
- const pickupMethods = methods.filter((method) => method.pickup || method.pickup_point)
- const digitalMethods = methods.filter((method) => method.digital)
- const shippingMethods = methods.filter(
- (method) => !method.digital && !method.pickup && !method.pickup_point,
- )
-
- const groups = [...(profile.origin_groups ?? [])].sort(
- (a, b) => (a.position ?? 0) - (b.position ?? 0),
- )
- // Until a profile is split, the origin-group layer is invisible: one group
- // means one flat list of zones, exactly as before groups existed.
- const split = groups.length > 1
-
- if (zonesLoading || methodsLoading) {
- return <p className="text-muted-foreground">{t('admin.common.loading')}</p>
- }
-
- // A digital profile has no destination and no counter, so zones would be
- // meaningless there — it gets the digital card alone. The method sheet still
- // rides along, since digital methods are edited through it too.
- if (profile.digital) {
- return (
- <>
- <DigitalMethodsCard methods={digitalMethods} />
- <MethodSheetOutlet profile={profile} zones={zones ?? []} />
- </>
- )
- }
-
- return (
- <>
- <div className="flex items-center justify-between">
- <h2 className="font-medium text-base">{t('admin.delivery_profiles.detail.zones_title')}</h2>
- <div className="flex items-center gap-2">
- <Can I="update" a={Subject.DeliveryProfile}>
- <Button type="button" variant="ghost" size="sm" onClick={() => setSplitting(true)}>
- <SplitIcon className="size-4" />
- {t('admin.delivery_origin_groups.split_cta')}
- </Button>
- </Can>
- {!split && (
- <Can I="create" a={Subject.DeliveryZone}>
- <Button type="button" variant="outline" size="sm" onClick={() => setZoneSheet({})}>
- <PlusIcon className="size-4" />
- {t('admin.delivery_zones.add_cta')}
- </Button>
- </Can>
- )}
- </div>
- </div>
-
- {split ? (
- groups.map((group) => (
- <OriginGroupSection
- key={group.id}
- profile={profile}
- group={group}
- zones={(zones ?? []).filter((zone) => zone.delivery_origin_group_id === group.id)}
- methods={shippingMethods.filter(
- (method) => method.delivery_origin_group_id === group.id,
- )}
- onAddZone={() => setZoneSheet({ groupId: group.id })}
- onEditZone={(zoneId) => setZoneSheet({ zoneId })}
- />
- ))
- ) : (
- <FlatZoneList
- zones={zones ?? []}
- methods={shippingMethods}
- onEditZone={(zoneId) => setZoneSheet({ zoneId })}
- />
- )}
-
- <PickupCard methods={pickupMethods} />
-
- {digitalMethods.length > 0 && <DigitalMethodsCard methods={digitalMethods} />}
-
- {zoneSheet && (
- <DeliveryZoneSheet
- deliveryProfileId={profile.id}
- deliveryOriginGroupId={zoneSheet.groupId}
- zoneId={zoneSheet.zoneId}
- siblingZones={zones ?? []}
- open
- onOpenChange={(open) => !open && setZoneSheet(null)}
- />
- )}
-
- {splitting && (
- <DeliveryOriginGroupDialog
- deliveryProfileId={profile.id}
- open
- onOpenChange={(open) => !open && setSplitting(false)}
- />
- )}
-
- <MethodSheetOutlet profile={profile} zones={zones ?? []} />
- </>
- )
-}
-
-/**
- * Renders the method sheet whenever the URL asks for one. Kept apart from the
- * page body so the profile stays mounted underneath: opening a method is a
- * search-param change, not a navigation away.
- */
-function MethodSheetOutlet({
- profile,
- zones,
-}: {
- profile: DeliveryProfile
- zones: DeliveryZone[]
-}) {
- const search = Route.useSearch() as ProfileDetailSearch
- const { closeMethodSheet } = useMethodSheetNavigation()
-
- if (!search.method) return null
-
- const creating = search.method === 'new'
-
- return (
- <DeliveryMethodSheet
- // Remounting on the method being edited drops the previous record's
- // form state, which a shared instance would otherwise carry over.
- key={search.method}
- profile={profile}
- zones={zones}
- methodId={creating ? undefined : search.method}
- zoneId={creating ? search.zone : undefined}
- originGroupId={creating ? search.group : undefined}
- provider={creating ? search.provider : undefined}
- open
- onOpenChange={(open) => !open && closeMethodSheet()}
- />
- )
-}
-
-/**
- * The zones of one profile with no origin-group framing at all — what a
- * merchant who never split their origins sees, and what they return to after
- * deleting the second group.
- */
-function FlatZoneList({
- zones,
- methods,
- onEditZone,
-}: {
- zones: DeliveryZone[]
- methods: DeliveryMethod[]
- onEditZone: (zoneId: string) => void
-}) {
- const unrestricted = methods.filter((method) => !method.delivery_zone_id)
-
- return (
- <>
- {zones.map((zone) => (
- <ZoneCard
- key={zone.id}
- zone={zone}
- methods={methods.filter((method) => method.delivery_zone_id === zone.id)}
- onEdit={() => onEditZone(zone.id)}
- />
- ))}
-
- <UnrestrictedMethodsCard methods={unrestricted} />
- </>
- )
-}
-
-/**
- * One origin group of a split profile: the warehouses it ships from, and the
- * zones and methods priced from them. Same cards as the flat rendering, under
- * a header that names the origin.
- */
-function OriginGroupSection({
- profile,
- group,
- zones,
- methods,
- onAddZone,
- onEditZone,
-}: {
- profile: DeliveryProfile
- group: DeliveryProfile['origin_groups'][number]
- zones: DeliveryZone[]
- methods: DeliveryMethod[]
- onAddZone: () => void
- onEditZone: (zoneId: string) => void
-}) {
- const { t } = useTranslation()
- const confirm = useConfirm()
- const { permissions } = usePermissions()
- const { data: stockLocations } = useStockLocations()
- const deleteMutation = useDeleteDeliveryOriginGroup(profile.id)
- const [editing, setEditing] = useState(false)
-
- const unrestricted = methods.filter((method) => !method.delivery_zone_id)
- const locationNames = (stockLocations?.data ?? [])
- .filter((location) => group.stock_location_ids.includes(location.id))
- .map((location) => location.name)
-
- async function handleDelete() {
- const ok = await confirm({
- title: t('admin.delivery_origin_groups.delete_confirm.title'),
- message: t('admin.delivery_origin_groups.delete_confirm.message', {
- name: group.name ?? t('admin.delivery_profiles.all_locations'),
- }),
- variant: 'destructive',
- confirmLabel: t('admin.actions.delete'),
- })
- if (!ok) return
- // Deleting cascades to the group's zones and methods — the confirm says
- // so. Only the profile's last group is refused (422, surfaced as a toast).
- await deleteMutation.mutateAsync(group.id).catch(() => undefined)
- }
-
- return (
- <section className="flex flex-col gap-4 rounded-lg border p-4">
- <div className="flex items-start justify-between gap-2">
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-2">
- <WarehouseIcon className="size-4 text-muted-foreground" />
- <span className="font-medium text-sm">
- {group.name || t('admin.delivery_profiles.all_locations')}
- </span>
- </div>
- <span className="text-muted-foreground text-xs">
- {locationNames.length > 0
- ? t('admin.delivery_origin_groups.ships_from', {
- locations: locationNames.join(', '),
- })
- : t('admin.delivery_origin_groups.ships_from_all')}
- </span>
- </div>
- <div className="flex items-center gap-2">
- <Can I="create" a={Subject.DeliveryZone}>
- <Button type="button" variant="outline" size="sm" onClick={onAddZone}>
- <PlusIcon className="size-4" />
- {t('admin.delivery_zones.add_cta')}
- </Button>
- </Can>
- <RowActions
- actions={[
- {
- key: 'edit',
- visible: permissions.can('update', Subject.DeliveryProfile),
- onSelect: () => setEditing(true),
- },
- {
- key: 'delete',
- destructive: true,
- visible: permissions.can('update', Subject.DeliveryProfile),
- disabled: deleteMutation.isPending,
- onSelect: handleDelete,
- },
- ]}
- />
- </div>
- </div>
-
- {zones.map((zone) => (
- <ZoneCard
- key={zone.id}
- zone={zone}
- methods={methods.filter((method) => method.delivery_zone_id === zone.id)}
- onEdit={() => onEditZone(zone.id)}
- originGroupId={group.id}
- />
- ))}
-
- <UnrestrictedMethodsCard methods={unrestricted} originGroupId={group.id} />
-
- {editing && (
- <DeliveryOriginGroupDialog
- deliveryProfileId={profile.id}
- group={group as DeliveryOriginGroup}
- open
- onOpenChange={(open) => !open && setEditing(false)}
- />
- )}
- </section>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Pickup — the methods customers collect in person, and which counters they
-// can collect from.
-// ---------------------------------------------------------------------------
-
-function PickupCard({ methods }: { methods: DeliveryMethod[] }) {
- const { t } = useTranslation()
- const { openNewMethod } = useMethodSheetNavigation()
-
- return (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <StoreIcon className="size-4 text-muted-foreground" />
- {t('admin.delivery_profiles.detail.pickup_title')}
- </CardTitle>
- <span className="text-muted-foreground text-xs">
- {t('admin.delivery_profiles.detail.pickup_hint')}
- </span>
- </CardHeader>
- <CardContent className="flex flex-col gap-4">
- {methods.length > 0 ? (
- <MethodList methods={methods} icon={StoreIcon} />
- ) : (
- <div className="flex flex-col items-start gap-2">
- <p className="text-muted-foreground text-sm">
- {t('admin.delivery_profiles.detail.pickup_empty')}
- </p>
- <Can I="create" a={Subject.DeliveryMethod}>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => openNewMethod({ provider: 'pickup' })}
- >
- <PlusIcon className="size-4" />
- {t('admin.delivery_profiles.detail.offer_pickup')}
- </Button>
- </Can>
- </div>
- )}
-
- <PickupLocationsBlock />
- </CardContent>
- </Card>
- )
-}
-
-/**
- * Every stock location of the store, each a counter customers can collect
- * from. Toggling writes straight through — the surrounding page is a set of
- * saved forms, so the helper line says these changes are immediate.
- */
-function PickupLocationsBlock() {
- const { t } = useTranslation()
- const { data: stockLocations, isLoading } = useStockLocations()
- const updateMutation = useUpdateStockLocationById()
-
- const locations = stockLocations?.data ?? []
-
- return (
- <div className="flex flex-col gap-2 border-t pt-4">
- <span className="font-medium text-sm">
- {t('admin.delivery_profiles.detail.collect_from')}
- </span>
- <span className="text-muted-foreground text-xs">
- {t('admin.delivery_profiles.detail.collect_from_hint')}
- </span>
-
- {isLoading ? (
- <p className="text-muted-foreground text-sm">{t('admin.common.loading')}</p>
- ) : locations.length === 0 ? (
- <p className="text-muted-foreground text-sm">
- {t('admin.delivery_profiles.detail.no_stock_locations')}
- </p>
- ) : (
- <div className="flex flex-col gap-2">
- {locations.map((location) => (
- <label
- key={location.id}
- htmlFor={`pickup-location-${location.id}`}
- className="flex items-center gap-2 text-sm"
- >
- <Checkbox
- id={`pickup-location-${location.id}`}
- checked={location.pickup_enabled}
- disabled={updateMutation.isPending}
- onCheckedChange={(next) =>
- updateMutation
- .mutateAsync({
- id: location.id,
- params: { pickup_enabled: !!next },
- })
- .catch(() => undefined)
- }
- />
- {location.name}
- </label>
- ))}
- </div>
- )}
- </div>
- )
-}
-
-// ---------------------------------------------------------------------------
-// Digital — delivered without a destination of any kind
-// ---------------------------------------------------------------------------
-
-function DigitalMethodsCard({ methods }: { methods: DeliveryMethod[] }) {
- const { t } = useTranslation()
- const { openNewMethod } = useMethodSheetNavigation()
-
- return (
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <ZapIcon className="size-4 text-muted-foreground" />
- {t('admin.delivery_profiles.detail.digital_title')}
- </CardTitle>
- <span className="text-muted-foreground text-xs">
- {t('admin.delivery_profiles.detail.digital_hint')}
- </span>
- </CardHeader>
- <CardContent>
- {methods.length > 0 ? (
- <MethodList methods={methods} icon={ZapIcon} />
- ) : (
- <div className="flex flex-col items-start gap-2">
- <p className="text-muted-foreground text-sm">
- {t('admin.delivery_profiles.detail.digital_empty')}
- </p>
- <Can I="create" a={Subject.DeliveryMethod}>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => openNewMethod({ provider: 'digital' })}
- >
- <PlusIcon className="size-4" />
- {t('admin.delivery_profiles.detail.add_digital_method')}
- </Button>
- </Can>
- </div>
- )}
- </CardContent>
- </Card>
- )
-}
-
-function ZoneCard({
- zone,
- methods,
- onEdit,
- originGroupId,
-}: {
- zone: DeliveryZone
- methods: DeliveryMethod[]
- onEdit: () => void
- /** Set only on a split profile, so a new method lands in the right group. */
- originGroupId?: string
-}) {
- const { t } = useTranslation()
- const { openNewMethod } = useMethodSheetNavigation()
- const confirm = useConfirm()
- const deleteMutation = useDeleteDeliveryZone()
- const { permissions } = usePermissions()
-
- async function handleDelete() {
- const ok = await confirm({
- title: t('admin.delivery_zones.delete_confirm.title'),
- message: t('admin.delivery_zones.delete_confirm.message', { name: zone.name }),
- variant: 'destructive',
- confirmLabel: t('admin.actions.delete'),
- })
- if (!ok) return
- await deleteMutation.mutateAsync(zone.id).catch(() => undefined)
- }
-
- return (
- <Card>
- <CardHeader className="flex flex-row items-start justify-between gap-2">
- <div className="flex flex-col gap-1">
- <CardTitle className="flex items-center gap-2">
- <MapIcon className="size-4 text-muted-foreground" />
- {zone.name}
- </CardTitle>
- <ZoneMembersSummary zone={zone} />
- </div>
- <div className="flex items-center gap-2">
- <Can I="create" a={Subject.DeliveryMethod}>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => openNewMethod({ zone: zone.id, group: originGroupId })}
- >
- <PlusIcon className="size-4" />
- {t('admin.delivery_profiles.detail.add_method')}
- </Button>
- </Can>
- <RowActions
- actions={[
- { key: 'edit', onSelect: onEdit },
- {
- key: 'delete',
- destructive: true,
- visible: permissions.can('destroy', Subject.DeliveryZone),
- disabled: deleteMutation.isPending,
- onSelect: handleDelete,
- },
- ]}
- />
- </div>
- </CardHeader>
- <CardContent>
- <MethodList methods={methods} />
- </CardContent>
- </Card>
- )
-}
-
-/**
- * Methods offered wherever the profile reaches. Always rendered, even empty:
- * a profile with no zones would otherwise have nowhere to add a method from,
- * and a carrier method that quotes worldwide never wants a zone at all.
- */
-function UnrestrictedMethodsCard({
- methods,
- originGroupId,
-}: {
- methods: DeliveryMethod[]
- originGroupId?: string
-}) {
- const { t } = useTranslation()
- const { openNewMethod } = useMethodSheetNavigation()
-
- return (
- <Card>
- <CardHeader className="flex flex-row items-start justify-between gap-2">
- <div className="flex flex-col gap-1">
- <CardTitle className="flex items-center gap-2">
- <GlobeIcon className="size-4 text-muted-foreground" />
- {t('admin.delivery_profiles.detail.no_zone_title')}
- </CardTitle>
- <span className="text-muted-foreground text-xs">
- {t('admin.delivery_profiles.detail.no_zone_hint')}
- </span>
- </div>
- <Can I="create" a={Subject.DeliveryMethod}>
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => openNewMethod({ group: originGroupId })}
- >
- <PlusIcon className="size-4" />
- {t('admin.delivery_profiles.detail.add_method')}
- </Button>
- </Can>
- </CardHeader>
- {methods.length > 0 && (
- <CardContent>
- <MethodList methods={methods} />
- </CardContent>
- )}
- </Card>
- )
-}
-
-/**
- * Names the places a zone covers: the first few members, then the rest behind
- * a tooltip. Countries come first because they are how merchants think about
- * a zone; states and postal-code rules follow when a zone is finer-grained.
- */
-function ZoneMembersSummary({ zone }: { zone: DeliveryZone }) {
- const { t } = useTranslation()
-
- const names = useMemo(() => {
- const members = zone.members ?? []
- const label = (member: DeliveryZoneMember): string | null => {
- if (member.member_type === 'country') return member.country_name ?? member.country_code
- if (member.member_type === 'state') return member.state_name ?? member.state_code
- if (member.postal_code_prefix) return `${member.postal_code_prefix}*`
- if (member.postal_code_from && member.postal_code_to) {
- return `${member.postal_code_from}–${member.postal_code_to}`
- }
- return member.postal_code_from ?? member.postal_code_to
- }
-
- const order = { country: 0, state: 1 } as Record<string, number>
- return [...members]
- .sort((a, b) => (order[a.member_type] ?? 2) - (order[b.member_type] ?? 2))
- .map(label)
- .filter((name): name is string => !!name)
- }, [zone.members])
-
- if (names.length === 0) return null
-
- const shown = names.slice(0, 3)
- const remaining = names.slice(3)
-
- return (
- <span className="text-muted-foreground text-xs">
- {shown.join(t('admin.delivery_zones.member_separator'))}
- {remaining.length > 0 && (
- <>
- {t('admin.delivery_zones.member_separator')}
- <Tooltip>
- <TooltipTrigger asChild>
- <button type="button" className="underline decoration-dotted underline-offset-2">
- {t('admin.delivery_zones.members_more', { count: remaining.length })}
- </button>
- </TooltipTrigger>
- <TooltipContent className="max-w-xs">
- {remaining.join(t('admin.delivery_zones.member_separator'))}
- </TooltipContent>
- </Tooltip>
- </>
- )}
- </span>
- )
-}
-
-function MethodList({
- methods,
- icon: Icon = TruckIcon,
-}: {
- methods: DeliveryMethod[]
- icon?: typeof TruckIcon
-}) {
- const { t, i18n } = useTranslation()
- const { store, defaultCurrency } = useStore()
- const { openMethod } = useMethodSheetNavigation()
- const confirm = useConfirm()
- const deleteMutation = useDeleteDeliveryMethod()
- const { permissions } = usePermissions()
- const { data: rateProviders } = useDeliveryRateProviders()
- const defaultRateProvider = rateProviders?.default ?? ''
-
- async function handleDelete(method: DeliveryMethod) {
- const ok = await confirm({
- title: t('admin.delivery_methods.delete_confirm.title'),
- message: t('admin.delivery_methods.delete_confirm.message', { name: method.name }),
- variant: 'destructive',
- confirmLabel: t('admin.actions.delete'),
- })
- if (!ok) return
- await deleteMutation.mutateAsync(method.id).catch(() => undefined)
- }
-
- if (methods.length === 0) {
- return (
- <p className="text-muted-foreground text-sm">
- {t('admin.delivery_profiles.detail.no_methods')}
- </p>
- )
- }
-
- return (
- <div className="flex flex-col divide-y">
- {methods.map((method) => {
- const rateProvider = (rateProviders?.data ?? []).find(
- (provider) => provider.type === method.rate_provider,
- )
- // A carrier quotes each shipment live, so this column answers what the
- // price IS rather than naming the provider — which the method is
- // usually named after anyway. Everything else is priced up front: an
- // amount, or free when there is none.
- //
- // A method carrying a rate provider absent from the registry (an
- // uninstalled gem, a disconnected integration) is still not
- // calculator-priced, and calling it free would be a lie about money.
- const carrierPriced = rateProvider
- ? rateProvider.uses_calculator === false
- : !!method.rate_provider && method.rate_provider !== defaultRateProvider
- const amount = flatAmount(method.calculator_preferences)
- const price = carrierPriced
- ? t('admin.delivery_methods.carrier_rates')
- : amount === null || amount === 0
- ? t('admin.delivery_methods.free')
- : formatAmount(amount, defaultCurrency, i18n.language)
-
- const ruleSummary = summarizeRules(method.rules, {
- t,
- currency: defaultCurrency,
- weightUnit: store?.preferred_weight_unit ?? 'lb',
- locale: i18n.language,
- })
-
- return (
- <div key={method.id} className="flex items-center justify-between gap-2 py-2">
- <button
- type="button"
- className="flex flex-1 items-center gap-2 text-left"
- onClick={() => openMethod(method.id)}
- >
- <Icon className="size-4 shrink-0 text-muted-foreground" />
- <span className="flex flex-col">
- <span className="text-sm">{method.name}</span>
- {ruleSummary && (
- <span className="text-muted-foreground text-xs">{ruleSummary}</span>
- )}
- </span>
- </button>
- {!method.storefront_visible && (
- <Badge variant="outline">{t('admin.delivery_profiles.detail.hidden_badge')}</Badge>
- )}
- {carrierPriced ? (
- <Tooltip>
- <TooltipTrigger
- render={
- <span className="shrink-0 cursor-default text-sm underline decoration-dotted underline-offset-2">
- {price}
- </span>
- }
- />
- <TooltipContent className="max-w-xs">
- {t('admin.delivery_methods.carrier_rates_hint', {
- name: rateProvider?.name ?? method.name,
- })}
- </TooltipContent>
- </Tooltip>
- ) : (
- <span className="shrink-0 text-sm tabular-nums">{price}</span>
- )}
- <RowActions
- actions={[
- {
- key: 'edit',
- onSelect: () => openMethod(method.id),
- },
- {
- key: 'delete',
- destructive: true,
- visible: permissions.can('destroy', Subject.DeliveryMethod),
- disabled: deleteMutation.isPending,
- onSelect: () => handleDelete(method),
- },
- ]}
- />
- </div>
- )
- })}
- </div>
- )
-}