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.

Added Custom field management in admin spa (#14080)

Damian Legawiec7be6c5309cfc
diff --git a/packages/admin/e2e/custom-field-definitions.spec.ts b/packages/admin/e2e/custom-field-definitions.spec.ts
new file mode 100644
index 0000000000..7c4cbc90e9
--- /dev/null
+++ b/packages/admin/e2e/custom-field-definitions.spec.ts
@@ -0,0 +1,88 @@
+import { expect, type Page, test } from '@playwright/test'
+import { gotoIndex, login, openRowMenu, rowButton } from './helpers'
+
+const PATH = (storeId: string) => `/${storeId}/settings/custom-field-definitions`
+const CTA = /add custom field/i
+
+async function createDefinition(
+ page: Page,
+ attrs: { label: string; key: string; namespace?: string },
+) {
+ await page.getByRole('button', { name: CTA }).click()
+ await expect(page.getByRole('heading', { name: /add custom field/i })).toBeVisible()
+
+ await page.getByLabel(/^label$/i).fill(attrs.label)
+ if (attrs.namespace) {
+ await page.getByLabel(/^namespace$/i).fill(attrs.namespace)
+ }
+ await page.getByLabel(/^key$/i).fill(attrs.key)
+ await page.getByRole('button', { name: /create custom field/i }).click()
+}
+
+test.describe('custom field definitions', () => {
+ test('lists custom field definitions', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, PATH(creds.store_id), CTA)
+ })
+
+ test('creates a new definition', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, PATH(creds.store_id), CTA)
+
+ const suffix = Date.now()
+ const label = `E2E Field ${suffix}`
+ const key = `e2e_${suffix}`
+
+ await createDefinition(page, { label, key })
+ await expect(rowButton(page, label)).toBeVisible({ timeout: 15_000 })
+ })
+
+ test('edits a definition', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, PATH(creds.store_id), CTA)
+
+ const suffix = Date.now()
+ const original = `E2E Edit Field ${suffix}`
+ const updated = `${original} (updated)`
+ const key = `edit_${suffix}`
+
+ await createDefinition(page, { label: original, key })
+ await expect(rowButton(page, original)).toBeVisible({ timeout: 15_000 })
+
+ await rowButton(page, original).click()
+ await expect(page.getByRole('heading', { name: original })).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByLabel(/^label$/i)).toHaveValue(original)
+
+ // Resource type + field type pickers must be disabled in edit mode —
+ // changing either would orphan or misinterpret stored values.
+ await expect(page.getByLabel(/^applies to$/i)).toBeDisabled()
+ await expect(page.getByLabel(/^type$/i)).toBeDisabled()
+
+ await page.getByLabel(/^label$/i).fill(updated)
+ await page.getByRole('button', { name: /^save$/i }).click()
+
+ await expect(rowButton(page, updated)).toBeVisible({ timeout: 15_000 })
+ })
+
+ test('deletes a definition', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, PATH(creds.store_id), CTA)
+
+ const suffix = Date.now()
+ const label = `E2E Delete Field ${suffix}`
+ const key = `delete_${suffix}`
+
+ await createDefinition(page, { label, key })
+ await expect(rowButton(page, label)).toBeVisible({ timeout: 15_000 })
+
+ await openRowMenu(page, label)
+ await page.getByRole('menuitem', { name: /^delete$/i }).click()
+ await expect(page.getByRole('heading', { name: /delete custom field\?/i })).toBeVisible()
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^delete$/i })
+ .click()
+
+ await expect(rowButton(page, label)).toHaveCount(0, { timeout: 15_000 })
+ })
+})
diff --git a/packages/admin/src/components/spree/custom-fields/definition-form.tsx b/packages/admin/src/components/spree/custom-fields/definition-form.tsx
index 3715f5c7f0..88b24e0b6f 100644
--- a/packages/admin/src/components/spree/custom-fields/definition-form.tsx
+++ b/packages/admin/src/components/spree/custom-fields/definition-form.tsx
@@ -1,11 +1,10 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { Loader2Icon } from 'lucide-react'
import type { ReactNode } from 'react'
-import { Controller, useForm } from 'react-hook-form'
+import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
-import { z } from 'zod/v4'
import { Button } from '@/components/ui/button'
-import { Field, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -17,99 +16,89 @@ import {
import { Switch } from '@/components/ui/switch'
import { useCreateCustomFieldDefinition } from '@/hooks/use-custom-fields'
import { mapSpreeErrorsToForm } from '@/lib/form-errors'
-import { i18n } from '@/lib/i18n'
-import { requiredMessage } from '@/lib/validation-messages'
-
-// Labels live in `en.json` under
-// `admin.fields.custom_field_definition.field_type.options.*` — consumers
-// translate at render time.
-const FIELD_TYPES = ['short_text', 'long_text', 'rich_text', 'number', 'boolean', 'json'] as const
-
-const definitionSchema = z.object({
- label: z.string().min(1, { error: requiredMessage('custom_field_definition.label') }),
- namespace: z.string().min(1, { error: requiredMessage('custom_field_definition.namespace') }),
- key: z
- .string()
- .min(1, { error: requiredMessage('custom_field_definition.key') })
- .regex(/^[a-z0-9_]+$/i, {
- error: () => i18n.t('admin.fields.custom_field_definition.key.invalid_format'),
- }),
- field_type: z.enum(FIELD_TYPES),
- storefront_visible: z.boolean(),
-})
-
-export type DefinitionFormValues = z.infer<typeof definitionSchema>
+import {
+ CUSTOM_FIELD_DEFINITION_DEFAULTS,
+ type CustomFieldDefinitionFormValues,
+ customFieldDefinitionSchema,
+ customFieldDefinitionValuesToCreateParams,
+ DEFAULT_RESOURCE_TYPES,
+ FIELD_TYPES,
+ fieldTypeLabel,
+ resourceTypeLabel,
+} from '@/schemas/custom-field-definition'
-interface DefinitionFormProps {
- resourceType: string
- /** Default namespace; "custom" mirrors Shopify/Saleor convention. */
- defaultNamespace?: string
- onSuccess: (definitionId: string) => void
+// Re-export so existing callers (drawer) don't have to chase paths.
+export type { CustomFieldDefinitionFormValues as DefinitionFormValues }
+
+interface DefinitionFormFieldsProps {
+ form: UseFormReturn<CustomFieldDefinitionFormValues>
/**
- * Render-prop that builds the surrounding chrome (header/footer/etc) AROUND
- * the form fields and the submit button. The submit button must stay inside
- * the same `<form>` as the inputs, so the consumer composes layout, not the
- * form element itself.
+ * When true, the `resource_type` picker is rendered. Off by default — the
+ * drawer creates definitions for a known owner and pre-fills the resource,
+ * but the settings page (where the user picks from a list) opts in.
*/
- renderShell: (parts: { fields: ReactNode; submitButton: ReactNode }) => ReactNode
+ showResourceType?: boolean
+ /**
+ * Disable the `resource_type` picker. Used in edit mode where changing the
+ * owner would orphan stored values.
+ */
+ resourceTypeReadOnly?: boolean
+ /**
+ * Disable the `field_type` picker. Used in edit mode — flipping the type
+ * after values have been stored would leave them misinterpreted by the UI.
+ */
+ fieldTypeReadOnly?: boolean
}
-export function DefinitionForm({
- resourceType,
- defaultNamespace = 'custom',
- onSuccess,
- renderShell,
-}: DefinitionFormProps) {
+/**
+ * Pure form fields for a custom field definition. The caller supplies the
+ * `<form>` element and submit handler — this just renders the controls.
+ *
+ * Used by:
+ * - `<DefinitionForm>` below (drawer's inline create flow, owner pre-set).
+ * - The Settings → Custom field definitions page (create + edit sheets).
+ */
+export function DefinitionFormFields({
+ form,
+ showResourceType = false,
+ resourceTypeReadOnly = false,
+ fieldTypeReadOnly = false,
+}: DefinitionFormFieldsProps) {
const { t } = useTranslation()
- const create = useCreateCustomFieldDefinition(resourceType)
-
- const form = useForm<DefinitionFormValues>({
- resolver: zodResolver(definitionSchema),
- defaultValues: {
- label: '',
- namespace: defaultNamespace,
- key: '',
- field_type: 'short_text',
- storefront_visible: false,
- },
- })
const { errors } = form.formState
- const onSubmit = async (values: DefinitionFormValues) => {
- try {
- const result = await create.mutateAsync({ ...values, resource_type: resourceType })
- onSuccess(result.id)
- } catch (err) {
- // 422s map to inline field errors; anything else (network, 5xx) lands
- // on the form-level `root` so the user gets feedback inside the sheet.
- if (!mapSpreeErrorsToForm(err, form.setError)) {
- form.setError('root', {
- type: 'server',
- message: err instanceof Error ? err.message : t('admin.errors.unexpected'),
- })
- }
- }
- }
+ const fieldTypeItems = FIELD_TYPES.map((value) => ({
+ value,
+ label: fieldTypeLabel(value),
+ }))
- const fields = (
+ const resourceTypeItems = DEFAULT_RESOURCE_TYPES.map((value) => ({
+ value,
+ label: resourceTypeLabel(value),
+ }))
+
+ return (
<div className="flex flex-col gap-4">
{errors.root?.message && (
<p className="text-sm text-destructive" role="alert">
{errors.root.message}
</p>
)}
+
<Field>
<FieldLabel htmlFor="cfd-label">
{t('admin.fields.custom_field_definition.label.label')}
</FieldLabel>
<Input
id="cfd-label"
+ autoFocus
placeholder={t('admin.fields.custom_field_definition.label.placeholder')}
aria-invalid={!!errors.label || undefined}
{...form.register('label')}
/>
- {errors.label && <p className="text-sm text-destructive">{errors.label.message}</p>}
+ <FieldError errors={[errors.label]} />
</Field>
+
<div className="grid grid-cols-3 gap-3">
<Field className="col-span-1">
<FieldLabel htmlFor="cfd-namespace">
@@ -121,9 +110,7 @@ export function DefinitionForm({
aria-invalid={!!errors.namespace || undefined}
{...form.register('namespace')}
/>
- {errors.namespace && (
- <p className="text-sm text-destructive">{errors.namespace.message}</p>
- )}
+ <FieldError errors={[errors.namespace]} />
</Field>
<Field className="col-span-2">
<FieldLabel htmlFor="cfd-key">
@@ -135,38 +122,85 @@ export function DefinitionForm({
aria-invalid={!!errors.key || undefined}
{...form.register('key')}
/>
- {errors.key && <p className="text-sm text-destructive">{errors.key.message}</p>}
+ <FieldError errors={[errors.key]} />
</Field>
</div>
- <Field>
- <FieldLabel htmlFor="cfd-field-type">
- {t('admin.fields.custom_field_definition.field_type.label')}
- </FieldLabel>
- <Controller
- name="field_type"
- control={form.control}
- render={({ field }) => {
- const items = FIELD_TYPES.map((value) => ({
- value,
- label: t(`admin.fields.custom_field_definition.field_type.options.${value}`),
- }))
- return (
- <Select items={items} value={field.value} onValueChange={field.onChange}>
- <SelectTrigger id="cfd-field-type" aria-invalid={!!errors.field_type || undefined}>
+
+ {showResourceType && (
+ <Field>
+ <FieldLabel htmlFor="cfd-resource-type">
+ {t('admin.fields.custom_field_definition.resource_type.label')}
+ </FieldLabel>
+ <Controller
+ name="resource_type"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ items={resourceTypeItems}
+ value={field.value}
+ onValueChange={field.onChange}
+ disabled={resourceTypeReadOnly}
+ >
+ <SelectTrigger
+ id="cfd-resource-type"
+ aria-invalid={!!errors.resource_type || undefined}
+ >
<SelectValue />
</SelectTrigger>
<SelectContent>
- {items.map((o) => (
+ {resourceTypeItems.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
- )
- }}
+ )}
+ />
+ {resourceTypeReadOnly && (
+ <span className="text-xs text-muted-foreground">
+ {t('admin.fields.custom_field_definition.resource_type.read_only_help')}
+ </span>
+ )}
+ <FieldError errors={[errors.resource_type]} />
+ </Field>
+ )}
+
+ <Field>
+ <FieldLabel htmlFor="cfd-field-type">
+ {t('admin.fields.custom_field_definition.field_type.label')}
+ </FieldLabel>
+ <Controller
+ name="field_type"
+ control={form.control}
+ render={({ field }) => (
+ <Select
+ items={fieldTypeItems}
+ value={field.value}
+ onValueChange={field.onChange}
+ disabled={fieldTypeReadOnly}
+ >
+ <SelectTrigger id="cfd-field-type" aria-invalid={!!errors.field_type || undefined}>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {fieldTypeItems.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
/>
+ {fieldTypeReadOnly && (
+ <span className="text-xs text-muted-foreground">
+ {t('admin.fields.custom_field_definition.field_type.read_only_help')}
+ </span>
+ )}
+ <FieldError errors={[errors.field_type]} />
</Field>
+
<Field>
<div className="flex items-start justify-between gap-4">
<FieldLabel htmlFor="cfd-storefront-visible" className="cursor-pointer">
@@ -187,11 +221,67 @@ export function DefinitionForm({
</Field>
</div>
)
+}
+
+interface DefinitionFormProps {
+ resourceType: string
+ /** Default namespace; "custom" mirrors Shopify/Saleor convention. */
+ defaultNamespace?: string
+ onSuccess: (definitionId: string) => void
+ /**
+ * Render-prop that builds the surrounding chrome (header/footer/etc) AROUND
+ * the form fields and the submit button. The submit button must stay inside
+ * the same `<form>` as the inputs, so the consumer composes layout, not the
+ * form element itself.
+ */
+ renderShell: (parts: { fields: ReactNode; submitButton: ReactNode }) => ReactNode
+}
+
+/**
+ * Drawer-style create form. Owns its own `useForm` + create mutation, and
+ * pre-fills `resource_type` from the owning record (so the resource picker
+ * is hidden — the drawer only ever creates fields for one specific owner).
+ */
+export function DefinitionForm({
+ resourceType,
+ defaultNamespace = 'custom',
+ onSuccess,
+ renderShell,
+}: DefinitionFormProps) {
+ const { t } = useTranslation()
+ const create = useCreateCustomFieldDefinition(resourceType)
+
+ const form = useForm<CustomFieldDefinitionFormValues>({
+ resolver: zodResolver(customFieldDefinitionSchema),
+ defaultValues: {
+ ...CUSTOM_FIELD_DEFINITION_DEFAULTS,
+ namespace: defaultNamespace,
+ resource_type: resourceType,
+ },
+ })
+
+ const onSubmit = async (values: CustomFieldDefinitionFormValues) => {
+ try {
+ const result = await create.mutateAsync(
+ customFieldDefinitionValuesToCreateParams({ ...values, resource_type: resourceType }),
+ )
+ onSuccess(result.id)
+ } catch (err) {
+ // 422s map to inline field errors; anything else (network, 5xx) lands
+ // on the form-level `root` so the user gets feedback inside the sheet.
+ if (!mapSpreeErrorsToForm(err, form.setError)) {
+ form.setError('root', {
+ type: 'server',
+ message: err instanceof Error ? err.message : t('admin.errors.unexpected'),
+ })
+ }
+ }
+ }
const submitButton = (
<Button type="submit" size="sm" disabled={create.isPending}>
{create.isPending && <Loader2Icon className="size-4 animate-spin" />}
- Create definition
+ {t('admin.custom_field_definitions.create_label')}
</Button>
)
@@ -204,7 +294,7 @@ export function DefinitionForm({
// product form's onSubmit also fires. Hard-stop here.
onSubmitCapture={(e) => e.stopPropagation()}
>
- {renderShell({ fields, submitButton })}
+ {renderShell({ fields: <DefinitionFormFields form={form} />, submitButton })}
</form>
)
}
diff --git a/packages/admin/src/components/spree/table-toolbar.tsx b/packages/admin/src/components/spree/table-toolbar.tsx
index 26426d4654..5e20f6c88e 100644
--- a/packages/admin/src/components/spree/table-toolbar.tsx
+++ b/packages/admin/src/components/spree/table-toolbar.tsx
@@ -291,6 +291,10 @@ function FilterChip({
<ResourceFilterValue value={filter.value} config={col.filterResource} />
) : col?.filterType === 'tags' ? (
<span className="font-medium">{parseFilterIds(filter.value).join(', ')}</span>
+ ) : col?.filterType === 'enum' && col.filterOptions ? (
+ <span className="font-medium">
+ {col.filterOptions.find((o) => o.value === filter.value)?.label ?? filter.value}
+ </span>
) : (
<span className="font-medium">{filter.value}</span>
))}
diff --git a/packages/admin/src/hooks/use-custom-fields.ts b/packages/admin/src/hooks/use-custom-fields.ts
index 75815c3a39..1eaf8fc2cb 100644
--- a/packages/admin/src/hooks/use-custom-fields.ts
+++ b/packages/admin/src/hooks/use-custom-fields.ts
@@ -1,5 +1,6 @@
import type {
CustomFieldCreateParams,
+ CustomFieldDefinition,
CustomFieldDefinitionCreateParams,
CustomFieldDefinitionUpdateParams,
CustomFieldOwnerType,
@@ -7,11 +8,20 @@ import type {
} from '@spree/admin-sdk'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { adminClient } from '@/client'
+import { useResourceMutation } from '@/hooks/use-resource-mutation'
const valuesKey = (ownerType: CustomFieldOwnerType, ownerId: string) =>
['custom-fields', ownerType, ownerId] as const
-const definitionsKey = (resourceType: string) => ['custom-field-definitions', resourceType] as const
+// Root key used to invalidate every definitions query at once. The
+// per-resource and per-id keys below extend it so TanStack's prefix
+// invalidation catches them.
+export const customFieldDefinitionsRootKey = ['custom-field-definitions'] as const
+
+const definitionsKey = (resourceType: string) =>
+ [...customFieldDefinitionsRootKey, resourceType] as const
+
+const definitionByIdKey = (id: string) => [...customFieldDefinitionsRootKey, 'id', id] as const
export function useCustomFields(ownerType: CustomFieldOwnerType, ownerId: string) {
return useQuery({
@@ -65,6 +75,58 @@ export function useDeleteCustomField(ownerType: CustomFieldOwnerType, ownerId: s
})
}
+export function useCustomFieldDefinition(id: string | undefined) {
+ return useQuery({
+ queryKey: id ? definitionByIdKey(id) : [...customFieldDefinitionsRootKey, 'id', 'noop'],
+ queryFn: () => adminClient.customFieldDefinitions.get(id as string),
+ enabled: !!id,
+ })
+}
+
+/**
+ * Settings-page variant — no `resourceType` argument. Invalidates the root
+ * key, which covers every per-resource and per-id definition query.
+ *
+ * Toast + 422 handling come for free via `useResourceMutation`: validation
+ * errors surface inline through `mapSpreeErrorsToForm`, everything else
+ * (network, 5xx) shows a toast.
+ */
+export function useCreateCustomFieldDefinitionForSettings() {
+ return useResourceMutation<CustomFieldDefinition, Error, CustomFieldDefinitionCreateParams>({
+ mutationFn: (params) => adminClient.customFieldDefinitions.create(params),
+ invalidate: [customFieldDefinitionsRootKey],
+ successMessage: 'Custom field definition created',
+ errorMessage: 'Failed to create custom field definition',
+ })
+}
+
+export function useUpdateCustomFieldDefinitionForSettings(id: string) {
+ return useResourceMutation<CustomFieldDefinition, Error, CustomFieldDefinitionUpdateParams>({
+ mutationFn: (params) => adminClient.customFieldDefinitions.update(id, params),
+ invalidate: [customFieldDefinitionsRootKey, definitionByIdKey(id)],
+ successMessage: 'Custom field definition updated',
+ errorMessage: 'Failed to update custom field definition',
+ })
+}
+
+export function useDeleteCustomFieldDefinitionForSettings() {
+ const queryClient = useQueryClient()
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (id) => adminClient.customFieldDefinitions.delete(id),
+ invalidate: [customFieldDefinitionsRootKey],
+ successMessage: 'Custom field definition deleted',
+ errorMessage: 'Failed to delete custom field definition',
+ onSuccess: (_data, id) => {
+ queryClient.removeQueries({ queryKey: definitionByIdKey(id) })
+ },
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Drawer-only variants — pinned to a single `resourceType`. Existing call
+// sites (product/order/customer detail pages) keep these.
+// ---------------------------------------------------------------------------
+
export function useCreateCustomFieldDefinition(resourceType: string) {
const queryClient = useQueryClient()
return useMutation({
@@ -72,6 +134,7 @@ export function useCreateCustomFieldDefinition(resourceType: string) {
adminClient.customFieldDefinitions.create(params),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: definitionsKey(resourceType) })
+ queryClient.invalidateQueries({ queryKey: customFieldDefinitionsRootKey })
},
})
}
@@ -83,6 +146,7 @@ export function useUpdateCustomFieldDefinition(resourceType: string) {
adminClient.customFieldDefinitions.update(id, params),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: definitionsKey(resourceType) })
+ queryClient.invalidateQueries({ queryKey: customFieldDefinitionsRootKey })
},
})
}
@@ -93,6 +157,7 @@ export function useDeleteCustomFieldDefinition(resourceType: string) {
mutationFn: (id: string) => adminClient.customFieldDefinitions.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: definitionsKey(resourceType) })
+ queryClient.invalidateQueries({ queryKey: customFieldDefinitionsRootKey })
},
})
}
diff --git a/packages/admin/src/lib/permissions.ts b/packages/admin/src/lib/permissions.ts
index e737450eec..30a527e993 100644
--- a/packages/admin/src/lib/permissions.ts
+++ b/packages/admin/src/lib/permissions.ts
@@ -19,6 +19,7 @@ export const Subject = {
OptionType: 'Spree::OptionType',
OptionValue: 'Spree::OptionValue',
TaxCategory: 'Spree::TaxCategory',
+ CustomFieldDefinition: 'Spree::MetafieldDefinition',
PaymentMethod: 'Spree::PaymentMethod',
ShippingMethod: 'Spree::ShippingMethod',
StockLocation: 'Spree::StockLocation',
diff --git a/packages/admin/src/locales/en.json b/packages/admin/src/locales/en.json
index 65ebacc5e7..471d31e004 100644
--- a/packages/admin/src/locales/en.json
+++ b/packages/admin/src/locales/en.json
@@ -287,7 +287,22 @@
"json": "JSON"
}
},
- "storefront_visible": { "label": "Visible on storefront" }
+ "resource_type": {
+ "label": "Applies to",
+ "read_only_help": "The owner can't be changed once values exist for this field.",
+ "options": {
+ "Spree::Product": "Products",
+ "Spree::Variant": "Variants",
+ "Spree::Order": "Orders",
+ "Spree::User": "Customers",
+ "Spree::Category": "Categories",
+ "Spree::OptionType": "Option types"
+ }
+ },
+ "storefront_visible": {
+ "label": "Visible on storefront",
+ "column_label": "Storefront"
+ }
},
"tax_category": {
"name": { "placeholder": "e.g. Reduced rate" },
@@ -815,6 +830,10 @@
"add_sheet_title": "Add tax category",
"edit_sheet_title": "Edit tax category"
},
+ "custom_field_definitions": {
+ "add_sheet_title": "Add custom field",
+ "edit_sheet_title": "Edit custom field"
+ },
"stock_locations": {
"add_sheet_title": "Add stock location",
"edit_sheet_title": "Edit stock location",
@@ -1243,6 +1262,23 @@
"message": "{{name}} will be removed. Products in this category fall back to the default."
}
},
+ "custom_field_definitions": {
+ "add_cta": "Add custom field",
+ "create_label": "Create custom field",
+ "create_description": "Define a typed field your team can fill in on any matching record.",
+ "edit_description": "Update the label, key, or storefront visibility. The owner can't change once values exist.",
+ "table_title": "Custom field definitions",
+ "search_placeholder": "Search by label, namespace, or key…",
+ "empty": "No custom field definitions yet",
+ "storefront_visible": {
+ "visible": "Visible",
+ "admin_only": "Admin only"
+ },
+ "delete_confirm": {
+ "title": "Delete custom field?",
+ "message": "{{label}} will be removed along with every value stored for it."
+ }
+ },
"stock_locations": {
"add_cta": "Add stock location",
"create_label": "Create stock location",
diff --git a/packages/admin/src/nav/settings.ts b/packages/admin/src/nav/settings.ts
index 5cdc58fd97..f0e9ba902e 100644
--- a/packages/admin/src/nav/settings.ts
+++ b/packages/admin/src/nav/settings.ts
@@ -3,6 +3,7 @@ import {
KeyRoundIcon,
PercentIcon,
StoreIcon,
+ TagIcon,
UsersRoundIcon,
WarehouseIcon,
} from 'lucide-react'
@@ -54,6 +55,16 @@ settingsNav.add({
subject: Subject.StockLocation,
})
+settingsNav.add({
+ key: 'settings.custom-field-definitions',
+ label: 'Custom fields',
+ path: '/custom-field-definitions',
+ icon: TagIcon,
+ group: 'store',
+ position: 200,
+ subject: Subject.CustomFieldDefinition,
+})
+
settingsNav.add({
key: 'settings.staff',
label: 'Staff',
diff --git a/packages/admin/src/routeTree.gen.ts b/packages/admin/src/routeTree.gen.ts
index c5db86e67b..e1076edf54 100644
--- a/packages/admin/src/routeTree.gen.ts
+++ b/packages/admin/src/routeTree.gen.ts
@@ -26,6 +26,7 @@ import { Route as AuthenticatedStoreIdSettingsStoreRouteImport } from './routes/
import { Route as AuthenticatedStoreIdSettingsStockLocationsRouteImport } from './routes/_authenticated/$storeId/settings/stock-locations'
import { Route as AuthenticatedStoreIdSettingsStaffRouteImport } from './routes/_authenticated/$storeId/settings/staff'
import { Route as AuthenticatedStoreIdSettingsPaymentMethodsRouteImport } from './routes/_authenticated/$storeId/settings/payment-methods'
+import { Route as AuthenticatedStoreIdSettingsCustomFieldDefinitionsRouteImport } from './routes/_authenticated/$storeId/settings/custom-field-definitions'
import { Route as AuthenticatedStoreIdSettingsApiKeysRouteImport } from './routes/_authenticated/$storeId/settings/api-keys'
import { Route as AuthenticatedStoreIdPromotionsNewRouteImport } from './routes/_authenticated/$storeId/promotions/new'
import { Route as AuthenticatedStoreIdPromotionsGiftCardsRouteImport } from './routes/_authenticated/$storeId/promotions/gift-cards'
@@ -136,6 +137,12 @@ const AuthenticatedStoreIdSettingsPaymentMethodsRoute =
path: '/payment-methods',
getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
} as any)
+const AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute =
+ AuthenticatedStoreIdSettingsCustomFieldDefinitionsRouteImport.update({
+ id: '/custom-field-definitions',
+ path: '/custom-field-definitions',
+ getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
+ } as any)
const AuthenticatedStoreIdSettingsApiKeysRoute =
AuthenticatedStoreIdSettingsApiKeysRouteImport.update({
id: '/api-keys',
@@ -228,6 +235,7 @@ export interface FileRoutesByFullPath {
'/$storeId/promotions/gift-cards': typeof AuthenticatedStoreIdPromotionsGiftCardsRoute
'/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
+ '/$storeId/settings/custom-field-definitions': typeof AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute
'/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
'/$storeId/settings/staff': typeof AuthenticatedStoreIdSettingsStaffRoute
'/$storeId/settings/stock-locations': typeof AuthenticatedStoreIdSettingsStockLocationsRoute
@@ -256,6 +264,7 @@ export interface FileRoutesByTo {
'/$storeId/promotions/gift-cards': typeof AuthenticatedStoreIdPromotionsGiftCardsRoute
'/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
+ '/$storeId/settings/custom-field-definitions': typeof AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute
'/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
'/$storeId/settings/staff': typeof AuthenticatedStoreIdSettingsStaffRoute
'/$storeId/settings/stock-locations': typeof AuthenticatedStoreIdSettingsStockLocationsRoute
@@ -288,6 +297,7 @@ export interface FileRoutesById {
'/_authenticated/$storeId/promotions/gift-cards': typeof AuthenticatedStoreIdPromotionsGiftCardsRoute
'/_authenticated/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/_authenticated/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
+ '/_authenticated/$storeId/settings/custom-field-definitions': typeof AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute
'/_authenticated/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
'/_authenticated/$storeId/settings/staff': typeof AuthenticatedStoreIdSettingsStaffRoute
'/_authenticated/$storeId/settings/stock-locations': typeof AuthenticatedStoreIdSettingsStockLocationsRoute
@@ -320,6 +330,7 @@ export interface FileRouteTypes {
| '/$storeId/promotions/gift-cards'
| '/$storeId/promotions/new'
| '/$storeId/settings/api-keys'
+ | '/$storeId/settings/custom-field-definitions'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/staff'
| '/$storeId/settings/stock-locations'
@@ -348,6 +359,7 @@ export interface FileRouteTypes {
| '/$storeId/promotions/gift-cards'
| '/$storeId/promotions/new'
| '/$storeId/settings/api-keys'
+ | '/$storeId/settings/custom-field-definitions'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/staff'
| '/$storeId/settings/stock-locations'
@@ -379,6 +391,7 @@ export interface FileRouteTypes {
| '/_authenticated/$storeId/promotions/gift-cards'
| '/_authenticated/$storeId/promotions/new'
| '/_authenticated/$storeId/settings/api-keys'
+ | '/_authenticated/$storeId/settings/custom-field-definitions'
| '/_authenticated/$storeId/settings/payment-methods'
| '/_authenticated/$storeId/settings/staff'
| '/_authenticated/$storeId/settings/stock-locations'
@@ -518,6 +531,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedStoreIdSettingsPaymentMethodsRouteImport
parentRoute: typeof AuthenticatedStoreIdSettingsRoute
}
+ '/_authenticated/$storeId/settings/custom-field-definitions': {
+ id: '/_authenticated/$storeId/settings/custom-field-definitions'
+ path: '/custom-field-definitions'
+ fullPath: '/$storeId/settings/custom-field-definitions'
+ preLoaderRoute: typeof AuthenticatedStoreIdSettingsCustomFieldDefinitionsRouteImport
+ parentRoute: typeof AuthenticatedStoreIdSettingsRoute
+ }
'/_authenticated/$storeId/settings/api-keys': {
id: '/_authenticated/$storeId/settings/api-keys'
path: '/api-keys'
@@ -607,6 +627,7 @@ declare module '@tanstack/react-router' {
interface AuthenticatedStoreIdSettingsRouteChildren {
AuthenticatedStoreIdSettingsApiKeysRoute: typeof AuthenticatedStoreIdSettingsApiKeysRoute
+ AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute: typeof AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute
AuthenticatedStoreIdSettingsPaymentMethodsRoute: typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
AuthenticatedStoreIdSettingsStaffRoute: typeof AuthenticatedStoreIdSettingsStaffRoute
AuthenticatedStoreIdSettingsStockLocationsRoute: typeof AuthenticatedStoreIdSettingsStockLocationsRoute
@@ -619,6 +640,8 @@ const AuthenticatedStoreIdSettingsRouteChildren: AuthenticatedStoreIdSettingsRou
{
AuthenticatedStoreIdSettingsApiKeysRoute:
AuthenticatedStoreIdSettingsApiKeysRoute,
+ AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute:
+ AuthenticatedStoreIdSettingsCustomFieldDefinitionsRoute,
AuthenticatedStoreIdSettingsPaymentMethodsRoute:
AuthenticatedStoreIdSettingsPaymentMethodsRoute,
AuthenticatedStoreIdSettingsStaffRoute:
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/custom-field-definitions.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/custom-field-definitions.tsx
new file mode 100644
index 0000000000..476c959b2b
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/custom-field-definitions.tsx
@@ -0,0 +1,300 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { CustomFieldDefinition } from '@spree/admin-sdk'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { useEffect } from 'react'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { z } from 'zod/v4'
+import { adminClient } from '@/client'
+import { Can } from '@/components/spree/can'
+import { useConfirm } from '@/components/spree/confirm-dialog'
+import { DefinitionFormFields } from '@/components/spree/custom-fields/definition-form'
+import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'
+import { RowActions } from '@/components/spree/row-actions'
+import { useRowClickBridge } from '@/components/spree/row-click-bridge'
+import { Button } from '@/components/ui/button'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet'
+import {
+ useCreateCustomFieldDefinitionForSettings,
+ useCustomFieldDefinition,
+ useDeleteCustomFieldDefinitionForSettings,
+ useUpdateCustomFieldDefinitionForSettings,
+} from '@/hooks/use-custom-fields'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
+import { Subject } from '@/lib/permissions'
+import { usePermissions } from '@/providers/permission-provider'
+import {
+ CUSTOM_FIELD_DEFINITION_DEFAULTS,
+ type CustomFieldDefinitionFormValues,
+ customFieldDefinitionSchema,
+ customFieldDefinitionValuesToCreateParams,
+ customFieldDefinitionValuesToUpdateParams,
+} from '@/schemas/custom-field-definition'
+import '@/tables/custom-field-definitions'
+
+const searchSchema = resourceSearchSchema.extend({
+ edit: z.string().optional(),
+ new: z.coerce.boolean().optional(),
+})
+
+export const Route = createFileRoute('/_authenticated/$storeId/settings/custom-field-definitions')({
+ validateSearch: searchSchema,
+ component: CustomFieldDefinitionsPage,
+})
+
+function CustomFieldDefinitionsPage() {
+ const { t } = useTranslation()
+ const search = Route.useSearch() as z.infer<typeof searchSchema>
+ const navigate = useNavigate()
+ const confirm = useConfirm()
+ const deleteMutation = useDeleteCustomFieldDefinitionForSettings()
+ const { permissions } = usePermissions()
+ const canCreate = permissions.can('create', Subject.CustomFieldDefinition)
+ const canUpdate = permissions.can('update', Subject.CustomFieldDefinition)
+
+ // Gate by permission *before* honoring `?edit=`/`?new=` so a hand-crafted
+ // URL or row-click bridge can't open a sheet whose save the server will
+ // reject. Action menus also gate visibility, but deep-links bypass them.
+ const editId = canUpdate ? search.edit : undefined
+ const isCreating = canCreate && !!search.new
+
+ const closeSheet = () =>
+ navigate({
+ search: (prev: Record<string, unknown>) => {
+ const { edit: _e, new: _n, ...rest } = prev
+ return rest as never
+ },
+ })
+
+ const openCreate = () => {
+ if (!canCreate) return
+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, new: true }) as never })
+ }
+
+ const openEdit = (id: string) => {
+ if (!canUpdate) return
+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, edit: id }) as never })
+ }
+
+ useRowClickBridge('data-custom-field-definition-id', openEdit)
+
+ async function handleDelete(def: CustomFieldDefinition) {
+ const ok = await confirm({
+ title: t('admin.custom_field_definitions.delete_confirm.title'),
+ message: t('admin.custom_field_definitions.delete_confirm.message', {
+ label: def.label,
+ }),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return
+ await deleteMutation.mutateAsync(def.id).catch(() => undefined)
+ }
+
+ return (
+ <>
+ <ResourceTable<CustomFieldDefinition>
+ tableKey="custom-field-definitions"
+ queryKey="custom-field-definitions"
+ queryFn={(params) => adminClient.customFieldDefinitions.list(params)}
+ searchParams={search}
+ rowActions={(def) => (
+ <RowActions
+ actions={[
+ {
+ key: 'edit',
+ visible: canUpdate,
+ onSelect: () => openEdit(def.id),
+ },
+ {
+ key: 'delete',
+ destructive: true,
+ visible: permissions.can('destroy', Subject.CustomFieldDefinition),
+ disabled: deleteMutation.isPending,
+ onSelect: () => handleDelete(def),
+ },
+ ]}
+ />
+ )}
+ actions={
+ <Can I="create" a={Subject.CustomFieldDefinition}>
+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>
+ <PlusIcon className="size-4" />
+ {t('admin.custom_field_definitions.add_cta')}
+ </Button>
+ </Can>
+ }
+ />
+
+ {isCreating && <CreateSheet open onOpenChange={(o) => !o && closeSheet()} />}
+ {editId && <EditSheet id={editId} open onOpenChange={(o) => !o && closeSheet()} />}
+ </>
+ )
+}
+
+function CreateSheet({
+ open,
+ onOpenChange,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const createMutation = useCreateCustomFieldDefinitionForSettings()
+ const form = useForm<CustomFieldDefinitionFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(customFieldDefinitionSchema) as any,
+ defaultValues: CUSTOM_FIELD_DEFINITION_DEFAULTS,
+ })
+
+ async function onSubmit(values: CustomFieldDefinitionFormValues) {
+ try {
+ await createMutation.mutateAsync(customFieldDefinitionValuesToCreateParams(values))
+ form.reset(CUSTOM_FIELD_DEFINITION_DEFAULTS)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Sheet
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) form.reset(CUSTOM_FIELD_DEFINITION_DEFAULTS)
+ onOpenChange(next)
+ }}
+ >
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>
+ {t('admin.pages.settings.custom_field_definitions.add_sheet_title')}
+ </SheetTitle>
+ <SheetDescription>
+ {t('admin.custom_field_definitions.create_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">
+ <DefinitionFormFields form={form} showResourceType />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button type="submit" size="sm" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting
+ ? t('admin.actions.creating')
+ : t('admin.custom_field_definitions.create_label')}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function EditSheet({
+ id,
+ open,
+ onOpenChange,
+}: {
+ id: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ const { data: definition, isLoading } = useCustomFieldDefinition(id)
+ const updateMutation = useUpdateCustomFieldDefinitionForSettings(id)
+
+ const form = useForm<CustomFieldDefinitionFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(customFieldDefinitionSchema) as any,
+ defaultValues: CUSTOM_FIELD_DEFINITION_DEFAULTS,
+ })
+
+ useEffect(() => {
+ if (definition) {
+ form.reset({
+ label: definition.label,
+ namespace: definition.namespace,
+ key: definition.key,
+ field_type: definition.field_type,
+ resource_type: definition.resource_type,
+ storefront_visible: definition.storefront_visible,
+ })
+ }
+ }, [definition, form])
+
+ async function onSubmit(values: CustomFieldDefinitionFormValues) {
+ try {
+ await updateMutation.mutateAsync(customFieldDefinitionValuesToUpdateParams(values))
+ form.reset(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>
+ {definition?.label ??
+ t('admin.pages.settings.custom_field_definitions.edit_sheet_title')}
+ </SheetTitle>
+ <SheetDescription>
+ {t('admin.custom_field_definitions.edit_description')}
+ </SheetDescription>
+ </SheetHeader>
+ {isLoading ? (
+ <div className="p-4 text-sm text-muted-foreground">{t('admin.common.loading')}</div>
+ ) : (
+ <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">
+ <DefinitionFormFields
+ form={form}
+ showResourceType
+ resourceTypeReadOnly
+ fieldTypeReadOnly
+ />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ {t('admin.actions.cancel')}
+ </Button>
+ <Button
+ type="submit"
+ size="sm"
+ disabled={form.formState.isSubmitting || !form.formState.isDirty}
+ >
+ {form.formState.isSubmitting ? t('admin.actions.saving') : t('admin.actions.save')}
+ </Button>
+ </SheetFooter>
+ </form>
+ )}
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/packages/admin/src/schemas/custom-field-definition.ts b/packages/admin/src/schemas/custom-field-definition.ts
new file mode 100644
index 0000000000..d6f968a5eb
--- /dev/null
+++ b/packages/admin/src/schemas/custom-field-definition.ts
@@ -0,0 +1,110 @@
+import type {
+ CustomFieldDefinitionCreateParams,
+ CustomFieldDefinitionUpdateParams,
+} from '@spree/admin-sdk'
+import { z } from 'zod/v4'
+import { i18n } from '@/lib/i18n'
+import { requiredMessage } from '@/lib/validation-messages'
+
+// Mirrors `Spree::Metafield::FIELD_TYPE_TOKENS` on the backend. Keep in sync
+// with the typelized `field_type` union on `CustomFieldDefinition`. Labels
+// come from i18n via `fieldTypeLabel()` below.
+export const FIELD_TYPES = [
+ 'short_text',
+ 'long_text',
+ 'rich_text',
+ 'number',
+ 'boolean',
+ 'json',
+] as const
+
+export type FieldType = (typeof FIELD_TYPES)[number]
+
+export function fieldTypeLabel(value: string): string {
+ return i18n.t(`admin.fields.custom_field_definition.field_type.options.${value}`, {
+ defaultValue: value,
+ })
+}
+
+// Owner types that have a first-class admin UI. The server allows more (see
+// `Spree.metafields.enabled_resources`); these are the ones admins can pick
+// when defining a field. Extending this is a one-line add — the API already
+// accepts any resource type registered in core.
+export const DEFAULT_RESOURCE_TYPES = [
+ 'Spree::Product',
+ 'Spree::Variant',
+ 'Spree::Order',
+ 'Spree::User',
+ 'Spree::Category',
+ 'Spree::OptionType',
+] as const
+
+export type ResourceType = (typeof DEFAULT_RESOURCE_TYPES)[number] | (string & {})
+
+export function resourceTypeLabel(value: string): string {
+ // `nsSeparator: false` because resource type keys contain `::`, which
+ // i18next would otherwise parse as a namespace separator and miss the
+ // lookup. `defaultValue` strips the `Spree::` prefix for any owner the
+ // i18n bundle doesn't enumerate (plugin-defined resource types).
+ return i18n.t(`admin.fields.custom_field_definition.resource_type.options.${value}`, {
+ nsSeparator: false,
+ defaultValue: value.replace(/^Spree::/, ''),
+ })
+}
+
+export const customFieldDefinitionSchema = z.object({
+ label: z.string().min(1, { error: requiredMessage('custom_field_definition.label') }),
+ namespace: z.string().min(1, { error: requiredMessage('custom_field_definition.namespace') }),
+ key: z
+ .string()
+ .min(1, { error: requiredMessage('custom_field_definition.key') })
+ .regex(/^[a-z0-9_]+$/i, {
+ error: () => i18n.t('admin.fields.custom_field_definition.key.invalid_format'),
+ }),
+ field_type: z.enum(FIELD_TYPES),
+ resource_type: z
+ .string()
+ .min(1, { error: requiredMessage('custom_field_definition.resource_type') }),
+ storefront_visible: z.boolean(),
+})
+
+export type CustomFieldDefinitionFormValues = z.infer<typeof customFieldDefinitionSchema>
+
+export const CUSTOM_FIELD_DEFINITION_DEFAULTS: CustomFieldDefinitionFormValues = {
+ label: '',
+ namespace: 'custom',
+ key: '',
+ field_type: 'short_text',
+ resource_type: 'Spree::Product',
+ storefront_visible: false,
+}
+
+export function customFieldDefinitionValuesToCreateParams(
+ v: CustomFieldDefinitionFormValues,
+): CustomFieldDefinitionCreateParams {
+ return {
+ label: v.label,
+ namespace: v.namespace,
+ key: v.key,
+ field_type: v.field_type,
+ resource_type: v.resource_type,
+ storefront_visible: v.storefront_visible,
+ }
+}
+
+export function customFieldDefinitionValuesToUpdateParams(
+ v: CustomFieldDefinitionFormValues,
+): CustomFieldDefinitionUpdateParams {
+ // `resource_type` and `field_type` are intentionally omitted — changing
+ // either would orphan or invalidate stored values. `Spree::Metafield` rows
+ // serialize via their own STI subclass (set from the definition at write
+ // time), so flipping `field_type` post-hoc would leave existing values
+ // misinterpreted by the UI. The controller still accepts these fields;
+ // the UI just doesn't offer them as editable.
+ return {
+ label: v.label,
+ namespace: v.namespace,
+ key: v.key,
+ storefront_visible: v.storefront_visible,
+ }
+}
diff --git a/packages/admin/src/tables/custom-field-definitions.tsx b/packages/admin/src/tables/custom-field-definitions.tsx
new file mode 100644
index 0000000000..0fa954e7c1
--- /dev/null
+++ b/packages/admin/src/tables/custom-field-definitions.tsx
@@ -0,0 +1,80 @@
+import type { CustomFieldDefinition } from '@spree/admin-sdk'
+import { TagIcon } from 'lucide-react'
+import { ResourceNameCell } from '@/components/spree/resource-name-cell'
+import { ActiveBadge, Badge } from '@/components/ui/badge'
+import { i18n } from '@/lib/i18n'
+import { defineTable } from '@/lib/table-registry'
+import {
+ DEFAULT_RESOURCE_TYPES,
+ FIELD_TYPES,
+ fieldTypeLabel,
+ resourceTypeLabel,
+} from '@/schemas/custom-field-definition'
+
+const t = (key: string) => i18n.t(key)
+
+defineTable<CustomFieldDefinition>('custom-field-definitions', {
+ title: t('admin.custom_field_definitions.table_title'),
+ searchParam: 'search',
+ searchPlaceholder: t('admin.custom_field_definitions.search_placeholder'),
+ defaultSort: { field: 'resource_type', direction: 'asc' },
+ emptyIcon: <TagIcon className="size-8 text-muted-foreground" />,
+ emptyMessage: t('admin.custom_field_definitions.empty'),
+ columns: [
+ {
+ key: 'name',
+ label: t('admin.fields.custom_field_definition.label.label'),
+ sortable: true,
+ filterable: true,
+ default: true,
+ ransackAttribute: 'name',
+ render: (def) => (
+ <ResourceNameCell
+ id={def.id}
+ dataAttr="data-custom-field-definition-id"
+ name={def.label}
+ secondary={
+ <code className="font-mono">
+ {def.namespace}.{def.key}
+ </code>
+ }
+ />
+ ),
+ },
+ {
+ key: 'resource_type',
+ label: t('admin.fields.custom_field_definition.resource_type.label'),
+ sortable: true,
+ filterable: true,
+ filterType: 'enum',
+ filterOptions: DEFAULT_RESOURCE_TYPES.map((value) => ({
+ value,
+ label: resourceTypeLabel(value),
+ })),
+ default: true,
+ render: (def) => <Badge variant="secondary">{resourceTypeLabel(def.resource_type)}</Badge>,
+ },
+ {
+ key: 'field_type',
+ label: t('admin.fields.custom_field_definition.field_type.label'),
+ sortable: true,
+ filterable: true,
+ filterType: 'enum',
+ filterOptions: FIELD_TYPES.map((value) => ({ value, label: fieldTypeLabel(value) })),
+ default: true,
+ render: (def) => <Badge variant="outline">{fieldTypeLabel(def.field_type)}</Badge>,
+ },
+ {
+ key: 'storefront_visible',
+ label: t('admin.fields.custom_field_definition.storefront_visible.column_label'),
+ default: true,
+ render: (def) => (
+ <ActiveBadge
+ active={def.storefront_visible}
+ activeLabel={t('admin.custom_field_definitions.storefront_visible.visible')}
+ inactiveLabel={t('admin.custom_field_definitions.storefront_visible.admin_only')}
+ />
+ ),
+ },
+ ],
+})