Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add ability to manage option tyoes and values in Admin SPA
Damian Legawiecdc68ba6159bf
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3b830510cf..fa01453e1e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -191,6 +191,8 @@ def permitted_paramsend```+**Read and write attribute names must match.** Whatever a serializer exposes (`label`, `status`, `customer_note`) is what the controller's `permitted_params` must accept on write — no "we expose `label` but accept `presentation`" mismatches. This is non-negotiable for v3: clients should not have to translate field names between read and write. When the underlying column has a legacy name, define a writer alias on the **model** (`def label=(value); self.presentation = value; end` — pair it with the matching reader) and permit the public name in the controller. The model owns the bridge, never the client. Example: `Spree::OptionType#label` / `label=` aliases — the serializer returns `label`, the controller permits `:label`, and the model translates to the underlying `presentation` column.+```rubymodule Spree::Api::V3::Storeclass ProductsController < ResourceController@@ -471,6 +473,19 @@ There are two correct ways to make the trigger show the label:For free-text **searchable** pickers, prefer `<Combobox>` over `<Select>` — see `components/spree/country-state-fields.tsx` for the country/state pattern.+**Form schemas live in `packages/admin/src/schemas/<resource>.ts`** when shared across 2+ files or non-trivial (~30+ lines, nested sub-schemas, companion option/constant arrays); inline is fine for single-file routes with a short schema. Filename is the kebab-case singular resource name (`product.ts`, `option-type.ts`, `tax-category.ts`). The schema file owns the entire form contract end-to-end: the Zod schema, its inferred `FormValues` type, default-values constants, dropdown option arrays, regex constants, **and** any form↔API mapper functions. Co-locating the schema with its mappers prevents the two from drifting (editing the schema almost always means editing the mappers). References: `schemas/product.ts`, `schemas/store.ts`.++Mappers should only exist for **pure frontend state** (upload progress flags, transient UI bookkeeping, derived display values). If you find yourself renaming an API field on the way in or out (`ot.label → form.presentation`), **fix the API instead** — see the read/write symmetry rule under "API Controllers" above. Frontend translation layers are a code smell and a maintenance tax; mappers shouldn't paper over inconsistent backend naming.++**`acts_as_list` ⇒ drag-and-drop reorder, never a numeric position input.** Whenever a model uses `acts_as_list` (in Ruby), the admin SPA surface for that model — both top-level list tables and nested collection editors inside forms — must reorder via **dnd-kit**, not via an exposed `position` number field. The user expects to grab a row and drop it, not type a number into a spreadsheet. Two reference patterns ship in the codebase:++1. **Top-level resource tables**: pass `reorder={{ onReorder: (id, position) => adminClient.X.update(id, { position }) }}` to `<ResourceTable>`. The table renders a grip column, owns the `DndContext` + `SortableContext` + `verticalListSortingStrategy` internally, and does optimistic local state with rollback on failure. Reference: `routes/_authenticated/$storeId/settings/payment-methods.tsx`. The position is 1-indexed; the server's `acts_as_list` shifts siblings.+2. **Nested collection editors inside a form** (e.g. an `option_values[]` array on an option type sheet): wrap the `useFieldArray` rows in `DndContext` + `SortableContext`, give each row a `<GripVerticalIcon>` grip with `{...attributes} {...listeners}` from `useSortable`, and on drag end call `valuesArray.move(from, to)` and rewrite each row's `position` to its new index. The position field is **not rendered** in the form; it's a computed output. Reference: `routes/_authenticated/$storeId/products/options.tsx` (option values) and `routes/_authenticated/$storeId/products/$productId.tsx` (product media — grid layout, uses `rectSortingStrategy`).++Use `verticalListSortingStrategy` for table rows / vertical lists, `rectSortingStrategy` for grids. Always include `KeyboardSensor` with `sortableKeyboardCoordinates` alongside `PointerSensor` for accessibility. Set `activationConstraint: { distance: 5 }` on the pointer sensor so clicks on row content don't hijack as drags.++**Base UI `<Popover>` is unreliable when nested inside a `<Sheet>`'s portal tree.** Symptom: the trigger button gets `aria-expanded="true"` and `data-popup-open=""` on click, but no `[data-slot="popover-content"]` ever appears in the DOM — the Popup component silently fails to mount its rendered output. Happens in deeply-nested portal trees (Sheet → SortableContext → TableRow → Popover). When clicks fire and state opens but no panel appears, **don't keep poking at Popover** — render the panel inline with `absolute top-full left-0 z-50` + a `document.pointerdown` click-outside listener + Escape-to-close. The picker doesn't need a portal unless it must escape an `overflow: hidden` ancestor; for table cells and form fields, inline is fine. Reference: `components/spree/color-picker.tsx`.+### @spree/sdk-core — Shared HTTP LayerPrivate package providing `createRequestFn()`, `SpreeError`, retry logic, and Ransack param transformation. Used internally by both SDKs.diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex cdca98a601..1238a445a8 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -9,29 +9,39 @@ export interface StoreUpdateParams {preferred_unit_system?: string}+export interface OptionValueParams {+ /** Present for existing rows. Omit to create a new value. */+ id?: string+ name?: string+ label?: string+ position?: number+ /** Hex color (e.g. `#FF0000`). Only meaningful when the parent option type's `kind` is `color_swatch`. */+ color_code?: string | null+ /** Active Storage signed_id from a direct upload. */+ image?: string | null+}+export interface OptionTypeCreateParams {name: string- presentation: string+ label: stringposition?: numberfilterable?: boolean- option_values?: Array<{- name?: string- presentation?: string- position?: number- }>+ /** `dropdown`, `color_swatch`, or `buttons`. */+ kind?: string+ /**+ * Inline option values. Values omitted from the array on update are destroyed —+ * send the full set every time you write.+ */+ option_values?: Array<OptionValueParams>}export interface OptionTypeUpdateParams {name?: string- presentation?: string+ label?: stringposition?: numberfilterable?: boolean- option_values?: Array<{- id?: string- name?: string- presentation?: string- position?: number- }>+ kind?: string+ option_values?: Array<OptionValueParams>}export interface LineItemCreateParams {diff --git a/packages/admin-sdk/src/types/generated/OptionType.ts b/packages/admin-sdk/src/types/generated/OptionType.tsindex 62a58b393c..8fd0edfdc3 100644--- a/packages/admin-sdk/src/types/generated/OptionType.ts+++ b/packages/admin-sdk/src/types/generated/OptionType.ts@@ -1,4 +1,4 @@-// Typelizer digest 4277db9a34a5e4f9e919ebdb57bd7e79+// Typelizer digest cf1a6f218cd866074bc2c46e5d506ef3//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {OptionValue} from '@/types'@@ -13,7 +13,7 @@ interface OptionType {filterable: boolean;created_at: string;updated_at: string;- option_values: Array<OptionValue>;+ option_values?: Array<OptionValue>;}export default OptionType;diff --git a/packages/admin/src/components/ui/badge.tsx b/packages/admin/src/components/ui/badge.tsxindex 6cdfbdd57d..a161e017ca 100644--- a/packages/admin/src/components/ui/badge.tsx+++ b/packages/admin/src/components/ui/badge.tsx@@ -134,7 +134,11 @@ function ActiveBadge({if (dashWhenInactive) {return <span className={cn('text-muted-foreground', className)}>—</span>}- return <Badge variant="outline">{inactiveLabel}</Badge>+ return (+ <Badge variant="outline" className={className}>+ {inactiveLabel}+ </Badge>+ )}export { ActiveBadge, Badge, badgeVariants, StatusBadge }diff --git a/packages/admin/src/hooks/use-option-types.ts b/packages/admin/src/hooks/use-option-types.tsnew file mode 100644index 0000000000..4bdc29fd48--- /dev/null+++ b/packages/admin/src/hooks/use-option-types.ts@@ -0,0 +1,70 @@+import type { OptionType, OptionTypeCreateParams, OptionTypeUpdateParams } from '@spree/admin-sdk'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import { adminClient } from '@/client'+import { useResourceMutation } from '@/hooks/use-resource-mutation'++export const optionTypesQueryKey = ['option-types'] as const++export function optionTypeQueryKey(id: string) {+ return ['option-types', id] as const+}++interface UseOptionTypesParams {+ page?: number+ limit?: number+ q?: Record<string, unknown>+}++export function useOptionTypes({ page = 1, limit = 100, q }: UseOptionTypesParams = {}) {+ return useQuery({+ queryKey: [...optionTypesQueryKey, { page, limit, q }],+ queryFn: () =>+ adminClient.optionTypes.list({+ page,+ limit,+ q,+ expand: ['option_values'],+ }),+ staleTime: 1000 * 60 * 5,+ })+}++export function useOptionType(id: string | undefined) {+ return useQuery({+ queryKey: id ? optionTypeQueryKey(id) : ['option-types', 'noop'],+ queryFn: () => adminClient.optionTypes.get(id as string, { expand: ['option_values'] }),+ enabled: !!id,+ })+}++export function useCreateOptionType() {+ return useResourceMutation<OptionType, Error, OptionTypeCreateParams>({+ mutationFn: (params) => adminClient.optionTypes.create(params),+ invalidate: [optionTypesQueryKey],+ successMessage: 'Option type created',+ errorMessage: 'Failed to create option type',+ })+}++export function useUpdateOptionType(id: string) {+ return useResourceMutation<OptionType, Error, OptionTypeUpdateParams>({+ mutationFn: (params) => adminClient.optionTypes.update(id, params),+ invalidate: [optionTypesQueryKey, optionTypeQueryKey(id)],+ successMessage: 'Option type updated',+ errorMessage: 'Failed to update option type',+ })+}++export function useDeleteOptionType() {+ const queryClient = useQueryClient()++ return useResourceMutation<void, Error, string>({+ mutationFn: (id) => adminClient.optionTypes.delete(id),+ invalidate: [optionTypesQueryKey],+ successMessage: 'Option type deleted',+ errorMessage: 'Failed to delete option type',+ onSuccess: (_data, id) => {+ queryClient.removeQueries({ queryKey: optionTypeQueryKey(id) })+ },+ })+}diff --git a/packages/admin/src/routeTree.gen.ts b/packages/admin/src/routeTree.gen.tsindex dbf17a274c..120ca8dbe3 100644--- a/packages/admin/src/routeTree.gen.ts+++ b/packages/admin/src/routeTree.gen.ts@@ -30,12 +30,12 @@ import { Route as AuthenticatedStoreIdSettingsApiKeysRouteImport } from './routeimport { Route as AuthenticatedStoreIdPromotionsNewRouteImport } from './routes/_authenticated/$storeId/promotions/new'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'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'import { Route as AuthenticatedStoreIdOrdersOrderIdRouteImport } from './routes/_authenticated/$storeId/orders/$orderId'import { Route as AuthenticatedStoreIdCustomersCustomerIdRouteImport } from './routes/_authenticated/$storeId/customers/$customerId'-import { Route as AuthenticatedStoreIdProductsStockTransfersRouteImport } from './routes/_authenticated/$storeId/products/stock/transfers'const LoginRoute = LoginRouteImport.update({id: '/login',@@ -158,6 +158,12 @@ const AuthenticatedStoreIdProductsTransfersRoute =path: '/products/transfers',getParentRoute: () => AuthenticatedStoreIdRoute,} as any)+const AuthenticatedStoreIdProductsOptionsRoute =+ AuthenticatedStoreIdProductsOptionsRouteImport.update({+ id: '/products/options',+ path: '/products/options',+ getParentRoute: () => AuthenticatedStoreIdRoute,+ } as any)const AuthenticatedStoreIdProductsProductIdRoute =AuthenticatedStoreIdProductsProductIdRouteImport.update({id: '/products/$productId',@@ -201,6 +207,7 @@ export interface FileRoutesByFullPath {'/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute'/$storeId/orders/new': typeof AuthenticatedStoreIdOrdersNewRoute'/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute+ '/$storeId/products/options': typeof AuthenticatedStoreIdProductsOptionsRoute'/$storeId/products/transfers': typeof AuthenticatedStoreIdProductsTransfersRoute'/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute'/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute@@ -226,6 +233,8 @@ export interface FileRoutesByTo {'/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute'/$storeId/orders/new': typeof AuthenticatedStoreIdOrdersNewRoute'/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute+ '/$storeId/products/options': typeof AuthenticatedStoreIdProductsOptionsRoute+ '/$storeId/products/transfers': typeof AuthenticatedStoreIdProductsTransfersRoute'/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute'/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute'/$storeId/settings/api-keys': typeof AuthenticatedStoreIdSettingsApiKeysRoute@@ -239,7 +248,6 @@ export interface FileRoutesByTo {'/$storeId/products': typeof AuthenticatedStoreIdProductsIndexRoute'/$storeId/promotions': typeof AuthenticatedStoreIdPromotionsIndexRoute'/$storeId/settings': typeof AuthenticatedStoreIdSettingsIndexRoute- '/$storeId/products/stock/transfers': typeof AuthenticatedStoreIdProductsStockTransfersRoute}export interface FileRoutesById {__root__: typeof rootRouteImport@@ -255,6 +263,7 @@ export interface FileRoutesById {'/_authenticated/$storeId/orders/drafts': typeof AuthenticatedStoreIdOrdersDraftsRoute'/_authenticated/$storeId/orders/new': typeof AuthenticatedStoreIdOrdersNewRoute'/_authenticated/$storeId/products/$productId': typeof AuthenticatedStoreIdProductsProductIdRoute+ '/_authenticated/$storeId/products/options': typeof AuthenticatedStoreIdProductsOptionsRoute'/_authenticated/$storeId/products/transfers': typeof AuthenticatedStoreIdProductsTransfersRoute'/_authenticated/$storeId/promotions/$promotionId': typeof AuthenticatedStoreIdPromotionsPromotionIdRoute'/_authenticated/$storeId/promotions/new': typeof AuthenticatedStoreIdPromotionsNewRoute@@ -284,6 +293,7 @@ export interface FileRouteTypes {| '/$storeId/orders/drafts'| '/$storeId/orders/new'| '/$storeId/products/$productId'+ | '/$storeId/products/options'| '/$storeId/products/transfers'| '/$storeId/promotions/$promotionId'| '/$storeId/promotions/new'@@ -298,7 +308,6 @@ export interface FileRouteTypes {| '/$storeId/products/'| '/$storeId/promotions/'| '/$storeId/settings/'- | '/$storeId/products/stock/transfers'fileRoutesByTo: FileRoutesByToto:| '/login'@@ -310,6 +319,7 @@ export interface FileRouteTypes {| '/$storeId/orders/drafts'| '/$storeId/orders/new'| '/$storeId/products/$productId'+ | '/$storeId/products/options'| '/$storeId/products/transfers'| '/$storeId/promotions/$promotionId'| '/$storeId/promotions/new'@@ -324,7 +334,6 @@ export interface FileRouteTypes {| '/$storeId/products'| '/$storeId/promotions'| '/$storeId/settings'- | '/$storeId/products/stock/transfers'id:| '__root__'| '/_authenticated'@@ -339,6 +348,7 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/orders/drafts'| '/_authenticated/$storeId/orders/new'| '/_authenticated/$storeId/products/$productId'+ | '/_authenticated/$storeId/products/options'| '/_authenticated/$storeId/products/transfers'| '/_authenticated/$storeId/promotions/$promotionId'| '/_authenticated/$storeId/promotions/new'@@ -353,7 +363,6 @@ export interface FileRouteTypes {| '/_authenticated/$storeId/products/'| '/_authenticated/$storeId/promotions/'| '/_authenticated/$storeId/settings/'- | '/_authenticated/$storeId/products/stock/transfers'fileRoutesById: FileRoutesById}export interface RootRouteChildren {@@ -511,6 +520,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthenticatedStoreIdProductsTransfersRouteImportparentRoute: typeof AuthenticatedStoreIdRoute}+ '/_authenticated/$storeId/products/options': {+ id: '/_authenticated/$storeId/products/options'+ path: '/products/options'+ fullPath: '/$storeId/products/options'+ preLoaderRoute: typeof AuthenticatedStoreIdProductsOptionsRouteImport+ parentRoute: typeof AuthenticatedStoreIdRoute+ }'/_authenticated/$storeId/products/$productId': {id: '/_authenticated/$storeId/products/$productId'path: '/products/$productId'@@ -590,6 +606,7 @@ interface AuthenticatedStoreIdRouteChildren {AuthenticatedStoreIdOrdersDraftsRoute: typeof AuthenticatedStoreIdOrdersDraftsRouteAuthenticatedStoreIdOrdersNewRoute: typeof AuthenticatedStoreIdOrdersNewRouteAuthenticatedStoreIdProductsProductIdRoute: typeof AuthenticatedStoreIdProductsProductIdRoute+ AuthenticatedStoreIdProductsOptionsRoute: typeof AuthenticatedStoreIdProductsOptionsRouteAuthenticatedStoreIdProductsTransfersRoute: typeof AuthenticatedStoreIdProductsTransfersRouteAuthenticatedStoreIdPromotionsPromotionIdRoute: typeof AuthenticatedStoreIdPromotionsPromotionIdRouteAuthenticatedStoreIdPromotionsNewRoute: typeof AuthenticatedStoreIdPromotionsNewRoute@@ -597,7 +614,6 @@ interface AuthenticatedStoreIdRouteChildren {AuthenticatedStoreIdOrdersIndexRoute: typeof AuthenticatedStoreIdOrdersIndexRouteAuthenticatedStoreIdProductsIndexRoute: typeof AuthenticatedStoreIdProductsIndexRouteAuthenticatedStoreIdPromotionsIndexRoute: typeof AuthenticatedStoreIdPromotionsIndexRoute- AuthenticatedStoreIdProductsStockTransfersRoute: typeof AuthenticatedStoreIdProductsStockTransfersRoute}const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {@@ -612,6 +628,8 @@ const AuthenticatedStoreIdRouteChildren: AuthenticatedStoreIdRouteChildren = {AuthenticatedStoreIdOrdersNewRoute: AuthenticatedStoreIdOrdersNewRoute,AuthenticatedStoreIdProductsProductIdRoute:AuthenticatedStoreIdProductsProductIdRoute,+ AuthenticatedStoreIdProductsOptionsRoute:+ AuthenticatedStoreIdProductsOptionsRoute,AuthenticatedStoreIdProductsTransfersRoute:AuthenticatedStoreIdProductsTransfersRoute,AuthenticatedStoreIdPromotionsPromotionIdRoute:diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsxindex 47968cb1ee..cf9d2c36b6 100644--- a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -113,7 +113,7 @@ function productToFormValues(product: Product): ProductFormValues {available_on: product.available_on ?? null,discontinue_on: product.discontinue_on ?? null,category_ids: product.categories?.map((t) => t.id) ?? [],- tags: product.tags?.map((t: any) => t.name ?? t) ?? [],+ tags: product.tags ?? [],tax_category_id: product.tax_category_id ?? null,meta_title: product.meta_title ?? '',meta_description: product.meta_description ?? '',diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/options.tsxnew file mode 100644index 0000000000..f109da9fc5--- /dev/null+++ b/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx@@ -0,0 +1,876 @@+import {+ closestCenter,+ DndContext,+ type DragEndEvent,+ KeyboardSensor,+ PointerSensor,+ useSensor,+ useSensors,+} from '@dnd-kit/core'+import {+ SortableContext,+ sortableKeyboardCoordinates,+ useSortable,+ verticalListSortingStrategy,+} from '@dnd-kit/sortable'+import { CSS } from '@dnd-kit/utilities'+import { zodResolver } from '@hookform/resolvers/zod'+import type {+ OptionType,+ OptionTypeCreateParams,+ OptionValue,+ OptionValueParams,+} from '@spree/admin-sdk'+import { useQueryClient } from '@tanstack/react-query'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { ImageIcon, PlusIcon, Trash2Icon, UploadCloudIcon, XIcon } from 'lucide-react'+import { type CSSProperties, useEffect, useId, useRef, useState } from 'react'+import {+ type Control,+ Controller,+ type UseFormReturn,+ useFieldArray,+ useForm,+} from 'react-hook-form'+import { toast } from 'sonner'+import { z } from 'zod/v4'+import { adminClient } from '@/client'+import { Can } from '@/components/spree/can'+import { ColorPicker } from '@/components/spree/color-picker'+import { useConfirm } from '@/components/spree/confirm-dialog'+import { DragHandle } from '@/components/spree/drag-handle'+import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'+import { useRowClickBridge } from '@/components/spree/row-click-bridge'+import { Button } from '@/components/ui/button'+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '@/components/ui/data-table'+import { Dialog, DialogContent } from '@/components/ui/dialog'+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 { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'+import { useDirectUpload } from '@/hooks/use-direct-upload'+import {+ optionTypesQueryKey,+ useCreateOptionType,+ useDeleteOptionType,+ useOptionType,+ useUpdateOptionType,+} from '@/hooks/use-option-types'+import { Subject } from '@/lib/permissions'+import { cn } from '@/lib/utils'+import '@/tables/option-types'++const optionTypesSearchSchema = resourceSearchSchema.extend({+ edit: z.string().optional(),+ new: z.coerce.boolean().optional(),+})++export const Route = createFileRoute('/_authenticated/$storeId/products/options')({+ validateSearch: optionTypesSearchSchema,+ component: OptionTypesPage,+})++function OptionTypesPage() {+ const search = Route.useSearch() as z.infer<typeof optionTypesSearchSchema>+ const navigate = useNavigate()+ const queryClient = useQueryClient()++ 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-option-type-id', openEdit)++ return (+ <>+ <ResourceTable<OptionType>+ tableKey="option-types"+ queryKey="option-types"+ queryFn={(params) => adminClient.optionTypes.list({ ...params, expand: ['option_values'] })}+ searchParams={search}+ actions={+ <Can I="create" a={Subject.OptionType}>+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>+ <PlusIcon className="size-4" />+ Add option type+ </Button>+ </Can>+ }+ reorder={{+ onReorder: async (id, position) => {+ await adminClient.optionTypes.update(id, { position })+ queryClient.invalidateQueries({ queryKey: optionTypesQueryKey })+ },+ }}+ />++ {isCreating && <CreateOptionTypeSheet open onOpenChange={(o) => !o && closeSheet()} />}+ {editId && <EditOptionTypeSheet id={editId} open onOpenChange={(o) => !o && closeSheet()} />}+ </>+ )+}++// ---------------------------------------------------------------------------+// Form schema+// ---------------------------------------------------------------------------++const KIND_OPTIONS = [+ { value: 'dropdown', label: 'Dropdown' },+ { value: 'color_swatch', label: 'Color swatch' },+ { value: 'buttons', label: 'Buttons' },+] as const++const HEX_RE = /^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$/++const optionValueSchema = z.object({+ id: z.string().optional(),+ name: z.string().min(1, 'Name is required'),+ label: z.string().min(1, 'Label is required'),+ color_code: z+ .string()+ .nullable()+ .optional()+ .refine((v) => !v || HEX_RE.test(v), 'Invalid hex color'),+ /** Active Storage signed_id from a fresh direct upload. Frontend-only state. */+ image_signed_id: z.string().nullable().optional(),+ /** Existing image URL (for preview only — never sent back). Frontend-only state. */+ image_url: z.string().nullable().optional(),+ /** True when the user clicks the trash icon next to an existing image. Frontend-only state. */+ image_cleared: z.boolean().optional(),+})++const formSchema = z.object({+ name: z.string().min(1, 'Name is required'),+ label: z.string().min(1, 'Label is required'),+ kind: z.enum(['dropdown', 'color_swatch', 'buttons']),+ filterable: z.boolean(),+ option_values: z.array(optionValueSchema),+})++type FormValues = z.infer<typeof formSchema>+type OptionValueFormValue = z.infer<typeof optionValueSchema>++const DEFAULT_VALUES: FormValues = {+ name: '',+ label: '',+ kind: 'dropdown',+ filterable: false,+ option_values: [],+}++/**+ * Hydrate the form from an API option_value row. Spreads all API fields 1:1 and+ * attaches the frontend-only image upload-state fields (`image_signed_id`,+ * `image_cleared`) initialized to their resting values.+ */+function optionValueToFormRow(ov: OptionValue): OptionValueFormValue {+ return {+ ...ov,+ image_signed_id: null,+ image_cleared: false,+ }+}++/**+ * Build the API payload for a single option_value row. `index` is the row's+ * current array position; we send `position: index + 1` (1-indexed) so+ * `acts_as_list` persists the drag-reordered order. The frontend-only image+ * upload state collapses into the API's `image` field: a fresh signed_id is+ * sent, an explicit clear sends `null`, and an untouched row omits `image`+ * entirely so the existing attachment stays.+ */+function valueToParam(v: OptionValueFormValue, index: number): OptionValueParams {+ const { image_signed_id, image_url: _imageUrl, image_cleared, ...rest } = v+ return {+ ...rest,+ position: index + 1,+ ...(image_signed_id ? { image: image_signed_id } : image_cleared ? { image: null } : {}),+ }+}++// ---------------------------------------------------------------------------+// Create+// ---------------------------------------------------------------------------++function CreateOptionTypeSheet({+ open,+ onOpenChange,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const createMutation = useCreateOptionType()+ const form = useForm<FormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(formSchema) as any,+ defaultValues: DEFAULT_VALUES,+ })++ async function onSubmit(values: FormValues) {+ await createMutation.mutateAsync({+ ...values,+ option_values: values.option_values.map(valueToParam),+ } as OptionTypeCreateParams)+ form.reset(DEFAULT_VALUES)+ onOpenChange(false)+ }++ return (+ <Sheet+ open={open}+ onOpenChange={(next) => {+ if (!next) form.reset(DEFAULT_VALUES)+ onOpenChange(next)+ }}+ >+ <SheetContent className="sm:max-w-2xl">+ <SheetHeader>+ <SheetTitle>Add option type</SheetTitle>+ <SheetDescription>+ Option types group the choices a customer makes per variant — size, color, material.+ </SheetDescription>+ </SheetHeader>+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">+ <div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">+ <OptionTypeFormFields form={form} />+ <OptionValuesFieldArray form={form} />+ </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…' : 'Create option type'}+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>+ )+}++// ---------------------------------------------------------------------------+// Edit+// ---------------------------------------------------------------------------++function EditOptionTypeSheet({+ id,+ open,+ onOpenChange,+}: {+ id: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { data: optionType, isLoading } = useOptionType(id)+ const updateMutation = useUpdateOptionType(id)+ const deleteMutation = useDeleteOptionType()+ const confirm = useConfirm()++ const form = useForm<FormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(formSchema) as any,+ defaultValues: DEFAULT_VALUES,+ })++ useEffect(() => {+ if (optionType) {+ form.reset({+ ...optionType,+ kind: optionType.kind as FormValues['kind'],+ option_values: (optionType.option_values ?? []).map(optionValueToFormRow),+ })+ }+ }, [optionType, form])++ async function onSubmit(values: FormValues) {+ await updateMutation.mutateAsync({+ ...values,+ option_values: values.option_values.map(valueToParam),+ })+ // The sheet closes here; the `useOptionType` cache invalidation done by+ // the mutation hook re-hydrates the form via `useEffect` the next time+ // the sheet opens. Don't reset from the update response — the v3+ // serializer omits `option_values` when not expanded, and resetting with+ // `[]` flashes empty rows during the closing animation.+ onOpenChange(false)+ }++ async function onDelete() {+ const ok = await confirm({+ title: 'Delete option type?',+ message: `${optionType?.name ?? 'This option type'} and its option values will be removed. Variants currently using it will lose those option assignments.`,+ variant: 'destructive',+ confirmLabel: 'Delete',+ })+ if (!ok) return+ await deleteMutation.mutateAsync(id)+ onOpenChange(false)+ }++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent className="sm:max-w-2xl">+ <SheetHeader>+ <SheetTitle>{optionType?.name ?? 'Edit option type'}</SheetTitle>+ <SheetDescription>+ Update the option type and its values. Drag rows to reorder. Values omitted from this+ list will be removed.+ </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-6 overflow-y-auto p-4">+ <OptionTypeFormFields form={form} />+ <OptionValuesFieldArray form={form} />+ </div>+ <SheetFooter>+ <Can I="destroy" a={Subject.OptionType}>+ <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={form.formState.isSubmitting || !form.formState.isDirty}+ >+ {form.formState.isSubmitting ? 'Saving…' : 'Save'}+ </Button>+ </SheetFooter>+ </form>+ )}+ </SheetContent>+ </Sheet>+ )+}++// ---------------------------------------------------------------------------+// Top-level fields+// ---------------------------------------------------------------------------++function OptionTypeFormFields({+ form,+}: {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ form: any+}) {+ return (+ <FieldGroup>+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">+ <Field>+ <FieldLabel htmlFor="label">Label</FieldLabel>+ <Input+ id="label"+ autoFocus+ placeholder="e.g. Shirt size"+ {...form.register('label')}+ aria-invalid={!!form.formState.errors.label}+ />+ <p className="text-xs text-muted-foreground">Shown to customers on the storefront.</p>+ {form.formState.errors.label && (+ <p className="text-sm text-destructive">{form.formState.errors.label.message}</p>+ )}+ </Field>++ <Field>+ <FieldLabel htmlFor="name">Internal name</FieldLabel>+ <Input+ id="name"+ placeholder="e.g. shirt-size"+ {...form.register('name')}+ aria-invalid={!!form.formState.errors.name}+ />+ <p className="text-xs text-muted-foreground">+ Lowercase identifier. Must be unique across the store.+ </p>+ {form.formState.errors.name && (+ <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>+ )}+ </Field>+ </div>++ <Field>+ <FieldLabel htmlFor="kind">Kind</FieldLabel>+ <Controller+ name="kind"+ control={form.control}+ render={({ field }) => (+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger id="kind">+ <SelectValue>+ {(value) =>+ KIND_OPTIONS.find((o) => o.value === value)?.label ?? (value as string)+ }+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {KIND_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ <p className="text-xs text-muted-foreground">+ Controls how the option renders on the storefront. Color swatch shows a hex color; buttons+ show a thumbnail image.+ </p>+ </Field>++ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel htmlFor="filterable" className="cursor-pointer">+ Filterable+ </FieldLabel>+ <span className="text-xs text-muted-foreground">+ Show this option as a filter in storefront product listings.+ </span>+ </div>+ <Controller+ name="filterable"+ control={form.control}+ render={({ field }) => (+ <Switch id="filterable" checked={!!field.value} onCheckedChange={field.onChange} />+ )}+ />+ </div>+ </Field>+ </FieldGroup>+ )+}++// ---------------------------------------------------------------------------+// Nested option_values — sortable table+// ---------------------------------------------------------------------------++function OptionValuesFieldArray({+ form,+}: {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ form: any+}) {+ const valuesArray = useFieldArray<FormValues, 'option_values', '_key'>({+ control: form.control as Control<FormValues>,+ name: 'option_values',+ keyName: '_key',+ })+ const kind = form.watch('kind') as FormValues['kind']+ const showColor = kind === 'color_swatch'+ const showImage = kind === 'color_swatch' || kind === 'buttons'++ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),+ )++ function handleDragEnd(event: DragEndEvent) {+ const { active, over } = event+ if (!over || active.id === over.id) return+ const fromIndex = valuesArray.fields.findIndex((f) => f._key === active.id)+ const toIndex = valuesArray.fields.findIndex((f) => f._key === over.id)+ if (fromIndex === -1 || toIndex === -1) return+ valuesArray.move(fromIndex, toIndex)+ }++ const dataColCount = 2 + (showColor ? 1 : 0) + (showImage ? 1 : 0)+ // grip + data cols + delete+ const totalColCount = 1 + dataColCount + 1++ return (+ <div className="flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <div className="flex flex-col">+ <h3 className="text-sm font-medium">Option values</h3>+ <p className="text-xs text-muted-foreground">+ The individual choices (e.g. Small, Medium, Large). Drag rows to reorder.+ </p>+ </div>+ {valuesArray.fields.length > 0 && (+ <span className="text-xs text-muted-foreground">+ {valuesArray.fields.length === 1 ? '1 value' : `${valuesArray.fields.length} values`}+ </span>+ )}+ </div>++ <div className="overflow-hidden rounded-md border border-border bg-card">+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>+ <SortableContext+ items={valuesArray.fields.map((f) => f._key)}+ strategy={verticalListSortingStrategy}+ >+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-8" aria-label="Reorder" />+ <TableHead>Internal name</TableHead>+ <TableHead>Label</TableHead>+ {showColor && <TableHead>Color</TableHead>}+ {showImage && <TableHead>Image</TableHead>}+ <TableHead aria-label="Actions" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {valuesArray.fields.length === 0 && (+ <TableRow>+ <TableCell+ colSpan={totalColCount}+ className="py-6 text-center text-sm text-muted-foreground"+ >+ No values yet. Add one to get started.+ </TableCell>+ </TableRow>+ )}+ {valuesArray.fields.map((field, index) => (+ <SortableOptionValueRow+ key={field._key}+ sortableId={field._key}+ form={form}+ index={index}+ showColor={showColor}+ showImage={showImage}+ onRemove={() => valuesArray.remove(index)}+ />+ ))}+ <TableRow className="hover:bg-transparent">+ <TableCell colSpan={totalColCount} className="p-0">+ <button+ type="button"+ onClick={() =>+ valuesArray.append({+ name: '',+ label: '',+ color_code: null,+ image_signed_id: null,+ image_url: null,+ image_cleared: false,+ })+ }+ className="flex w-full items-center justify-center gap-2 px-3 py-3 text-sm font-medium text-foreground transition-colors hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <PlusIcon className="size-4" />+ Add option value+ </button>+ </TableCell>+ </TableRow>+ </TableBody>+ </Table>+ </SortableContext>+ </DndContext>+ </div>+ </div>+ )+}++function SortableOptionValueRow({+ sortableId,+ form,+ index,+ showColor,+ showImage,+ onRemove,+}: {+ sortableId: string+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ form: any+ index: number+ showColor: boolean+ showImage: boolean+ onRemove: () => void+}) {+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({+ id: sortableId,+ })+ const style: CSSProperties = {+ transform: CSS.Transform.toString(transform),+ transition,+ }++ const errors = form.formState.errors?.option_values?.[index] as+ | Partial<Record<keyof OptionValueFormValue, { message?: string }>>+ | undefined++ return (+ <TableRow+ ref={setNodeRef}+ style={style}+ className={cn(isDragging && 'relative z-10 bg-card opacity-80 shadow-lg')}+ >+ <TableCell className="w-8 touch-none p-0">+ <DragHandle attributes={attributes} listeners={listeners} />+ </TableCell>++ <TableCell>+ <Input+ aria-label="Internal name"+ placeholder="e.g. small"+ {...form.register(`option_values.${index}.name` as const)}+ aria-invalid={!!errors?.name}+ />+ {errors?.name?.message && (+ <p className="mt-1 text-xs text-destructive">{errors.name.message}</p>+ )}+ </TableCell>++ <TableCell>+ <Input+ aria-label="Label"+ placeholder="e.g. Small"+ {...form.register(`option_values.${index}.label` as const)}+ aria-invalid={!!errors?.label}+ />+ {errors?.label?.message && (+ <p className="mt-1 text-xs text-destructive">{errors.label.message}</p>+ )}+ </TableCell>++ {showColor && (+ <TableCell>+ <Controller+ name={`option_values.${index}.color_code` as const}+ control={form.control}+ render={({ field }) => (+ <ColorPicker+ value={field.value as string | null | undefined}+ onChange={field.onChange}+ aria-invalid={!!errors?.color_code}+ compact+ panelAlign="end"+ />+ )}+ />+ {errors?.color_code?.message && (+ <p className="mt-1 text-xs text-destructive">{errors.color_code.message}</p>+ )}+ </TableCell>+ )}++ {showImage && (+ <TableCell>+ <OptionValueImageField form={form} index={index} />+ </TableCell>+ )}++ <TableCell className="w-10 text-right">+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ aria-label="Remove value"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={onRemove}+ className="text-destructive hover:bg-destructive/10 hover:text-destructive"+ >+ <Trash2Icon className="size-4" />+ </Button>+ </TableCell>+ </TableRow>+ )+}++// ---------------------------------------------------------------------------+// Image upload — compact (table-cell sized) variant+// ---------------------------------------------------------------------------++function OptionValueImageField({+ form,+ index,+}: {+ form: UseFormReturn<FormValues>+ index: number+}) {+ const fileInputId = useId()+ const fileInputRef = useRef<HTMLInputElement>(null)+ const directUpload = useDirectUpload()+ const [localPreview, setLocalPreview] = useState<string | null>(null)+ const [uploading, setUploading] = useState(false)+ const [zoomOpen, setZoomOpen] = useState(false)+ // Track the latest blob URL so the unmount cleanup sees the current+ // value without forcing the effect to re-run (and re-create the closure)+ // on every replace.+ const localPreviewRef = useRef<string | null>(null)+ localPreviewRef.current = localPreview+ useEffect(() => {+ return () => {+ if (localPreviewRef.current) URL.revokeObjectURL(localPreviewRef.current)+ }+ }, [])++ const imageUrl = form.watch(`option_values.${index}.image_url`) as string | null | undefined+ const cleared = form.watch(`option_values.${index}.image_cleared`) as boolean | undefined++ const preview = localPreview ?? (cleared ? null : (imageUrl ?? null))++ async function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {+ const file = e.target.files?.[0]+ if (!file) return+ setUploading(true)+ try {+ const result = await directUpload.mutateAsync(file)+ if (localPreview) URL.revokeObjectURL(localPreview)+ setLocalPreview(result.previewUrl)+ form.setValue(`option_values.${index}.image_signed_id`, result.signedId, {+ shouldDirty: true,+ })+ form.setValue(`option_values.${index}.image_cleared`, false, { shouldDirty: true })+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Upload failed'+ toast.error(message)+ } finally {+ setUploading(false)+ if (fileInputRef.current) fileInputRef.current.value = ''+ }+ }++ function clear() {+ if (localPreview) {+ URL.revokeObjectURL(localPreview)+ setLocalPreview(null)+ }+ form.setValue(`option_values.${index}.image_signed_id`, null, { shouldDirty: true })+ form.setValue(`option_values.${index}.image_cleared`, true, { shouldDirty: true })+ setZoomOpen(false)+ }++ return (+ <div className="relative size-10">+ <button+ type="button"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={() => (preview ? setZoomOpen(true) : fileInputRef.current?.click())}+ disabled={uploading}+ className={cn(+ 'relative size-10 shrink-0 overflow-hidden rounded-md border border-border bg-muted',+ 'transition-colors hover:border-foreground/30',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ preview && 'cursor-zoom-in',+ )}+ aria-label={preview ? 'View image' : 'Upload image'}+ >+ {preview ? (+ <img src={preview} alt="" className="size-full object-cover" />+ ) : (+ <div className="flex size-full items-center justify-center text-muted-foreground">+ {uploading ? (+ <UploadCloudIcon className="size-4 animate-pulse" />+ ) : (+ <ImageIcon className="size-4" />+ )}+ </div>+ )}+ </button>+ <input+ ref={fileInputRef}+ id={fileInputId}+ type="file"+ accept="image/*"+ className="sr-only"+ onChange={onFileChange}+ disabled={uploading}+ />+ {preview && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button+ type="button"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={clear}+ disabled={uploading}+ aria-label="Remove image"+ className={cn(+ 'absolute -right-1.5 -top-1.5 flex size-4 items-center justify-center rounded-full',+ 'border border-border bg-background text-muted-foreground shadow-xs',+ 'transition-colors hover:bg-destructive hover:text-destructive-foreground hover:border-destructive',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ >+ <XIcon className="size-3" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Remove image</TooltipContent>+ </Tooltip>+ )}+ {preview && (+ <Dialog open={zoomOpen} onOpenChange={setZoomOpen}>+ <DialogContent+ showCloseButton={true}+ // Full-viewport popup with no chrome so the bare image floats+ // on the backdrop and the surrounding area is dismissable.+ className="fixed inset-0 left-0 top-0 flex h-screen w-screen max-w-none translate-x-0 translate-y-0 items-center justify-center border-0 p-4 shadow-none sm:max-w-none"+ style={{ maxHeight: '100vh' }}+ >+ <img+ src={preview}+ alt=""+ className="block max-h-[90vh] max-w-[90vw] rounded-lg object-contain"+ />+ </DialogContent>+ </Dialog>+ )}+ </div>+ )+}diff --git a/packages/admin/src/tables/option-types.tsx b/packages/admin/src/tables/option-types.tsxnew file mode 100644index 0000000000..149ef57e7c--- /dev/null+++ b/packages/admin/src/tables/option-types.tsx@@ -0,0 +1,91 @@+import type { OptionType } from '@spree/admin-sdk'+import { ListChecksIcon, PencilIcon } from 'lucide-react'+import { RelativeTime } from '@/components/spree/relative-time'+import { ResourceNameCell } from '@/components/spree/resource-name-cell'+import { ActiveBadge, Badge } from '@/components/ui/badge'+import { Button } from '@/components/ui/button'+import { defineTable } from '@/lib/table-registry'++const KIND_LABELS: Record<string, string> = {+ dropdown: 'Dropdown',+ color_swatch: 'Color swatch',+ buttons: 'Buttons',+}++defineTable<OptionType>('option-types', {+ title: 'Option Types',+ searchParam: 'name_cont',+ searchPlaceholder: 'Search by name…',+ defaultSort: { field: 'position', direction: 'asc' },+ emptyIcon: <ListChecksIcon className="size-8 text-muted-foreground/50" />,+ emptyMessage: 'No option types yet',+ columns: [+ {+ key: 'name',+ label: 'Name',+ sortable: true,+ filterable: true,+ default: true,+ render: (ot) => (+ <ResourceNameCell+ id={ot.id}+ dataAttr="data-option-type-id"+ name={ot.name}+ secondary={ot.label && ot.label !== ot.name ? ot.label : undefined}+ />+ ),+ },+ {+ key: 'kind',+ label: 'Kind',+ sortable: true,+ filterable: true,+ default: true,+ render: (ot) => <Badge variant="secondary">{KIND_LABELS[ot.kind] ?? ot.kind}</Badge>,+ },+ {+ key: 'option_values',+ label: 'Values',+ default: true,+ render: (ot) => {+ const count = ot.option_values?.length ?? 0+ return (+ <span className="text-sm text-muted-foreground">+ {count === 1 ? '1 value' : `${count} values`}+ </span>+ )+ },+ },+ {+ key: 'filterable',+ label: 'Filterable',+ default: true,+ render: (ot) => <ActiveBadge active={ot.filterable ?? false} dashWhenInactive />,+ },+ {+ key: 'updated_at',+ label: 'Updated',+ sortable: true,+ render: (ot) => <RelativeTime iso={ot.updated_at} />,+ },+ {+ key: 'actions',+ label: '',+ default: true,+ className: 'w-12 text-right',+ // Same `data-stock-location-id` hook as the Name column — the route's+ // RowClickBridge picks this up and opens the edit Sheet.+ render: (ot) => (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ data-option-type-id={ot.id}+ aria-label={`Edit ${ot.name}`}+ >+ <PencilIcon data-option-type-id={ot.id} className="size-4" />+ </Button>+ ),+ },+ ],+})diff --git a/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rbindex e2d8e7da02..b9383545cd 100644--- a/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/option_types_controller.rb@@ -5,37 +5,6 @@ module Spreeclass OptionTypesController < ResourceControllerscoped_resource :products- # POST /api/v3/admin/option_types- def create- authorize!(:create, Spree::OptionType)-- result = Spree.option_type_create_service.call(- params: option_type_service_params- )-- if result.success?- @resource = result.value[:option_type]- render json: serialize_resource(@resource), status: :created- else- render_result_error(result)- end- end-- # PATCH /api/v3/admin/option_types/:id- def update- result = Spree.option_type_update_service.call(- option_type: @resource,- params: option_type_service_params- )-- if result.success?- @resource = result.value[:option_type]- render json: serialize_resource(@resource)- else- render_result_error(result)- end- end-protecteddef model_class@@ -50,13 +19,11 @@ module Spree[:option_values]end- private-- def option_type_service_params+ def permitted_paramsparams.permit(- :name, :presentation, :position, :filterable, :kind,+ :name, :label, :position, :filterable, :kind,option_values: [- :id, :name, :presentation, :position, :color_code, :image, :_destroy+ :id, :name, :label, :position, :color_code, :image])enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/option_type_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/option_type_serializer.rbindex cd1cb02618..bf236bc250 100644--- a/spree/api/app/serializers/spree/api/v3/admin/option_type_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/option_type_serializer.rb@@ -3,13 +3,14 @@ module Spreemodule V3module Adminclass OptionTypeSerializer < V3::OptionTypeSerializer- typelize metadata: 'Record<string, unknown>'+ typelize metadata: 'Record<string, unknown>', filterable: :boolean- attributes :metadata,+ attributes :metadata, :filterable,created_at: :iso8601, updated_at: :iso8601many :option_values,- resource: Spree.api.admin_option_value_serializer+ resource: Spree.api.admin_option_value_serializer,+ if: proc { expand?('option_values') }endendenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/option_types_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/option_types_controller_spec.rbindex 3a2523c0c7..e510b1f1cd 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/option_types_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/option_types_controller_spec.rb@@ -12,8 +12,8 @@ RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller dbefore { request.headers.merge!(headers) }describe 'GET #index' do- it 'returns option types with nested option values' do- get :index, as: :json+ it 'returns option types with nested option values when expanded' do+ get :index, params: { expand: 'option_values' }, as: :jsonexpect(response).to have_http_status(:ok)expect(json_response['data']).to be_an(Array)@@ -26,8 +26,8 @@ RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller denddescribe 'GET #show' do- it 'returns the option type with option values' do- get :show, params: { id: option_type.prefixed_id }, as: :json+ it 'returns the option type with option values when expanded' do+ get :show, params: { id: option_type.prefixed_id, expand: 'option_values' }, as: :jsonexpect(response).to have_http_status(:ok)expect(json_response['id']).to eq(option_type.prefixed_id)@@ -40,10 +40,11 @@ RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller dexpect {post :create, params: {name: 'material',- presentation: 'Material',+ label: 'Material',+ expand: 'option_values',option_values: [- { name: 'cotton', presentation: 'Cotton', position: 1 },- { name: 'silk', presentation: 'Silk', position: 2 }+ { name: 'cotton', label: 'Cotton', position: 1 },+ { name: 'silk', label: 'Silk', position: 2 }]}, as: :json}.to change(Spree::OptionType, :count).by(1)@@ -57,7 +58,7 @@ RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller dit 'creates an option type without option values' doexpect {- post :create, params: { name: 'size', presentation: 'Size' }, as: :json+ post :create, params: { name: 'size', label: 'Size' }, as: :json}.to change(Spree::OptionType, :count).by(1)expect(response).to have_http_status(:created)@@ -66,11 +67,30 @@ RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller dcontext 'with invalid params' doit 'returns validation errors' do- post :create, params: { name: '', presentation: '' }, as: :json+ post :create, params: { name: '', label: '' }, as: :jsonexpect(response).to have_http_status(:unprocessable_content)expect(json_response['error']['code']).to eq('validation_error')end++ it 'returns 422 (not 500) when a nested option_value is invalid' do+ post :create, params: {+ name: 'material',+ label: 'Material',+ option_values: [{ name: '', label: '' }]+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('validation_error')+ # Pin that this exercises the *nested* validation path: parent fields+ # are valid (`name`/`label` set), and the failure surfaces under the+ # autosave key for the child association — not on a top-level parent+ # attribute. Without this check the test could pass via the parent's+ # own `validates :presentation` if a future rename silently filtered+ # `label` from `permitted_params`.+ expect(json_response['error']['details'].keys).to include('option_values.name')+ expect(Spree::OptionType.where(name: 'material')).to be_empty+ endendend@@ -78,15 +98,16 @@ RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller dit 'updates option type and syncs option values' dopatch :update, params: {id: option_type.prefixed_id,- presentation: 'Updated Presentation',+ label: 'Updated Label',+ expand: 'option_values',option_values: [- { id: option_value_1.prefixed_id, name: option_value_1.name, presentation: 'Updated Value 1', position: 1 },- { name: 'new-value', presentation: 'New Value', position: 2 }+ { id: option_value_1.prefixed_id, name: option_value_1.name, label: 'Updated Value 1', position: 1 },+ { name: 'new-value', label: 'New Value', position: 2 }]}, as: :jsonexpect(response).to have_http_status(:ok)- expect(json_response['label']).to eq('Updated Presentation')+ expect(json_response['label']).to eq('Updated Label')expect(json_response['option_values'].length).to eq(2)# option_value_2 was not in the payload, so it should be deleted@@ -96,12 +117,33 @@ RSpec.describe Spree::Api::V3::Admin::OptionTypesController, type: :controller dit 'updates option type without touching option values' dopatch :update, params: {id: option_type.prefixed_id,- presentation: 'Just Presentation'+ label: 'Just Label'}, as: :jsonexpect(response).to have_http_status(:ok)expect(option_type.reload.option_values.count).to eq(2)end++ it 'returns 422 (not 500) when a nested option_value is invalid' do+ original_presentation = option_type.presentation++ patch :update, params: {+ id: option_type.prefixed_id,+ label: 'Updated',+ # `color_code` must be a valid hex; `not-a-hex` trips the format validator+ # so we exercise the nested-validation path without depending on which+ # presence rules normalize / backfill which fields.+ option_values: [{ id: option_value_1.prefixed_id, color_code: 'not-a-hex' }]+ }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('validation_error')+ # Pin that the failure comes from the nested record (autosave-style key)+ # rather than from a top-level parent attribute.+ expect(json_response['error']['details'].keys).to include('option_values.color_code')+ # Parent attribute change must roll back when option_values validation fails.+ expect(option_type.reload.presentation).to eq(original_presentation)+ endenddescribe 'DELETE #destroy' dodiff --git a/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rbindex 259ad15f6c..8ddea56abc 100644--- a/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/option_types_spec.rb@@ -28,7 +28,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-referparameter name: :expand, in: :query, type: :string, required: false,description: 'Comma-separated associations to expand (e.g., option_values). Use dot notation for nested expand (max 4 levels).'parameter name: :fields, in: :query, type: :string, required: false,- description: 'Comma-separated list of fields to include (e.g., name,presentation,position). id is always included.'+ description: 'Comma-separated list of fields to include (e.g., name,label,position). id is always included.'response '200', 'option types found' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }@@ -73,7 +73,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refertype: :object,properties: {name: { type: :string, example: 'color' },- presentation: { type: :string, example: 'Color' },+ label: { type: :string, example: 'Color' },position: { type: :integer, example: 1 },filterable: { type: :boolean, example: true },option_values: {@@ -82,18 +82,18 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refertype: :object,properties: {name: { type: :string, example: 'red' },- presentation: { type: :string, example: 'Red' },+ label: { type: :string, example: 'Red' },position: { type: :integer }}}}},- required: %w[name presentation]+ required: %w[name label]}response '201', 'option type created' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }- let(:body) { { name: 'material', presentation: 'Material' } }+ let(:body) { { name: 'material', label: 'Material' } }schema '$ref' => '#/components/schemas/OptionType'@@ -106,7 +106,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-referresponse '422', 'validation error' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }- let(:body) { { name: '', presentation: '' } }+ let(:body) { { name: '', label: '' } }schema '$ref' => '#/components/schemas/ErrorResponse'@@ -132,7 +132,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-referparameter name: :expand, in: :query, type: :string, required: false,description: 'Comma-separated associations to expand (e.g., option_values). Use dot notation for nested expand (max 4 levels).'parameter name: :fields, in: :query, type: :string, required: false,- description: 'Comma-separated list of fields to include (e.g., name,presentation,position). id is always included.'+ description: 'Comma-separated list of fields to include (e.g., name,label,position). id is always included.'response '200', 'option type found' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }@@ -174,7 +174,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-refertype: :object,properties: {name: { type: :string, example: 'color' },- presentation: { type: :string, example: 'Color' },+ label: { type: :string, example: 'Color' },position: { type: :integer, example: 1 },filterable: { type: :boolean, example: true },option_values: {@@ -184,7 +184,7 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-referproperties: {id: { type: :string, description: 'Existing option value ID to update' },name: { type: :string, example: 'red' },- presentation: { type: :string, example: 'Red' },+ label: { type: :string, example: 'Red' },position: { type: :integer }}}@@ -195,20 +195,20 @@ RSpec.describe 'Admin Option Types API', type: :request, swagger_doc: 'api-referresponse '200', 'option type updated' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }let(:id) { option_type.prefixed_id }- let(:body) { { presentation: 'Updated Presentation' } }+ let(:body) { { label: 'Updated Label' } }schema '$ref' => '#/components/schemas/OptionType'run_test! do |response|data = JSON.parse(response.body)- expect(data['label']).to eq('Updated Presentation')+ expect(data['label']).to eq('Updated Label')endendresponse '422', 'validation error' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }let(:id) { option_type.prefixed_id }- let(:body) { { presentation: '' } }+ let(:body) { { label: '' } }schema '$ref' => '#/components/schemas/ErrorResponse'diff --git a/spree/core/app/models/spree/option_type.rb b/spree/core/app/models/spree/option_type.rbindex b09e222317..7b6f4d73d7 100644--- a/spree/core/app/models/spree/option_type.rb+++ b/spree/core/app/models/spree/option_type.rb@@ -27,7 +27,14 @@ module Spree## Associationswith_options dependent: :destroy, inverse_of: :option_type do- has_many :option_values, -> { order(:position) }+ # `autosave: true` makes the parent's `save`/`update`:+ # - persist any built / mutated children in one transaction,+ # - collect their validation errors onto `self.errors`,+ # - destroy any child marked via `mark_for_destruction`.+ # The custom `option_values=` writer below leans on this so the v3+ # ResourceController gets `save returning false` + structured errors+ # rather than raised exceptions.+ has_many :option_values, -> { order(:position) }, autosave: truehas_many :product_option_typesendhas_many :products, through: :product_option_types@@ -88,6 +95,46 @@ module Spreecolor_swatch?end+ # Syncs option values from an array of hashes by mutating the in-memory+ # `option_values` association — built/assigned children get persisted by+ # `autosave: true` when the parent saves, and absent IDs get destroyed+ # via `mark_for_destruction`. The single transaction is owned by the+ # parent's `save`, so validation failures surface as `errors` and the+ # whole thing rolls back together.+ #+ # Falls back to ActiveRecord's collection writer when given OptionValue+ # records (e.g. from `accepts_nested_attributes_for` used by the legacy admin).+ #+ # @param option_values_params [Array<Hash>] array of option value attribute hashes+ # @return [void]+ def option_values=(option_values_params)+ return super if option_values_params.blank? || option_values_params.first.is_a?(Spree::OptionValue)++ # Load the association into the in-memory collection so subsequent+ # `option_values.build` / `mark_for_destruction` mutations stay on the+ # same instances `autosave` will traverse at parent-save time.+ existing_by_id = option_values.to_a.index_by(&:id)+ retained_ids = []++ option_values_params.each do |value_data|+ data = value_data.to_h.with_indifferent_access+ value_id = data.delete(:id)++ record = if value_id.present?+ existing_by_id[Spree::PrefixedId.decode_prefixed_id(value_id) || value_id] ||+ raise(ActiveRecord::RecordNotFound.new("Couldn't find Spree::OptionValue with param=#{value_id}", 'Spree::OptionValue'))+ else+ option_values.build+ end+ record.assign_attributes(data)+ retained_ids << record.id if record.persisted?+ end++ existing_by_id.each_value do |existing|+ existing.mark_for_destruction unless retained_ids.include?(existing.id)+ end+ end+privatedef touch_all_productsdiff --git a/spree/core/app/services/spree/option_types/create.rb b/spree/core/app/services/spree/option_types/create.rbdeleted file mode 100644index 3d6f16a283..0000000000--- a/spree/core/app/services/spree/option_types/create.rb+++ /dev/null@@ -1,51 +0,0 @@-module Spree- module OptionTypes- class Create- prepend Spree::ServiceModule::Base-- def call(params:)- ApplicationRecord.transaction do- run :create_option_type- run :sync_option_values- end- end-- private-- def create_option_type(params:)- params = params.to_h.with_indifferent_access- option_values_params = params.delete(:option_values)-- option_type = Spree::OptionType.new(params)-- if option_type.save- success(option_type: option_type, option_values_params: option_values_params)- else- failure(option_type, option_type.errors)- end- end-- def sync_option_values(option_type:, option_values_params:)- return success(option_type: option_type) if option_values_params.blank?-- now = Time.current-- records = option_values_params.each_with_index.map do |value_data, index|- value_data = value_data.to_h.with_indifferent_access- {- option_type_id: option_type.id,- name: value_data[:name],- presentation: value_data[:presentation],- position: value_data[:position] || (index + 1),- created_at: now,- updated_at: now- }- end-- Spree::OptionValue.insert_all!(records)-- success(option_type: option_type.reload)- end- end- end-enddiff --git a/spree/core/app/services/spree/option_types/update.rb b/spree/core/app/services/spree/option_types/update.rbdeleted file mode 100644index d681dc079b..0000000000--- a/spree/core/app/services/spree/option_types/update.rb+++ /dev/null@@ -1,62 +0,0 @@-module Spree- module OptionTypes- class Update- prepend Spree::ServiceModule::Base-- def call(option_type:, params:)- ApplicationRecord.transaction do- run :update_option_type- run :sync_option_values- end- end-- private-- def update_option_type(option_type:, params:)- params = params.to_h.with_indifferent_access- option_values_params = params.delete(:option_values)- sync_values = !option_values_params.nil?-- if option_type.update(params)- success(option_type: option_type, option_values_params: option_values_params, sync_values: sync_values)- else- failure(option_type, option_type.errors)- end- end-- def sync_option_values(option_type:, option_values_params:, sync_values:)- return success(option_type: option_type) unless sync_values-- now = Time.current- names = []-- records = (option_values_params || []).each_with_index.map do |value_data, index|- value_data = value_data.to_h.with_indifferent_access- names << value_data[:name]- {- option_type_id: option_type.id,- name: value_data[:name],- presentation: value_data[:presentation],- position: value_data[:position] || (index + 1),- created_at: now,- updated_at: now- }- end-- # Remove option values not in the payload- option_type.option_values.where.not(name: names).destroy_all-- if records.any?- # Deduplicate by name (last wins) to avoid PG's "ON CONFLICT cannot affect row a second time"- records = records.reverse.uniq { |r| r[:name] }.reverse-- opts = { update_only: [:presentation, :position] }- opts[:unique_by] = :index_spree_option_values_on_option_type_id_and_name unless ActiveRecord::Base.connection.adapter_name == 'Mysql2'- Spree::OptionValue.upsert_all(records, **opts)- end-- success(option_type: option_type.reload)- end- end- end-enddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 2653102431..0639a29af6 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -41,10 +41,6 @@ module Spreegift_card_remove_service: 'Spree::GiftCards::Remove',gift_card_redeem_service: 'Spree::GiftCards::Redeem',- # option types- option_type_create_service: 'Spree::OptionTypes::Create',- option_type_update_service: 'Spree::OptionTypes::Update',-# orderorder_approve_service: 'Spree::Orders::Approve',order_cancel_service: 'Spree::Orders::Cancel',diff --git a/spree/core/spec/models/spree/option_type_spec.rb b/spree/core/spec/models/spree/option_type_spec.rbindex 1e223db636..65ea373b31 100644--- a/spree/core/spec/models/spree/option_type_spec.rb+++ b/spree/core/spec/models/spree/option_type_spec.rb@@ -179,4 +179,83 @@ describe Spree::OptionType, type: :model doSpree::OptionType.color.id == option_type.idendend++ describe '#option_values=' do+ context 'with an array of OptionValue records' do+ let(:option_type) { create(:option_type) }+ let(:option_value) { build(:option_value, option_type: option_type) }++ it 'delegates to the AR collection writer' do+ option_type.option_values = [option_value]+ expect(option_type.option_values).to eq([option_value])+ end+ end++ context 'on a new option type' do+ it 'persists option values when the parent is saved' do+ option_type = build(:option_type)+ option_type.option_values = [{ name: 'red', presentation: 'Red' }]++ # Children mutate the in-memory association and ride the parent's+ # save via `autosave: true` — no DB hits until `save!`.+ expect(option_type.option_values.first).not_to be_persisted+ option_type.save!+ expect(option_type.option_values.pluck(:name)).to eq(['red'])+ end+ end++ context 'on a persisted option type' do+ let!(:option_type) { create(:option_type) }+ let!(:red) { create(:option_value, option_type: option_type, name: 'red', presentation: 'Red', position: 1) }+ let!(:blue) { create(:option_value, option_type: option_type, name: 'blue', presentation: 'Blue', position: 2) }++ it 'updates existing values matched by id on save' do+ option_type.option_values = [{ id: red.prefixed_id, presentation: 'Bright Red' }]+ option_type.save!+ expect(red.reload.presentation).to eq('Bright Red')+ end++ it 'renames a value when name is sent with its id (id-based matching)' do+ option_type.option_values = [{ id: red.prefixed_id, name: 'crimson', presentation: 'Crimson' }]+ option_type.save!+ expect(red.reload.name).to eq('crimson')+ end++ it 'creates new values when id is absent' do+ option_type.option_values = [+ { id: red.prefixed_id, name: 'red', presentation: 'Red' },+ { id: blue.prefixed_id, name: 'blue', presentation: 'Blue' },+ { name: 'green', presentation: 'Green' }+ ]+ option_type.save!+ expect(option_type.reload.option_values.pluck(:name)).to match_array(%w[red blue green])+ end++ it 'destroys values not referenced in the payload' do+ option_type.option_values = [{ id: red.prefixed_id, name: 'red', presentation: 'Red' }]+ option_type.save!+ expect(option_type.reload.option_values.pluck(:name)).to eq(['red'])+ expect { blue.reload }.to raise_error(ActiveRecord::RecordNotFound)+ end++ it 'destroys all values when given an empty array' do+ option_type.option_values = []+ expect(option_type.reload.option_values).to be_empty+ end++ it 'leaves values untouched when the writer is not called' do+ option_type.update!(presentation: 'Updated')+ expect(option_type.reload.option_values.pluck(:name)).to match_array(%w[red blue])+ end++ it 'returns false from save and surfaces validation errors when option values are invalid' do+ option_type.option_values = [{ name: '', presentation: '' }]+ expect(option_type.save).to be false+ # Rails autosave surfaces nested errors as `option_values.<attr>`.+ expect(option_type.errors.attribute_names.map(&:to_s)).to include('option_values.name')+ # Existing rows must not be touched when the parent save fails.+ expect(option_type.reload.option_values.pluck(:name)).to match_array(%w[red blue])+ end+ end+ endenddiff --git a/spree/core/spec/services/spree/option_types/create_spec.rb b/spree/core/spec/services/spree/option_types/create_spec.rbdeleted file mode 100644index c6b0cba847..0000000000--- a/spree/core/spec/services/spree/option_types/create_spec.rb+++ /dev/null@@ -1,96 +0,0 @@-require 'spec_helper'--RSpec.describe Spree::OptionTypes::Create do- subject(:result) { described_class.call(params: params) }-- describe 'basic creation' do- let(:params) { { name: 'color', presentation: 'Color' } }-- it 'creates an option type' do- expect(result).to be_success- expect(result.value[:option_type].name).to eq('color')- expect(result.value[:option_type].presentation).to eq('Color')- end- end-- describe 'validation error - missing presentation' do- let(:params) { { name: 'bad' } }-- it 'returns failure' do- expect(result).not_to be_success- end- end-- describe 'validation error - blank name and presentation' do- let(:params) { { name: '', presentation: '' } }-- it 'returns failure' do- expect(result).not_to be_success- end- end-- describe 'duplicate name' do- before { create(:option_type, name: 'size') }- let(:params) { { name: 'size', presentation: 'Size' } }-- it 'returns failure' do- expect(result).not_to be_success- end- end-- describe 'with nested option values' do- let(:params) do- {- name: 'material',- presentation: 'Material',- option_values: [- { name: 'cotton', presentation: 'Cotton' },- { name: 'silk', presentation: 'Silk' },- { name: 'wool', presentation: 'Wool' }- ]- }- end-- it 'creates option values via insert_all' do- expect(result).to be_success- ot = result.value[:option_type]- expect(ot.option_values.count).to eq(3)- expect(ot.option_values.pluck(:name)).to match_array(%w[cotton silk wool])- end-- it 'assigns positions' do- ot = result.value[:option_type]- positions = ot.option_values.order(:position).pluck(:position)- expect(positions).to eq([1, 2, 3])- end- end-- describe 'with explicit positions' do- let(:params) do- {- name: 'size',- presentation: 'Size',- option_values: [- { name: 'large', presentation: 'Large', position: 3 },- { name: 'small', presentation: 'Small', position: 1 }- ]- }- end-- it 'uses provided positions' do- expect(result).to be_success- ot = result.value[:option_type]- expect(ot.option_values.find_by(name: 'small').position).to eq(1)- expect(ot.option_values.find_by(name: 'large').position).to eq(3)- end- end-- describe 'without option values' do- let(:params) { { name: 'weight', presentation: 'Weight' } }-- it 'creates option type with no values' do- expect(result).to be_success- expect(result.value[:option_type].option_values).to be_empty- end- end-enddiff --git a/spree/core/spec/services/spree/option_types/update_spec.rb b/spree/core/spec/services/spree/option_types/update_spec.rbdeleted file mode 100644index 7f04ff3a87..0000000000--- a/spree/core/spec/services/spree/option_types/update_spec.rb+++ /dev/null@@ -1,106 +0,0 @@-require 'spec_helper'--RSpec.describe Spree::OptionTypes::Update do- subject(:result) { described_class.call(option_type: option_type, params: params) }-- let!(:option_type) { create(:option_type) }- let!(:ov1) { create(:option_value, option_type: option_type, name: 'red', presentation: 'Red', position: 1) }- let!(:ov2) { create(:option_value, option_type: option_type, name: 'blue', presentation: 'Blue', position: 2) }-- describe 'basic update' do- let(:params) { { presentation: 'Updated' } }-- it 'updates option type attributes' do- expect(result).to be_success- expect(result.value[:option_type].presentation).to eq('Updated')- end-- it 'does not touch option values when key is absent' do- expect(result).to be_success- expect(option_type.option_values.count).to eq(2)- end- end-- describe 'validation error' do- let(:params) { { presentation: '' } }-- it 'returns failure' do- expect(result).not_to be_success- end- end-- describe 'sync option values - update existing, add new, remove missing' do- let(:params) do- {- option_values: [- { name: 'red', presentation: 'Bright Red' },- { name: 'green', presentation: 'Green' }- ]- }- end-- it 'updates red, creates green, removes blue' do- expect(result).to be_success- ot = result.value[:option_type]-- expect(ot.option_values.count).to eq(2)- expect(ot.option_values.find_by(name: 'red').presentation).to eq('Bright Red')- expect(ot.option_values.find_by(name: 'green')).to be_present- expect(ot.option_values.find_by(name: 'blue')).to be_nil- end- end-- describe 'empty option_values array removes all' do- let(:params) { { option_values: [] } }-- it 'removes all option values' do- expect(result).to be_success- expect(option_type.reload.option_values.count).to eq(0)- end- end-- describe 'option_values key absent does not sync' do- let(:params) { { presentation: 'New Pres' } }-- it 'keeps existing option values' do- expect(result).to be_success- expect(option_type.reload.option_values.count).to eq(2)- end- end-- describe 'upsert updates position' do- let(:params) do- {- option_values: [- { name: 'red', presentation: 'Red', position: 5 },- { name: 'blue', presentation: 'Blue', position: 10 }- ]- }- end-- it 'updates positions' do- expect(result).to be_success- ot = result.value[:option_type]- expect(ot.option_values.find_by(name: 'red').position).to eq(5)- expect(ot.option_values.find_by(name: 'blue').position).to eq(10)- end- end-- describe 'duplicate name in same option type' do- let(:params) do- {- option_values: [- { name: 'red', presentation: 'Red' },- { name: 'red', presentation: 'Also Red' }- ]- }- end-- it 'handles duplicate gracefully via upsert (last wins)' do- expect(result).to be_success- ot = result.value[:option_type]- # upsert_all with duplicate keys: only one record persists- expect(ot.option_values.where(name: 'red').count).to eq(1)- end- end-end