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
Reuse existing helpers in the product types code
Damian Legawiec17edc74d65a1
diff --git a/packages/dashboard/src/components/spree/products/product-custom-fields-provider.tsx b/packages/dashboard/src/components/spree/products/product-custom-fields-provider.tsxnew file mode 100644index 0000000000..8aeff3b0db--- /dev/null+++ b/packages/dashboard/src/components/spree/products/product-custom-fields-provider.tsx@@ -0,0 +1,48 @@+import type { ReactNode } from 'react'+import { useMemo } from 'react'+import type { UseFormReturn } from 'react-hook-form'+import { useProductType } from '../../../hooks/use-product-types'+import {+ type CustomFieldsFormShape,+ FormBackedCustomFieldsProvider,+} from '../custom-fields/custom-fields-inline'++interface ProductCustomFieldsProviderProps<T extends CustomFieldsFormShape> {+ form: UseFormReturn<T>+ /** Prefixed id of the product's type, when it has one. */+ productTypeId?: string | null+ children: ReactNode+}++/**+ * Custom fields for a product, scoped to its product type.+ *+ * The type decides which definitions the form shows and in which order — read+ * live, so editing a type updates every product form of that type. Products+ * without a type show every product definition, as before. Both the create and+ * edit routes go through here so they cannot drift apart.+ */+export function ProductCustomFieldsProvider<T extends CustomFieldsFormShape>({+ form,+ productTypeId,+ children,+}: ProductCustomFieldsProviderProps<T>) {+ const { data: productType } = useProductType(productTypeId ?? undefined)++ // Stable identity: the provider memoizes its definition list against this,+ // and a fresh array each render would defeat that memo on every keystroke.+ const definitionIds = useMemo(+ () => productType?.custom_field_definitions?.map((definition) => definition.id),+ [productType?.custom_field_definitions],+ )++ return (+ <FormBackedCustomFieldsProvider+ form={form}+ resourceType="Spree::Product"+ definitionIds={definitionIds}+ >+ {children}+ </FormBackedCustomFieldsProvider>+ )+}diff --git a/packages/dashboard/src/hooks/use-product-types.ts b/packages/dashboard/src/hooks/use-product-types.tsindex 60a8010afe..ba649b51c6 100644--- a/packages/dashboard/src/hooks/use-product-types.ts+++ b/packages/dashboard/src/hooks/use-product-types.ts@@ -30,6 +30,7 @@ export function useProductType(id: string | undefined) {queryKey: useResourceKey('product-types', id ?? 'noop'),queryFn: () => adminClient.productTypes.get(id as string),enabled: !!id,+ staleTime: 1000 * 60 * 5,})}@@ -51,21 +52,6 @@ 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.diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 541a438c22..a57a649378 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2598,6 +2598,7 @@},"no_categories": "لا توجد فئات بعد","no_option_types": "لا توجد أنواع خيارات بعد",+ "option_type_search_placeholder": "البحث في أنواع الخيارات","search_placeholder": "ابحث في أنواع المنتجات"},"products": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex d438cfc95b..2ed1c7ec91 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2598,6 +2598,7 @@},"no_categories": "Noch keine Kategorien","no_option_types": "Noch keine Optionstypen",+ "option_type_search_placeholder": "Optionstypen suchen","search_placeholder": "Produkttypen durchsuchen"},"products": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 4b905eb5b3..c7e8579232 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2598,6 +2598,7 @@},"no_categories": "No categories yet","no_option_types": "No option types yet",+ "option_type_search_placeholder": "Search option types","search_placeholder": "Search product types"},"products": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex c887e52469..290f8227ac 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2598,6 +2598,7 @@},"no_categories": "Aucune catégorie","no_option_types": "Aucun type d’option",+ "option_type_search_placeholder": "Rechercher des types 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 cdc2badef9..a804dd844c 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2634,6 +2634,7 @@},"no_categories": "Brak kategorii","no_option_types": "Brak typów opcji",+ "option_type_search_placeholder": "Szukaj 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 63faede2bf..901f9fed2a 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2598,6 +2598,7 @@},"no_categories": "暂无分类","no_option_types": "暂无选项类型",+ "option_type_search_placeholder": "搜索选项类型","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 039b55b869..34243e37bd 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -24,10 +24,8 @@ import { useEffect } from 'react'import { FormProvider, useForm, useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'-import {- CustomFieldsInlineCard,- FormBackedCustomFieldsProvider,-} from '../../../../components/spree/custom-fields/custom-fields-inline'+import { CustomFieldsInlineCard } from '../../../../components/spree/custom-fields/custom-fields-inline'+import { ProductCustomFieldsProvider } from '../../../../components/spree/products/product-custom-fields-provider'import {CategorizationCard,GeneralCard,@@ -43,7 +41,6 @@ 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,@@ -277,13 +274,7 @@ 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@@ -451,13 +442,9 @@ 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"- definitionIds={typeCustomFieldDefinitionIds}- >+ <ProductCustomFieldsProvider form={form} productTypeId={selectedProductTypeId}><CustomFieldsInlineCard />- </FormBackedCustomFieldsProvider>+ </ProductCustomFieldsProvider><ResourceTranslationsCard resourceType="product" resourceId={productId} /><MetadataCardmetadata={product.metadata}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsxindex d2911d4982..b0cd2ade67 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/products/new.tsx@@ -11,10 +11,8 @@ import { createFileRoute, useNavigate } from '@tanstack/react-router'import { FormProvider, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'-import {- CustomFieldsInlineCard,- FormBackedCustomFieldsProvider,-} from '../../../../components/spree/custom-fields/custom-fields-inline'+import { CustomFieldsInlineCard } from '../../../../components/spree/custom-fields/custom-fields-inline'+import { ProductCustomFieldsProvider } from '../../../../components/spree/products/product-custom-fields-provider'import {CategorizationCard,GeneralCard,@@ -187,9 +185,12 @@ function NewProductPage() {productName={form.watch('name') || t('admin.pages.products.new.title')}/><InventoryCard form={form} storeId={storeId} />- <FormBackedCustomFieldsProvider form={form} resourceType="Spree::Product">+ <ProductCustomFieldsProvider+ form={form}+ productTypeId={form.watch('product_type_id')}+ ><CustomFieldsInlineCard />- </FormBackedCustomFieldsProvider>+ </ProductCustomFieldsProvider></>}sidebar={diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsxindex 64dd180985..07ace0800f 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/product-types.tsx@@ -15,20 +15,23 @@ import {} from '@dnd-kit/sortable'import { CSS } from '@dnd-kit/utilities'import { zodResolver } from '@hookform/resolvers/zod'-import type { ProductType, ProductTypeUpdateParams } from '@spree/admin-sdk'+import type { ProductType } from '@spree/admin-sdk'import {adminClient,Can,mapSpreeErrorsToForm,+ ResourceMultiAutocomplete,ResourceTable,resourceSearchSchema,Subject,+ useCustomFieldDefinitions,usePermissions,} from '@spree/dashboard-core'import {Button,Checkbox,cn,+ DragHandle,Field,FieldError,FieldGroup,@@ -45,19 +48,17 @@ import {useRowClickBridge,} from '@spree/dashboard-ui'import { createFileRoute, useNavigate } from '@tanstack/react-router'-import { GripVerticalIcon, PlusIcon, XIcon } from 'lucide-react'-import { type CSSProperties, useEffect } from 'react'+import { PlusIcon, XIcon } from 'lucide-react'+import { type CSSProperties, useEffect, useMemo } 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 { categoryAutocompleteProps } 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'@@ -88,7 +89,7 @@ const PRODUCT_TYPE_DEFAULTS: ProductTypeFormValues = {}/** Sort order is the row's index — never an input the merchant types. */-function withSortOrder(values: ProductTypeFormValues): ProductTypeUpdateParams {+function withSortOrder(values: ProductTypeFormValues) {return {...values,custom_field_definitions: values.custom_field_definitions.map((row, index) => ({@@ -202,7 +203,7 @@ function CreateProductTypeSheet({async function onSubmit(values: ProductTypeFormValues) {try {- await createMutation.mutateAsync({ ...withSortOrder(values), name: values.name })+ await createMutation.mutateAsync(withSortOrder(values))form.reset(PRODUCT_TYPE_DEFAULTS)onOpenChange(false)} catch (err) {@@ -386,8 +387,6 @@ function ProductTypeFormFields({ form }: { form: UseFormReturn<ProductTypeFormVaconst { 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@@ -461,15 +460,15 @@ function ProductTypeFormFields({ form }: { form: UseFormReturn<ProductTypeFormVaname="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}+ <ResourceMultiAutocomplete+ queryKey="product-type-option-types"+ value={field.value}onChange={field.onChange}- emptyLabel={t('admin.product_types.no_option_types')}- idPrefix="option-type"+ search={(q) => adminClient.optionTypes.list({ name_cont: q, limit: 20 })}+ hydrate={(ids) => adminClient.optionTypes.list({ id_in: ids, limit: ids.length })}+ getOptionLabel={(optionType) => optionType.name ?? optionType.id}+ placeholder={t('admin.product_types.option_type_search_placeholder')}+ emptyText={t('admin.product_types.no_option_types')}/>)}/>@@ -484,15 +483,10 @@ function ProductTypeFormFields({ form }: { form: UseFormReturn<ProductTypeFormVaname="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}+ <ResourceMultiAutocomplete+ {...categoryAutocompleteProps('product-type-categories')}+ value={field.value}onChange={field.onChange}- emptyLabel={t('admin.product_types.no_categories')}- idPrefix="category"/>)}/>@@ -503,45 +497,6 @@ function ProductTypeFormFields({ form }: { form: UseFormReturn<ProductTypeFormVa)}-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@@ -549,19 +504,25 @@ function CheckboxList({*/function CustomFieldDefinitionsEditor({ form }: { form: UseFormReturn<ProductTypeFormValues> }) {const { t } = useTranslation()- const { data: definitions } = useProductCustomFieldDefinitions()+ const { data: definitions } = useCustomFieldDefinitions('Spree::Product')const fieldArray = useFieldArray({ control: form.control, name: 'custom_field_definitions' })const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),)+ // One index over the pool — this list re-renders on every drag frame.+ const definitionsById = useMemo(+ () => new Map((definitions?.data ?? []).map((definition) => [definition.id, definition])),+ [definitions?.data],+ )const selectedIds = fieldArray.fields.map((row) => row.id)- const available = (definitions?.data ?? []).filter(- (definition) => !selectedIds.includes(definition.id),+ const selectedIdSet = new Set(selectedIds)+ const available = [...definitionsById.values()].filter(+ (definition) => !selectedIdSet.has(definition.id),)const labelFor = (id: string) => {- const definition = definitions?.data?.find((candidate) => candidate.id === id)+ const definition = definitionsById.get(id)return definition?.label ?? definition?.key ?? id}@@ -651,15 +612,9 @@ function SortableCustomFieldRow({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="w-8 touch-none">+ <DragHandle attributes={attributes} listeners={listeners} />+ </span><span className="flex-1 truncate">{label}</span>diff --git a/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rbindex ed3e928acf..17c2d614b0 100644--- a/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/product_types_controller.rb@@ -32,8 +32,21 @@ module SpreeSpree.api.admin_product_type_serializerend+ # The join tables, not the targets — the serializer reports association+ # ids, so loading the option types and categories themselves would pay+ # for records nothing reads.def collection_includes- [:option_types, :categories, { product_type_custom_field_definitions: :custom_field_definition }]+ [+ :option_type_product_types,+ :product_type_categories,+ { product_type_custom_field_definitions: :custom_field_definition }+ ]+ end++ # Single-resource actions need the same eager-loading; without it every+ # custom field row re-queries its definition.+ def find_resource+ scope.includes(collection_includes).find_by_prefix_id!(params[:id])enddef permitted_params@@ -44,18 +57,20 @@ module Spreecategory_ids: [],custom_field_definitions: [:id, :required, :sort_order])- reject_foreign_associations(attrs)+ scope_category_ids(attrs)end# `category_ids=` resolves prefixed ids with no store scoping, so a# type in this store could otherwise be pointed at another store's- # categories. (OptionType is global — nothing to scope there.)- def reject_foreign_associations(attrs)- if attrs[:category_ids].present?- resolved = Array(attrs[:category_ids]).filter_map { |id| Spree::Category.find_by_prefix_id(id)&.id }- attrs[:category_ids] = current_store.categories.where(id: resolved).pluck(:id)- end+ # categories. Mirrors ProductsController#apply_categories.+ # (OptionType is global — nothing to scope there.)+ def scope_category_ids(attrs)+ return attrs if attrs[:category_ids].blank?+ category_ids = decode_ids(attrs[:category_ids], Spree::Category)+ attrs[:category_ids] = current_store.categories.+ accessible_by(current_ability, :update).+ where(id: category_ids).pluck(:id)attrsendenddiff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex 8263536ed2..c385f65f18 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -858,35 +858,45 @@ module Spreedef required_custom_fields_presentreturn if product_type.blank?- required_definitions = product_type.product_type_custom_field_definitions.required.- includes(:custom_field_definition).map(&:custom_field_definition)- return if required_definitions.empty?+ required = product_type.product_type_custom_field_definitions.required.+ joins(:custom_field_definition).pluck(:custom_field_definition_id, :name)+ return if required.empty?- filled_definition_ids = metafields.reject(&:marked_for_destruction?).- filter_map { |metafield| metafield.metafield_definition_id if metafield.value.present? }+ filled_definition_ids = filled_custom_field_definition_ids- required_definitions.each do |definition|- next if filled_definition_ids.include?(definition.id)+ required.each do |definition_id, name|+ next if filled_definition_ids.include?(definition_id)- errors.add(:base, :missing_required_custom_field, name: definition.name)+ errors.add(:base, :missing_required_custom_field, name: name)+ end+ end++ # Reads from memory when the association is already loaded (nested writes in+ # the same save); otherwise asks the database for ids alone, since the+ # association eager-loads every definition it touches.+ def filled_custom_field_definition_ids+ if metafields.loaded?+ metafields.reject(&:marked_for_destruction?).+ filter_map { |metafield| metafield.metafield_definition_id if metafield.value.present? }.to_set+ else+ metafields.where.not(value: [nil, '']).pluck(:metafield_definition_id).to_setendend# Additive, unlike the legacy prototype callback which replaced both sets —# the type seeds the product when attached (creation, later assignment,# reassignment) and never removes anything; detaching seeds nothing.- # Presence guards query the join tables directly: the cached associations- # can be stale here (pending variants insert option-type joins through- # product_option_types within the same save).+ # The already-linked sets come from the join tables in one query each: the+ # cached associations can be stale here (pending variants insert option-type+ # joins through product_option_types within the same save).def sync_associations_from_product_typereturn unless product_type- product_type.option_types.each do |option_type|- option_types << option_type unless product_option_types.exists?(option_type_id: option_type.id)- end- product_type.categories.each do |category|- categories << category unless product_categories.exists?(category_id: category.id)- end+ missing_option_type_ids = product_type.option_type_ids - product_option_types.pluck(:option_type_id)+ Spree::OptionType.where(id: missing_option_type_ids).each { |option_type| option_types << option_type }++ missing_category_ids = product_type.category_ids - product_categories.pluck(:category_id)+ Spree::Category.where(id: missing_category_ids).each { |category| categories << category }enddef any_variants_not_track_inventory?diff --git a/spree/core/app/models/spree/product_type.rb b/spree/core/app/models/spree/product_type.rbindex f2ed02c0d9..715f58c8dd 100644--- a/spree/core/app/models/spree/product_type.rb+++ b/spree/core/app/models/spree/product_type.rb@@ -51,15 +51,15 @@ module Spree@pending_custom_field_definitions = Array(rows).map { |row| row.to_h.with_indifferent_access }end- # @return [Array<String>] prefixed option type ids, encoded inline to avoid- # hydrating the records just to serialize their ids+ # @return [Array<String>] prefixed option type ids, encoded from the ids to+ # avoid hydrating the records just to serialize themdef option_type_prefixed_ids- encode_prefixed_ids(Spree::OptionType, option_type_ids)+ option_type_ids.map { |id| Spree::OptionType.prefixed_id_for(id) }end# @return [Array<String>] prefixed category idsdef category_prefixed_ids- encode_prefixed_ids(Spree::Category, category_ids)+ category_ids.map { |id| Spree::Category.prefixed_id_for(id) }end# @return [Boolean] true when products of this type are delivered digitally only@@ -74,29 +74,28 @@ module Spreeprivate- def encode_prefixed_ids(klass, ids)- prefix = klass._prefix_id_prefix- ids.map { |id| "#{prefix}_#{Spree::PrefixedId::SQIDS.encode([id])}" }- end-# Applied after save so a newly created type has an id to join against.+ # Ids arrive prefixed from the API and raw from console/importer callers, so+ # each row is resolved once here and carried through both passes.def apply_pending_custom_field_definitionsrows = @pending_custom_field_definitions@pending_custom_field_definitions = nil- definition_ids = rows.filter_map do |row|- Spree::MetafieldDefinition.find_by_prefix_id(row[:id])&.id+ resolved = rows.filter_map do |row|+ definition_id = Spree::MetafieldDefinition.find_by_prefix_id(row[:id])&.id+ [definition_id, row] if definition_idend- product_type_custom_field_definitions.where.not(custom_field_definition_id: definition_ids).destroy_all+ product_type_custom_field_definitions.+ where.not(custom_field_definition_id: resolved.map(&:first)).destroy_all- rows.each_with_index do |row, index|- definition_id = Spree::MetafieldDefinition.find_by_prefix_id(row[:id])&.id- next if definition_id.nil?+ existing_joins = product_type_custom_field_definitions.index_by(&:custom_field_definition_id)- join = product_type_custom_field_definitions.find_or_initialize_by(custom_field_definition_id: definition_id)- join.required = ActiveModel::Type::Boolean.new.cast(row[:required]) || false- join.sort_order = row.key?(:sort_order) ? row[:sort_order].to_i : index+ resolved.each_with_index do |(definition_id, row), index|+ join = existing_joins[definition_id] ||+ product_type_custom_field_definitions.build(custom_field_definition_id: definition_id)+ join.required = row[:required]+ join.sort_order = row[:sort_order] || indexjoin.saveenddiff --git a/spree/core/app/services/spree/product_types/apply_to_products.rb b/spree/core/app/services/spree/product_types/apply_to_products.rbindex 46c97554bc..36861735d6 100644--- a/spree/core/app/services/spree/product_types/apply_to_products.rb+++ b/spree/core/app/services/spree/product_types/apply_to_products.rb@@ -14,29 +14,39 @@ module Spree# @param product_type [Spree::ProductType]# @return [Spree::ServiceModule::Base::Result] count of products changeddef call(product_type:)- option_types = product_type.option_types.to_a- categories = product_type.categories.to_a+ option_type_ids = product_type.option_type_ids+ category_ids = product_type.category_ids- return success(0) if option_types.empty? && categories.empty?+ return success(0) if option_type_ids.empty? && category_ids.empty?changed_product_ids = Set.new+ categorized_product_ids = Set.new- product_type.products.find_in_batches(batch_size: BATCH_SIZE) do |products|- changed_product_ids.merge(add_option_types(products, option_types))- changed_product_ids.merge(add_categories(products, categories))+ # Only ids are ever needed — hydrating products would run their+ # after_initialize callbacks for nothing.+ product_type.products.select(:id).find_in_batches(batch_size: BATCH_SIZE) do |products|+ product_ids = products.map(&:id)++ changed_product_ids.merge(add_option_types(product_ids, option_type_ids))++ newly_categorized = add_categories(product_ids, category_ids)+ categorized_product_ids.merge(newly_categorized)+ changed_product_ids.merge(newly_categorized)end+ # Counter caches, branch counts and reindexing are settled once for the+ # whole run rather than per category per batch — each is a subtree-wide+ # recount or a job per product.+ settle_category_bookkeeping(categorized_product_ids.to_a, category_ids)+success(changed_product_ids.size)endprivate# @return [Array] ids of products that gained at least one option type- def add_option_types(products, option_types)- return [] if option_types.empty?-- product_ids = products.map(&:id)- option_type_ids = option_types.map(&:id)+ def add_option_types(product_ids, option_type_ids)+ return [] if option_type_ids.empty?existing = Spree::ProductOptionType.where(product_id: product_ids, option_type_id: option_type_ids).pluck(:product_id, :option_type_id).to_set@@ -46,6 +56,7 @@ module Spreehighest_positions = Spree::ProductOptionType.where(product_id: product_ids).group(:product_id).maximum(:position)+ now = Time.currentrows = product_ids.flat_map do |product_id|position = highest_positions[product_id].to_i@@ -54,7 +65,7 @@ module Spreeposition += 1{ product_id: product_id, option_type_id: option_type_id, position: position,- created_at: Time.current, updated_at: Time.current }+ created_at: now, updated_at: now }endend@@ -64,33 +75,51 @@ module Spreerows.pluck(:product_id).uniqend- # Delegates to the bulk category service, which owns the counter-cache,- # position and search-index bookkeeping that insert_all would skip.- ## @return [Array] ids of products that gained at least one category- def add_categories(products, categories)- return [] if categories.empty?-- product_ids = products.map(&:id)- linked = Spree::ProductCategory.where(product_id: product_ids, category_id: categories.map(&:id)).- pluck(:category_id, :product_id).group_by(&:first)-- changed_product_ids = []-- categories.each do |category|- already_linked = linked.fetch(category.id, []).map(&:last).to_set- missing = products.reject { |product| already_linked.include?(product.id) }- next if missing.empty?-- missing_ids = missing.map(&:id)- Spree::Categories::AddProducts.call(- categories: Spree::Category.where(id: category.id),- products: Spree::Product.where(id: missing_ids)- )- changed_product_ids.concat(missing_ids)+ def add_categories(product_ids, category_ids)+ return [] if category_ids.empty?++ existing = Spree::ProductCategory.where(product_id: product_ids, category_id: category_ids).+ pluck(:product_id, :category_id).to_set++ # acts_as_list scopes position per category here (unlike option types,+ # which scope per product), so each category continues its own sequence.+ highest_positions = Spree::ProductCategory.where(category_id: category_ids).+ group(:category_id).maximum(:position)++ now = Time.current+ rows = category_ids.flat_map do |category_id|+ position = highest_positions[category_id].to_i++ product_ids.filter_map do |product_id|+ next if existing.include?([product_id, category_id])++ position += 1+ { product_id: product_id, category_id: category_id, position: position,+ created_at: now, updated_at: now }+ end+ end++ return [] if rows.empty?++ Spree::ProductCategory.insert_all(rows)+ rows.pluck(:product_id).uniq+ end++ # insert_all skips the ProductCategory callbacks, so the counts they+ # maintain are recomputed here — once, for every product touched.+ def settle_category_bookkeeping(product_ids, category_ids)+ return if product_ids.empty?++ counts = Spree::ProductCategory.where(product_id: product_ids).group(:product_id).count+ counts.each do |product_id, count|+ Spree::Product.where(id: product_id).update_all(categories_count: count)end- changed_product_ids.uniq+ Spree::Category.recalculate_products_count(category_ids)+ Spree::Category.where(id: category_ids).touch_all++ Spree::Product.where(id: product_ids).find_each(&:enqueue_search_index)endendend