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
Manage product type schema from the dashboard
Damian Legawiec7d50266d35eb
diff --git a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsxindex fd29a4a3e7..860d9f87aa 100644--- a/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx+++ b/packages/dashboard/src/components/spree/custom-fields/custom-fields-inline.tsx@@ -177,6 +177,12 @@ interface FormBackedProviderProps<T extends CustomFieldsFormShape> {resourceType: string/** Plural, human-readable resource name for empty-state copy. */resourceLabel?: string+ /**+ * Restricts and orders the rendered definitions — the product type's schema.+ * Ids not in this list are hidden; the order given is the order shown. Omit+ * to render every definition for the resource type.+ */+ definitionIds?: string[]children: ReactNode}@@ -184,6 +190,7 @@ export function FormBackedCustomFieldsProvider<T extends CustomFieldsFormShape>(form,resourceType,resourceLabel,+ definitionIds,children,}: FormBackedProviderProps<T>) {// The provider only ever touches the `custom_fields` field; narrow to the@@ -194,7 +201,14 @@ export function FormBackedCustomFieldsProvider<T extends CustomFieldsFormShape>(// Memoize against the fetched array's identity. Without this the `?? []`// fallback returns a fresh array on every render, which propagates into the// context value and triggers every consumer to re-render unnecessarily.- const definitions = useMemo(() => definitionsResponse?.data ?? [], [definitionsResponse?.data])+ const allDefinitions = useMemo(() => definitionsResponse?.data ?? [], [definitionsResponse?.data])+ // When a schema is supplied (the product's type), it decides both which+ // definitions appear and in what order.+ const definitions = useMemo(() => {+ if (!definitionIds) return allDefinitions++ return definitionIds.flatMap((id) => allDefinitions.filter((def) => def.id === id))+ }, [allDefinitions, definitionIds])const watchedCustomFields = cfForm.watch('custom_fields') ?? []const values = useMemo<Record<string, unknown>>(() => {diff --git a/packages/dashboard/src/hooks/use-product-types.ts b/packages/dashboard/src/hooks/use-product-types.tsindex 7a5725fcfd..60a8010afe 100644--- a/packages/dashboard/src/hooks/use-product-types.ts+++ b/packages/dashboard/src/hooks/use-product-types.ts@@ -51,6 +51,34 @@ export function useUpdateProductType(id: string) {})}+/**+ * Product custom field definitions — the pool a product type picks from.+ */+export function useProductCustomFieldDefinitions() {+ return useQuery({+ queryKey: useResourceKey('custom-field-definitions', { resource_type: 'Spree::Product' }),+ queryFn: () =>+ adminClient.customFieldDefinitions.list({+ limit: 100,+ filter: { resource_type_eq: 'Spree::Product' },+ }),+ staleTime: 1000 * 60 * 5,+ })+}++/**+ * Backfills a type's option types and categories onto products that already+ * carry it. Additive — the only path from a type edit to existing products.+ */+export function useApplyProductTypeToProducts(id: string) {+ return useResourceMutation<{ products_count: number }, Error, void>({+ mutationFn: () => adminClient.productTypes.applyToProducts(id),+ invalidate: [['product-types'], ['products']],+ successMessage: i18n.t('admin.product_types.messages.applied_to_products'),+ errorMessage: i18n.t('admin.errors.failed_to_update'),+ })+}+export function useDeleteProductType() {const queryClient = useQueryClient()const buildKey = useResourceKeyBuilder()diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 0b06f7aa65..541a438c22 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1007,6 +1007,15 @@}},"product_type": {+ "categories": {+ "help": "تُضاف إلى المنتجات المُنشأة بهذا النوع.",+ "label": "الفئات"+ },+ "custom_field_definitions": {+ "help": "تظهر بهذا الترتيب في نموذج كل منتج من هذا النوع. يجب ملء الحقول المطلوبة قبل تفعيل المنتج.",+ "label": "الحقول المخصصة",+ "required": "مطلوب"+ },"fulfillment_types": {"help": "كيف يمكن تسليم منتجات هذا النوع — شحن، استلام من المتجر، نقطة استلام، أو رقمي.","label": "طرق التنفيذ"@@ -1014,6 +1023,10 @@"name": {"placeholder": "مثال: تي شيرت"},+ "option_types": {+ "help": "تُضاف إلى المنتجات المُنشأة بهذا النوع. يمكن للمنتجات إضافة المزيد لاحقًا.",+ "label": "أنواع الخيارات"+ },"products_count": {"label": "المنتجات"}@@ -2556,6 +2569,18 @@"product_types": {"add_cta": "إضافة نوع منتج","add_sheet_title": "نوع منتج جديد",+ "affects_new_only": {+ "description": "تعديل أنواع الخيارات والفئات يؤثر على المنتجات التي تُنشأ من الآن فصاعدًا. المنتجات التي تحمل هذا النوع تحتفظ بما لديها. الحقول المخصصة أدناه تظهر دائمًا في كل منتج من هذا النوع.",+ "title": "التغييرات تنطبق على المنتجات الجديدة"+ },+ "apply_to_products": {+ "confirm_label": "تطبيق",+ "cta_one": "تطبيق على {{count}} منتج حالي",+ "cta_other": "تطبيق على {{count}} منتج حالي",+ "message_one": "سيضيف هذا أنواع الخيارات والفئات الناقصة إلى {{count}} منتج. لن يُحذف شيء.",+ "message_other": "سيضيف هذا أنواع الخيارات والفئات الناقصة إلى {{count}} منتج. لن يُحذف شيء.",+ "title": "تطبيق على المنتجات الحالية"+ },"create_description": "جمّع المنتجات وحدد طرق تسليمها.","create_label": "إنشاء نوع منتج","delete_confirm": {@@ -2566,10 +2591,13 @@"edit_sheet_title": "تعديل نوع المنتج","empty": "لا توجد أنواع منتجات بعد","messages": {+ "applied_to_products": "جارٍ التطبيق على المنتجات الحالية","created": "تم إنشاء نوع المنتج","deleted": "تم حذف نوع المنتج","updated": "تم تحديث نوع المنتج"},+ "no_categories": "لا توجد فئات بعد",+ "no_option_types": "لا توجد أنواع خيارات بعد","search_placeholder": "ابحث في أنواع المنتجات"},"products": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex fd9099095b..d438cfc95b 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1007,6 +1007,15 @@}},"product_type": {+ "categories": {+ "help": "Werden Produkten hinzugefügt, die mit diesem Typ erstellt werden.",+ "label": "Kategorien"+ },+ "custom_field_definitions": {+ "help": "Erscheinen in dieser Reihenfolge im Produktformular aller Produkte dieses Typs. Pflichtfelder müssen ausgefüllt sein, bevor ein Produkt aktiviert werden kann.",+ "label": "Benutzerdefinierte Felder",+ "required": "Pflichtfeld"+ },"fulfillment_types": {"help": "Wie Produkte dieses Typs geliefert werden können — Versand, Abholung im Geschäft, Abholstation oder digital.","label": "Fulfillment-Arten"@@ -1014,6 +1023,10 @@"name": {"placeholder": "z. B. T-Shirt"},+ "option_types": {+ "help": "Werden Produkten hinzugefügt, die mit diesem Typ erstellt werden. Produkte können später weitere hinzufügen.",+ "label": "Optionstypen"+ },"products_count": {"label": "Produkte"}@@ -2556,6 +2569,18 @@"product_types": {"add_cta": "Produkttyp hinzufügen","add_sheet_title": "Neuer Produkttyp",+ "affects_new_only": {+ "description": "Das Bearbeiten von Optionstypen und Kategorien wirkt sich auf ab jetzt erstellte Produkte aus. Produkte mit diesem Typ behalten, was sie haben. Die benutzerdefinierten Felder unten erscheinen immer bei allen Produkten dieses Typs.",+ "title": "Änderungen gelten für neue Produkte"+ },+ "apply_to_products": {+ "confirm_label": "Anwenden",+ "cta_one": "Auf {{count}} bestehendes Produkt anwenden",+ "cta_other": "Auf {{count}} bestehende Produkte anwenden",+ "message_one": "Dies fügt {{count}} Produkt die fehlenden Optionstypen und Kategorien dieses Typs hinzu. Es wird nichts entfernt.",+ "message_other": "Dies fügt {{count}} Produkten die fehlenden Optionstypen und Kategorien dieses Typs hinzu. Es wird nichts entfernt.",+ "title": "Auf bestehende Produkte anwenden"+ },"create_description": "Produkte gruppieren und festlegen, wie sie geliefert werden können.","create_label": "Produkttyp erstellen","delete_confirm": {@@ -2566,10 +2591,13 @@"edit_sheet_title": "Produkttyp bearbeiten","empty": "Noch keine Produkttypen","messages": {+ "applied_to_products": "Wird auf bestehende Produkte angewendet","created": "Produkttyp erstellt","deleted": "Produkttyp gelöscht","updated": "Produkttyp aktualisiert"},+ "no_categories": "Noch keine Kategorien",+ "no_option_types": "Noch keine Optionstypen","search_placeholder": "Produkttypen durchsuchen"},"products": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 9fccf9f1a3..4b905eb5b3 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1007,6 +1007,15 @@}},"product_type": {+ "categories": {+ "help": "Added to products created with this type.",+ "label": "Categories"+ },+ "custom_field_definitions": {+ "help": "Shown on the product form for every product of this type, in this order. Required fields must be filled before a product can be activated.",+ "label": "Custom fields",+ "required": "Required"+ },"fulfillment_types": {"help": "How products of this type can be delivered — shipping, store pickup, pickup point, or digital.","label": "Fulfillment types"@@ -1014,6 +1023,10 @@"name": {"placeholder": "e.g. T-Shirt"},+ "option_types": {+ "help": "Added to products created with this type. Products can add more later.",+ "label": "Option types"+ },"products_count": {"label": "Products"}@@ -2556,6 +2569,18 @@"product_types": {"add_cta": "Add product type","add_sheet_title": "New product type",+ "affects_new_only": {+ "description": "Editing option types and categories shapes products created from now on. Products that already have this type keep what they have. The custom fields below always show on every product of this type.",+ "title": "Changes apply to new products"+ },+ "apply_to_products": {+ "confirm_label": "Apply",+ "cta_one": "Apply to {{count}} existing product",+ "cta_other": "Apply to {{count}} existing products",+ "message_one": "This adds this type’s missing option types and categories to {{count}} product. Nothing is removed.",+ "message_other": "This adds this type’s missing option types and categories to {{count}} products. Nothing is removed.",+ "title": "Apply to existing products"+ },"create_description": "Group products and define how they can be delivered.","create_label": "Create product type","delete_confirm": {@@ -2566,10 +2591,13 @@"edit_sheet_title": "Edit product type","empty": "No product types yet","messages": {+ "applied_to_products": "Applying to existing products","created": "Product type created","deleted": "Product type deleted","updated": "Product type updated"},+ "no_categories": "No categories yet",+ "no_option_types": "No option types yet","search_placeholder": "Search product types"},"products": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 1c9d84c2f4..c887e52469 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1007,6 +1007,15 @@}},"product_type": {+ "categories": {+ "help": "Ajoutées aux produits créés avec ce type.",+ "label": "Catégories"+ },+ "custom_field_definitions": {+ "help": "Affichés dans cet ordre sur le formulaire de tous les produits de ce type. Les champs obligatoires doivent être remplis avant d’activer un produit.",+ "label": "Champs personnalisés",+ "required": "Obligatoire"+ },"fulfillment_types": {"help": "Comment les produits de ce type peuvent être livrés — expédition, retrait en magasin, point relais ou numérique.","label": "Modes d'expédition"@@ -1014,6 +1023,10 @@"name": {"placeholder": "p. ex. T-Shirt"},+ "option_types": {+ "help": "Ajoutés aux produits créés avec ce type. Les produits peuvent en ajouter d’autres ensuite.",+ "label": "Types d’option"+ },"products_count": {"label": "Produits"}@@ -2556,6 +2569,18 @@"product_types": {"add_cta": "Ajouter un type de produit","add_sheet_title": "Nouveau type de produit",+ "affects_new_only": {+ "description": "Modifier les types d’option et les catégories affecte les produits créés à partir de maintenant. Les produits ayant déjà ce type conservent ce qu’ils ont. Les champs personnalisés ci-dessous apparaissent toujours sur tous les produits de ce type.",+ "title": "Les modifications s’appliquent aux nouveaux produits"+ },+ "apply_to_products": {+ "confirm_label": "Appliquer",+ "cta_one": "Appliquer à {{count}} produit existant",+ "cta_other": "Appliquer à {{count}} produits existants",+ "message_one": "Cela ajoute les types d’option et catégories manquants de ce type à {{count}} produit. Rien n’est supprimé.",+ "message_other": "Cela ajoute les types d’option et catégories manquants de ce type à {{count}} produits. Rien n’est supprimé.",+ "title": "Appliquer aux produits existants"+ },"create_description": "Regroupez les produits et définissez leurs modes de livraison.","create_label": "Créer le type de produit","delete_confirm": {@@ -2566,10 +2591,13 @@"edit_sheet_title": "Modifier le type de produit","empty": "Aucun type de produit","messages": {+ "applied_to_products": "Application aux produits existants","created": "Type de produit créé","deleted": "Type de produit supprimé","updated": "Type de produit mis à jour"},+ "no_categories": "Aucune catégorie",+ "no_option_types": "Aucun type d’option","search_placeholder": "Rechercher des types de produit"},"products": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 574f05a4ee..cdc2badef9 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1015,6 +1015,15 @@}},"product_type": {+ "categories": {+ "help": "Dodawane do produktów tworzonych z tym typem.",+ "label": "Kategorie"+ },+ "custom_field_definitions": {+ "help": "Widoczne w tej kolejności w formularzu każdego produktu tego typu. Pola wymagane trzeba wypełnić przed aktywacją produktu.",+ "label": "Pola niestandardowe",+ "required": "Wymagane"+ },"fulfillment_types": {"help": "Jak produkty tego typu mogą być dostarczane — wysyłka, odbiór w sklepie, punkt odbioru lub cyfrowo.","label": "Sposoby realizacji"@@ -1022,6 +1031,10 @@"name": {"placeholder": "np. T-Shirt"},+ "option_types": {+ "help": "Dodawane do produktów tworzonych z tym typem. Produkty mogą później dodać kolejne.",+ "label": "Typy opcji"+ },"products_count": {"label": "Produkty"}@@ -2588,6 +2601,22 @@"product_types": {"add_cta": "Dodaj typ produktu","add_sheet_title": "Nowy typ produktu",+ "affects_new_only": {+ "description": "Edycja typów opcji i kategorii wpływa na produkty tworzone od teraz. Produkty, które już mają ten typ, zachowują to, co mają. Pola niestandardowe poniżej zawsze pojawiają się przy każdym produkcie tego typu.",+ "title": "Zmiany dotyczą nowych produktów"+ },+ "apply_to_products": {+ "confirm_label": "Zastosuj",+ "cta_few": "Zastosuj do {{count}} istniejących produktów",+ "cta_many": "Zastosuj do {{count}} istniejących produktów",+ "cta_one": "Zastosuj do {{count}} istniejącego produktu",+ "cta_other": "Zastosuj do {{count}} istniejącego produktu",+ "message_few": "To doda brakujące typy opcji i kategorie tego typu do {{count}} produktów. Nic nie zostanie usunięte.",+ "message_many": "To doda brakujące typy opcji i kategorie tego typu do {{count}} produktów. Nic nie zostanie usunięte.",+ "message_one": "To doda brakujące typy opcji i kategorie tego typu do {{count}} produktu. Nic nie zostanie usunięte.",+ "message_other": "To doda brakujące typy opcji i kategorie tego typu do {{count}} produktu. Nic nie zostanie usunięte.",+ "title": "Zastosuj do istniejących produktów"+ },"create_description": "Grupuj produkty i określ, jak mogą być dostarczane.","create_label": "Utwórz typ produktu","delete_confirm": {@@ -2598,10 +2627,13 @@"edit_sheet_title": "Edytuj typ produktu","empty": "Brak typów produktów","messages": {+ "applied_to_products": "Stosowanie do istniejących produktów","created": "Utworzono typ produktu","deleted": "Usunięto typ produktu","updated": "Zaktualizowano typ produktu"},+ "no_categories": "Brak kategorii",+ "no_option_types": "Brak typów opcji","search_placeholder": "Szukaj typów produktów"},"products": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex bb82ed114f..63faede2bf 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1007,6 +1007,15 @@}},"product_type": {+ "categories": {+ "help": "添加到使用此类型创建的商品。",+ "label": "分类"+ },+ "custom_field_definitions": {+ "help": "按此顺序显示在此类型每个商品的表单上。必填字段需在商品激活前填写。",+ "label": "自定义字段",+ "required": "必填"+ },"fulfillment_types": {"help": "此类型商品的交付方式 — 配送、到店自提、自提点或数字交付。","label": "履约方式"@@ -1014,6 +1023,10 @@"name": {"placeholder": "例如:T恤"},+ "option_types": {+ "help": "添加到使用此类型创建的商品。商品之后可以再添加。",+ "label": "选项类型"+ },"products_count": {"label": "商品数"}@@ -2556,6 +2569,18 @@"product_types": {"add_cta": "添加商品类型","add_sheet_title": "新建商品类型",+ "affects_new_only": {+ "description": "编辑选项类型和分类只影响今后创建的商品。已使用此类型的商品保持不变。下方的自定义字段始终显示在此类型的每个商品上。",+ "title": "更改仅影响新商品"+ },+ "apply_to_products": {+ "confirm_label": "应用",+ "cta_one": "应用到 {{count}} 个现有商品",+ "cta_other": "应用到 {{count}} 个现有商品",+ "message_one": "这将为 {{count}} 个商品添加此类型缺失的选项类型和分类。不会删除任何内容。",+ "message_other": "这将为 {{count}} 个商品添加此类型缺失的选项类型和分类。不会删除任何内容。",+ "title": "应用到现有商品"+ },"create_description": "将商品分组并定义其交付方式。","create_label": "创建商品类型","delete_confirm": {@@ -2566,10 +2591,13 @@"edit_sheet_title": "编辑商品类型","empty": "暂无商品类型","messages": {+ "applied_to_products": "正在应用到现有商品","created": "商品类型已创建","deleted": "商品类型已删除","updated": "商品类型已更新"},+ "no_categories": "暂无分类",+ "no_option_types": "暂无选项类型","search_placeholder": "搜索商品类型"},"products": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsxindex 6cee9fa92b..039b55b869 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -43,6 +43,7 @@ import { PublishingCard } from '../../../../components/spree/products/publishingimport { ResourceTranslationsCard } from '../../../../components/spree/translations/resource-translations-card'import { useDeleteProduct, useProduct, useUpdateProduct } from '../../../../hooks/use-product'import { useProductMedia } from '../../../../hooks/use-product-media'+import { useProductType } from '../../../../hooks/use-product-types'import { spreeJsonLinkResolver } from '../../../../lib/json-link-resolver'import {type ProductFormValues,@@ -276,6 +277,14 @@ function ProductForm({ product }: { product: Product }) {},})+ // The product type decides which custom fields the form shows and in which+ // order. Read live — editing a type updates every product form of that type.+ const selectedProductTypeId = form.watch('product_type_id')+ const { data: productType } = useProductType(selectedProductTypeId ?? undefined)+ const typeCustomFieldDefinitionIds = productType?.custom_field_definitions?.map(+ (definition) => definition.id,+ )+// Variants the MediaCard can assign uploaded images to. Only server-persisted// variants have an `id` that can ride media[].variant_ids on the PATCH, so we// start from `product.variants`. But the merchant may have queued one of those@@ -442,7 +451,11 @@ function ProductForm({ product }: { product: Product }) {<MediaCard productId={productId} variants={assignableVariants} form={form} /><PricesCard form={form} productName={product.name} /><InventoryCard form={form} storeId={storeId} />- <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Product">+ <FormBackedCustomFieldsProvider+ form={form}+ resourceType="Spree::Product"+ definitionIds={typeCustomFieldDefinitionIds}+ ><CustomFieldsInlineCard /></FormBackedCustomFieldsProvider><ResourceTranslationsCard resourceType="product" resourceId={productId} />diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsxindex ca146fa9da..64dd180985 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx@@ -1,5 +1,21 @@+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 { ProductType } from '@spree/admin-sdk'+import type { ProductType, ProductTypeUpdateParams } from '@spree/admin-sdk'import {adminClient,Can,@@ -12,6 +28,7 @@ import {import {Button,Checkbox,+ cn,Field,FieldError,FieldGroup,@@ -28,15 +45,19 @@ import {useRowClickBridge,} from '@spree/dashboard-ui'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 { GripVerticalIcon, PlusIcon, XIcon } from 'lucide-react'+import { type CSSProperties, useEffect } from 'react'+import { Controller, type UseFormReturn, useFieldArray, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'+import { useCategories } from '../../../../hooks/use-categories'import { useFulfillmentProviders } from '../../../../hooks/use-delivery-methods'+import { useOptionTypes } from '../../../../hooks/use-option-types'import {+ useApplyProductTypeToProducts,useCreateProductType,useDeleteProductType,+ useProductCustomFieldDefinitions,useProductType,useUpdateProductType,} from '../../../../hooks/use-product-types'@@ -46,6 +67,14 @@ import '../../../../tables/product-types'const productTypeFormSchema = z.object({name: z.string().min(1),fulfillment_types: z.array(z.string()).min(1),+ option_type_ids: z.array(z.string()),+ category_ids: z.array(z.string()),+ custom_field_definitions: z.array(+ z.object({+ id: z.string(),+ required: z.boolean(),+ }),+ ),})type ProductTypeFormValues = z.infer<typeof productTypeFormSchema>@@ -53,6 +82,20 @@ type ProductTypeFormValues = z.infer<typeof productTypeFormSchema>const PRODUCT_TYPE_DEFAULTS: ProductTypeFormValues = {name: '',fulfillment_types: ['shipping'],+ option_type_ids: [],+ category_ids: [],+ custom_field_definitions: [],+}++/** Sort order is the row's index — never an input the merchant types. */+function withSortOrder(values: ProductTypeFormValues): ProductTypeUpdateParams {+ return {+ ...values,+ custom_field_definitions: values.custom_field_definitions.map((row, index) => ({+ ...row,+ sort_order: index,+ })),+ }}const productTypesSearchSchema = resourceSearchSchema.extend({@@ -159,7 +202,7 @@ function CreateProductTypeSheet({async function onSubmit(values: ProductTypeFormValues) {try {- await createMutation.mutateAsync(values)+ await createMutation.mutateAsync({ ...withSortOrder(values), name: values.name })form.reset(PRODUCT_TYPE_DEFAULTS)onOpenChange(false)} catch (err) {@@ -230,13 +273,21 @@ function EditProductTypeSheet({form.reset({name: productType.name,fulfillment_types: productType.fulfillment_types ?? ['shipping'],+ option_type_ids: productType.option_type_ids ?? [],+ category_ids: productType.category_ids ?? [],+ custom_field_definitions: (productType.custom_field_definitions ?? []).map(+ (definition) => ({+ id: definition.id,+ required: definition.required,+ }),+ ),})}}, [productType, form])async function onSubmit(values: ProductTypeFormValues) {try {- await updateMutation.mutateAsync(values)+ await updateMutation.mutateAsync(withSortOrder(values))form.reset(values)onOpenChange(false)} catch (err) {@@ -257,6 +308,7 @@ function EditProductTypeSheet({<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"><ProductTypeFormFields form={form} />+ <ApplyToProductsSection id={id} productType={productType} /></div><SheetFooter><Button@@ -283,10 +335,59 @@ function EditProductTypeSheet({)}+/**+ * Type edits only shape products created from here on. This is the one action+ * that reaches back to products that already carry the type — additive, so it+ * never removes anything.+ */+function ApplyToProductsSection({+ id,+ productType,+}: {+ id: string+ productType: ProductType | undefined+}) {+ const { t } = useTranslation()+ const confirm = useConfirm()+ const applyMutation = useApplyProductTypeToProducts(id)+ const productsCount = productType?.products_count ?? 0++ async function handleApply() {+ const ok = await confirm({+ title: t('admin.product_types.apply_to_products.title'),+ message: t('admin.product_types.apply_to_products.message', { count: productsCount }),+ confirmLabel: t('admin.product_types.apply_to_products.confirm_label'),+ })+ if (!ok) return+ await applyMutation.mutateAsync().catch(() => undefined)+ }++ return (+ <div className="flex flex-col gap-2 rounded-md border border-dashed p-3">+ <span className="font-medium text-sm">{t('admin.product_types.affects_new_only.title')}</span>+ <span className="text-muted-foreground text-xs">+ {t('admin.product_types.affects_new_only.description')}+ </span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="self-start"+ disabled={productsCount === 0 || applyMutation.isPending}+ onClick={handleApply}+ >+ {t('admin.product_types.apply_to_products.cta', { count: productsCount })}+ </Button>+ </div>+ )+}+function ProductTypeFormFields({ form }: { form: UseFormReturn<ProductTypeFormValues> }) {const { t } = useTranslation()const { errors } = form.formStateconst { data: fulfillmentProviders } = useFulfillmentProviders()+ const { data: optionTypes } = useOptionTypes()+ const { data: categories } = useCategories()// Registry-driven: extension-registered types appear without a dashboard// change; the shipped const only covers the pre-fetch render.const registeredFulfillmentTypes = fulfillmentProviders?.fulfillment_types ?? FULFILLMENT_TYPES@@ -350,6 +451,240 @@ function ProductTypeFormFields({ form }: { form: UseFormReturn<ProductTypeFormVa/><FieldError errors={[errors.fulfillment_types]} /></Field>++ <Field>+ <FieldLabel>{t('admin.fields.product_type.option_types.label')}</FieldLabel>+ <span className="text-muted-foreground text-xs">+ {t('admin.fields.product_type.option_types.help')}+ </span>+ <Controller+ name="option_type_ids"+ control={form.control}+ render={({ field }) => (+ <CheckboxList+ items={(optionTypes?.data ?? []).map((optionType) => ({+ id: optionType.id,+ label: optionType.name ?? optionType.id,+ }))}+ selected={field.value}+ onChange={field.onChange}+ emptyLabel={t('admin.product_types.no_option_types')}+ idPrefix="option-type"+ />+ )}+ />+ </Field>++ <Field>+ <FieldLabel>{t('admin.fields.product_type.categories.label')}</FieldLabel>+ <span className="text-muted-foreground text-xs">+ {t('admin.fields.product_type.categories.help')}+ </span>+ <Controller+ name="category_ids"+ control={form.control}+ render={({ field }) => (+ <CheckboxList+ items={(categories?.data ?? []).map((category) => ({+ id: category.id,+ label: category.pretty_name ?? category.name ?? category.id,+ }))}+ selected={field.value}+ onChange={field.onChange}+ emptyLabel={t('admin.product_types.no_categories')}+ idPrefix="category"+ />+ )}+ />+ </Field>++ <CustomFieldDefinitionsEditor form={form} /></FieldGroup>)}++function CheckboxList({+ items,+ selected,+ onChange,+ emptyLabel,+ idPrefix,+}: {+ items: Array<{ id: string; label: string }>+ selected: string[]+ onChange: (next: string[]) => void+ emptyLabel: string+ idPrefix: string+}) {+ if (items.length === 0) {+ return <span className="text-muted-foreground text-sm">{emptyLabel}</span>+ }++ return (+ <div className="flex max-h-48 flex-col gap-2 overflow-y-auto rounded-md border p-3">+ {items.map((item) => (+ <label+ key={item.id}+ htmlFor={`${idPrefix}-${item.id}`}+ className="flex items-center gap-2 text-sm"+ >+ <Checkbox+ id={`${idPrefix}-${item.id}`}+ checked={selected.includes(item.id)}+ onCheckedChange={(next) => {+ onChange(next ? [...selected, item.id] : selected.filter((id) => id !== item.id))+ }}+ />+ {item.label}+ </label>+ ))}+ </div>+ )+}++/**+ * Which custom fields a product of this type gets, in which order, and which+ * must be filled before it can be activated. Order is the row position — the+ * sort order is never typed in.+ */+function CustomFieldDefinitionsEditor({ form }: { form: UseFormReturn<ProductTypeFormValues> }) {+ const { t } = useTranslation()+ const { data: definitions } = useProductCustomFieldDefinitions()+ const fieldArray = useFieldArray({ control: form.control, name: 'custom_field_definitions' })+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),+ )++ const selectedIds = fieldArray.fields.map((row) => row.id)+ const available = (definitions?.data ?? []).filter(+ (definition) => !selectedIds.includes(definition.id),+ )+ const labelFor = (id: string) => {+ const definition = definitions?.data?.find((candidate) => candidate.id === id)+ return definition?.label ?? definition?.key ?? id+ }++ function handleDragEnd(event: DragEndEvent) {+ const { active, over } = event+ if (!over || active.id === over.id) return++ const from = fieldArray.fields.findIndex((row) => row.id === active.id)+ const to = fieldArray.fields.findIndex((row) => row.id === over.id)+ if (from >= 0 && to >= 0) fieldArray.move(from, to)+ }++ return (+ <Field>+ <FieldLabel>{t('admin.fields.product_type.custom_field_definitions.label')}</FieldLabel>+ <span className="text-muted-foreground text-xs">+ {t('admin.fields.product_type.custom_field_definitions.help')}+ </span>++ {fieldArray.fields.length > 0 && (+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>+ <SortableContext items={selectedIds} strategy={verticalListSortingStrategy}>+ <div className="flex flex-col gap-1 rounded-md border p-2">+ {fieldArray.fields.map((row, index) => (+ <SortableCustomFieldRow+ key={row.id}+ sortableId={row.id}+ label={labelFor(row.id)}+ form={form}+ index={index}+ onRemove={() => fieldArray.remove(index)}+ />+ ))}+ </div>+ </SortableContext>+ </DndContext>+ )}++ {available.length > 0 && (+ <div className="flex flex-wrap gap-2 pt-2">+ {available.map((definition) => (+ <Button+ key={definition.id}+ type="button"+ variant="outline"+ size="sm"+ onClick={() => fieldArray.append({ id: definition.id, required: false })}+ >+ <PlusIcon className="size-3" />+ {definition.label ?? definition.key}+ </Button>+ ))}+ </div>+ )}+ </Field>+ )+}++function SortableCustomFieldRow({+ sortableId,+ label,+ form,+ index,+ onRemove,+}: {+ sortableId: string+ label: string+ form: UseFormReturn<ProductTypeFormValues>+ index: number+ onRemove: () => void+}) {+ const { t } = useTranslation()+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({+ id: sortableId,+ })+ const style: CSSProperties = {+ transform: CSS.Transform.toString(transform),+ transition,+ }++ return (+ <div+ ref={setNodeRef}+ style={style}+ className={cn(+ 'flex items-center gap-2 rounded-md px-1 py-1.5 text-sm',+ isDragging && 'relative z-10 bg-card opacity-80 shadow-lg',+ )}+ >+ <button+ type="button"+ className="cursor-grab touch-none text-muted-foreground"+ aria-label={t('admin.actions.reorder')}+ {...attributes}+ {...listeners}+ >+ <GripVerticalIcon className="size-4" />+ </button>++ <span className="flex-1 truncate">{label}</span>++ <Controller+ name={`custom_field_definitions.${index}.required` as const}+ control={form.control}+ render={({ field }) => (+ <label+ htmlFor={`cfdef-required-${sortableId}`}+ className="flex items-center gap-1.5 text-muted-foreground text-xs"+ >+ <Checkbox+ id={`cfdef-required-${sortableId}`}+ checked={field.value}+ onCheckedChange={(next) => field.onChange(!!next)}+ />+ {t('admin.fields.product_type.custom_field_definitions.required')}+ </label>+ )}+ />++ <Button type="button" variant="ghost" size="sm" onClick={onRemove}>+ <XIcon className="size-4" />+ <span className="sr-only">{t('admin.actions.remove')}</span>+ </Button>+ </div>+ )+}