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.

Sprint 4 SPA — promotion editor + universal preferences form

Damian Legawiec1407f52e0d4a
diff --git a/packages/admin/src/components/spree/preferences-form.tsx b/packages/admin/src/components/spree/preferences-form.tsx
new file mode 100644
index 0000000000..eb05d4734f
--- /dev/null
+++ b/packages/admin/src/components/spree/preferences-form.tsx
@@ -0,0 +1,195 @@
+import type { PreferenceField as PreferenceFieldDef } from '@spree/admin-sdk'
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Input } from '@/components/ui/input'
+import { Switch } from '@/components/ui/switch'
+import { Textarea } from '@/components/ui/textarea'
+
+interface PreferencesFormProps {
+ schema: PreferenceFieldDef[]
+ values: Record<string, unknown>
+ onChange: (next: Record<string, unknown>) => void
+ /** When true, replaces sensitive `password`-typed fields with a stub label. */
+ redactPasswords?: boolean
+ /** Optional human-readable name overrides keyed by preference key. */
+ labelOverrides?: Record<string, string>
+}
+
+/**
+ * Renders a generic configuration form from a `preference_schema` payload.
+ * Used by the Payment Methods edit sheet and the Promotion editor's action
+ * and rule cards — anywhere we let admins tune a STI subclass's settings
+ * without hard-coding a per-subclass form.
+ *
+ * The schema itself is the source of truth; this component intentionally
+ * stays "dumb" — server-side validation surfaces errors back via the
+ * mutation hook's error handling. Booleans are switches, strings are
+ * inputs, integers/decimals get number inputs, and unknown types fall
+ * back to a plain text input.
+ */
+export function PreferencesForm({
+ schema,
+ values,
+ onChange,
+ redactPasswords = false,
+ labelOverrides,
+}: PreferencesFormProps) {
+ if (!schema?.length) return null
+
+ function setValue(key: string, value: unknown) {
+ onChange({ ...values, [key]: value })
+ }
+
+ return (
+ <FieldGroup>
+ {schema.map((field) => (
+ <PreferenceField
+ key={field.key}
+ field={field}
+ value={values[field.key] ?? field.default}
+ label={labelOverrides?.[field.key]}
+ onChange={(v) => setValue(field.key, v)}
+ redactPasswords={redactPasswords}
+ />
+ ))}
+ </FieldGroup>
+ )
+}
+
+interface PreferenceFieldProps {
+ field: PreferenceFieldDef
+ value: unknown
+ label?: string
+ onChange: (value: unknown) => void
+ redactPasswords?: boolean
+}
+
+export function PreferenceField({
+ field,
+ value,
+ label,
+ onChange,
+ redactPasswords,
+}: PreferenceFieldProps) {
+ const id = `preference-${field.key}`
+ const displayLabel = label ?? humanizeKey(field.key)
+
+ switch (field.type) {
+ case 'boolean':
+ return (
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <FieldLabel htmlFor={id} className="cursor-pointer">
+ {displayLabel}
+ </FieldLabel>
+ <Switch id={id} checked={!!value} onCheckedChange={(checked) => onChange(checked)} />
+ </div>
+ </Field>
+ )
+
+ case 'text':
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
+ <Textarea
+ id={id}
+ rows={4}
+ value={(value as string) ?? ''}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ </Field>
+ )
+
+ case 'integer':
+ case 'decimal':
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
+ <Input
+ id={id}
+ type="number"
+ step={field.type === 'integer' ? 1 : 'any'}
+ value={value === null || value === undefined ? '' : String(value)}
+ onChange={(e) => {
+ const raw = e.target.value
+ if (raw === '') return onChange(null)
+ const parsed = field.type === 'integer' ? parseInt(raw, 10) : parseFloat(raw)
+ onChange(Number.isNaN(parsed) ? null : parsed)
+ }}
+ />
+ </Field>
+ )
+
+ case 'array':
+ // A generic "comma-separated list" works for the common case where
+ // arrays hold IDs or short tokens. Subclasses with structured
+ // arrays (option values, eligible products) ship with custom
+ // editors and don't reach here.
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
+ <Input
+ id={id}
+ value={Array.isArray(value) ? value.join(', ') : ((value as string) ?? '')}
+ placeholder="comma-separated"
+ onChange={(e) =>
+ onChange(
+ e.target.value
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean),
+ )
+ }
+ />
+ <span className="text-xs text-muted-foreground">Separate values with commas.</span>
+ </Field>
+ )
+
+ case 'password':
+ if (redactPasswords) {
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
+ <Input
+ id={id}
+ type="password"
+ autoComplete="new-password"
+ placeholder="Stored — leave blank to keep current"
+ value={(value as string) ?? ''}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ </Field>
+ )
+ }
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
+ <Input
+ id={id}
+ type="password"
+ autoComplete="new-password"
+ value={(value as string) ?? ''}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ </Field>
+ )
+
+ default:
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
+ <Input
+ id={id}
+ value={(value as string) ?? ''}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ </Field>
+ )
+ }
+}
+
+function humanizeKey(key: string): string {
+ return key
+ .split('_')
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(' ')
+}
diff --git a/packages/admin/src/hooks/use-promotions.ts b/packages/admin/src/hooks/use-promotions.ts
new file mode 100644
index 0000000000..1bb384d1a0
--- /dev/null
+++ b/packages/admin/src/hooks/use-promotions.ts
@@ -0,0 +1,201 @@
+import type {
+ Promotion,
+ PromotionAction,
+ PromotionActionCreateParams,
+ PromotionActionUpdateParams,
+ PromotionCreateParams,
+ PromotionRule,
+ PromotionRuleCreateParams,
+ PromotionRuleUpdateParams,
+ PromotionUpdateParams,
+} from '@spree/admin-sdk'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { adminClient } from '@/client'
+import { useResourceMutation } from '@/hooks/use-resource-mutation'
+
+export const promotionsQueryKey = ['promotions'] as const
+
+export function promotionQueryKey(id: string) {
+ return ['promotions', id] as const
+}
+
+export function promotionActionsQueryKey(promotionId: string) {
+ return ['promotions', promotionId, 'actions'] as const
+}
+
+export function promotionRulesQueryKey(promotionId: string) {
+ return ['promotions', promotionId, 'rules'] as const
+}
+
+export function promotionCouponCodesQueryKey(promotionId: string) {
+ return ['promotions', promotionId, 'coupon-codes'] as const
+}
+
+interface UsePromotionsParams {
+ page?: number
+ limit?: number
+}
+
+export function usePromotion(id: string | undefined) {
+ return useQuery({
+ queryKey: id ? promotionQueryKey(id) : ['promotions', 'noop'],
+ queryFn: () => adminClient.promotions.get(id as string),
+ enabled: !!id,
+ })
+}
+
+export function useCreatePromotion() {
+ return useResourceMutation<Promotion, Error, PromotionCreateParams>({
+ mutationFn: (params) => adminClient.promotions.create(params),
+ invalidate: [promotionsQueryKey],
+ successMessage: 'Promotion created',
+ errorMessage: 'Failed to create promotion',
+ })
+}
+
+export function useUpdatePromotion(id: string) {
+ return useResourceMutation<Promotion, Error, PromotionUpdateParams>({
+ mutationFn: (params) => adminClient.promotions.update(id, params),
+ invalidate: [promotionsQueryKey, promotionQueryKey(id)],
+ successMessage: 'Promotion updated',
+ errorMessage: 'Failed to update promotion',
+ })
+}
+
+export function useDeletePromotion() {
+ const queryClient = useQueryClient()
+
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (id) => adminClient.promotions.delete(id),
+ invalidate: [promotionsQueryKey],
+ successMessage: 'Promotion deleted',
+ errorMessage: 'Failed to delete promotion',
+ onSuccess: (_data, id) => {
+ queryClient.removeQueries({ queryKey: promotionQueryKey(id) })
+ },
+ })
+}
+
+// ============================================
+// Actions
+// ============================================
+
+export function usePromotionActions(promotionId: string | undefined) {
+ return useQuery({
+ queryKey: promotionId
+ ? promotionActionsQueryKey(promotionId)
+ : ['promotions', 'noop', 'actions'],
+ queryFn: () => adminClient.promotions.actions.list(promotionId as string, { limit: 100 }),
+ enabled: !!promotionId,
+ })
+}
+
+export function useCreatePromotionAction(promotionId: string) {
+ return useResourceMutation<PromotionAction, Error, PromotionActionCreateParams>({
+ mutationFn: (params) => adminClient.promotions.actions.create(promotionId, params),
+ invalidate: [promotionActionsQueryKey(promotionId), promotionQueryKey(promotionId)],
+ successMessage: 'Action added',
+ errorMessage: 'Failed to add action',
+ })
+}
+
+export function useUpdatePromotionAction(promotionId: string, actionId: string) {
+ return useResourceMutation<PromotionAction, Error, PromotionActionUpdateParams>({
+ mutationFn: (params) => adminClient.promotions.actions.update(promotionId, actionId, params),
+ invalidate: [promotionActionsQueryKey(promotionId), promotionQueryKey(promotionId)],
+ successMessage: 'Action updated',
+ errorMessage: 'Failed to update action',
+ })
+}
+
+export function useDeletePromotionAction(promotionId: string) {
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (actionId) => adminClient.promotions.actions.delete(promotionId, actionId),
+ invalidate: [promotionActionsQueryKey(promotionId), promotionQueryKey(promotionId)],
+ successMessage: 'Action removed',
+ errorMessage: 'Failed to remove action',
+ })
+}
+
+// ============================================
+// Rules
+// ============================================
+
+export function usePromotionRules(promotionId: string | undefined) {
+ return useQuery({
+ queryKey: promotionId ? promotionRulesQueryKey(promotionId) : ['promotions', 'noop', 'rules'],
+ queryFn: () => adminClient.promotions.rules.list(promotionId as string, { limit: 100 }),
+ enabled: !!promotionId,
+ })
+}
+
+export function useCreatePromotionRule(promotionId: string) {
+ return useResourceMutation<PromotionRule, Error, PromotionRuleCreateParams>({
+ mutationFn: (params) => adminClient.promotions.rules.create(promotionId, params),
+ invalidate: [promotionRulesQueryKey(promotionId), promotionQueryKey(promotionId)],
+ successMessage: 'Rule added',
+ errorMessage: 'Failed to add rule',
+ })
+}
+
+export function useUpdatePromotionRule(promotionId: string, ruleId: string) {
+ return useResourceMutation<PromotionRule, Error, PromotionRuleUpdateParams>({
+ mutationFn: (params) => adminClient.promotions.rules.update(promotionId, ruleId, params),
+ invalidate: [promotionRulesQueryKey(promotionId), promotionQueryKey(promotionId)],
+ successMessage: 'Rule updated',
+ errorMessage: 'Failed to update rule',
+ })
+}
+
+export function useDeletePromotionRule(promotionId: string) {
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (ruleId) => adminClient.promotions.rules.delete(promotionId, ruleId),
+ invalidate: [promotionRulesQueryKey(promotionId), promotionQueryKey(promotionId)],
+ successMessage: 'Rule removed',
+ errorMessage: 'Failed to remove rule',
+ })
+}
+
+// ============================================
+// Coupon codes (read-only)
+// ============================================
+
+export function usePromotionCouponCodes(
+ promotionId: string | undefined,
+ params: UsePromotionsParams = {},
+) {
+ return useQuery({
+ queryKey: promotionId
+ ? [...promotionCouponCodesQueryKey(promotionId), params]
+ : ['promotions', 'noop', 'coupon-codes'],
+ queryFn: () =>
+ adminClient.promotions.couponCodes.list(promotionId as string, {
+ page: params.page ?? 1,
+ limit: params.limit ?? 50,
+ }),
+ enabled: !!promotionId,
+ })
+}
+
+// ============================================
+// Type registries (cached forever — registries are static at runtime)
+// ============================================
+
+export const promotionActionTypesQueryKey = ['promotion-actions', 'types'] as const
+export const promotionRuleTypesQueryKey = ['promotion-rules', 'types'] as const
+
+export function usePromotionActionTypes() {
+ return useQuery({
+ queryKey: promotionActionTypesQueryKey,
+ queryFn: () => adminClient.promotionActions.types(),
+ staleTime: Infinity,
+ })
+}
+
+export function usePromotionRuleTypes() {
+ return useQuery({
+ queryKey: promotionRuleTypesQueryKey,
+ queryFn: () => adminClient.promotionRules.types(),
+ staleTime: Infinity,
+ })
+}
diff --git a/packages/admin/src/lib/permissions.ts b/packages/admin/src/lib/permissions.ts
index 0554579278..fad98cb4df 100644
--- a/packages/admin/src/lib/permissions.ts
+++ b/packages/admin/src/lib/permissions.ts
@@ -24,6 +24,8 @@ export const Subject = {
StockItem: 'Spree::StockItem',
StockTransfer: 'Spree::StockTransfer',
Promotion: 'Spree::Promotion',
+ PromotionAction: 'Spree::PromotionAction',
+ PromotionRule: 'Spree::PromotionRule',
Wishlist: 'Spree::Wishlist',
} as const
diff --git a/packages/admin/src/routeTree.gen.ts b/packages/admin/src/routeTree.gen.ts
index 915a4d4f3d..2c84bbf8d4 100644
--- a/packages/admin/src/routeTree.gen.ts
+++ b/packages/admin/src/routeTree.gen.ts
@@ -17,6 +17,7 @@ import { Route as AuthenticatedStoreIdRouteImport } from './routes/_authenticate
import { Route as AuthenticatedStoreIdIndexRouteImport } from './routes/_authenticated/$storeId/index'
import { Route as AuthenticatedStoreIdSettingsRouteImport } from './routes/_authenticated/$storeId/settings'
import { Route as AuthenticatedStoreIdSettingsIndexRouteImport } from './routes/_authenticated/$storeId/settings/index'
+import { Route as AuthenticatedStoreIdPromotionsIndexRouteImport } from './routes/_authenticated/$storeId/promotions/index'
import { Route as AuthenticatedStoreIdProductsIndexRouteImport } from './routes/_authenticated/$storeId/products/index'
import { Route as AuthenticatedStoreIdOrdersIndexRouteImport } from './routes/_authenticated/$storeId/orders/index'
import { Route as AuthenticatedStoreIdCustomersIndexRouteImport } from './routes/_authenticated/$storeId/customers/index'
@@ -27,6 +28,8 @@ import { Route as AuthenticatedStoreIdSettingsStockLocationsRouteImport } from '
import { Route as AuthenticatedStoreIdSettingsStaffRouteImport } from './routes/_authenticated/$storeId/settings/staff'
import { Route as AuthenticatedStoreIdSettingsPaymentMethodsRouteImport } from './routes/_authenticated/$storeId/settings/payment-methods'
import { Route as AuthenticatedStoreIdSettingsApiKeysRouteImport } from './routes/_authenticated/$storeId/settings/api-keys'
+import { Route as AuthenticatedStoreIdPromotionsNewRouteImport } from './routes/_authenticated/$storeId/promotions/new'
+import { Route as AuthenticatedStoreIdPromotionsPromotionIdRouteImport } from './routes/_authenticated/$storeId/promotions/$promotionId'
import { Route as AuthenticatedStoreIdProductsProductIdRouteImport } from './routes/_authenticated/$storeId/products/$productId'
import { Route as AuthenticatedStoreIdOrdersNewRouteImport } from './routes/_authenticated/$storeId/orders/new'
import { Route as AuthenticatedStoreIdOrdersDraftsRouteImport } from './routes/_authenticated/$storeId/orders/drafts'
@@ -76,6 +79,12 @@ const AuthenticatedStoreIdSettingsIndexRoute =
path: '/',
getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
} as any)
+const AuthenticatedStoreIdPromotionsIndexRoute =
+ AuthenticatedStoreIdPromotionsIndexRouteImport.update({
+ id: '/promotions/',
+ path: '/promotions/',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
const AuthenticatedStoreIdProductsIndexRoute =
AuthenticatedStoreIdProductsIndexRouteImport.update({
id: '/products/',
@@ -136,6 +145,18 @@ const AuthenticatedStoreIdSettingsApiKeysRoute =
path: '/api-keys',
getParentRoute: () => AuthenticatedStoreIdSettingsRoute,
} as any)
+const AuthenticatedStoreIdPromotionsNewRoute =
+ AuthenticatedStoreIdPromotionsNewRouteImport.update({
+ id: '/promotions/new',
+ path: '/promotions/new',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
+const AuthenticatedStoreIdPromotionsPromotionIdRoute =
+ AuthenticatedStoreIdPromotionsPromotionIdRouteImport.update({
+ id: '/promotions/$promotionId',
+ path: '/promotions/$promotionId',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
const AuthenticatedStoreIdProductsProductIdRoute =
AuthenticatedStoreIdProductsProductIdRouteImport.update({
id: '/products/$productId',
@@ -179,6 +200,8 @@ export interface FileRoutesByFullPath {
'/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute
'/$storeId/orders/new': typeof AuthenticatedStoreIdOrdersNewRoute
'/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute
+ '/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ '/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
'/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
'/$storeId/settings/staff': typeof AuthenticatedStoreIdSettingsStaffRoute
@@ -189,6 +212,7 @@ export interface FileRoutesByFullPath {
'/$storeId/customers/': typeof AuthenticatedStoreIdCustomersIndexRoute
'/$storeId/orders/': typeof AuthenticatedStoreIdOrdersIndexRoute
'/$storeId/products/': typeof AuthenticatedStoreIdProductsIndexRoute
+ '/$storeId/promotions/': typeof AuthenticatedStoreIdPromotionsIndexRoute
'/$storeId/settings/': typeof AuthenticatedStoreIdSettingsIndexRoute
}
export interface FileRoutesByTo {
@@ -201,6 +225,8 @@ export interface FileRoutesByTo {
'/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute
'/$storeId/orders/new': typeof AuthenticatedStoreIdOrdersNewRoute
'/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute
+ '/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ '/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
'/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
'/$storeId/settings/staff': typeof AuthenticatedStoreIdSettingsStaffRoute
@@ -211,6 +237,7 @@ export interface FileRoutesByTo {
'/$storeId/customers': typeof AuthenticatedStoreIdCustomersIndexRoute
'/$storeId/orders': typeof AuthenticatedStoreIdOrdersIndexRoute
'/$storeId/products': typeof AuthenticatedStoreIdProductsIndexRoute
+ '/$storeId/promotions': typeof AuthenticatedStoreIdPromotionsIndexRoute
'/$storeId/settings': typeof AuthenticatedStoreIdSettingsIndexRoute
}
export interface FileRoutesById {
@@ -227,6 +254,8 @@ export interface FileRoutesById {
'/_authenticated/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute
'/_authenticated/$storeId/orders/new': typeof AuthenticatedStoreIdOrdersNewRoute
'/_authenticated/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute
+ '/_authenticated/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ '/_authenticated/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/_authenticated/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
'/_authenticated/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
'/_authenticated/$storeId/settings/staff': typeof AuthenticatedStoreIdSettingsStaffRoute
@@ -237,6 +266,7 @@ export interface FileRoutesById {
'/_authenticated/$storeId/customers/': typeof AuthenticatedStoreIdCustomersIndexRoute
'/_authenticated/$storeId/orders/': typeof AuthenticatedStoreIdOrdersIndexRoute
'/_authenticated/$storeId/products/': typeof AuthenticatedStoreIdProductsIndexRoute
+ '/_authenticated/$storeId/promotions/': typeof AuthenticatedStoreIdPromotionsIndexRoute
'/_authenticated/$storeId/settings/': typeof AuthenticatedStoreIdSettingsIndexRoute
}
export interface FileRouteTypes {
@@ -253,6 +283,8 @@ export interface FileRouteTypes {
| '/$storeId/orders/drafts'
| '/$storeId/orders/new'
| '/$storeId/products/$productId'
+ | '/$storeId/promotions/$promotionId'
+ | '/$storeId/promotions/new'
| '/$storeId/settings/api-keys'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/staff'
@@ -263,6 +295,7 @@ export interface FileRouteTypes {
| '/$storeId/customers/'
| '/$storeId/orders/'
| '/$storeId/products/'
+ | '/$storeId/promotions/'
| '/$storeId/settings/'
fileRoutesByTo: FileRoutesByTo
to:
@@ -275,6 +308,8 @@ export interface FileRouteTypes {
| '/$storeId/orders/drafts'
| '/$storeId/orders/new'
| '/$storeId/products/$productId'
+ | '/$storeId/promotions/$promotionId'
+ | '/$storeId/promotions/new'
| '/$storeId/settings/api-keys'
| '/$storeId/settings/payment-methods'
| '/$storeId/settings/staff'
@@ -285,6 +320,7 @@ export interface FileRouteTypes {
| '/$storeId/customers'
| '/$storeId/orders'
| '/$storeId/products'
+ | '/$storeId/promotions'
| '/$storeId/settings'
id:
| '__root__'
@@ -300,6 +336,8 @@ export interface FileRouteTypes {
| '/_authenticated/$storeId/orders/drafts'
| '/_authenticated/$storeId/orders/new'
| '/_authenticated/$storeId/products/$productId'
+ | '/_authenticated/$storeId/promotions/$promotionId'
+ | '/_authenticated/$storeId/promotions/new'
| '/_authenticated/$storeId/settings/api-keys'
| '/_authenticated/$storeId/settings/payment-methods'
| '/_authenticated/$storeId/settings/staff'
@@ -310,6 +348,7 @@ export interface FileRouteTypes {
| '/_authenticated/$storeId/customers/'
| '/_authenticated/$storeId/orders/'
| '/_authenticated/$storeId/products/'
+ | '/_authenticated/$storeId/promotions/'
| '/_authenticated/$storeId/settings/'
fileRoutesById: FileRoutesById
}
@@ -377,6 +416,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedStoreIdSettingsIndexRouteImport
parentRoute: typeof AuthenticatedStoreIdSettingsRoute
}
+ '/_authenticated/$storeId/promotions/': {
+ id: '/_authenticated/$storeId/promotions/'
+ path: '/promotions'
+ fullPath: '/$storeId/promotions/'
+ preLoaderRoute: typeof AuthenticatedStoreIdPromotionsIndexRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
'/_authenticated/$storeId/products/': {
id: '/_authenticated/$storeId/products/'
path: '/products'
@@ -447,6 +493,20 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedStoreIdSettingsApiKeysRouteImport
parentRoute: typeof AuthenticatedStoreIdSettingsRoute
}
+ '/_authenticated/$storeId/promotions/new': {
+ id: '/_authenticated/$storeId/promotions/new'
+ path: '/promotions/new'
+ fullPath: '/$storeId/promotions/new'
+ preLoaderRoute: typeof AuthenticatedStoreIdPromotionsNewRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
+ '/_authenticated/$storeId/promotions/$promotionId': {
+ id: '/_authenticated/$storeId/promotions/$promotionId'
+ path: '/promotions/$promotionId'
+ fullPath: '/$storeId/promotions/$promotionId'
+ preLoaderRoute: typeof AuthenticatedStoreIdPromotionsPromotionIdRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
'/_authenticated/$storeId/products/$productId': {
id: '/_authenticated/$storeId/products/$productId'
path: '/products/$productId'
@@ -529,9 +589,12 @@ interface AuthenticatedStoreIdRouteChildren {
AuthenticatedStoreIdOrdersDraftsRoute: typeof AuthenticatedStoreIdOrdersDraftsRoute
AuthenticatedStoreIdOrdersNewRoute: typeof AuthenticatedStoreIdOrdersNewRoute
AuthenticatedStoreIdProductsProductIdRoute: typeof AuthenticatedStoreIdProductsProductIdRoute
+ AuthenticatedStoreIdPromotionsPromotionIdRoute: typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ AuthenticatedStoreIdPromotionsNewRoute: typeof AuthenticatedStoreIdPromotionsNewRoute
AuthenticatedStoreIdCustomersIndexRoute: typeof AuthenticatedStoreIdCustomersIndexRoute
AuthenticatedStoreIdOrdersIndexRoute: typeof AuthenticatedStoreIdOrdersIndexRoute
AuthenticatedStoreIdProductsIndexRoute: typeof AuthenticatedStoreIdProductsIndexRoute
+ AuthenticatedStoreIdPromotionsIndexRoute: typeof AuthenticatedStoreIdPromotionsIndexRoute
}
const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {
@@ -546,11 +609,17 @@ const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {
AuthenticatedStoreIdOrdersNewRoute: AuthenticatedStoreIdOrdersNewRoute,
AuthenticatedStoreIdProductsProductIdRoute:
AuthenticatedStoreIdProductsProductIdRoute,
+ AuthenticatedStoreIdPromotionsPromotionIdRoute:
+ AuthenticatedStoreIdPromotionsPromotionIdRoute,
+ AuthenticatedStoreIdPromotionsNewRoute:
+ AuthenticatedStoreIdPromotionsNewRoute,
AuthenticatedStoreIdCustomersIndexRoute:
AuthenticatedStoreIdCustomersIndexRoute,
AuthenticatedStoreIdOrdersIndexRoute: AuthenticatedStoreIdOrdersIndexRoute,
AuthenticatedStoreIdProductsIndexRoute:
AuthenticatedStoreIdProductsIndexRoute,
+ AuthenticatedStoreIdPromotionsIndexRoute:
+ AuthenticatedStoreIdPromotionsIndexRoute,
}
const AuthenticatedStoreIdRouteWithChildren =
diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx
new file mode 100644
index 0000000000..681f7ca812
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/$promotionId.tsx
@@ -0,0 +1,894 @@
+import type { PromotionAction, PromotionRule, ResourceTypeDefinition } from '@spree/admin-sdk'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { PlusIcon, TrashIcon } from 'lucide-react'
+import { useEffect, useState } from 'react'
+import { Controller, useForm } from 'react-hook-form'
+import { Can } from '@/components/spree/can'
+import { useConfirm } from '@/components/spree/confirm-dialog'
+import { PageHeader } from '@/components/spree/page-header'
+import { PreferencesForm } from '@/components/spree/preferences-form'
+import { ResourceLayout } from '@/components/spree/resource-layout'
+import { Badge } from '@/components/ui/badge'
+import { Button } from '@/components/ui/button'
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Input } from '@/components/ui/input'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet'
+import { Switch } from '@/components/ui/switch'
+import { Textarea } from '@/components/ui/textarea'
+import {
+ useCreatePromotionAction,
+ useCreatePromotionRule,
+ useDeletePromotion,
+ useDeletePromotionAction,
+ useDeletePromotionRule,
+ usePromotion,
+ usePromotionActions,
+ usePromotionActionTypes,
+ usePromotionCouponCodes,
+ usePromotionRules,
+ usePromotionRuleTypes,
+ useUpdatePromotion,
+ useUpdatePromotionAction,
+ useUpdatePromotionRule,
+} from '@/hooks/use-promotions'
+import { Subject } from '@/lib/permissions'
+
+export const Route = createFileRoute('/_authenticated/$storeId/promotions/$promotionId')({
+ component: EditPromotionPage,
+})
+
+interface BasicsFormValues {
+ name: string
+ description: string
+ starts_at: string
+ expires_at: string
+ usage_limit: number | undefined
+ match_policy: 'all' | 'any'
+ advertise: boolean
+}
+
+function EditPromotionPage() {
+ const { storeId, promotionId } = Route.useParams()
+ const navigate = useNavigate()
+ const { data: promotion, isLoading } = usePromotion(promotionId)
+ const updateMutation = useUpdatePromotion(promotionId)
+ const deleteMutation = useDeletePromotion()
+ const confirm = useConfirm()
+
+ const form = useForm<BasicsFormValues>({
+ defaultValues: {
+ name: '',
+ description: '',
+ starts_at: '',
+ expires_at: '',
+ usage_limit: undefined,
+ match_policy: 'all',
+ advertise: false,
+ },
+ })
+
+ useEffect(() => {
+ if (promotion) {
+ form.reset({
+ name: promotion.name,
+ description: promotion.description ?? '',
+ starts_at: promotion.starts_at ? promotion.starts_at.slice(0, 16) : '',
+ expires_at: promotion.expires_at ? promotion.expires_at.slice(0, 16) : '',
+ usage_limit: promotion.usage_limit ?? undefined,
+ match_policy: (promotion.match_policy as 'all' | 'any') ?? 'all',
+ advertise: promotion.advertise,
+ })
+ }
+ }, [promotion, form])
+
+ async function onSubmit(values: BasicsFormValues) {
+ await updateMutation.mutateAsync({
+ name: values.name,
+ description: values.description?.length ? values.description : null,
+ starts_at: values.starts_at || null,
+ expires_at: values.expires_at || null,
+ usage_limit: values.usage_limit ?? null,
+ match_policy: values.match_policy,
+ advertise: values.advertise,
+ })
+ }
+
+ async function onDelete() {
+ const ok = await confirm({
+ title: 'Delete promotion?',
+ message: `${promotion?.name ?? 'This promotion'} will be removed permanently. Promotions referenced by completed orders cannot be deleted.`,
+ variant: 'destructive',
+ confirmLabel: 'Delete',
+ })
+ if (!ok) return
+ await deleteMutation.mutateAsync(promotionId)
+ navigate({ to: '/$storeId/promotions', params: { storeId } })
+ }
+
+ if (isLoading || !promotion) {
+ return (
+ <ResourceLayout
+ header={<PageHeader title="Loading…" backTo="promotions" />}
+ main={<div className="text-sm text-muted-foreground">Loading promotion…</div>}
+ />
+ )
+ }
+
+ return (
+ <ResourceLayout
+ header={
+ <PageHeader
+ title={promotion.name}
+ backTo="promotions"
+ actions={
+ <div className="flex gap-2">
+ <Can I="destroy" a={Subject.Promotion}>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ onClick={onDelete}
+ disabled={deleteMutation.isPending}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ Delete
+ </Button>
+ </Can>
+ <Button
+ type="button"
+ size="sm"
+ onClick={form.handleSubmit(onSubmit)}
+ disabled={!form.formState.isDirty || form.formState.isSubmitting}
+ >
+ {form.formState.isSubmitting ? 'Saving…' : 'Save'}
+ </Button>
+ </div>
+ }
+ />
+ }
+ main={
+ <>
+ <PromotionBasicsCard form={form} promotion={promotion} />
+ <PromotionRulesCard promotionId={promotionId} matchPolicy={promotion.match_policy} />
+ <PromotionActionsCard promotionId={promotionId} />
+ {promotion.multi_codes && <PromotionCouponCodesCard promotionId={promotionId} />}
+ </>
+ }
+ />
+ )
+}
+
+// ============================================================================
+// Basics
+// ============================================================================
+
+interface PromotionBasicsCardProps {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form: any
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ promotion: any
+}
+
+function PromotionBasicsCard({ form, promotion }: PromotionBasicsCardProps) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Basics</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="name">Name</FieldLabel>
+ <Input id="name" {...form.register('name')} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="description">Description</FieldLabel>
+ <Textarea id="description" rows={2} {...form.register('description')} />
+ </Field>
+
+ <div className="rounded-md border bg-muted/30 px-3 py-2 text-sm">
+ <span className="font-medium">Trigger: </span>
+ {promotion.kind === 'automatic' ? (
+ <Badge variant="outline">Automatic</Badge>
+ ) : promotion.multi_codes ? (
+ <span>
+ Multi-code coupon ({promotion.number_of_codes ?? 0} codes
+ {promotion.code_prefix ? ` with prefix "${promotion.code_prefix}"` : ''})
+ </span>
+ ) : (
+ <span>
+ Single coupon code:{' '}
+ <code className="rounded bg-muted px-1 py-0.5 text-xs">
+ {promotion.code ?? '—'}
+ </code>
+ </span>
+ )}
+ <p className="mt-1 text-xs text-muted-foreground">
+ Trigger settings can't be changed after creation. Make a new promotion to change them.
+ </p>
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <Field>
+ <FieldLabel htmlFor="starts_at">Starts</FieldLabel>
+ <Input id="starts_at" type="datetime-local" {...form.register('starts_at')} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="expires_at">Expires</FieldLabel>
+ <Input id="expires_at" type="datetime-local" {...form.register('expires_at')} />
+ </Field>
+ </div>
+
+ <Field>
+ <FieldLabel htmlFor="usage_limit">Usage limit</FieldLabel>
+ <Input
+ id="usage_limit"
+ type="number"
+ min={1}
+ placeholder="Unlimited"
+ {...form.register('usage_limit')}
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="match_policy">When promotion has multiple rules</FieldLabel>
+ <Controller
+ name="match_policy"
+ control={form.control}
+ render={({ field }) => (
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger id="match_policy">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All rules must match</SelectItem>
+ <SelectItem value="any">Any rule may match</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </Field>
+
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col">
+ <FieldLabel htmlFor="advertise" className="cursor-pointer">
+ Advertise on storefront
+ </FieldLabel>
+ </div>
+ <Controller
+ name="advertise"
+ control={form.control}
+ render={({ field }) => (
+ <Switch id="advertise" checked={!!field.value} onCheckedChange={field.onChange} />
+ )}
+ />
+ </div>
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+ )
+}
+
+// ============================================================================
+// Rules
+// ============================================================================
+
+function PromotionRulesCard({
+ promotionId,
+ matchPolicy,
+}: {
+ promotionId: string
+ matchPolicy: string
+}) {
+ const { data: rulesData } = usePromotionRules(promotionId)
+ const { data: typesData } = usePromotionRuleTypes()
+ const [pickerOpen, setPickerOpen] = useState(false)
+ const [editingId, setEditingId] = useState<string | null>(null)
+
+ const rules = rulesData?.data ?? []
+ const types = typesData?.data ?? []
+ const editing = rules.find((r) => r.id === editingId)
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Rules</CardTitle>
+ <p className="text-sm text-muted-foreground">
+ Conditions that decide whether the promotion applies.{' '}
+ {matchPolicy === 'all' ? 'All rules must match.' : 'Any rule may match.'}
+ </p>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ {rules.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ No rules. Without rules, the promotion always qualifies (subject to schedule and usage
+ limit).
+ </p>
+ ) : (
+ rules.map((rule) => (
+ <RuleRow
+ key={rule.id}
+ rule={rule}
+ promotionId={promotionId}
+ onEdit={() => setEditingId(rule.id)}
+ />
+ ))
+ )}
+ <Can I="create" a={Subject.PromotionRule}>
+ <Button type="button" variant="outline" size="sm" onClick={() => setPickerOpen(true)}>
+ <PlusIcon className="size-4" />
+ Add rule
+ </Button>
+ </Can>
+ </div>
+
+ {pickerOpen && (
+ <RulePickerSheet
+ promotionId={promotionId}
+ types={types}
+ open
+ onOpenChange={(o) => !o && setPickerOpen(false)}
+ onCreated={(id) => {
+ setPickerOpen(false)
+ setEditingId(id)
+ }}
+ />
+ )}
+
+ {editing && (
+ <RuleEditSheet
+ promotionId={promotionId}
+ rule={editing}
+ open
+ onOpenChange={(o) => !o && setEditingId(null)}
+ />
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function RuleRow({
+ rule,
+ promotionId,
+ onEdit,
+}: {
+ rule: PromotionRule
+ promotionId: string
+ onEdit: () => void
+}) {
+ const deleteMutation = useDeletePromotionRule(promotionId)
+ const confirm = useConfirm()
+
+ async function onDelete(e: React.MouseEvent) {
+ e.stopPropagation()
+ const ok = await confirm({
+ title: 'Remove rule?',
+ message: 'This rule will be removed from the promotion.',
+ variant: 'destructive',
+ confirmLabel: 'Remove',
+ })
+ if (!ok) return
+ deleteMutation.mutate(rule.id)
+ }
+
+ return (
+ <button
+ type="button"
+ onClick={onEdit}
+ className="flex w-full items-center justify-between rounded-md border bg-card px-3 py-2 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <div className="min-w-0">
+ <div className="text-sm font-medium">
+ {rule.label ?? rule.type.replace(/^Spree::Promotion::Rules::/, '')}
+ </div>
+ {Object.keys(rule.preferences ?? {}).length > 0 && (
+ <div className="truncate text-xs text-muted-foreground">
+ {Object.entries(rule.preferences as Record<string, unknown>)
+ .map(([k, v]) => `${k}: ${formatPrefValue(v)}`)
+ .join(' · ')}
+ </div>
+ )}
+ </div>
+ <Can I="destroy" a={Subject.PromotionRule}>
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ onClick={onDelete}
+ disabled={deleteMutation.isPending}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <TrashIcon className="size-4" />
+ </Button>
+ </Can>
+ </button>
+ )
+}
+
+function RulePickerSheet({
+ promotionId,
+ types,
+ open,
+ onOpenChange,
+ onCreated,
+}: {
+ promotionId: string
+ types: ResourceTypeDefinition[]
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onCreated: (id: string) => void
+}) {
+ const [selected, setSelected] = useState<string>('')
+ const createMutation = useCreatePromotionRule(promotionId)
+
+ async function handleCreate() {
+ if (!selected) return
+ const rule = await createMutation.mutateAsync({ type: selected })
+ onCreated(rule.id)
+ setSelected('')
+ }
+
+ const selectedType = types.find((t) => t.type === selected)
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>Add rule</SheetTitle>
+ <SheetDescription>
+ Pick a rule type. Configure its values after it's added.
+ </SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">
+ {types.map((t) => (
+ <button
+ key={t.type}
+ type="button"
+ onClick={() => setSelected(t.type)}
+ className={`flex flex-col items-start rounded-md border p-3 text-left transition-colors ${
+ selected === t.type ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'
+ }`}
+ >
+ <span className="text-sm font-medium">{t.label}</span>
+ {t.description && (
+ <span className="text-xs text-muted-foreground">{t.description}</span>
+ )}
+ </button>
+ ))}
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={createMutation.isPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={handleCreate}
+ disabled={!selected || createMutation.isPending}
+ >
+ {createMutation.isPending
+ ? 'Adding…'
+ : selectedType
+ ? `Add ${selectedType.label}`
+ : 'Add rule'}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function RuleEditSheet({
+ promotionId,
+ rule,
+ open,
+ onOpenChange,
+}: {
+ promotionId: string
+ rule: PromotionRule
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const updateMutation = useUpdatePromotionRule(promotionId, rule.id)
+ const [values, setValues] = useState<Record<string, unknown>>(rule.preferences ?? {})
+
+ useEffect(() => {
+ setValues(rule.preferences ?? {})
+ }, [rule])
+
+ async function handleSave() {
+ await updateMutation.mutateAsync({ preferences: values })
+ onOpenChange(false)
+ }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>
+ {rule.label ?? rule.type.replace(/^Spree::Promotion::Rules::/, '')}
+ </SheetTitle>
+ <SheetDescription>Tune the rule's parameters.</SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {rule.preference_schema?.length ? (
+ <PreferencesForm schema={rule.preference_schema} values={values} onChange={setValues} />
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ This rule has no configurable options — its presence alone applies the constraint.
+ </p>
+ )}
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={updateMutation.isPending}
+ >
+ Cancel
+ </Button>
+ {rule.preference_schema?.length ? (
+ <Button
+ type="button"
+ size="sm"
+ onClick={handleSave}
+ disabled={updateMutation.isPending}
+ >
+ {updateMutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ ) : null}
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+// ============================================================================
+// Actions
+// ============================================================================
+
+function PromotionActionsCard({ promotionId }: { promotionId: string }) {
+ const { data: actionsData } = usePromotionActions(promotionId)
+ const { data: typesData } = usePromotionActionTypes()
+ const [pickerOpen, setPickerOpen] = useState(false)
+ const [editingId, setEditingId] = useState<string | null>(null)
+
+ const actions = actionsData?.data ?? []
+ const types = typesData?.data ?? []
+ const editing = actions.find((a) => a.id === editingId)
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Actions</CardTitle>
+ <p className="text-sm text-muted-foreground">What happens when the promotion qualifies.</p>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ {actions.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ No actions yet. A promotion without actions doesn't do anything when applied.
+ </p>
+ ) : (
+ actions.map((action) => (
+ <ActionRow
+ key={action.id}
+ action={action}
+ promotionId={promotionId}
+ onEdit={() => setEditingId(action.id)}
+ />
+ ))
+ )}
+ <Can I="create" a={Subject.PromotionAction}>
+ <Button type="button" variant="outline" size="sm" onClick={() => setPickerOpen(true)}>
+ <PlusIcon className="size-4" />
+ Add action
+ </Button>
+ </Can>
+ </div>
+
+ {pickerOpen && (
+ <ActionPickerSheet
+ promotionId={promotionId}
+ types={types}
+ open
+ onOpenChange={(o) => !o && setPickerOpen(false)}
+ onCreated={(id) => {
+ setPickerOpen(false)
+ setEditingId(id)
+ }}
+ />
+ )}
+
+ {editing && (
+ <ActionEditSheet
+ promotionId={promotionId}
+ action={editing}
+ open
+ onOpenChange={(o) => !o && setEditingId(null)}
+ />
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function ActionRow({
+ action,
+ promotionId,
+ onEdit,
+}: {
+ action: PromotionAction
+ promotionId: string
+ onEdit: () => void
+}) {
+ const deleteMutation = useDeletePromotionAction(promotionId)
+ const confirm = useConfirm()
+
+ async function onDelete(e: React.MouseEvent) {
+ e.stopPropagation()
+ const ok = await confirm({
+ title: 'Remove action?',
+ message: 'This action will be removed from the promotion.',
+ variant: 'destructive',
+ confirmLabel: 'Remove',
+ })
+ if (!ok) return
+ deleteMutation.mutate(action.id)
+ }
+
+ return (
+ <button
+ type="button"
+ onClick={onEdit}
+ className="flex w-full items-center justify-between rounded-md border bg-card px-3 py-2 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <div className="min-w-0">
+ <div className="text-sm font-medium">
+ {action.label ?? action.type.replace(/^Spree::Promotion::Actions::/, '')}
+ </div>
+ {Object.keys(action.preferences ?? {}).length > 0 && (
+ <div className="truncate text-xs text-muted-foreground">
+ {Object.entries(action.preferences as Record<string, unknown>)
+ .map(([k, v]) => `${k}: ${formatPrefValue(v)}`)
+ .join(' · ')}
+ </div>
+ )}
+ </div>
+ <Can I="destroy" a={Subject.PromotionAction}>
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ onClick={onDelete}
+ disabled={deleteMutation.isPending}
+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ <TrashIcon className="size-4" />
+ </Button>
+ </Can>
+ </button>
+ )
+}
+
+function ActionPickerSheet({
+ promotionId,
+ types,
+ open,
+ onOpenChange,
+ onCreated,
+}: {
+ promotionId: string
+ types: ResourceTypeDefinition[]
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onCreated: (id: string) => void
+}) {
+ const [selected, setSelected] = useState<string>('')
+ const createMutation = useCreatePromotionAction(promotionId)
+
+ async function handleCreate() {
+ if (!selected) return
+ const action = await createMutation.mutateAsync({ type: selected })
+ onCreated(action.id)
+ setSelected('')
+ }
+
+ const selectedType = types.find((t) => t.type === selected)
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>Add action</SheetTitle>
+ <SheetDescription>Pick what should happen when the promotion qualifies.</SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto p-4">
+ {types.map((t) => (
+ <button
+ key={t.type}
+ type="button"
+ onClick={() => setSelected(t.type)}
+ className={`flex flex-col items-start rounded-md border p-3 text-left transition-colors ${
+ selected === t.type ? 'border-primary bg-primary/5' : 'hover:bg-muted/50'
+ }`}
+ >
+ <span className="text-sm font-medium">{t.label}</span>
+ {t.description && (
+ <span className="text-xs text-muted-foreground">{t.description}</span>
+ )}
+ </button>
+ ))}
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={createMutation.isPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={handleCreate}
+ disabled={!selected || createMutation.isPending}
+ >
+ {createMutation.isPending
+ ? 'Adding…'
+ : selectedType
+ ? `Add ${selectedType.label}`
+ : 'Add action'}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+function ActionEditSheet({
+ promotionId,
+ action,
+ open,
+ onOpenChange,
+}: {
+ promotionId: string
+ action: PromotionAction
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const updateMutation = useUpdatePromotionAction(promotionId, action.id)
+ const [values, setValues] = useState<Record<string, unknown>>(action.preferences ?? {})
+
+ useEffect(() => {
+ setValues(action.preferences ?? {})
+ }, [action])
+
+ async function handleSave() {
+ await updateMutation.mutateAsync({ preferences: values })
+ onOpenChange(false)
+ }
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>
+ {action.label ?? action.type.replace(/^Spree::Promotion::Actions::/, '')}
+ </SheetTitle>
+ <SheetDescription>Configure the action's parameters.</SheetDescription>
+ </SheetHeader>
+ <div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {action.preference_schema?.length ? (
+ <PreferencesForm
+ schema={action.preference_schema}
+ values={values}
+ onChange={setValues}
+ />
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ This action has no configurable options.
+ </p>
+ )}
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={updateMutation.isPending}
+ >
+ Cancel
+ </Button>
+ {action.preference_schema?.length ? (
+ <Button
+ type="button"
+ size="sm"
+ onClick={handleSave}
+ disabled={updateMutation.isPending}
+ >
+ {updateMutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ ) : null}
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+// ============================================================================
+// Coupon codes (multi-codes only)
+// ============================================================================
+
+function PromotionCouponCodesCard({ promotionId }: { promotionId: string }) {
+ const { data: codesData } = usePromotionCouponCodes(promotionId, { limit: 50 })
+ const codes = codesData?.data ?? []
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Coupon codes</CardTitle>
+ <p className="text-sm text-muted-foreground">
+ Auto-generated codes for this promotion. Codes are read-only; regenerate by changing the
+ promotion's number-of-codes setting.
+ </p>
+ </CardHeader>
+ <CardContent>
+ {codes.length === 0 ? (
+ <p className="text-sm text-muted-foreground">No codes generated yet.</p>
+ ) : (
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
+ {codes.map((c) => (
+ <code
+ key={c.id}
+ className={`rounded border px-2 py-1 font-mono text-xs ${
+ c.state && c.state !== 'unused' ? 'text-muted-foreground line-through' : ''
+ }`}
+ title={c.state ?? undefined}
+ >
+ {c.code}
+ </code>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
+
+function formatPrefValue(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.length}]`
+ if (typeof value === 'boolean') return value ? 'yes' : 'no'
+ if (value === null || value === undefined || value === '') return '—'
+ return String(value)
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/index.tsx
new file mode 100644
index 0000000000..5e5a9ebd49
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/index.tsx
@@ -0,0 +1,48 @@
+import type { Promotion } from '@spree/admin-sdk'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { adminClient } from '@/client'
+import { Can } from '@/components/spree/can'
+import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'
+import { useRowClickBridge } from '@/components/spree/row-click-bridge'
+import { Button } from '@/components/ui/button'
+import { Subject } from '@/lib/permissions'
+import '@/tables/promotions'
+
+export const Route = createFileRoute('/_authenticated/$storeId/promotions/')({
+ validateSearch: resourceSearchSchema,
+ component: PromotionsPage,
+})
+
+function PromotionsPage() {
+ const search = Route.useSearch()
+ const navigate = useNavigate()
+ const { storeId } = Route.useParams()
+
+ function openEdit(id: string) {
+ navigate({ to: '/$storeId/promotions/$promotionId', params: { storeId, promotionId: id } })
+ }
+
+ function openCreate() {
+ navigate({ to: '/$storeId/promotions/new', params: { storeId } })
+ }
+
+ useRowClickBridge('data-promotion-id', openEdit)
+
+ return (
+ <ResourceTable<Promotion>
+ tableKey="promotions"
+ queryKey="promotions"
+ queryFn={(params) => adminClient.promotions.list(params)}
+ searchParams={search}
+ actions={
+ <Can I="create" a={Subject.Promotion}>
+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>
+ <PlusIcon className="size-4" />
+ New promotion
+ </Button>
+ </Can>
+ }
+ />
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx
new file mode 100644
index 0000000000..2ce544328e
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/new.tsx
@@ -0,0 +1,355 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { Controller, useForm } from 'react-hook-form'
+import { z } from 'zod/v4'
+import { PageHeader } from '@/components/spree/page-header'
+import { ResourceLayout } from '@/components/spree/resource-layout'
+import { Button } from '@/components/ui/button'
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Input } from '@/components/ui/input'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
+import { Switch } from '@/components/ui/switch'
+import { Textarea } from '@/components/ui/textarea'
+import { useCreatePromotion } from '@/hooks/use-promotions'
+
+export const Route = createFileRoute('/_authenticated/$storeId/promotions/new')({
+ component: NewPromotionPage,
+})
+
+const formSchema = z
+ .object({
+ name: z.string().min(1, 'Name is required'),
+ description: z.string().optional(),
+ kind: z.enum(['coupon_code', 'automatic']),
+ code: z.string().optional(),
+ multi_codes: z.boolean(),
+ number_of_codes: z.coerce.number().int().positive().optional(),
+ code_prefix: z.string().optional(),
+ starts_at: z.string().optional(),
+ expires_at: z.string().optional(),
+ usage_limit: z.coerce.number().int().positive().optional(),
+ match_policy: z.enum(['all', 'any']),
+ advertise: z.boolean(),
+ })
+ .superRefine((v, ctx) => {
+ if (v.kind === 'coupon_code' && !v.multi_codes && !v.code?.trim()) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['code'],
+ message: 'Coupon promotions need a code (or enable multi-codes).',
+ })
+ }
+ if (v.kind === 'coupon_code' && v.multi_codes && !v.number_of_codes) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['number_of_codes'],
+ message: 'How many codes should be generated?',
+ })
+ }
+ })
+
+type FormValues = z.infer<typeof formSchema>
+
+const DEFAULTS: FormValues = {
+ name: '',
+ description: '',
+ kind: 'coupon_code',
+ code: '',
+ multi_codes: false,
+ number_of_codes: undefined,
+ code_prefix: '',
+ starts_at: '',
+ expires_at: '',
+ usage_limit: undefined,
+ match_policy: 'all',
+ advertise: false,
+}
+
+function NewPromotionPage() {
+ const navigate = useNavigate()
+ const { storeId } = Route.useParams()
+ const createMutation = useCreatePromotion()
+
+ const form = useForm<FormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(formSchema) as any,
+ defaultValues: DEFAULTS,
+ })
+
+ const kind = form.watch('kind')
+ const multiCodes = form.watch('multi_codes')
+
+ async function onSubmit(values: FormValues) {
+ const promotion = await createMutation.mutateAsync({
+ name: values.name,
+ description: values.description?.length ? values.description : null,
+ kind: values.kind,
+ code: values.kind === 'coupon_code' && !values.multi_codes ? values.code || null : null,
+ multi_codes: values.kind === 'coupon_code' ? values.multi_codes : false,
+ number_of_codes:
+ values.kind === 'coupon_code' && values.multi_codes ? values.number_of_codes : null,
+ code_prefix:
+ values.kind === 'coupon_code' && values.multi_codes ? values.code_prefix || null : null,
+ starts_at: values.starts_at || null,
+ expires_at: values.expires_at || null,
+ usage_limit: values.usage_limit ?? null,
+ match_policy: values.match_policy,
+ advertise: values.advertise,
+ })
+ navigate({
+ to: '/$storeId/promotions/$promotionId',
+ params: { storeId, promotionId: promotion.id },
+ })
+ }
+
+ return (
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <ResourceLayout
+ header={
+ <PageHeader
+ title="New promotion"
+ backTo="promotions"
+ actions={
+ <Button type="submit" size="sm" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting ? 'Creating…' : 'Create promotion'}
+ </Button>
+ }
+ />
+ }
+ main={
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>Basics</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="name">Name</FieldLabel>
+ <Input
+ id="name"
+ placeholder="Summer Sale"
+ {...form.register('name')}
+ aria-invalid={!!form.formState.errors.name}
+ />
+ {form.formState.errors.name && (
+ <p className="text-sm text-destructive">
+ {form.formState.errors.name.message}
+ </p>
+ )}
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="description">Description</FieldLabel>
+ <Textarea
+ id="description"
+ rows={2}
+ placeholder="Internal description (optional)"
+ {...form.register('description')}
+ />
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Trigger</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="kind">How is this promotion applied?</FieldLabel>
+ <Controller
+ name="kind"
+ control={form.control}
+ render={({ field }) => (
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger id="kind">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="coupon_code">Coupon code</SelectItem>
+ <SelectItem value="automatic">Automatic (no code)</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </Field>
+
+ {kind === 'coupon_code' && (
+ <>
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col">
+ <FieldLabel htmlFor="multi_codes" className="cursor-pointer">
+ Generate a batch of unique codes
+ </FieldLabel>
+ <span className="text-xs text-muted-foreground">
+ Useful for one-time-use codes — each customer redeems a different
+ code.
+ </span>
+ </div>
+ <Controller
+ name="multi_codes"
+ control={form.control}
+ render={({ field }) => (
+ <Switch
+ id="multi_codes"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
+ />
+ </div>
+ </Field>
+
+ {!multiCodes ? (
+ <Field>
+ <FieldLabel htmlFor="code">Code</FieldLabel>
+ <Input
+ id="code"
+ placeholder="SUMMER2026"
+ {...form.register('code')}
+ aria-invalid={!!form.formState.errors.code}
+ />
+ {form.formState.errors.code && (
+ <p className="text-sm text-destructive">
+ {form.formState.errors.code.message}
+ </p>
+ )}
+ </Field>
+ ) : (
+ <>
+ <Field>
+ <FieldLabel htmlFor="number_of_codes">Number of codes</FieldLabel>
+ <Input
+ id="number_of_codes"
+ type="number"
+ min={1}
+ placeholder="100"
+ {...form.register('number_of_codes')}
+ aria-invalid={!!form.formState.errors.number_of_codes}
+ />
+ {form.formState.errors.number_of_codes && (
+ <p className="text-sm text-destructive">
+ {form.formState.errors.number_of_codes.message}
+ </p>
+ )}
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="code_prefix">Code prefix (optional)</FieldLabel>
+ <Input
+ id="code_prefix"
+ placeholder="VIP"
+ {...form.register('code_prefix')}
+ />
+ <span className="text-xs text-muted-foreground">
+ Each generated code will start with this prefix.
+ </span>
+ </Field>
+ </>
+ )}
+ </>
+ )}
+ </FieldGroup>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Schedule & limits</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <FieldGroup>
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <Field>
+ <FieldLabel htmlFor="starts_at">Starts</FieldLabel>
+ <Input id="starts_at" type="datetime-local" {...form.register('starts_at')} />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="expires_at">Expires</FieldLabel>
+ <Input
+ id="expires_at"
+ type="datetime-local"
+ {...form.register('expires_at')}
+ />
+ </Field>
+ </div>
+
+ <Field>
+ <FieldLabel htmlFor="usage_limit">Usage limit</FieldLabel>
+ <Input
+ id="usage_limit"
+ type="number"
+ min={1}
+ placeholder="Unlimited"
+ {...form.register('usage_limit')}
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="match_policy">
+ When promotion has multiple rules
+ </FieldLabel>
+ <Controller
+ name="match_policy"
+ control={form.control}
+ render={({ field }) => (
+ <Select value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger id="match_policy">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="all">All rules must match</SelectItem>
+ <SelectItem value="any">Any rule may match</SelectItem>
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </Field>
+
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col">
+ <FieldLabel htmlFor="advertise" className="cursor-pointer">
+ Advertise this promotion
+ </FieldLabel>
+ <span className="text-xs text-muted-foreground">
+ Surface it on the storefront when applicable.
+ </span>
+ </div>
+ <Controller
+ name="advertise"
+ control={form.control}
+ render={({ field }) => (
+ <Switch
+ id="advertise"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
+ />
+ </div>
+ </Field>
+ </FieldGroup>
+ </CardContent>
+ </Card>
+
+ <p className="text-sm text-muted-foreground">
+ You'll add actions and rules after the promotion is created.
+ </p>
+ </>
+ }
+ />
+ </form>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
index 9acafc4920..e40228a59c 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
@@ -7,12 +7,13 @@ import type {
} from '@spree/admin-sdk'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { PlusIcon } from 'lucide-react'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
import { z } from 'zod/v4'
import { adminClient } from '@/client'
import { Can } from '@/components/spree/can'
import { useConfirm } from '@/components/spree/confirm-dialog'
+import { PreferencesForm } from '@/components/spree/preferences-form'
import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'
import { useRowClickBridge } from '@/components/spree/row-click-bridge'
import { Button } from '@/components/ui/button'
@@ -266,6 +267,8 @@ function EditPaymentMethodSheet({
resolver: zodResolver(baseFormSchema) as any,
defaultValues: BASE_DEFAULTS,
})
+ const [preferences, setPreferences] = useState<Record<string, unknown>>({})
+ const [preferencesDirty, setPreferencesDirty] = useState(false)
useEffect(() => {
if (paymentMethod) {
@@ -277,12 +280,17 @@ function EditPaymentMethodSheet({
auto_capture: paymentMethod.auto_capture ?? false,
position: paymentMethod.position ?? undefined,
})
+ setPreferences((paymentMethod.preferences as Record<string, unknown>) ?? {})
+ setPreferencesDirty(false)
}
}, [paymentMethod, form])
async function onSubmit(values: BaseFormValues) {
- await updateMutation.mutateAsync(valuesToUpdateParams(values))
+ const params = valuesToUpdateParams(values)
+ if (preferencesDirty) params.preferences = preferences
+ await updateMutation.mutateAsync(params)
form.reset(values)
+ setPreferencesDirty(false)
onOpenChange(false)
}
@@ -316,6 +324,21 @@ function EditPaymentMethodSheet({
<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">
<PaymentMethodFormFields form={form} />
+
+ {paymentMethod?.preference_schema?.length ? (
+ <div className="rounded-md border bg-muted/30 p-3">
+ <h3 className="mb-2 text-sm font-medium">Provider configuration</h3>
+ <PreferencesForm
+ schema={paymentMethod.preference_schema}
+ values={preferences}
+ onChange={(next) => {
+ setPreferences(next)
+ setPreferencesDirty(true)
+ }}
+ redactPasswords
+ />
+ </div>
+ ) : null}
</div>
<SheetFooter>
<Can I="destroy" a={Subject.PaymentMethod}>
@@ -342,7 +365,9 @@ function EditPaymentMethodSheet({
<Button
type="submit"
size="sm"
- disabled={form.formState.isSubmitting || !form.formState.isDirty}
+ disabled={
+ form.formState.isSubmitting || (!form.formState.isDirty && !preferencesDirty)
+ }
>
{form.formState.isSubmitting ? 'Saving…' : 'Save'}
</Button>
diff --git a/packages/admin/src/tables/promotions.tsx b/packages/admin/src/tables/promotions.tsx
new file mode 100644
index 0000000000..16156c9f7d
--- /dev/null
+++ b/packages/admin/src/tables/promotions.tsx
@@ -0,0 +1,71 @@
+import type { Promotion } from '@spree/admin-sdk'
+import { TagIcon } from 'lucide-react'
+import { RelativeTime } from '@/components/spree/relative-time'
+import { Badge } from '@/components/ui/badge'
+import { defineTable } from '@/lib/table-registry'
+
+defineTable<Promotion>('promotions', {
+ title: 'Promotions',
+ searchParam: 'name_cont',
+ searchPlaceholder: 'Search by name…',
+ defaultSort: { field: 'created_at', direction: 'desc' },
+ emptyIcon: <TagIcon className="size-8 text-muted-foreground/50" />,
+ emptyMessage: 'No promotions yet',
+ columns: [
+ {
+ key: 'name',
+ label: 'Name',
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (p) => (
+ <button
+ type="button"
+ data-promotion-id={p.id}
+ className="flex flex-col items-start text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring rounded"
+ >
+ <span className="font-medium">{p.name}</span>
+ {p.description && <span className="text-xs text-muted-foreground">{p.description}</span>}
+ </button>
+ ),
+ },
+ {
+ key: 'code',
+ label: 'Code',
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (p) => {
+ if (p.kind === 'automatic') return <Badge variant="outline">Automatic</Badge>
+ if (p.multi_codes) return <Badge variant="outline">{p.code_prefix ?? 'multi'}…</Badge>
+ return p.code ? <code className="text-xs">{p.code}</code> : '—'
+ },
+ },
+ {
+ key: 'starts_at',
+ label: 'Starts',
+ sortable: true,
+ filterType: 'date',
+ default: true,
+ className: 'text-sm text-muted-foreground whitespace-nowrap',
+ render: (p) => (p.starts_at ? <RelativeTime iso={p.starts_at} /> : '—'),
+ },
+ {
+ key: 'expires_at',
+ label: 'Expires',
+ sortable: true,
+ filterType: 'date',
+ default: true,
+ className: 'text-sm text-muted-foreground whitespace-nowrap',
+ render: (p) => {
+ if (!p.expires_at) return <span className="text-muted-foreground">No end</span>
+ const expired = new Date(p.expires_at) < new Date()
+ return (
+ <span className={expired ? 'text-destructive' : undefined}>
+ <RelativeTime iso={p.expires_at} />
+ </span>
+ )
+ },
+ },
+ ],
+})