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 Gift Card management UI

Damian Legawiecc3d22eb65c31
diff --git a/packages/admin/e2e/gift-cards.spec.ts b/packages/admin/e2e/gift-cards.spec.ts
new file mode 100644
index 0000000000..4d58a03f9d
--- /dev/null
+++ b/packages/admin/e2e/gift-cards.spec.ts
@@ -0,0 +1,99 @@
+import { expect, type Page, test } from '@playwright/test'
+import { gotoIndex, login, rowButton } from './helpers'
+
+const GIFT_CARDS_PATH = (storeId: string) => `/${storeId}/promotions/gift-cards`
+const CTA = /new gift card/i
+
+async function createGiftCard(
+ page: Page,
+ attrs: { amount: string; code?: string; expiresAt?: string },
+) {
+ await page.getByRole('button', { name: /new gift card/i }).click()
+ await expect(page.getByRole('heading', { name: /new gift card/i })).toBeVisible()
+
+ if (attrs.code) await page.locator('#code').fill(attrs.code)
+ await page.locator('#amount').fill(attrs.amount)
+ if (attrs.expiresAt) await page.locator('#expires_at').fill(attrs.expiresAt)
+
+ await page.getByRole('button', { name: /create gift card/i }).click()
+}
+
+test.describe('gift cards', () => {
+ test('lists gift cards', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, GIFT_CARDS_PATH(creds.store_id), CTA)
+ })
+
+ test('creates a gift card with an auto-generated code', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, GIFT_CARDS_PATH(creds.store_id), CTA)
+
+ await createGiftCard(page, { amount: '25.00' })
+
+ // Auto-generated code is uppercase hex; just confirm a row with the
+ // freshly-issued amount appears in the table.
+ await expect(page.getByText(/\$25\.00/).first()).toBeVisible({ timeout: 15_000 })
+ })
+
+ test('creates a gift card with a custom code and edits it', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, GIFT_CARDS_PATH(creds.store_id), CTA)
+
+ const code = `E2E${Date.now().toString().slice(-6)}`
+ await createGiftCard(page, { amount: '50.00', code, expiresAt: '2030-12-31' })
+
+ await expect(rowButton(page, code)).toBeVisible({ timeout: 15_000 })
+
+ await rowButton(page, code).click()
+ await expect(page.getByRole('heading', { name: code })).toBeVisible({ timeout: 15_000 })
+
+ await page.locator('#amount').fill('75.00')
+ await page.getByRole('button', { name: /^save$/i }).click()
+
+ // Reopen the row to verify the new amount stuck.
+ await expect(page.getByText(/\$75\.00/).first()).toBeVisible({ timeout: 15_000 })
+ })
+
+ test('bulk-issues a batch when quantity > 1', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, GIFT_CARDS_PATH(creds.store_id), CTA)
+
+ const prefix = `E2EB${Date.now().toString().slice(-6)}`
+
+ await page.getByRole('button', { name: /new gift card/i }).click()
+ await expect(page.getByRole('heading', { name: /new gift card/i })).toBeVisible()
+
+ // Quantity > 1 flips the sheet into batch mode — the Code field
+ // relabels to Prefix and the customer picker disappears.
+ await page.locator('#quantity').fill('3')
+ await expect(page.getByText(/Bulk-issue 3 gift cards/i)).toBeVisible()
+ await page.locator('#code').fill(prefix)
+ await page.locator('#amount').fill('20.00')
+
+ await page.getByRole('button', { name: /create 3 gift cards/i }).click()
+
+ // Three cards generated with the prefix should now be in the list.
+ await expect(page.getByText(new RegExp(prefix, 'i')).first()).toBeVisible({ timeout: 15_000 })
+ })
+
+ test('deletes a gift card', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, GIFT_CARDS_PATH(creds.store_id), CTA)
+
+ const code = `E2EDEL${Date.now().toString().slice(-6)}`
+ await createGiftCard(page, { amount: '10.00', code })
+ await expect(rowButton(page, code)).toBeVisible({ timeout: 15_000 })
+
+ await rowButton(page, code).click()
+ await expect(page.getByRole('heading', { name: code })).toBeVisible({ timeout: 15_000 })
+
+ await page.getByRole('button', { name: /^delete$/i }).click()
+ await expect(page.getByRole('heading', { name: /delete gift card\?/i })).toBeVisible()
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^delete$/i })
+ .click()
+
+ await expect(rowButton(page, code)).toHaveCount(0, { timeout: 15_000 })
+ })
+})
diff --git a/packages/admin/src/hooks/use-gift-cards.ts b/packages/admin/src/hooks/use-gift-cards.ts
new file mode 100644
index 0000000000..28a5618f99
--- /dev/null
+++ b/packages/admin/src/hooks/use-gift-cards.ts
@@ -0,0 +1,92 @@
+import type {
+ GiftCard,
+ GiftCardBatch,
+ GiftCardBatchCreateParams,
+ GiftCardCreateParams,
+ GiftCardUpdateParams,
+} from '@spree/admin-sdk'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { adminClient } from '@/client'
+import { useResourceMutation } from '@/hooks/use-resource-mutation'
+
+export const giftCardsQueryKey = ['gift-cards'] as const
+
+export function giftCardQueryKey(id: string, expand?: string[]) {
+ return expand?.length ? (['gift-cards', id, { expand }] as const) : (['gift-cards', id] as const)
+}
+
+export function useGiftCard(id: string | undefined, expand?: string[]) {
+ return useQuery({
+ queryKey: id ? giftCardQueryKey(id, expand) : ['gift-cards', 'noop'],
+ queryFn: () => adminClient.giftCards.get(id as string, { expand }),
+ enabled: !!id,
+ })
+}
+
+export function useCreateGiftCard() {
+ return useResourceMutation<GiftCard, Error, GiftCardCreateParams>({
+ mutationFn: (params) => adminClient.giftCards.create(params),
+ invalidate: [giftCardsQueryKey],
+ successMessage: 'Gift card created',
+ errorMessage: 'Failed to create gift card',
+ })
+}
+
+export function useUpdateGiftCard(id: string) {
+ return useResourceMutation<GiftCard, Error, GiftCardUpdateParams>({
+ mutationFn: (params) => adminClient.giftCards.update(id, params),
+ invalidate: [giftCardsQueryKey, giftCardQueryKey(id)],
+ successMessage: 'Gift card updated',
+ errorMessage: 'Failed to update gift card',
+ })
+}
+
+export function useDeleteGiftCard() {
+ const queryClient = useQueryClient()
+
+ return useResourceMutation<void, Error, string>({
+ mutationFn: (id) => adminClient.giftCards.delete(id),
+ invalidate: [giftCardsQueryKey],
+ successMessage: 'Gift card deleted',
+ errorMessage: 'Failed to delete gift card',
+ onSuccess: (_data, id) => {
+ queryClient.removeQueries({ queryKey: giftCardQueryKey(id) })
+ },
+ })
+}
+
+// ---------------------------------------------------------------------------
+// Batches
+// ---------------------------------------------------------------------------
+
+export const giftCardBatchesQueryKey = ['gift-card-batches'] as const
+
+export function useCreateGiftCardBatch() {
+ return useResourceMutation<GiftCardBatch, Error, GiftCardBatchCreateParams>({
+ mutationFn: (params) => adminClient.giftCardBatches.create(params),
+ // Creating a batch generates N cards inline (or kicks off a job for
+ // larger batches), so the gift cards list is the surface that needs to
+ // refetch — not the batches collection itself.
+ invalidate: [giftCardsQueryKey, giftCardBatchesQueryKey],
+ successMessage: 'Gift card batch created',
+ errorMessage: 'Failed to create gift card batch',
+ })
+}
+
+/**
+ * Shared config for any `<ResourceCombobox>`/`<ResourceMultiAutocomplete>`
+ * picking gift card batches (filter chip on the cards table, batch detail
+ * lookups). Pass a unique `queryKey` per instance so independent caches
+ * don't collide.
+ */
+export function giftCardBatchAutocompleteProps(queryKey: string) {
+ return {
+ queryKey,
+ search: (q: string) =>
+ adminClient.giftCardBatches.list({ prefix_cont: q, limit: 20, sort: '-created_at' }),
+ hydrate: (ids: string[]) => adminClient.giftCardBatches.list({ id_in: ids, limit: ids.length }),
+ getOptionLabel: (b: GiftCardBatch) => b.prefix ?? b.id,
+ placeholder: 'Search batches by prefix…',
+ emptyText: 'No batches match',
+ }
+}
diff --git a/packages/admin/src/lib/permissions.ts b/packages/admin/src/lib/permissions.ts
index 75cde7d282..e737450eec 100644
--- a/packages/admin/src/lib/permissions.ts
+++ b/packages/admin/src/lib/permissions.ts
@@ -27,6 +27,8 @@ export const Subject = {
Promotion: 'Spree::Promotion',
PromotionAction: 'Spree::PromotionAction',
PromotionRule: 'Spree::PromotionRule',
+ GiftCard: 'Spree::GiftCard',
+ Market: 'Spree::Market',
Wishlist: 'Spree::Wishlist',
} as const
diff --git a/packages/admin/src/nav/default.ts b/packages/admin/src/nav/default.ts
index 29f57f91e0..78298ebe84 100644
--- a/packages/admin/src/nav/default.ts
+++ b/packages/admin/src/nav/default.ts
@@ -105,7 +105,7 @@ nav.add({
key: 'promotions.gift-cards',
label: 'Gift Cards',
path: '/promotions/gift-cards',
- subject: Subject.Promotion,
+ subject: Subject.GiftCard,
position: 100,
},
],
diff --git a/packages/admin/src/routeTree.gen.ts b/packages/admin/src/routeTree.gen.ts
index 85a9e0f5c3..c5db86e67b 100644
--- a/packages/admin/src/routeTree.gen.ts
+++ b/packages/admin/src/routeTree.gen.ts
@@ -28,6 +28,7 @@ import { Route as AuthenticatedStoreIdSettingsStaffRouteImport } from './routes/
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 AuthenticatedStoreIdPromotionsGiftCardsRouteImport } from './routes/_authenticated/$storeId/promotions/gift-cards'
import { Route as AuthenticatedStoreIdPromotionsPromotionIdRouteImport } from './routes/_authenticated/$storeId/promotions/$promotionId'
import { Route as AuthenticatedStoreIdProductsTransfersRouteImport } from './routes/_authenticated/$storeId/products/transfers'
import { Route as AuthenticatedStoreIdProductsOptionsRouteImport } from './routes/_authenticated/$storeId/products/options'
@@ -147,6 +148,12 @@ const AuthenticatedStoreIdPromotionsNewRoute =
path: '/promotions/new',
getParentRoute: () => AuthenticatedStoreIdRoute,
} as any)
+const AuthenticatedStoreIdPromotionsGiftCardsRoute =
+ AuthenticatedStoreIdPromotionsGiftCardsRouteImport.update({
+ id: '/promotions/gift-cards',
+ path: '/promotions/gift-cards',
+ getParentRoute: () => AuthenticatedStoreIdRoute,
+ } as any)
const AuthenticatedStoreIdPromotionsPromotionIdRoute =
AuthenticatedStoreIdPromotionsPromotionIdRouteImport.update({
id: '/promotions/$promotionId',
@@ -218,6 +225,7 @@ export interface FileRoutesByFullPath {
'/$storeId/products/options': typeof AuthenticatedStoreIdProductsOptionsRoute
'/$storeId/products/transfers': typeof AuthenticatedStoreIdProductsTransfersRoute
'/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ '/$storeId/promotions/gift-cards': typeof AuthenticatedStoreIdPromotionsGiftCardsRoute
'/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
'/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
@@ -245,6 +253,7 @@ export interface FileRoutesByTo {
'/$storeId/products/options': typeof AuthenticatedStoreIdProductsOptionsRoute
'/$storeId/products/transfers': typeof AuthenticatedStoreIdProductsTransfersRoute
'/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ '/$storeId/promotions/gift-cards': typeof AuthenticatedStoreIdPromotionsGiftCardsRoute
'/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
'/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
@@ -276,6 +285,7 @@ export interface FileRoutesById {
'/_authenticated/$storeId/products/options': typeof AuthenticatedStoreIdProductsOptionsRoute
'/_authenticated/$storeId/products/transfers': typeof AuthenticatedStoreIdProductsTransfersRoute
'/_authenticated/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ '/_authenticated/$storeId/promotions/gift-cards': typeof AuthenticatedStoreIdPromotionsGiftCardsRoute
'/_authenticated/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute
'/_authenticated/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute
'/_authenticated/$storeId/settings/payment-methods': typeof AuthenticatedStoreIdSettingsPaymentMethodsRoute
@@ -307,6 +317,7 @@ export interface FileRouteTypes {
| '/$storeId/products/options'
| '/$storeId/products/transfers'
| '/$storeId/promotions/$promotionId'
+ | '/$storeId/promotions/gift-cards'
| '/$storeId/promotions/new'
| '/$storeId/settings/api-keys'
| '/$storeId/settings/payment-methods'
@@ -334,6 +345,7 @@ export interface FileRouteTypes {
| '/$storeId/products/options'
| '/$storeId/products/transfers'
| '/$storeId/promotions/$promotionId'
+ | '/$storeId/promotions/gift-cards'
| '/$storeId/promotions/new'
| '/$storeId/settings/api-keys'
| '/$storeId/settings/payment-methods'
@@ -364,6 +376,7 @@ export interface FileRouteTypes {
| '/_authenticated/$storeId/products/options'
| '/_authenticated/$storeId/products/transfers'
| '/_authenticated/$storeId/promotions/$promotionId'
+ | '/_authenticated/$storeId/promotions/gift-cards'
| '/_authenticated/$storeId/promotions/new'
| '/_authenticated/$storeId/settings/api-keys'
| '/_authenticated/$storeId/settings/payment-methods'
@@ -519,6 +532,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticatedStoreIdPromotionsNewRouteImport
parentRoute: typeof AuthenticatedStoreIdRoute
}
+ '/_authenticated/$storeId/promotions/gift-cards': {
+ id: '/_authenticated/$storeId/promotions/gift-cards'
+ path: '/promotions/gift-cards'
+ fullPath: '/$storeId/promotions/gift-cards'
+ preLoaderRoute: typeof AuthenticatedStoreIdPromotionsGiftCardsRouteImport
+ parentRoute: typeof AuthenticatedStoreIdRoute
+ }
'/_authenticated/$storeId/promotions/$promotionId': {
id: '/_authenticated/$storeId/promotions/$promotionId'
path: '/promotions/$promotionId'
@@ -630,6 +650,7 @@ interface AuthenticatedStoreIdRouteChildren {
AuthenticatedStoreIdProductsOptionsRoute: typeof AuthenticatedStoreIdProductsOptionsRoute
AuthenticatedStoreIdProductsTransfersRoute: typeof AuthenticatedStoreIdProductsTransfersRoute
AuthenticatedStoreIdPromotionsPromotionIdRoute: typeof AuthenticatedStoreIdPromotionsPromotionIdRoute
+ AuthenticatedStoreIdPromotionsGiftCardsRoute: typeof AuthenticatedStoreIdPromotionsGiftCardsRoute
AuthenticatedStoreIdPromotionsNewRoute: typeof AuthenticatedStoreIdPromotionsNewRoute
AuthenticatedStoreIdCustomersIndexRoute: typeof AuthenticatedStoreIdCustomersIndexRoute
AuthenticatedStoreIdOrdersIndexRoute: typeof AuthenticatedStoreIdOrdersIndexRoute
@@ -657,6 +678,8 @@ const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {
AuthenticatedStoreIdProductsTransfersRoute,
AuthenticatedStoreIdPromotionsPromotionIdRoute:
AuthenticatedStoreIdPromotionsPromotionIdRoute,
+ AuthenticatedStoreIdPromotionsGiftCardsRoute:
+ AuthenticatedStoreIdPromotionsGiftCardsRoute,
AuthenticatedStoreIdPromotionsNewRoute:
AuthenticatedStoreIdPromotionsNewRoute,
AuthenticatedStoreIdCustomersIndexRoute:
diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx
new file mode 100644
index 0000000000..11e68a70e3
--- /dev/null
+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx
@@ -0,0 +1,647 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type {
+ Customer,
+ GiftCard,
+ GiftCardBatchCreateParams,
+ GiftCardCreateParams,
+ GiftCardUpdateParams,
+} from '@spree/admin-sdk'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { useEffect } from 'react'
+import { Controller, type UseFormReturn, 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 { CurrencySelect } from '@/components/spree/currency-select'
+import { ResourceCombobox } from '@/components/spree/resource-combobox'
+import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'
+import { useRowClickBridge } from '@/components/spree/row-click-bridge'
+import { StoreDatePicker } from '@/components/spree/store-date-picker'
+import { Button } from '@/components/ui/button'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Input } from '@/components/ui/input'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet'
+import { customerAutocompleteProps } from '@/hooks/use-customers'
+import {
+ useCreateGiftCard,
+ useCreateGiftCardBatch,
+ useDeleteGiftCard,
+ useGiftCard,
+ useUpdateGiftCard,
+} from '@/hooks/use-gift-cards'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
+import { Subject } from '@/lib/permissions'
+import { useStore } from '@/providers/store-provider'
+import '@/tables/gift-cards'
+
+const giftCardsSearchSchema = resourceSearchSchema.extend({
+ edit: z.string().optional(),
+ new: z.coerce.boolean().optional(),
+})
+
+export const Route = createFileRoute('/_authenticated/$storeId/promotions/gift-cards')({
+ validateSearch: giftCardsSearchSchema,
+ component: GiftCardsPage,
+})
+
+// `customer` chips on every row need the customer association inlined;
+// `created_by` is shown in the edit sheet; `gift_card_batch` powers the
+// per-row batch chip + filter. Pulling them on the index keeps the table
+// self-sufficient without a follow-up fetch per row.
+const LIST_EXPAND = ['customer', 'created_by', 'gift_card_batch']
+
+function GiftCardsPage() {
+ const search = Route.useSearch() as z.infer<typeof giftCardsSearchSchema>
+ const navigate = useNavigate()
+
+ const editId = search.edit
+ const isCreating = !!search.new
+
+ const closeSheet = () =>
+ navigate({
+ search: (prev: Record<string, unknown>) => {
+ const { edit: _e, new: _n, ...rest } = prev
+ return rest as never
+ },
+ })
+
+ const openCreate = () =>
+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, new: true }) as never })
+
+ const openEdit = (id: string) =>
+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, edit: id }) as never })
+
+ useRowClickBridge('data-gift-card-id', openEdit)
+
+ return (
+ <>
+ <ResourceTable<GiftCard>
+ tableKey="gift-cards"
+ queryKey="gift-cards"
+ queryFn={(params) => adminClient.giftCards.list(params)}
+ searchParams={search}
+ defaultParams={{ expand: LIST_EXPAND }}
+ actions={
+ <Can I="create" a={Subject.GiftCard}>
+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>
+ <PlusIcon className="size-4" />
+ New gift card
+ </Button>
+ </Can>
+ }
+ />
+
+ {isCreating && <CreateGiftCardSheet open onOpenChange={(o) => !o && closeSheet()} />}
+ {editId && <EditGiftCardSheet id={editId} open onOpenChange={(o) => !o && closeSheet()} />}
+ </>
+ )
+}
+
+// ----------------------------------------------------------------------------
+// Form schemas — separate for create (with `quantity`) vs edit (no quantity,
+// no code-prefix branching).
+// ----------------------------------------------------------------------------
+
+// Mirrors `Spree::Config[:gift_card_batch_limit]`. Hardcoded for now; if the
+// merchant overrides it we'll surface it via a store-settings endpoint later.
+const BATCH_LIMIT = 50_000
+
+const createFormSchema = z.object({
+ // When `quantity === 1` this is the optional caller-supplied code.
+ // When `quantity > 1` it becomes the required batch `prefix`.
+ code: z.string().optional(),
+ amount: z.coerce.number().positive('Amount must be greater than zero'),
+ currency: z.string().min(1, 'Currency is required'),
+ expires_at: z.string().optional(),
+ customer_id: z.string().optional(),
+ quantity: z.coerce.number().int().min(1).max(BATCH_LIMIT),
+})
+
+type CreateFormValues = z.infer<typeof createFormSchema>
+
+const editFormSchema = z.object({
+ code: z.string().optional(),
+ amount: z.coerce.number().positive('Amount must be greater than zero'),
+ currency: z.string().min(1, 'Currency is required'),
+ expires_at: z.string().optional(),
+ customer_id: z.string().optional(),
+})
+
+type EditFormValues = z.infer<typeof editFormSchema>
+
+function blank(s: string | undefined): string | undefined {
+ return s && s.length > 0 ? s : undefined
+}
+
+function editValuesToParams(v: EditFormValues): GiftCardUpdateParams {
+ return {
+ amount: v.amount,
+ expires_at: v.expires_at || null,
+ user_id: blank(v.customer_id) ?? null,
+ }
+}
+
+function singleValuesToParams(v: CreateFormValues): GiftCardCreateParams {
+ return {
+ code: blank(v.code),
+ amount: v.amount,
+ currency: v.currency,
+ expires_at: v.expires_at || null,
+ user_id: blank(v.customer_id) ?? null,
+ }
+}
+
+function batchValuesToParams(v: CreateFormValues): GiftCardBatchCreateParams {
+ // `code` carries the prefix in batch mode; required, validated below.
+ return {
+ prefix: v.code ?? '',
+ amount: v.amount,
+ currency: v.currency,
+ codes_count: v.quantity,
+ expires_at: v.expires_at || null,
+ }
+}
+
+// ----------------------------------------------------------------------------
+// Create sheet — single sheet for both single-issue and batch-issue. The
+// flow branches off `quantity`: `1` posts to `/gift_cards`; `>1` posts to
+// `/gift_card_batches` (server generates `codes_count` cards).
+// ----------------------------------------------------------------------------
+
+function CreateGiftCardSheet({
+ open,
+ onOpenChange,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const createMutation = useCreateGiftCard()
+ const createBatchMutation = useCreateGiftCardBatch()
+ // `CurrencySelect` falls back to the store default visually, but we have to
+ // seed `currency` here too so react-hook-form's validator doesn't reject
+ // the submit on a blank string before `mutate` ever runs.
+ const { defaultCurrency } = useStore()
+ const form = useForm<CreateFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(createFormSchema) as any,
+ defaultValues: {
+ code: '',
+ // Empty so the input shows its placeholder; zod's `z.coerce.number()`
+ // parses on submit and rejects blanks via `positive()`.
+ amount: '' as unknown as number,
+ currency: defaultCurrency,
+ expires_at: '',
+ customer_id: '',
+ quantity: 1,
+ },
+ })
+
+ const quantity = form.watch('quantity')
+ const isBatch = Number(quantity) > 1
+
+ async function onSubmit(values: CreateFormValues) {
+ try {
+ if (Number(values.quantity) > 1) {
+ // Batches require a prefix; surface the validation error inline rather
+ // than letting the server 422.
+ if (!values.code?.trim()) {
+ form.setError('code', { type: 'required', message: 'Prefix is required for batches' })
+ return
+ }
+ await createBatchMutation.mutateAsync(batchValuesToParams(values))
+ } else {
+ await createMutation.mutateAsync(singleValuesToParams(values))
+ }
+ form.reset()
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Sheet
+ open={open}
+ onOpenChange={(next) => {
+ if (!next) form.reset()
+ onOpenChange(next)
+ }}
+ >
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>New gift card</SheetTitle>
+ <SheetDescription>
+ {isBatch
+ ? `Bulk-issue ${quantity} gift cards. The server generates codes by suffixing random hex onto the prefix.`
+ : 'Issuing a gift card credits the recipient with the listed amount. The code is auto-generated unless you provide one. No email is sent — share the code manually.'}
+ </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">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
+ <CreateGiftCardFormFields form={form} isBatch={isBatch} />
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={form.formState.isSubmitting}>
+ {form.formState.isSubmitting
+ ? 'Creating…'
+ : isBatch
+ ? `Create ${quantity} gift cards`
+ : 'Create gift card'}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+// ----------------------------------------------------------------------------
+// Edit sheet
+// ----------------------------------------------------------------------------
+
+function EditGiftCardSheet({
+ id,
+ open,
+ onOpenChange,
+}: {
+ id: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { data: giftCard, isLoading } = useGiftCard(id, ['customer', 'created_by', 'orders'])
+ const updateMutation = useUpdateGiftCard(id)
+ const deleteMutation = useDeleteGiftCard()
+ const confirm = useConfirm()
+
+ const form = useForm<EditFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(editFormSchema) as any,
+ defaultValues: {
+ code: '',
+ amount: 0,
+ currency: '',
+ expires_at: '',
+ customer_id: '',
+ },
+ })
+
+ useEffect(() => {
+ if (giftCard) {
+ form.reset({
+ code: giftCard.code,
+ amount: Number(giftCard.amount),
+ currency: giftCard.currency,
+ expires_at: giftCard.expires_at ?? '',
+ customer_id: giftCard.customer?.id ?? '',
+ })
+ }
+ }, [giftCard, form])
+
+ async function onSubmit(values: EditFormValues) {
+ try {
+ await updateMutation.mutateAsync(editValuesToParams(values))
+ form.reset(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ async function onDelete() {
+ const ok = await confirm({
+ title: 'Delete gift card?',
+ message: `Gift card ${giftCard?.code ?? ''} will be removed. Codes that have already been redeemed cannot be deleted.`,
+ variant: 'destructive',
+ confirmLabel: 'Delete',
+ })
+ if (!ok) return
+ await deleteMutation.mutateAsync(id)
+ onOpenChange(false)
+ }
+
+ // Server-side `editable?` is `active?` — redeemed/canceled cards are
+ // read-only. Don't even show the form for those; let staff see the audit
+ // info only.
+ const editable = giftCard?.active ?? false
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>{giftCard?.code ?? 'Edit gift card'}</SheetTitle>
+ <SheetDescription>
+ {editable
+ ? 'Adjust amount, expiration, or recipient. Code cannot be changed.'
+ : 'This card cannot be edited — once redeemed, canceled, or expired, the details are locked.'}
+ </SheetDescription>
+ </SheetHeader>
+ {isLoading ? (
+ <div className="p-4 text-sm text-muted-foreground">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">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
+ <EditGiftCardFormFields form={form} readOnly={!editable} />
+ {giftCard && <GiftCardUsageSummary giftCard={giftCard} />}
+ </div>
+ <SheetFooter>
+ <Can I="destroy" a={Subject.GiftCard}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={onDelete}
+ disabled={form.formState.isSubmitting || deleteMutation.isPending}
+ className="mr-auto text-destructive hover:bg-destructive/10 hover:text-destructive"
+ >
+ Delete
+ </Button>
+ </Can>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={form.formState.isSubmitting}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ size="sm"
+ disabled={!editable || form.formState.isSubmitting || !form.formState.isDirty}
+ >
+ {form.formState.isSubmitting ? 'Saving…' : 'Save'}
+ </Button>
+ </SheetFooter>
+ </form>
+ )}
+ </SheetContent>
+ </Sheet>
+ )
+}
+
+// ----------------------------------------------------------------------------
+// Form fields
+// ----------------------------------------------------------------------------
+
+function CustomerPickerController({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form,
+ readOnly = false,
+}: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ form: any
+ readOnly?: boolean
+}) {
+ return (
+ <Controller
+ name="customer_id"
+ control={form.control}
+ render={({ field }) =>
+ readOnly ? (
+ <div className="text-sm text-muted-foreground">
+ {field.value || 'No customer attached'}
+ </div>
+ ) : (
+ <ResourceCombobox<Customer>
+ {...customerAutocompleteProps('customer-picker')}
+ value={field.value || undefined}
+ onChange={(id) => field.onChange(id ?? '')}
+ renderOption={(c) => (
+ <div>
+ <div className="font-medium">{c.email}</div>
+ {(c.first_name || c.last_name) && (
+ <div className="text-xs text-muted-foreground">{c.full_name}</div>
+ )}
+ </div>
+ )}
+ />
+ )
+ }
+ />
+ )
+}
+
+function AmountCurrencyRow<T extends CreateFormValues | EditFormValues>({
+ form,
+ readOnly,
+ currencyLocked,
+}: {
+ form: UseFormReturn<T>
+ readOnly: boolean
+ /** True on edit — currency can't change after creation. */
+ currencyLocked: boolean
+}) {
+ const { t } = useTranslation()
+ const errors = form.formState.errors as Record<string, { message?: string } | undefined>
+ return (
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor="gc-amount">{t('admin.fields.gift_card.amount.label')}</FieldLabel>
+ <Input
+ id="gc-amount"
+ type="number"
+ step="0.01"
+ min={0}
+ disabled={readOnly}
+ aria-invalid={!!errors.amount || undefined}
+ {...form.register('amount' as never)}
+ />
+ <FieldError errors={[errors.amount]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="gc-currency">{t('admin.fields.gift_card.currency.label')}</FieldLabel>
+ <Controller
+ name={'currency' as never}
+ control={form.control}
+ render={({ field }) => (
+ <CurrencySelect
+ id="gc-currency"
+ value={(field.value as string) || undefined}
+ onChange={field.onChange}
+ disabled={readOnly || currencyLocked}
+ />
+ )}
+ />
+ </Field>
+ </div>
+ )
+}
+
+function CreateGiftCardFormFields({
+ form,
+ isBatch,
+}: {
+ form: UseFormReturn<CreateFormValues>
+ isBatch: boolean
+}) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
+ return (
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="gc-quantity">{t('admin.fields.gift_card.quantity.label')}</FieldLabel>
+ <Input
+ id="gc-quantity"
+ type="number"
+ min={1}
+ max={BATCH_LIMIT}
+ step={1}
+ aria-invalid={!!errors.quantity || undefined}
+ {...form.register('quantity')}
+ />
+ <p className="text-xs text-muted-foreground">
+ {`Issue 1 card or bulk-issue up to ${BATCH_LIMIT.toLocaleString()} as a batch.`}
+ </p>
+ <FieldError errors={[errors.quantity]} />
+ </Field>
+
+ <Field>
+ <FieldLabel htmlFor="gc-code">
+ {isBatch ? 'Prefix' : t('admin.fields.gift_card.code.label')}
+ </FieldLabel>
+ <Input
+ id="gc-code"
+ placeholder={
+ isBatch ? 'e.g. WELCOME — codes will be WELCOME-abc123' : 'Auto-generated when blank'
+ }
+ aria-invalid={!!errors.code || undefined}
+ {...form.register('code')}
+ />
+ {!isBatch && (
+ <p className="text-xs text-muted-foreground">{t('admin.fields.gift_card.code.help')}</p>
+ )}
+ <FieldError errors={[errors.code]} />
+ </Field>
+
+ <AmountCurrencyRow form={form} readOnly={false} currencyLocked={false} />
+
+ <Field>
+ <FieldLabel htmlFor="gc-expires-at">
+ {t('admin.fields.gift_card.expires_at.label')}
+ </FieldLabel>
+ <Controller
+ name="expires_at"
+ control={form.control}
+ render={({ field }) => (
+ <StoreDatePicker
+ value={field.value || null}
+ onChange={(next) => field.onChange(next ?? '')}
+ placeholder={t('admin.fields.gift_card.expires_at.placeholder')}
+ inline
+ />
+ )}
+ />
+ </Field>
+
+ {/* A single customer can't be attached to a whole batch — hide the
+ field in batch mode to make the difference obvious. */}
+ {!isBatch && (
+ <Field>
+ <FieldLabel>{t('admin.fields.gift_card.customer_id.label')} (optional)</FieldLabel>
+ <CustomerPickerController form={form} />
+ </Field>
+ )}
+ </FieldGroup>
+ )
+}
+
+function EditGiftCardFormFields({
+ form,
+ readOnly = false,
+}: {
+ form: UseFormReturn<EditFormValues>
+ readOnly?: boolean
+}) {
+ const { t } = useTranslation()
+ return (
+ <FieldGroup>
+ <AmountCurrencyRow form={form} readOnly={readOnly} currencyLocked />
+
+ <Field>
+ <FieldLabel htmlFor="gc-expires-at">
+ {t('admin.fields.gift_card.expires_at.label')}
+ </FieldLabel>
+ <Controller
+ name="expires_at"
+ control={form.control}
+ render={({ field }) => (
+ <StoreDatePicker
+ value={field.value || null}
+ onChange={(next) => field.onChange(next ?? '')}
+ placeholder={t('admin.fields.gift_card.expires_at.placeholder')}
+ disabled={readOnly}
+ inline
+ />
+ )}
+ />
+ </Field>
+
+ <Field>
+ <FieldLabel>{t('admin.fields.gift_card.customer_id.label')} (optional)</FieldLabel>
+ <CustomerPickerController form={form} readOnly={readOnly} />
+ </Field>
+ </FieldGroup>
+ )
+}
+
+// ----------------------------------------------------------------------------
+// Usage summary — shown inside the edit sheet so staff can see redemption
+// progress without leaving the modal.
+// ----------------------------------------------------------------------------
+
+function GiftCardUsageSummary({ giftCard }: { giftCard: GiftCard }) {
+ return (
+ <div className="rounded-md border bg-muted/30 p-3 text-sm">
+ <div className="mb-2 font-medium">Usage</div>
+ <div className="grid grid-cols-2 gap-1 text-muted-foreground">
+ <span>Amount</span>
+ <span className="text-right text-foreground tabular-nums">{giftCard.display_amount}</span>
+ <span>Used</span>
+ <span className="text-right text-foreground tabular-nums">
+ {giftCard.display_amount_used}
+ </span>
+ <span>Remaining</span>
+ <span className="text-right text-foreground tabular-nums">
+ {giftCard.display_amount_remaining}
+ </span>
+ {giftCard.created_by && (
+ <>
+ <span>Issued by</span>
+ <span className="text-right text-foreground">{giftCard.created_by.email}</span>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/packages/admin/src/tables/gift-cards.tsx b/packages/admin/src/tables/gift-cards.tsx
new file mode 100644
index 0000000000..dec14b5c75
--- /dev/null
+++ b/packages/admin/src/tables/gift-cards.tsx
@@ -0,0 +1,169 @@
+import type { GiftCard } from '@spree/admin-sdk'
+import { GiftIcon } from 'lucide-react'
+import { RelativeTime } from '@/components/spree/relative-time'
+import { ResourceNameCell } from '@/components/spree/resource-name-cell'
+import { Badge } from '@/components/ui/badge'
+import { adminUserAutocompleteProps } from '@/hooks/use-admin-users'
+import { customerAutocompleteProps } from '@/hooks/use-customers'
+import { giftCardBatchAutocompleteProps } from '@/hooks/use-gift-cards'
+import { defineTable } from '@/lib/table-registry'
+
+// Server `Spree::GiftCard#display_state` exposes "expired" when the card
+// is past its expiration date, even though the underlying column is still
+// "active" — keep this list in sync with the state machine + display_state
+// override in `app/models/spree/gift_card.rb`.
+const STATUS_OPTIONS = [
+ { value: 'active', label: 'Active' },
+ { value: 'partially_redeemed', label: 'Partially redeemed' },
+ { value: 'redeemed', label: 'Redeemed' },
+ { value: 'canceled', label: 'Canceled' },
+] as const
+
+const STATUS_VARIANT: Record<
+ string,
+ 'success' | 'destructive' | 'secondary' | 'default' | 'outline'
+> = {
+ active: 'success',
+ partially_redeemed: 'default',
+ redeemed: 'secondary',
+ canceled: 'destructive',
+ expired: 'destructive',
+}
+
+function formatStatus(value: string): string {
+ return value.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
+}
+
+defineTable<GiftCard>('gift-cards', {
+ title: 'Gift Cards',
+ searchParam: 'code_cont',
+ searchPlaceholder: 'Search by code…',
+ defaultSort: { field: 'created_at', direction: 'desc' },
+ emptyIcon: <GiftIcon className="size-8 text-muted-foreground" />,
+ emptyMessage: 'No gift cards yet',
+ columns: [
+ {
+ key: 'code',
+ label: 'Code',
+ sortable: true,
+ filterable: true,
+ default: true,
+ render: (g) => (
+ <ResourceNameCell
+ id={g.id}
+ dataAttr="data-gift-card-id"
+ name={g.code}
+ secondary={g.customer?.email ?? undefined}
+ />
+ ),
+ },
+ {
+ key: 'status',
+ label: 'Status',
+ // Ransack filters off the underlying `state` column — `display_state`
+ // is a presentation-only override that returns 'expired' for active
+ // cards past their `expires_at`. Server still indexes `state`.
+ ransackAttribute: 'state',
+ filterable: true,
+ filterType: 'enum',
+ // Spread to narrow the readonly type into ColumnDef's mutable shape.
+ filterOptions: STATUS_OPTIONS.map(({ value, label }) => ({ value, label })),
+ default: true,
+ render: (g) => {
+ const status = g.status ?? 'active'
+ return <Badge variant={STATUS_VARIANT[status] ?? 'secondary'}>{formatStatus(status)}</Badge>
+ },
+ },
+ {
+ key: 'display_amount',
+ label: 'Amount',
+ default: true,
+ className: 'text-right tabular-nums whitespace-nowrap font-medium',
+ render: (g) => g.display_amount,
+ },
+ {
+ key: 'display_amount_used',
+ label: 'Used',
+ default: true,
+ className: 'text-right tabular-nums whitespace-nowrap',
+ render: (g) => g.display_amount_used,
+ },
+ {
+ key: 'display_amount_remaining',
+ label: 'Remaining',
+ default: true,
+ className: 'text-right tabular-nums whitespace-nowrap',
+ render: (g) => g.display_amount_remaining,
+ },
+ {
+ key: 'currency',
+ label: 'Currency',
+ sortable: true,
+ filterable: true,
+ filterType: 'currency',
+ default: false,
+ render: (g) => g.currency,
+ },
+ {
+ key: 'gift_card_batch',
+ label: 'Batch',
+ // Filter narrows to cards belonging to one or more batches via the
+ // `gift_card_batch_id_in` Ransack predicate (whitelisted on the
+ // GiftCard model). Picker renders inline batch prefixes.
+ ransackAttribute: 'gift_card_batch_id',
+ filterable: true,
+ filterType: 'resource',
+ filterResource: giftCardBatchAutocompleteProps('gift-card-batch-picker'),
+ default: false,
+ render: (g) =>
+ g.gift_card_batch ? (
+ <Badge variant="outline">{g.gift_card_batch.prefix ?? g.gift_card_batch.id}</Badge>
+ ) : (
+ '—'
+ ),
+ },
+ {
+ key: 'customer',
+ label: 'Customer',
+ // Whitelisted `user_id` on the GiftCard model.
+ ransackAttribute: 'user_id',
+ filterable: true,
+ filterType: 'resource',
+ filterResource: customerAutocompleteProps('gift-card-customer-filter'),
+ default: false,
+ render: (g) => g.customer?.email ?? '—',
+ },
+ {
+ key: 'created_by',
+ label: 'Issued by',
+ // GiftCard whitelists `code`, `user_id`, `state`, `gift_card_batch_id`.
+ // `created_by_id` is not whitelisted yet — Ransack will reject the
+ // predicate without it; we add it server-side alongside this column.
+ ransackAttribute: 'created_by_id',
+ filterable: true,
+ filterType: 'resource',
+ filterResource: adminUserAutocompleteProps('gift-card-created-by-filter'),
+ default: false,
+ render: (g) => g.created_by?.email ?? '—',
+ },
+ {
+ key: 'expires_at',
+ label: 'Expires',
+ sortable: true,
+ filterable: true,
+ filterType: 'date',
+ default: true,
+ className: 'text-sm text-muted-foreground whitespace-nowrap',
+ render: (g) => (g.expires_at ? <RelativeTime iso={g.expires_at} /> : '—'),
+ },
+ {
+ key: 'created_at',
+ label: 'Created',
+ sortable: true,
+ filterType: 'date',
+ default: false,
+ className: 'text-sm text-muted-foreground whitespace-nowrap',
+ render: (g) => <RelativeTime iso={g.created_at} />,
+ },
+ ],
+})