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
Offer a product type's options when creating a product
Damian Legawiec5be39e103f09
diff --git a/packages/dashboard/src/components/spree/products/product-form-cards.tsx b/packages/dashboard/src/components/spree/products/product-form-cards.tsxindex 98af36d3de..70afc07530 100644--- a/packages/dashboard/src/components/spree/products/product-form-cards.tsx+++ b/packages/dashboard/src/components/spree/products/product-form-cards.tsx@@ -46,6 +46,7 @@ import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import { categoryAutocompleteProps, useCategories } from '../../../hooks/use-categories'import { collectionAutocompleteProps, useCollections } from '../../../hooks/use-collections'+import { useOptionTypes } from '../../../hooks/use-option-types'import { useDeleteProductMedia } from '../../../hooks/use-product-media'import { useProductType, useProductTypes } from '../../../hooks/use-product-types'import { useTaxCategories } from '../../../hooks/use-tax-categories'@@ -108,8 +109,8 @@ export function GeneralCard({ form }: FormCardProps) {// Variants (just a passthrough so the page composition reads top-down)// ----------------------------------------------------------------------------export function VariantsCard({ form }: FormCardProps) {- return <VariantsSection form={form} />+export function VariantsCard({ form, seedFromType }: FormCardProps & { seedFromType?: boolean }) {+ return <VariantsSection form={form} seedFromType={seedFromType} />}// ---------------------------------------------------------------------------@@ -651,11 +652,25 @@ export function CategorizationCard({ form }: FormCardProps) {const productTypes = productTypesData?.data ?? []const selectedProductTypeId = form.watch('product_type_id') as string | null | undefinedconst { data: selectedProductType } = useProductType(selectedProductTypeId ?? undefined)+ const { data: optionTypesData } = useOptionTypes({ limit: 100 })+ const optionTypes = useMemo(() => optionTypesData?.data ?? [], [optionTypesData])// The server seeds the type's categories onto the product when it is saved.// Prefilling them here means the merchant sees what they are about to get and// can still edit the list first. Additive, like the server: nothing they// already picked is removed.+ // Named rather than counted: on a product that already has variants the+ // builder won't surface these, so the name is the only signal the merchant+ // gets about what the type contributes.+ const typeOptionTypeNames = useMemo(() => {+ const ids = selectedProductType?.option_type_ids ?? []+ return ids+ .map((id) => optionTypes.find((optionType) => optionType.id === id))+ .filter((optionType) => optionType !== undefined)+ .map((optionType) => optionType.label ?? optionType.name ?? '')+ .filter(Boolean)+ }, [selectedProductType?.option_type_ids, optionTypes])+useEffect(() => {const categoryIds = selectedProductType?.category_idsif (!categoryIds?.length) return@@ -709,13 +724,14 @@ export function CategorizationCard({ form }: FormCardProps) {<span className="text-muted-foreground text-xs">{t('admin.fields.product.product_type_id.help')}</span>- {selectedProductType?.option_type_ids?.length ? (+ {typeOptionTypeNames.length > 0 && (<span className="text-muted-foreground text-xs">{t('admin.products.product_type_adds_options', {- count: selectedProductType.option_type_ids.length,+ options: typeOptionTypeNames.join(', '),+ count: typeOptionTypeNames.length,})}</span>- ) : null}+ )}</Field><Field>diff --git a/packages/dashboard/src/components/spree/products/variants-section.tsx b/packages/dashboard/src/components/spree/products/variants-section.tsxindex 35a7f6b104..ae8224002a 100644--- a/packages/dashboard/src/components/spree/products/variants-section.tsx+++ b/packages/dashboard/src/components/spree/products/variants-section.tsx@@ -32,10 +32,11 @@ import {TableRow,} from '@spree/dashboard-ui'import { PencilIcon, XIcon } from 'lucide-react'-import { type CSSProperties, useMemo, useState } from 'react'+import { type CSSProperties, useEffect, useMemo, useState } from 'react'import { type UseFormReturn, useFieldArray, useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { useOptionTypes } from '../../../hooks/use-option-types'+import { useProductType } from '../../../hooks/use-product-types'import type { ProductFormValues, VariantFormValues } from '../../../schemas/product'import { VariantEditSheet } from './variant-edit-sheet'import {@@ -50,6 +51,12 @@ import { VariantsOptionsBuilder } from './variants-options-builder'interface Props {// eslint-disable-next-line @typescript-eslint/no-explicit-anyform: UseFormReturn<ProductFormValues, any, any>+ /**+ * Offer the product type's option types as empty rows when the product has+ * none of its own. New products only — a saved product's option set is+ * whatever it already has.+ */+ seedFromType?: boolean}// Derive the initial selected option types from current variant rows so the@@ -90,10 +97,33 @@ function deriveSelectedFromVariants(.filter((x): x is SelectedOptionType => x !== null)}-export function VariantsSection({ form }: Props) {+// Empty rows for a product type's option types — a starting point, not state.+function seedFromProductType(+ optionTypeIds: string[],+ allOptionTypes: OptionType[],+): SelectedOptionType[] {+ return optionTypeIds+ .map<SelectedOptionType | null>((id, idx) => {+ const optionType = allOptionTypes.find((candidate) => candidate.id === id)+ if (!optionType) return null++ return {+ id: optionType.id,+ name: optionType.name,+ label: optionType.label,+ position: optionType.position ?? idx,+ values: [],+ }+ })+ .filter((entry): entry is SelectedOptionType => entry !== null)+}++export function VariantsSection({ form, seedFromType = false }: Props) {const { t } = useTranslation()const { data: optionTypesData } = useOptionTypes({ limit: 100 })const allOptionTypes = useMemo(() => optionTypesData?.data ?? [], [optionTypesData])+ const productTypeId = form.watch('product_type_id') as string | null | undefined+ const { data: productType } = useProductType(productTypeId ?? undefined)const variantsArray = useFieldArray<ProductFormValues, 'variants', '_key'>({control: form.control,@@ -110,16 +140,46 @@ export function VariantsSection({ form }: Props) {// RHF variants → next render derives `selected` from the new variants. No// local state to drift out of sync.const watchedVariants = useWatch({ control: form.control, name: 'variants' })- const selected = useMemo(+ const derived = useMemo(() => deriveSelectedFromVariants(watchedVariants ?? [], allOptionTypes),[watchedVariants, allOptionTypes],)+ // A product type's option types are *offered* as empty rows, once, when the+ // merchant picks the type on a new product. They live in local state rather+ // than being derived every render: an empty row writes no variants, so a+ // derived version would regenerate itself the moment the merchant removed it.+ // Once any row has values the variants array takes over as the source.+ const [offeredOptionTypes, setOfferedOptionTypes] = useState<SelectedOptionType[]>([])+ const [offeredForTypeId, setOfferedForTypeId] = useState<string | null>(null)++ useEffect(() => {+ if (!seedFromType || !productTypeId || productTypeId === offeredForTypeId) return+ // Only on a product the merchant hasn't started building options for.+ if (derived.length > 0) return++ setOfferedForTypeId(productTypeId)+ setOfferedOptionTypes(seedFromProductType(productType?.option_type_ids ?? [], allOptionTypes))+ }, [+ seedFromType,+ productTypeId,+ offeredForTypeId,+ derived.length,+ productType?.option_type_ids,+ allOptionTypes,+ ])++ const selected = derived.length > 0 ? derived : offeredOptionTypes+const fields = variantsArray.fieldsconst hasOptionTypes = selected.length > 0const isSimpleProduct = !hasOptionTypes && fields.length <= 1const handleOptionsChange = (next: SelectedOptionType[]) => {+ // Keep the offered rows in step with the builder — including a removal,+ // which must not be undone by the seeding effect above.+ setOfferedOptionTypes(next)+const combinations = generateVariantCombinations(next)const existing = form.getValues('variants') ?? []if (combinations.length === 0) {diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 038d7a4158..d4ff291c82 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2677,8 +2677,8 @@"ends_after_starts": "يجب أن يكون بعد تاريخ البدء."}},- "product_type_adds_options_one": "يضيف هذا النوع خيارًا واحدًا إلى المنتجات الجديدة.",- "product_type_adds_options_other": "يضيف هذا النوع {{count}} خيارات إلى المنتجات الجديدة.",+ "product_type_adds_options_one": "يضيف هذا النوع {{options}} إلى المنتجات الجديدة.",+ "product_type_adds_options_other": "يضيف هذا النوع {{options}} إلى المنتجات الجديدة.","product_type_placeholder": "بدون نوع منتج","save_label": "حفظ المنتج","seo": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex cf10e63b7f..1a7ee7450a 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2677,8 +2677,8 @@"ends_after_starts": "Muss nach dem Startdatum liegen."}},- "product_type_adds_options_one": "Dieser Typ fügt neuen Produkten {{count}} Option hinzu.",- "product_type_adds_options_other": "Dieser Typ fügt neuen Produkten {{count}} Optionen hinzu.",+ "product_type_adds_options_one": "Dieser Typ fügt neuen Produkten {{options}} hinzu.",+ "product_type_adds_options_other": "Dieser Typ fügt neuen Produkten {{options}} hinzu.","product_type_placeholder": "Kein Produkttyp","save_label": "Produkt speichern","seo": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 3950607c34..1a6f2ebeb3 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2677,8 +2677,8 @@"ends_after_starts": "Must be after start date."}},- "product_type_adds_options_one": "This type adds {{count}} option to new products.",- "product_type_adds_options_other": "This type adds {{count}} options to new products.",+ "product_type_adds_options_one": "This type adds {{options}} to new products.",+ "product_type_adds_options_other": "This type adds {{options}} to new products.","product_type_placeholder": "No product type","save_label": "Save product","seo": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 0fe629f31e..1ffc266972 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2677,8 +2677,8 @@"ends_after_starts": "Doit être postérieur à la date de début."}},- "product_type_adds_options_one": "Ce type ajoute {{count}} option aux nouveaux produits.",- "product_type_adds_options_other": "Ce type ajoute {{count}} options aux nouveaux produits.",+ "product_type_adds_options_one": "Ce type ajoute {{options}} aux nouveaux produits.",+ "product_type_adds_options_other": "Ce type ajoute {{options}} aux nouveaux produits.","product_type_placeholder": "Aucun type de produit","save_label": "Enregistrer le produit","seo": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 552bcc8861..fe219f07a1 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2715,10 +2715,10 @@"ends_after_starts": "Musi być po dacie rozpoczęcia."}},- "product_type_adds_options_few": "Ten typ dodaje {{count}} opcje do nowych produktów.",- "product_type_adds_options_many": "Ten typ dodaje {{count}} opcji do nowych produktów.",- "product_type_adds_options_one": "Ten typ dodaje {{count}} opcję do nowych produktów.",- "product_type_adds_options_other": "Ten typ dodaje {{count}} opcji do nowych produktów.",+ "product_type_adds_options_few": "Ten typ dodaje {{options}} do nowych produktów.",+ "product_type_adds_options_many": "Ten typ dodaje {{options}} do nowych produktów.",+ "product_type_adds_options_one": "Ten typ dodaje {{options}} do nowych produktów.",+ "product_type_adds_options_other": "Ten typ dodaje {{options}} do nowych produktów.","product_type_placeholder": "Brak typu produktu","save_label": "Zapisz produkt","seo": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 6734cabc1c..6dd9f437b7 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2677,8 +2677,8 @@"ends_after_starts": "必须晚于开始日期。"}},- "product_type_adds_options_one": "此类型会为新商品添加 {{count}} 个选项。",- "product_type_adds_options_other": "此类型会为新商品添加 {{count}} 个选项。",+ "product_type_adds_options_one": "此类型会为新商品添加{{options}}。",+ "product_type_adds_options_other": "此类型会为新商品添加{{options}}。","product_type_placeholder": "无商品类型","save_label": "保存产品","seo": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex b0cd2ade67..bcec8b862f 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -176,7 +176,7 @@ function NewProductPage() {main={<><GeneralCard form={form} />- <VariantsCard form={form} />+ <VariantsCard form={form} seedFromType />{/* Form-backed media uploader — files are uploaded to ActiveStoragepre-save and their signed_ids ride the product POST. */}<MediaCard form={form} />