Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add the admin surface for editing product types

Damian Legawiec191591b0cd6d
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index b2eb11adfe..2030a8eb53 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -166,6 +166,7 @@ import type {
PriceListUpdateParams,
PriceUpdateParams,
ProductCreateParams,
+ ProductTypeApplyToProductsResponse,
ProductTypeCreateParams,
ProductTypeUpdateParams,
ProductUpdateParams,
@@ -2730,6 +2731,21 @@ export class AdminClient {
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/product_types/${id}`, options),
+
+ /**
+ * Backfills the type's option types and categories onto the products that
+ * already carry it. Additive — nothing is removed. Runs in the background;
+ * the response reports how many products are affected.
+ */
+ applyToProducts: (
+ id: string,
+ options?: RequestOptions,
+ ): Promise<ProductTypeApplyToProductsResponse> =>
+ this.request<ProductTypeApplyToProductsResponse>(
+ 'POST',
+ `/product_types/${id}/apply_to_products`,
+ options,
+ ),
}
readonly taxCategories = {
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 5eda37730b..1cb767759f 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -984,15 +984,40 @@ export interface WebhookEndpointDisableParams {
reason?: string
}
+/** How one custom field definition is used by a product type. */
+export interface ProductTypeCustomFieldDefinitionParams {
+ /** Prefixed id of the custom field definition (`cfdef_…`). */
+ id: string
+ required?: boolean
+ sort_order?: number
+}
+
export interface ProductTypeCreateParams {
name: string
/** Fulfillment types products of this type support (e.g. ['shipping', 'pickup']). */
fulfillment_types?: string[]
+ /**
+ * Option types seeded onto products that get this type. Editing them never
+ * changes existing products — use `applyToProducts` for that.
+ */
+ option_type_ids?: string[]
+ /** Categories seeded onto products that get this type. */
+ category_ids?: string[]
+ /** Replace-set: definitions not listed are removed from the type. */
+ custom_field_definitions?: ProductTypeCustomFieldDefinitionParams[]
}
export interface ProductTypeUpdateParams {
name?: string
fulfillment_types?: string[]
+ option_type_ids?: string[]
+ category_ids?: string[]
+ custom_field_definitions?: ProductTypeCustomFieldDefinitionParams[]
+}
+
+/** Result of enqueueing a backfill of a type's associations onto its products. */
+export interface ProductTypeApplyToProductsResponse {
+ products_count: number
}
export interface TaxCategoryCreateParams {
diff --git a/packages/admin-sdk/src/types/generated/ProductType.ts b/packages/admin-sdk/src/types/generated/ProductType.ts
index 9b78ae42d6..67c109506d 100644
--- a/packages/admin-sdk/src/types/generated/ProductType.ts
+++ b/packages/admin-sdk/src/types/generated/ProductType.ts
@@ -1,14 +1,19 @@
-// Typelizer digest fec9914b31bfc8048d81a9a0be2edd18
+// Typelizer digest 6967b30120ed76d125c3bf5770b61fae
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {ProductTypeCustomFieldDefinition} from '@/types'
interface ProductType {
id: string;
name: string;
+ translations?: Record<string, Record<string, string | number | null>>;
fulfillment_types: Array<string>;
products_count: number;
created_at: string;
updated_at: string;
+ option_type_ids: Array<string>;
+ category_ids: Array<string>;
+ custom_field_definitions: Array<ProductTypeCustomFieldDefinition>;
}
export default ProductType;
diff --git a/packages/admin-sdk/src/types/generated/ProductTypeCustomFieldDefinition.ts b/packages/admin-sdk/src/types/generated/ProductTypeCustomFieldDefinition.ts
new file mode 100644
index 0000000000..1792de9007
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/ProductTypeCustomFieldDefinition.ts
@@ -0,0 +1,15 @@
+// Typelizer digest 076da32800ce2f65740f68e41950d330
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface ProductTypeCustomFieldDefinition {
+ id: string;
+ key: string;
+ namespace: string;
+ label: string;
+ field_type: 'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json';
+ required: boolean;
+ sort_order: number;
+}
+
+export default ProductTypeCustomFieldDefinition;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 5534bb8c52..be9adb01cf 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -57,6 +57,7 @@ export type { default as PriceRule } from './PriceRule'
export type { default as Price } from './Price'
export type { default as ProductPublication } from './ProductPublication'
export type { default as Product } from './Product'
+export type { default as ProductTypeCustomFieldDefinition } from './ProductTypeCustomFieldDefinition'
export type { default as ProductType } from './ProductType'
export type { default as PromotionAction } from './PromotionAction'
export type { default as PromotionRule } from './PromotionRule'
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.rb
index 5d88a16d4a..ed3e928acf 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
@@ -2,9 +2,26 @@ module Spree
module Api
module V3
module Admin
+ # Product types are back-office only — there is no Store API counterpart.
+ #
+ # Editing a type never mutates existing products: option types and
+ # categories seed onto products when the type is attached, and the
+ # custom field list is read live when a product form renders. The one
+ # path from a type edit to existing products is `apply_to_products`.
class ProductTypesController < ResourceController
scoped_resource :products
+ # Backfills this type's option types and categories onto the products
+ # that already carry it. Additive and idempotent — nothing is removed.
+ def apply_to_products
+ @resource = find_resource
+ authorize!(:update, @resource)
+
+ Spree::ProductTypes::ApplyToProductsJob.perform_later(@resource.id)
+
+ render json: { products_count: @resource.products_count.to_i }, status: :accepted
+ end
+
protected
def model_class
@@ -15,8 +32,31 @@ module Spree
Spree.api.admin_product_type_serializer
end
+ def collection_includes
+ [:option_types, :categories, { product_type_custom_field_definitions: :custom_field_definition }]
+ end
+
def permitted_params
- params.permit(:name, fulfillment_types: [])
+ attrs = params.permit(
+ :name,
+ fulfillment_types: [],
+ option_type_ids: [],
+ category_ids: [],
+ custom_field_definitions: [:id, :required, :sort_order]
+ )
+ reject_foreign_associations(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
+
+ attrs
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_type_custom_field_definition_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_type_custom_field_definition_serializer.rb
new file mode 100644
index 0000000000..db4bf5b836
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_type_custom_field_definition_serializer.rb
@@ -0,0 +1,44 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # A custom field definition as used by one product type: the definition's
+ # own schema fields, plus how this type uses it (required, sort order).
+ #
+ # `id` is the definition's prefixed id (`cfdef_…`), not the join row's —
+ # that is what clients send back on PATCH.
+ class ProductTypeCustomFieldDefinitionSerializer < BaseSerializer
+ typelize id: :string,
+ key: :string,
+ namespace: :string,
+ label: :string,
+ field_type: Spree::Metafield::FIELD_TYPE_TOKENS,
+ required: :boolean,
+ sort_order: :number
+
+ attribute :id do |join|
+ join.custom_field_definition.prefixed_id
+ end
+
+ attribute :key do |join|
+ join.custom_field_definition.key
+ end
+
+ attribute :namespace do |join|
+ join.custom_field_definition.namespace
+ end
+
+ attribute :label do |join|
+ join.custom_field_definition.label
+ end
+
+ attribute :field_type do |join|
+ join.custom_field_definition.field_type
+ end
+
+ attributes :required, :sort_order
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/product_type_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/product_type_serializer.rb
index 6ec7f54bb2..46a462f750 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/product_type_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/product_type_serializer.rb
@@ -3,11 +3,24 @@ module Spree
module V3
module Admin
class ProductTypeSerializer < V3::ProductTypeSerializer
+ include Spree::Api::V3::Admin::Translatable
+
typelize fulfillment_types: [:string, multi: true],
- products_count: :number
+ products_count: :number,
+ option_type_ids: [:string, multi: true],
+ category_ids: [:string, multi: true]
attributes :fulfillment_types, :products_count,
created_at: :iso8601, updated_at: :iso8601
+
+ # Prefixed ids of the option types and categories this type seeds onto
+ # new products — the same payload the client sends back on PATCH.
+ attribute :option_type_ids, &:option_type_prefixed_ids
+ attribute :category_ids, &:category_prefixed_ids
+
+ many :product_type_custom_field_definitions,
+ key: :custom_field_definitions,
+ resource: proc { Spree.api.admin_product_type_custom_field_definition_serializer }
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/product_type_serializer.rb b/spree/api/app/serializers/spree/api/v3/product_type_serializer.rb
index f3bacffae2..13def07695 100644
--- a/spree/api/app/serializers/spree/api/v3/product_type_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/product_type_serializer.rb
@@ -1,8 +1,12 @@
module Spree
module Api
module V3
- # Store API Product Type Serializer
- # Read-only expand on products — customers only see the type's name.
+ # Base Product Type Serializer.
+ #
+ # ProductType is back-office vocabulary and is NOT exposed on the Store
+ # API — no endpoint, no expand, no filter. This class exists solely as the
+ # parent of the Admin serializer, per the house convention that every
+ # admin serializer extends a store-namespace base.
class ProductTypeSerializer < BaseSerializer
typelize name: :string
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 9e1b6787e1..2413af0e7a 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -237,7 +237,11 @@ Spree::Core::Engine.add_routes do
end
# Products
- resources :product_types
+ resources :product_types do
+ member do
+ post :apply_to_products
+ end
+ end
resources :products, concerns: [:custom_fieldable, :translatable] do
member do
post :clone
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 6a2633b15e..76df1c5153 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -105,6 +105,7 @@ module Spree
admin_order_serializer: 'Spree::Api::V3::Admin::OrderSerializer',
admin_product_serializer: 'Spree::Api::V3::Admin::ProductSerializer',
admin_product_type_serializer: 'Spree::Api::V3::Admin::ProductTypeSerializer',
+ admin_product_type_custom_field_definition_serializer: 'Spree::Api::V3::Admin::ProductTypeCustomFieldDefinitionSerializer',
admin_variant_serializer: 'Spree::Api::V3::Admin::VariantSerializer',
admin_price_serializer: 'Spree::Api::V3::Admin::PriceSerializer',
admin_price_history_serializer: 'Spree::Api::V3::Admin::PriceHistorySerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/product_types_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/product_types_controller_spec.rb
index 0278d27417..fbedd62e73 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/product_types_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/product_types_controller_spec.rb
@@ -5,64 +5,115 @@ RSpec.describe Spree::Api::V3::Admin::ProductTypesController, type: :controller
include_context 'API v3 Admin authenticated'
- let!(:product_type) { create(:product_type, name: 'T-Shirt', store: store) }
+ let!(:product_type) { create(:product_type, name: 'T-Shirt') }
+ let(:option_type) { create(:option_type, name: 'size') }
+ let(:category) { create(:category) }
+ let(:definition) { create(:custom_field_definition, key: 'material') }
before { request.headers.merge!(headers) }
- describe 'GET #index' do
- it 'lists the store product types' do
- get :index, params: {}, as: :json
+ describe 'GET #show' do
+ before do
+ product_type.option_types << option_type
+ product_type.categories << category
+ create(:product_type_custom_field_definition, :required, product_type: product_type,
+ custom_field_definition: definition, sort_order: 0)
+ end
+
+ it 'returns association ids as prefixed ids' do
+ get :show, params: { id: product_type.prefixed_id }, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['data'].map { |row| row['name'] }).to include('T-Shirt')
+ expect(json_response['option_type_ids']).to eq([option_type.prefixed_id])
+ expect(json_response['category_ids']).to eq([category.prefixed_id])
end
- it 'does not leak other stores types' do
- create(:product_type, name: 'Foreign', store: create(:store))
-
- get :index, params: {}, as: :json
+ it 'returns the custom field definitions with their usage' do
+ get :show, params: { id: product_type.prefixed_id }, as: :json
- expect(json_response['data'].map { |row| row['name'] }).not_to include('Foreign')
+ field = json_response['custom_field_definitions'].first
+ expect(field['id']).to eq(definition.prefixed_id)
+ expect(field['key']).to eq('material')
+ expect(field['required']).to be(true)
+ expect(field['sort_order']).to eq(0)
end
end
- describe 'POST #create' do
- it 'creates a product type with fulfillment types' do
- post :create, params: { name: 'Collectable', fulfillment_types: %w[shipping pickup] }, as: :json
+ describe 'PATCH #update' do
+ it 'replaces the option types and categories' do
+ patch :update, params: {
+ id: product_type.prefixed_id,
+ option_type_ids: [option_type.prefixed_id],
+ category_ids: [category.prefixed_id]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(product_type.reload.option_types).to eq([option_type])
+ expect(product_type.categories).to eq([category])
+ end
+
+ it 'does not touch existing products' do
+ product = create(:product)
+ product.update_column(:product_type_id, product_type.id)
- expect(response).to have_http_status(:created)
- expect(json_response['name']).to eq('Collectable')
- expect(json_response['fulfillment_types']).to eq(%w[shipping pickup])
+ patch :update, params: {
+ id: product_type.prefixed_id,
+ option_type_ids: [option_type.prefixed_id]
+ }, as: :json
- created = Spree::ProductType.find_by(name: 'Collectable')
- expect(created.store).to eq(store)
+ expect(product.reload.option_types).to be_empty
end
- end
- describe 'PATCH #update' do
- it 'updates fulfillment types' do
- patch :update, params: { id: product_type.prefixed_id, fulfillment_types: %w[shipping pickup] }, as: :json
+ it 'ignores categories from another store' do
+ foreign_category = create(:category, store: create(:store))
+
+ patch :update, params: {
+ id: product_type.prefixed_id,
+ category_ids: [foreign_category.prefixed_id]
+ }, as: :json
+
+ expect(product_type.reload.categories).to be_empty
+ end
+
+ it 'replaces the custom field definitions' do
+ other_definition = create(:custom_field_definition, key: 'care')
+ create(:product_type_custom_field_definition, product_type: product_type,
+ custom_field_definition: other_definition)
+
+ patch :update, params: {
+ id: product_type.prefixed_id,
+ custom_field_definitions: [{ id: definition.prefixed_id, required: true, sort_order: 3 }]
+ }, as: :json
expect(response).to have_http_status(:ok)
- expect(product_type.reload.fulfillment_types).to eq(%w[shipping pickup])
+ joins = product_type.reload.product_type_custom_field_definitions
+ expect(joins.map(&:custom_field_definition)).to eq([definition])
+ expect(joins.first.required).to be(true)
+ expect(joins.first.sort_order).to eq(3)
end
end
- describe 'DELETE #destroy' do
- it 'refuses while products still use the type' do
- create(:product, product_type: product_type, store: store)
+ describe 'POST #apply_to_products' do
+ it 'enqueues the backfill job and reports the affected count' do
+ create(:product, product_type: product_type)
- delete :destroy, params: { id: product_type.prefixed_id }, as: :json
+ expect {
+ post :apply_to_products, params: { id: product_type.prefixed_id }, as: :json
+ }.to have_enqueued_job(Spree::ProductTypes::ApplyToProductsJob)
- expect(response).to have_http_status(:unprocessable_entity)
- expect(product_type.reload).to be_present
+ expect(response).to have_http_status(:accepted)
+ expect(json_response['products_count']).to eq(1)
end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'refuses while products still use the type' do
+ create(:product, product_type: product_type)
- it 'deletes an unused type' do
delete :destroy, params: { id: product_type.prefixed_id }, as: :json
- expect(response).to have_http_status(:no_content)
- expect(Spree::ProductType.find_by(id: product_type.id)).to be_nil
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(Spree::ProductType.find_by(id: product_type.id)).to be_present
end
end
end
diff --git a/spree/core/app/jobs/spree/product_types/apply_to_products_job.rb b/spree/core/app/jobs/spree/product_types/apply_to_products_job.rb
new file mode 100644
index 0000000000..974959d99b
--- /dev/null
+++ b/spree/core/app/jobs/spree/product_types/apply_to_products_job.rb
@@ -0,0 +1,14 @@
+module Spree
+ module ProductTypes
+ class ApplyToProductsJob < ::Spree::BaseJob
+ queue_as Spree.queues.products
+
+ def perform(product_type_id)
+ product_type = Spree::ProductType.find_by(id: product_type_id)
+ return if product_type.nil?
+
+ Spree::ProductTypes::ApplyToProducts.call(product_type: product_type)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/product_type.rb b/spree/core/app/models/spree/product_type.rb
index 16fa32007b..f2ed02c0d9 100644
--- a/spree/core/app/models/spree/product_type.rb
+++ b/spree/core/app/models/spree/product_type.rb
@@ -28,6 +28,8 @@ module Spree
# invalidate its type-driven data, so types in use cannot be deleted
has_many :products, class_name: 'Spree::Product', dependent: :restrict_with_error
+ after_save :apply_pending_custom_field_definitions, if: -> { @pending_custom_field_definitions }
+
validates :name, presence: true, uniqueness: { case_sensitive: false, scope: :store_id }
validates :store, presence: true
validates :fulfillment_types, presence: true
@@ -36,6 +38,30 @@ module Spree
self.whitelisted_ransackable_attributes = %w[name]
self.whitelisted_ransackable_associations = %w[option_types]
+ # Replace-set writer for the flat API payload. Each entry is
+ # `{ id: 'cfdef_…', required: true, sort_order: 0 }` — rows not listed are
+ # removed from the type. Editing the list never touches products; the form
+ # is generated from it live.
+ #
+ # @param rows [Array<Hash>, nil]
+ # @return [void]
+ def custom_field_definitions=(rows)
+ return super if rows.blank? || rows.first.is_a?(Spree::MetafieldDefinition)
+
+ @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
+ def option_type_prefixed_ids
+ encode_prefixed_ids(Spree::OptionType, option_type_ids)
+ end
+
+ # @return [Array<String>] prefixed category ids
+ def category_prefixed_ids
+ encode_prefixed_ids(Spree::Category, category_ids)
+ end
+
# @return [Boolean] true when products of this type are delivered digitally only
def digital?
fulfillment_types == ['digital']
@@ -48,6 +74,35 @@ module Spree
private
+ 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.
+ def apply_pending_custom_field_definitions
+ rows = @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
+ end
+
+ product_type_custom_field_definitions.where.not(custom_field_definition_id: definition_ids).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?
+
+ 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
+ join.save
+ end
+
+ product_type_custom_field_definitions.reset
+ end
+
# Strict vocabulary against Spree.fulfillment_types — an unregistered
# token silently removes the product from every delivery method's
# eligibility, so typos must fail loudly. Change-only, so rows migrated
diff --git a/spree/core/app/services/spree/product_types/apply_to_products.rb b/spree/core/app/services/spree/product_types/apply_to_products.rb
new file mode 100644
index 0000000000..46c97554bc
--- /dev/null
+++ b/spree/core/app/services/spree/product_types/apply_to_products.rb
@@ -0,0 +1,97 @@
+module Spree
+ module ProductTypes
+ # Backfills a product type's option types and categories onto the products
+ # that already carry the type. This is the only path from a type edit to
+ # existing products — ordinary type edits leave products untouched.
+ #
+ # Additive and idempotent: products keep everything they already have, so a
+ # re-run after a crash is safe.
+ class ApplyToProducts
+ prepend ::Spree::ServiceModule::Base
+
+ BATCH_SIZE = 500
+
+ # @param product_type [Spree::ProductType]
+ # @return [Spree::ServiceModule::Base::Result] count of products changed
+ def call(product_type:)
+ option_types = product_type.option_types.to_a
+ categories = product_type.categories.to_a
+
+ return success(0) if option_types.empty? && categories.empty?
+
+ changed_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))
+ end
+
+ success(changed_product_ids.size)
+ end
+
+ private
+
+ # @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)
+
+ existing = Spree::ProductOptionType.where(product_id: product_ids, option_type_id: option_type_ids).
+ pluck(:product_id, :option_type_id).to_set
+
+ # acts_as_list scopes position per product, so continue each product's
+ # own sequence rather than restarting at 1.
+ highest_positions = Spree::ProductOptionType.where(product_id: product_ids).
+ group(:product_id).maximum(:position)
+
+ rows = product_ids.flat_map do |product_id|
+ position = highest_positions[product_id].to_i
+
+ option_type_ids.filter_map do |option_type_id|
+ next if existing.include?([product_id, option_type_id])
+
+ position += 1
+ { product_id: product_id, option_type_id: option_type_id, position: position,
+ created_at: Time.current, updated_at: Time.current }
+ end
+ end
+
+ return [] if rows.empty?
+
+ Spree::ProductOptionType.insert_all(rows)
+ rows.pluck(:product_id).uniq
+ end
+
+ # 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)
+ end
+
+ changed_product_ids.uniq
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/product_types/apply_to_products_spec.rb b/spree/core/spec/services/spree/product_types/apply_to_products_spec.rb
new file mode 100644
index 0000000000..685d01490a
--- /dev/null
+++ b/spree/core/spec/services/spree/product_types/apply_to_products_spec.rb
@@ -0,0 +1,109 @@
+require 'spec_helper'
+
+RSpec.describe Spree::ProductTypes::ApplyToProducts do
+ subject(:apply) { described_class.call(product_type: product_type) }
+
+ let(:size) { create(:option_type, name: 'size') }
+ let(:category) { create(:category) }
+ let(:product_type) { create(:product_type) }
+
+ describe 'option types' do
+ before { product_type.option_types << size }
+
+ it 'adds the missing option type to existing products' do
+ product = create(:product)
+ product.update_column(:product_type_id, product_type.id)
+
+ expect(apply.value).to eq(1)
+ expect(product.reload.option_types).to eq([size])
+ end
+
+ it 'keeps option types the product already had' do
+ color = create(:option_type, name: 'color')
+ product = create(:product, option_types: [color])
+ product.update_column(:product_type_id, product_type.id)
+
+ apply
+
+ expect(product.reload.option_types).to match_array([color, size])
+ end
+
+ it 'continues each product position sequence' do
+ color = create(:option_type, name: 'color')
+ product = create(:product, option_types: [color])
+ product.update_column(:product_type_id, product_type.id)
+
+ apply
+
+ positions = product.reload.product_option_types.order(:position).pluck(:option_type_id, :position)
+ expect(positions).to eq([[color.id, 1], [size.id, 2]])
+ end
+
+ it 'leaves products of other types alone' do
+ other_product = create(:product, product_type: create(:product_type))
+
+ apply
+
+ expect(other_product.reload.option_types).to be_empty
+ end
+
+ it 'is idempotent' do
+ product = create(:product)
+ product.update_column(:product_type_id, product_type.id)
+
+ apply
+ second_run = described_class.call(product_type: product_type)
+
+ expect(second_run.value).to eq(0)
+ expect(product.reload.option_types).to eq([size])
+ end
+ end
+
+ describe 'categories' do
+ before { product_type.categories << category }
+
+ it 'adds the missing category to existing products' do
+ product = create(:product)
+ product.update_column(:product_type_id, product_type.id)
+
+ expect(apply.value).to eq(1)
+ expect(product.reload.categories).to eq([category])
+ end
+
+ it 'keeps the category products count correct' do
+ product = create(:product)
+ product.update_column(:product_type_id, product_type.id)
+
+ apply
+
+ expect(category.reload.products_count).to eq(1)
+ end
+
+ it 'does not duplicate an existing link' do
+ product = create(:product, categories: [category])
+ product.update_column(:product_type_id, product_type.id)
+
+ apply
+
+ expect(product.reload.categories).to eq([category])
+ expect(category.reload.products_count).to eq(1)
+ end
+ end
+
+ describe 'when the type defines nothing' do
+ it 'reports no changes' do
+ create(:product, product_type: product_type)
+
+ expect(apply.value).to eq(0)
+ end
+ end
+
+ it 'counts each product once when both option types and categories are added' do
+ product_type.option_types << size
+ product_type.categories << category
+ product = create(:product)
+ product.update_column(:product_type_id, product_type.id)
+
+ expect(apply.value).to eq(1)
+ end
+end