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.

Update Product Types Spree 6 plan

Damian Legawiec0adacf38e7d5
diff --git a/docs/plans/5.5-6.0-custom-fields-rename.md b/docs/plans/5.4-6.0-custom-fields-rename.md
similarity index 100%
rename from docs/plans/5.5-6.0-custom-fields-rename.md
rename to docs/plans/5.4-6.0-custom-fields-rename.md
diff --git a/docs/plans/5.5-6.0-display-on-to-boolean.md b/docs/plans/5.5-6.0-display-on-to-boolean.md
index 1d5b3cae4a..213d0bacbc 100644
--- a/docs/plans/5.5-6.0-display-on-to-boolean.md
+++ b/docs/plans/5.5-6.0-display-on-to-boolean.md
@@ -2,13 +2,13 @@
**Status:** 5.5 bridge shipped (`storefront_visible` accessor + Ransacker on the `Spree::DisplayOn` concern); 6.0 schema rename + concern drop pending
**Target:** 5.5 (API alias + `alias_attribute` shim ✓) + 6.0 (schema rename, drop the `Spree::DisplayOn` tri-state concern)
-**Depends on:** `5.5-6.0-custom-fields-rename.md` (same bridge pattern, already in flight). `6.0-fulfillment-and-delivery.md` (drives the `ShippingMethod → DeliveryMethod` rename — this plan piggybacks on that wave).
+**Depends on:** `5.4-6.0-custom-fields-rename.md` (same bridge pattern, already in flight). `6.0-fulfillment-and-delivery.md` (drives the `ShippingMethod → DeliveryMethod` rename — this plan piggybacks on that wave).
**Author:** Damian + Claude
**Last updated:** 2026-05-20
## Summary
-Collapse the tri-state `display_on` enum (`both` / `front_end` / `back_end`) on `Spree::PaymentMethod` and `Spree::ShippingMethod` to a single boolean `storefront_visible`, mirroring what `5.5-6.0-custom-fields-rename.md` does for `MetafieldDefinition`. The `front_end`-only state (visible to customers but hidden from admin) doesn't map to any real workflow — staff need to see every payment / shipping option to look up past transactions, process refunds, edit orders, etc. The remaining two states (`both`, `back_end`) collapse cleanly to a boolean.
+Collapse the tri-state `display_on` enum (`both` / `front_end` / `back_end`) on `Spree::PaymentMethod` and `Spree::ShippingMethod` to a single boolean `storefront_visible`, mirroring what `5.4-6.0-custom-fields-rename.md` does for `MetafieldDefinition`. The `front_end`-only state (visible to customers but hidden from admin) doesn't map to any real workflow — staff need to see every payment / shipping option to look up past transactions, process refunds, edit orders, etc. The remaining two states (`both`, `back_end`) collapse cleanly to a boolean.
Ships in two phases:
@@ -21,7 +21,7 @@ Ships in two phases:
- **`storefront_visible` not `available_on_storefront`.** Matches the custom-fields plan exactly; one term for the same concept across the whole product.
- **Default `true`.** Most payment/shipping methods are customer-facing. `back_end` is the exception (manual check entry, internal wire-transfer methods, refund-only methods).
- **5.5 reads expose `storefront_visible` only; writes still accept both names.** The Admin API is the only consumer of `display_on` today (the admin SPA, which is `next`-tagged and pre-1.0); migrating the wire shape now is cheaper than carrying two read paths for six months. Writes stay permissive so any out-of-tree integration that sends `display_on` keeps working through the 5.5 cycle.
-- **Drop `Spree::DisplayOn` concern in 6.0.** The concern only had three callers (`PaymentMethod`, `ShippingMethod`, `MetafieldDefinition`); custom fields are already migrating off via `5.5-6.0-custom-fields-rename.md`, so removing the concern entirely in 6.0 is a clean sweep.
+- **Drop `Spree::DisplayOn` concern in 6.0.** The concern only had three callers (`PaymentMethod`, `ShippingMethod`, `MetafieldDefinition`); custom fields are already migrating off via `5.4-6.0-custom-fields-rename.md`, so removing the concern entirely in 6.0 is a clean sweep.
- **Migration is non-destructive in 5.5.** No data migration, no removed columns. Anyone reading `display_on` keeps working; anyone reading `storefront_visible` gets the boolean.
- **The `front_end`-only edge case (if any merchant set it) maps to `storefront_visible: true`.** Same as the custom-fields plan's data migration.
@@ -49,7 +49,7 @@ Ships in two phases:
### Phase 1: 5.5 API Bridge + `alias_attribute` shim
-Mirrors `5.5-6.0-custom-fields-rename.md` exactly. No schema changes.
+Mirrors `5.4-6.0-custom-fields-rename.md` exactly. No schema changes.
#### Shared accessor + scopes inside `Spree::DisplayOn`
@@ -94,7 +94,7 @@ end
Reads: `back_end` → `false`, anything else (`both` or the legacy `front_end`) → `true`. Writes: `true` → `both`, `false` → `back_end`. Round-trip works.
-`Spree::MetafieldDefinition` already defines `storefront_visible` accessors per `5.5-6.0-custom-fields-rename.md` — those become redundant once the concern provides them and can be deleted. Coordinate via that plan's checklist.
+`Spree::MetafieldDefinition` already defines `storefront_visible` accessors per `5.4-6.0-custom-fields-rename.md` — those become redundant once the concern provides them and can be deleted. Coordinate via that plan's checklist.
In 6.0, the entire concern goes away — `storefront_visible` becomes a real column accessor on each model, scopes inline where needed (or, if a third caller wants it post-6.0, a smaller `Spree::StorefrontVisible` concern can be extracted).
@@ -214,7 +214,7 @@ end
- **All new Spree code (5.5+) should use `storefront_visible`** in serializers, controllers, models, specs, and the Admin SPA. `display_on` is in soft-deprecation as of this plan's adoption.
- **The `<DisplayOnSelect>` component shipped in [PR adding payment-method UX] stays callable for one minor cycle**, but new forms should use the new `<StorefrontVisibleSwitch>` once it lands. The existing component is not deleted in 5.5 — it just has no new callers.
-- **Custom Fields (`MetafieldDefinition`) — handled by `5.5-6.0-custom-fields-rename.md`**. Don't try to consolidate the two plans; the custom-fields one is further along and renames more than just the visibility field.
+- **Custom Fields (`MetafieldDefinition`) — handled by `5.4-6.0-custom-fields-rename.md`**. Don't try to consolidate the two plans; the custom-fields one is further along and renames more than just the visibility field.
- **The `Spree::DisplayOn` concern is frozen.** No new models should `include Spree::DisplayOn`; new resources that need storefront/admin visibility should add a `storefront_visible:boolean` column directly.
## Open Questions
@@ -225,6 +225,6 @@ end
## References
-- `5.5-6.0-custom-fields-rename.md` — same bridge pattern, further along; the canonical reference for how to do this kind of rename.
+- `5.4-6.0-custom-fields-rename.md` — same bridge pattern, further along; the canonical reference for how to do this kind of rename.
- `6.0-fulfillment-and-delivery.md` — `ShippingMethod → DeliveryMethod` rename context. This plan touches the same model; coordinate the 6.0 migration order so the column rename and the table rename happen in the right order.
- `decisions.md` — visibility-system simplification decisions live here once this plan is finalized.
diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.md
index 5245e9b2ad..20c7dd6b88 100644
--- a/docs/plans/6.0-fulfillment-and-delivery.md
+++ b/docs/plans/6.0-fulfillment-and-delivery.md
@@ -233,7 +233,7 @@ Phase 1 as previously drafted was one ~20-operation migration; per CLAUDE.md (da
### Phase 0 — gates
-- `6.0-product-types.md` shipped (with the fulfillment_types addendum).
+- `6.0-product-types.md` shipped — **including the `fulfillment_types` column** (owned by that plan's Phase 1 migration; previously orphaned between the two plans).
- `6.0-cart-order-split.md` fleshed out enough to confirm the owner shape (Open Question 1).
- `6.0-delivery-rate-provider.md` Phase 1 (`store_id`) — independent, can land before or after.
- `6.0-typed-stock-movements.md` confirmed born with `fulfillment_id` (dependency inverted from the earlier draft).
diff --git a/docs/plans/6.0-product-types.md b/docs/plans/6.0-product-types.md
index cb33036e34..66c11d34ae 100644
--- a/docs/plans/6.0-product-types.md
+++ b/docs/plans/6.0-product-types.md
@@ -2,13 +2,13 @@
**Status:** Draft
**Target:** Spree 6.0
-**Depends on:** Metafields system (shipped in 5.4), Taxon → Category rename (6.0). Consumed by: `6.0-fulfillment-and-delivery.md` (fulfillment_types replaces ShippingCategory — that plan cannot ship before this one)
+**Depends on:** Custom Fields system (Metafields, shipped 5.4; 6.0 vocabulary per `5.4-6.0-custom-fields-rename.md`), `6.0-store-scoped-custom-field-definitions.md` (definitions become store-owned — the joins here validate same-store). Coordinates with: `6.0-replace-taxons-with-categories.md` (this plan ships **before** the Taxon→Category table rename; the `class_name` flip happens in that plan's wave). Consumed by: `6.0-fulfillment-and-delivery.md` (`fulfillment_types` replaces ShippingCategory — that plan cannot ship before this one).
**Author:** Damian + Claude
**Last updated:** 2026-07-27
## Summary
-Rename and extend the existing `Spree::Prototype` model into `Spree::ProductType` — a persistent, schema-defining association on Product. Today Prototype is a fire-and-forget creation template (copies option types and taxons, then has no ongoing relationship with the product). ProductType becomes a **live template** that defines what option types, categories, and metafield definitions a product has, driving admin UI form generation and enabling type-aware filtering.
+Rename and extend the existing `Spree::Prototype` model into `Spree::ProductType` — a persistent, schema-defining, **store-owned** association on Product. Today Prototype is a fire-and-forget creation template (it *replaces* the product's option types and taxons at creation, then has no ongoing relationship — and since the legacy admin's prototype UI was already deleted, prototypes are currently uncreatable outside the console). ProductType becomes a **live template** that defines what option types, categories, and custom field definitions a product has, driving dashboard form generation and enabling type-aware filtering.
ProductType acts as an **authoritative template** for option types: changes to a type's option types propagate to all products of that type. Products may add extra option types beyond what the type provides, but cannot remove type-defined ones. This ensures catalog consistency (all "T-Shirts" share Color and Size) while allowing per-product flexibility (one T-shirt can add "Sleeve Length").
@@ -18,24 +18,27 @@ This closes Spree's biggest functional gap in catalog modeling, while building o
1. **No product schema enforcement.** All Spree products share the same shape. A merchant selling T-shirts and laptops has no way to say "T-shirts must have Size and Color; laptops must have RAM and Storage" without custom code.
-2. **No admin form generation from type.** The admin UI shows the same fields for every product. Modern platforms auto-generate product editing forms based on ProductType — adding an attribute to a type instantly updates the form for all products of that type.
+2. **No admin form generation from type.** The dashboard shows the same fields for every product. Modern platforms auto-generate product editing forms based on ProductType — adding an attribute to a type instantly updates the form for all products of that type.
-3. **Prototype is wasted infrastructure.** The model, join tables (`spree_option_type_prototypes`, `spree_prototype_taxons`), and creation-time callback already exist but serve only as a copy template with no ongoing relationship.
+3. **Prototype is wasted infrastructure — more than previously stated.** The model, join tables (`spree_option_type_prototypes`, `spree_prototype_taxons`), and creation-time callback exist, but there is **no admin UI and no API endpoint for prototypes at all today** (verified: zero controllers/views/routes; only a dead locale key). The only living consumers are the `attr_accessor :prototype_id` + `add_associations_from_prototype` callback (`product.rb:137, 485, 868-873`), a factory, and a dangling v2 serializer registration.
-4. **Metafields are unstructured per product.** Any MetafieldDefinition can be attached to any product. There's no way to declare "products of this type should have these metafields."
+4. **Custom fields are unstructured per product.** Any definition can be attached to any product. There's no way to declare "products of this type should have these custom fields."
## Key Decisions (do not deviate without discussion)
- **Rename only, no new table.** `Spree::Prototype` → `Spree::ProductType`, `spree_prototypes` → `spree_product_types`. Existing join tables renamed accordingly. No data loss.
-- **Persistent `belongs_to`.** Product gets `product_type_id` FK (nullable — existing products don't require a type). The current `attr_accessor :prototype_id` + fire-and-forget callback is replaced by a real association.
-- **ProductType defines OptionTypes, Categories, and MetafieldDefinitions.** Three M2M associations on ProductType, all carried over or added via join tables.
-- **ProductType is a live template for option types.** Option types defined on a ProductType propagate to all products of that type. Adding an option type to the type adds it to all its products; removing one removes it from products (with safety checks). Products can add extra option types beyond the type's set but cannot remove type-defined ones. This is "additive override" — the type is the floor, not the ceiling.
-- **MetafieldDefinition association carries `required` and `sort_order`.** The join table `spree_product_type_metafield_definitions` determines which metafield definitions a product type uses, whether they're required, and their display order. This is the schema enforcement layer.
+- **All new surface is born with custom-field vocabulary** (the born-correct principle every other 6.0 plan follows). The new join is `Spree::ProductTypeCustomFieldDefinition` / `spree_product_type_custom_field_definitions` / `custom_field_definition_id`, associating via the `Spree::CustomFieldDefinition` constant (the 5.5 alias makes this work today, pre-rename). API keys are `custom_field_definitions`; prefixed IDs are the real ones (`cfdef_`). Naming the join against `MetafieldDefinition` would create a legacy-named model in the same release that deletes that constant.
+- **ProductType is store-owned** (`belongs_to :store`, `Spree::SingleStoreResource`), matching Product (single-owner since 5.5), Category (6.0), and CustomFieldDefinition (`6.0-store-scoped-custom-field-definitions.md`). A global type joining store-scoped definitions/categories onto store-owned products would be a cross-tenant surface. Joins validate same-store; the Admin API scopes through `current_store.product_types`. Backfill: existing prototypes → `Store.default`.
+- **Persistent `belongs_to`.** Product gets a `product_type` reference (nullable — existing products don't require a type), via `add_reference` (PK-type agnostic; no hardcoded `:bigint`). The `attr_accessor :prototype_id` + fire-and-forget callback is replaced by a real association. **Behavior change, stated plainly:** today's callback *replaces* the product's option types/taxons by assignment; the new sync is **additive**. API input takes prefixed IDs (`pt_…`), resolved via `find_by_prefix_id`.
+- **ProductType defines OptionTypes, Categories, and CustomFieldDefinitions.** Three M2M associations, carried over or added via join tables.
+- **ProductType is a live template for option types.** Adding an option type to the type adds it to all its products; removing one removes it from products (with safety checks). Products can add extra option types but cannot remove type-defined ones — "additive override": the type is the floor, not the ceiling.
+- **The custom-field join carries `required` and `sort_order`.** `spree_product_type_custom_field_definitions` determines which definitions a type uses, whether they're required, and display order. This is the schema enforcement layer.
- **Prefix ID: `pt_`.** Replaces `proto_`.
-- **No shared value pools in this phase.** Metafield values remain per-resource strings (no shared AttributeValue rows). Faceted filtering via shared pools is a future enhancement tracked in Open Questions.
+- **No shared value pools in this phase.** Custom-field values remain per-resource strings. Faceted filtering via shared pools stays in Open Questions.
- **ProductType is optional.** Products without a type work exactly as today. Type enforcement is additive, not breaking.
-- **ProductType is immutable on product after creation.** Changing a product's type would invalidate its metafield values. Block type changes once metafields are assigned. One-time exception: the 6.0 data migrations may assign an initial type to products that have none (see fulfillment-types addendum below) — immutability applies from then on.
-- **ProductType carries `fulfillment_types`** (addendum 2026-07-27, required by `6.0-fulfillment-and-delivery.md`) — see "Fulfillment types" under Design Details. This makes ProductType the replacement for `ShippingCategory`, so `6.0-fulfillment-and-delivery.md` now hard-depends on this plan shipping first.
+- **ProductType is immutable on product after creation — and deletion honors the same invariant.** Changing a product's type would invalidate its custom-field values, so type changes are blocked at the model level once custom fields are assigned; `has_many :products, dependent: :restrict_with_error` blocks deleting a type that products still use (deletion *is* a type change to nil — the previous `dependent: :nullify` contradicted this decision and would have bypassed the guard via `update_all`). One-time exception: the 6.0 data migrations may assign an initial type to products that have none (see fulfillment-types addendum); immutability applies from then on.
+- **ProductType carries `fulfillment_types`** (addendum 2026-07-27, required by `6.0-fulfillment-and-delivery.md`) — see "Fulfillment types" under Design Details. **This plan's Phase 1 owns the column** (previously orphaned: neither plan's migration created it, which would have silently broken digital checkout eligibility — `attribute` on a missing column is a virtual attribute that persists nothing).
+- **`name` is translatable** — `TRANSLATABLE_FIELDS = %i[name]` + Mobility `translates` + a `spree_product_type_translations` table + registration in `Spree.translatable_resources`, so ProductType appears in the `5.5-6.0-resource-translations-api.md` discovery and batch endpoints. (The `include Spree::TranslatableResource` alone is not enough — verified against Product/Taxon.)
## Design Details
@@ -47,38 +50,58 @@ class Spree::ProductType < Spree.base_class
has_prefix_id :pt
include Spree::Metadata
- include Spree::Metafields
- include Spree::TranslatableResource # translatable name
+ include Spree::Metafields # becomes Spree::HasCustomFields in the rename wave
+ include Spree::TranslatableResource
+ include Spree::SingleStoreResource
+
+ TRANSLATABLE_FIELDS = %i[name].freeze
+ translates(*TRANSLATABLE_FIELDS, column_fallback: Spree.mobility_column_fallback)
+
+ belongs_to :store, class_name: 'Spree::Store'
# Existing (renamed join tables)
has_many :option_type_product_types, class_name: 'Spree::OptionTypeProductType', dependent: :destroy
has_many :option_types, through: :option_type_product_types
has_many :product_type_categories, class_name: 'Spree::ProductTypeCategory', dependent: :destroy
- has_many :categories, through: :product_type_categories # taxons until 6.0 rename
+ has_many :categories, through: :product_type_categories # class_name flips Taxon→Category in the categories rename wave
# New
- has_many :product_type_metafield_definitions, class_name: 'Spree::ProductTypeMetafieldDefinition',
+ has_many :product_type_custom_field_definitions, class_name: 'Spree::ProductTypeCustomFieldDefinition',
dependent: :destroy
- has_many :metafield_definitions, through: :product_type_metafield_definitions
+ has_many :custom_field_definitions, through: :product_type_custom_field_definitions
+
+ # restrict, not nullify — deletion honors the immutability invariant and keeps products_count honest
+ has_many :products, class_name: 'Spree::Product', dependent: :restrict_with_error
+
+ validates :name, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
+ validates :store, presence: true, unless: -> { Spree::Config[:disable_store_presence_validation] }
+ validates :fulfillment_types, presence: true
+
+ attribute :fulfillment_types, default: ['shipping'] # model-level default; column has none (CLAUDE.md rule)
- has_many :products, class_name: 'Spree::Product', dependent: :nullify
+ self.whitelisted_ransackable_attributes = %w[name]
+ self.whitelisted_ransackable_associations = %w[option_types]
- validates :name, presence: true
+ def digital? = fulfillment_types == ['digital']
+ def requires_shipping? = fulfillment_types.include?('shipping')
end
```
+ProductType must also be registered in `Spree.metafields.enabled_resources` (its own `include Spree::Metafields` is rejected by the definition `resource_type` validation otherwise) and in `Spree.translatable_resources`.
+
```ruby
-# New join table: which metafield definitions does this type require?
-class Spree::ProductTypeMetafieldDefinition < Spree.base_class
+# New join: which custom field definitions does this type require?
+class Spree::ProductTypeCustomFieldDefinition < Spree.base_class
belongs_to :product_type, class_name: 'Spree::ProductType'
- belongs_to :metafield_definition, class_name: 'Spree::MetafieldDefinition'
+ belongs_to :custom_field_definition, class_name: 'Spree::CustomFieldDefinition'
- validates :product_type, :metafield_definition, presence: true
- validates :metafield_definition_id, uniqueness: { scope: :product_type_id }
+ validates :product_type, :custom_field_definition, presence: true
+ validates :custom_field_definition_id, uniqueness: { scope: :product_type_id }
+ validate :same_store # definition.store_id must match product_type.store_id
+ # (once 6.0-store-scoped-custom-field-definitions.md lands)
- # Schema enforcement
- attribute :required, :boolean, default: false
+ attribute :required, :boolean, default: false # defaults are model-level, not DB
attribute :sort_order, :integer, default: 0
scope :required, -> { where(required: true) }
@@ -101,14 +124,13 @@ class Spree::OptionTypeProductType < Spree.base_class
private
- # Add option type to all products of this type that don't already have it
def add_option_type_to_products
product_type.products.find_each do |product|
product.option_types << option_type unless product.option_types.include?(option_type)
end
end
- # Remove option type from products — only if no variants use values from it
+ # Remove from products — only if no variants use values from it
def remove_option_type_from_products
product_type.products.find_each do |product|
has_variants_using = product.variants.joins(:option_values)
@@ -125,11 +147,12 @@ end
```ruby
# Renamed from Spree::PrototypeTaxon
class Spree::ProductTypeCategory < Spree.base_class
- belongs_to :category, class_name: 'Spree::Taxon' # Taxon until 6.0 rename
+ belongs_to :category, class_name: 'Spree::Taxon' # flips to 'Spree::Category' in the categories rename wave
belongs_to :product_type, class_name: 'Spree::ProductType'
validates :product_type, :category, presence: true
validates :product_type_id, uniqueness: { scope: :category_id }
+ validate :same_store # once Category is store-owned (categories plan)
end
```
@@ -137,24 +160,20 @@ end
```ruby
class Spree::Product < Spree.base_class
- belongs_to :product_type, class_name: 'Spree::ProductType', optional: true
+ belongs_to :product_type, class_name: 'Spree::ProductType', optional: true,
+ counter_cache: :products_count
- # Remove: attr_accessor :prototype_id
- # On creation, sync option_types + categories from type
+ # Remove: attr_accessor :prototype_id + add_associations_from_prototype
+ # (also remove :prototype_id from Spree::PermittedAttributes.product_attributes)
after_create :sync_associations_from_product_type
- # New: validate required metafields on completion/activation
- validate :required_metafields_present, if: :active?
-
- # Prevent removing option types that come from the product type
+ validate :required_custom_fields_present, if: :active?
validate :type_option_types_present, if: :product_type
- # Check if an option type is inherited from the product type (cannot be removed)
def type_option_type?(option_type)
product_type&.option_types&.include?(option_type)
end
- # Returns option types added beyond what the product type provides
def extra_option_types
return option_types unless product_type
@@ -163,33 +182,27 @@ class Spree::Product < Spree.base_class
private
+ # ADDITIVE — deliberately unlike today's prototype callback, which REPLACES
+ # option_types/taxons by assignment (product.rb:870-871)
def sync_associations_from_product_type
return unless product_type
- # Add type's option types (additive — keeps any already assigned)
- product_type.option_types.each do |ot|
- option_types << ot unless option_types.include?(ot)
- end
-
- # Add type's categories (additive)
- product_type.categories.each do |cat|
- taxons << cat unless taxons.include?(cat)
- end
+ product_type.option_types.each { |ot| option_types << ot unless option_types.include?(ot) }
+ product_type.categories.each { |cat| taxons << cat unless taxons.include?(cat) }
end
def type_option_types_present
- missing = product_type.option_types - option_types
- missing.each do |ot|
+ (product_type.option_types - option_types).each do |ot|
errors.add(:option_types, "cannot remove type-defined option type: #{ot.name}")
end
end
- def required_metafields_present
+ def required_custom_fields_present
return unless product_type
- product_type.product_type_metafield_definitions.required.each do |ptmd|
- unless has_metafield?(ptmd.metafield_definition)
- errors.add(:base, "Missing required metafield: #{ptmd.metafield_definition.name}")
+ product_type.product_type_custom_field_definitions.required.each do |join|
+ unless has_custom_field?(join.custom_field_definition)
+ errors.add(:base, "Missing required custom field: #{join.custom_field_definition.name}")
end
end
end
@@ -203,88 +216,70 @@ GET /api/v3/admin/product_types
POST /api/v3/admin/product_types
GET /api/v3/admin/product_types/:id
PATCH /api/v3/admin/product_types/:id
-DELETE /api/v3/admin/product_types/:id
+DELETE /api/v3/admin/product_types/:id # 422 while products still use the type (restrict_with_error)
```
-Response shape (flat, prefixed IDs):
+Scoped through `current_store.product_types`. Response shape (flat, real prefixed IDs — OptionType is `opt_`, definitions are `cfdef_`):
+
```json
{
"id": "pt_k5nR8xLq",
"name": "T-Shirt",
- "option_type_ids": ["ot_abc", "ot_def"],
+ "fulfillment_types": ["shipping"],
+ "option_type_ids": ["opt_abc", "opt_def"],
"category_ids": ["ctg_xyz"],
- "metafield_definitions": [
- { "id": "mfdef_123", "key": "material", "namespace": "product", "required": true, "sort_order": 0 },
- { "id": "mfdef_456", "key": "care_instructions", "namespace": "product", "required": false, "sort_order": 1 }
+ "custom_field_definitions": [
+ { "id": "cfdef_123", "key": "material", "namespace": "product", "required": true, "sort_order": 0 },
+ { "id": "cfdef_456", "key": "care_instructions", "namespace": "product", "required": false, "sort_order": 1 }
],
"products_count": 142
}
```
+`products_count` is a real counter-cache column (added in Phase 1), not a per-row query. Writes use a nested replace-set payload mirroring the option-values-on-OptionType precedent — read and write field names match:
+
+```json
+PATCH /api/v3/admin/product_types/:id
+{ "custom_field_definitions": [ { "id": "cfdef_123", "required": true, "sort_order": 0 } ] }
+```
+
### Store API
-ProductType exposed as read-only `product_type` expand on products:
+Read-only `product_type` expand on products:
+
```
GET /api/v3/store/products/:id?expand=product_type
+→ "product_type": { "id": "pt_k5nR8xLq", "name": "T-Shirt" }
```
-```json
-{
- "id": "prod_86Rf07xd4z",
- "name": "Classic Tee",
- "product_type": {
- "id": "pt_k5nR8xLq",
- "name": "T-Shirt"
- }
-}
-```
-
-### Admin UI (React SPA)
+### Admin surface (React dashboard — no Rails admin in 6.0)
-When editing a product with a ProductType:
-1. Query ProductType's `option_types` and `metafield_definitions` (with `required` and `sort_order`)
-2. Show type-defined option types as locked (cannot remove), extra option types as removable
-3. Render metafield form fields in `sort_order`, grouped by namespace
-4. Show required indicators on required fields
-5. Validate required metafields before allowing product activation
+Admin API + `@spree/admin-sdk` `productTypes` resource + dashboard pages (list under products settings, edit page with option-type picker, category picker, and a sortable custom-field-definitions editor with `required` toggles — dnd-kit reorder per house convention, i18n keys in all locale files, `<Can>` gating).
-When creating a product:
-1. Optional ProductType selector
-2. Selecting a type adds the type's option types and categories (live — not just a copy)
-3. Shows the metafield form immediately
+Product form behavior:
+1. Type-defined option types render locked (cannot remove); extra option types removable.
+2. Custom-field form fields render in `sort_order`, grouped by namespace, with required indicators; required fields validated before activation.
+3. Creating a product: optional ProductType selector; selecting a type attaches its option types and categories (live — not a copy).
-When editing a ProductType:
-1. Adding an option type propagates to all products of that type
-2. Removing an option type removes it from products (blocked if variants use values from it)
-3. UI shows affected product count before confirming destructive changes
+ProductType editing:
+1. Adding an option type propagates to all products of the type.
+2. Removing one is blocked per-product where variants use its values.
+3. The UI shows affected product counts before destructive changes — **including deletion**, which is refused while products use the type (reassign first).
### Fulfillment types (addendum 2026-07-27)
`ShippingCategory` is dropped in 6.0 (`6.0-fulfillment-and-delivery.md`); its only real job — "which delivery methods may serve this product?" — moves here:
-```ruby
-class Spree::ProductType < Spree.base_class
- # JSON array (jsonb-guarded per CLAUDE.md), e.g. ["shipping"], ["digital"],
- # ["shipping", "pickup", "local_delivery"]
- attribute :fulfillment_types, default: ['shipping']
-
- validates :fulfillment_types, presence: true
-
- def digital? = fulfillment_types == ['digital']
- def requires_shipping? = fulfillment_types.include?('shipping')
-end
-```
-
-- **Products without a ProductType default to `['shipping']`** — this is the reconciliation between optional ProductType and today's effectively-mandatory ShippingCategory (every product presence-validates one). Most of the catalog rides the default and needs no type.
-- The fulfillment plan's data migration creates/assigns types **only where the category carried signal** — i.e. products in a digital shipping category get a `Digital` ProductType (`fulfillment_types: ['digital']`). This is the sanctioned one-time initial assignment noted in Key Decisions; it does not violate immutability, which governs *changes* after a type is set.
-- `Product#digital?` / `#fulfillment_types` re-implement on top of this (they currently derive from ShippingCategory → calculator class, a four-hop chain).
-- Delivery-method eligibility semantics (matching `fulfillment_types` against `DeliveryMethod#fulfillment_type`, per-product exclusions) are owned by `6.0-fulfillment-and-delivery.md`, not this plan.
+- `fulfillment_types` JSON column on `spree_product_types` (**created in this plan's Phase 1**, jsonb-guarded, nullable — the `['shipping']` default is model-level), e.g. `["shipping"]`, `["digital"]`, `["shipping", "pickup", "local_delivery"]`.
+- **Products without a ProductType default to `['shipping']`** — the reconciliation between optional ProductType and today's effectively-mandatory ShippingCategory (every product presence-validates one, with auto-assignment).
+- The fulfillment plan's data migration creates/assigns types **only where the category carried signal** — products in a digital shipping category get a `Digital` ProductType (`fulfillment_types: ['digital']`). This is the sanctioned one-time initial assignment; it doesn't violate immutability, which governs *changes* after a type is set.
+- `Product#digital?` re-implements on top of this (today it's a four-hop chain through ShippingCategory → shipping-method scope → calculator class). `Product#fulfillment_types` is **net-new** surface — no such method exists today.
+- Delivery-method eligibility semantics (matching against `DeliveryMethod#fulfillment_type`, per-product exclusions) are owned by `6.0-fulfillment-and-delivery.md`, not this plan.
## Migration Path
-### Phase 1: Rename (non-breaking)
+### Phase 1: Rename + schema
-Single migration:
```ruby
class RenamePrototypesToProductTypes < ActiveRecord::Migration[7.2]
def change
@@ -292,94 +287,116 @@ class RenamePrototypesToProductTypes < ActiveRecord::Migration[7.2]
rename_table :spree_option_type_prototypes, :spree_option_type_product_types
rename_table :spree_prototype_taxons, :spree_product_type_categories
- # Rename FK columns in join tables
rename_column :spree_option_type_product_types, :prototype_id, :product_type_id
rename_column :spree_product_type_categories, :prototype_id, :product_type_id
rename_column :spree_product_type_categories, :taxon_id, :category_id
- # Add persistent FK on products
- add_column :spree_products, :product_type_id, :bigint
- add_index :spree_products, :product_type_id
+ add_reference :spree_products, :product_type, index: true # PK-type agnostic
+ add_reference :spree_product_types, :store, index: true
+
+ # fulfillment_types — owned here (see addendum); nullable, no DB default
+ if connection.adapter_name.downcase.include?('postgresql')
+ add_column :spree_product_types, :fulfillment_types, :jsonb
+ else
+ add_column :spree_product_types, :fulfillment_types, :json
+ end
+
+ add_column :spree_product_types, :products_count, :integer
+
+ # match the model's uniqueness validation (the option-type join already has one)
+ remove_index :spree_product_type_categories, [:product_type_id, :category_id]
+ add_index :spree_product_type_categories, [:product_type_id, :category_id], unique: true
+
+ create_table :spree_product_type_translations do |t|
+ t.string :name
+ t.string :locale, null: false
+ t.references :product_type, null: false
+ t.timestamps
+ end
+ add_index :spree_product_type_translations, [:product_type_id, :locale], unique: true
end
end
```
-Model files:
-- Rename `prototype.rb` → `product_type.rb`
-- Rename `option_type_prototype.rb` → `option_type_product_type.rb`
-- Rename `prototype_taxon.rb` → `product_type_category.rb`
-- Add `Spree::Prototype = Spree::ProductType` alias in deprecation shim (remove in 6.1)
-- Update Product: replace `attr_accessor :prototype_id` with `belongs_to :product_type`
+Companion rake task (same wave, data never in migrations): backfill `store_id` → `Store.default`; delete orphaned join rows (today's Prototype associations carry no `dependent:` options, so orphans exist); `reset_counters` for `products_count`.
-### Phase 2: MetafieldDefinition association
+Code changes:
+- Rename `prototype.rb` → `product_type.rb`, `option_type_prototype.rb` → `option_type_product_type.rb`, `prototype_taxon.rb` → `product_type_category.rb`; `Spree::Prototype = Spree::ProductType` deprecation alias (remove in 6.1).
+- Rename the **inverse** associations too: `OptionType#option_type_prototypes`/`#prototypes` (`option_type.rb:47-48` — currently no `dependent:`, add `dependent: :destroy`) and `Taxon#prototype_taxons`/`#prototypes` (`taxon.rb:46-47`).
+- Product: replace `attr_accessor :prototype_id` + `add_associations_from_prototype` with `belongs_to :product_type`; **remove `:prototype_id` from `Spree::PermittedAttributes.product_attributes`** (`permitted_attributes.rb:188`).
+- Remove the dangling `platform_prototype_serializer` registration (`api/lib/spree/api/dependencies.rb:301` — points at a class that doesn't exist).
+- Registries: add `Spree::ProductType` to `Spree.metafields.enabled_resources` and `Spree.translatable_resources`.
+- Locale keys (core `en.yml` prototype keys → product_type; the dead `new_prototype` key in the legacy admin dies with `spree/admin`), factories (`prototype_factory` → `product_type_factory` with one-release aliases — `testing_support` is public API), specs (`prototype_spec`, `product_spec.rb:444-493` callback tests).
+
+### Phase 2: Custom-field-definition join
```ruby
-class CreateSpreeProductTypeMetafieldDefinitions < ActiveRecord::Migration[7.2]
+class CreateSpreeProductTypeCustomFieldDefinitions < ActiveRecord::Migration[7.2]
def change
- create_table :spree_product_type_metafield_definitions do |t|
+ create_table :spree_product_type_custom_field_definitions do |t|
t.references :product_type, null: false
- t.references :metafield_definition, null: false
- t.boolean :required, null: false, default: false
- t.integer :sort_order, null: false, default: 0
+ t.references :custom_field_definition, null: false
+ t.boolean :required, null: false # defaults live on the model, not the DB
+ t.integer :sort_order, null: false
t.timestamps
end
- add_index :spree_product_type_metafield_definitions,
- [:product_type_id, :metafield_definition_id],
+ add_index :spree_product_type_custom_field_definitions,
+ [:product_type_id, :custom_field_definition_id],
unique: true,
- name: 'idx_product_type_metafield_defs_unique'
+ name: 'idx_product_type_cf_defs_unique'
end
end
```
-### Phase 3: Admin API + serializers + typelizer
+The column name is born correct even though the definitions table is still `spree_metafield_definitions` until the rename wave — no FK constraints exist (house rule), so nothing binds the names.
+
+### Phase 3: Admin API + serializers + SDK
-- Add `ProductTypeSerializer` (Store + Admin)
-- Add `ProductTypeMetafieldDefinitionSerializer`
-- Add `product_type` expand to `ProductSerializer`
-- Admin CRUD controller
-- Run typelizer pipeline
+- `ProductTypeSerializer` (Store + Admin), `ProductTypeCustomFieldDefinitionSerializer`, `product_type` expand on `ProductSerializer`
+- Admin CRUD controller (store-scoped), nested `custom_field_definitions` write payload
+- `@spree/admin-sdk` `productTypes` resource; typelizer → Zod → OpenAPI pipeline
-### Phase 4: Admin UI integration
+### Phase 4: React dashboard
-- ProductType management CRUD pages
-- Product form: type selector, dynamic metafield form from type definition
-- Required metafield validation on product activation
+- ProductType list + edit pages; product form integration (locked type option types, dynamic custom-field form from the type definition, required-field validation on activation); i18n in all locale files.
-### Rake task: backfill product_type_id
+### Rake task: backfill product_type_id (advisory)
-For merchants who used Prototype at creation time and want to recover the association:
```ruby
# rake spree:backfill_product_types
# Looks at products sharing the same set of option_types and suggests type assignments
```
-This is advisory, not automatic — product_type_id stays nullable.
+Advisory, not automatic — `product_type_id` stays nullable. (Realistically a small population: prototypes have had no admin UI for some time, so few installs carry meaningful prototype data.)
## Constraints on Current Work
-- **Do not remove Prototype model yet.** It will be renamed, not deleted. Don't add new features to it either.
-- **Do not add `prototype_id` as a persisted column.** The rename migration will add `product_type_id` instead.
-- **New MetafieldDefinitions should be resource_type-aware.** When creating definitions intended for products, use `resource_type: 'Spree::Product'` — this will matter when ProductType filters which definitions are available.
-- **Don't create a separate Attribute/Property system.** Everything builds on existing Metafields. No new EAV tables.
-- **Don't build new Product ↔ OptionType management that bypasses ProductType.** New admin UI for managing a product's option types should be type-aware: type-defined option types are locked, only extra option types can be freely added/removed.
-
-## Open Questions
-
-1. **Shared value pools for faceted filtering.** Currently metafield values are per-resource strings. For efficient faceted navigation (count products by "Color = Red"), we'd need shared value rows for choice-type metafields (e.g., dropdown/select types). This is a significant addition — should it be a future phase of this plan or a separate plan?
+- **Do not remove Prototype yet.** It will be renamed, not deleted. Don't add features to it either.
+- **Do not add `prototype_id` as a persisted column.** The rename adds `product_type_id` instead.
+- **All new code around this feature uses custom-field vocabulary** (`custom_field_definition`, `has_custom_field?`, `cfdef_`) — never metafield naming (see `5.4-6.0-custom-fields-rename.md` constraints).
+- **New CustomFieldDefinitions should be resource_type-aware** (`resource_type: 'Spree::Product'` for product-intended definitions).
+- **Don't create a separate Attribute/Property system.** Everything builds on custom fields. No new EAV tables.
+- **Don't build Product ↔ OptionType management that bypasses ProductType.** Type-defined option types are locked; only extras are freely managed.
-2. **Variant-level metafield definitions on ProductType.** Some platforms distinguish product-level vs variant-level attributes on the ProductType join. Should `ProductTypeMetafieldDefinition` carry a `level` column (`:product` or `:variant`)? OptionTypes already handle the variant dimension identity, so variant-level metafields would be descriptive metadata per variant (e.g., "variant weight note"). Defer or include?
+## Resolved Questions
-3. **ProductType immutability enforcement.** Should changing `product_type_id` on a product be blocked at the model level, or just warned in the admin UI? We could allow it if no type-specific metafields have been set yet.
+1. **Immutability is enforced at the model level, including deletion** (2026-07-27, closing former Open Question 3): type changes are blocked once custom fields are assigned; `dependent: :restrict_with_error` blocks deletion while products use the type; migrations get the one-time initial-assignment exception.
+2. **ProductType is store-owned** (2026-07-27): global types joining store-scoped definitions/categories onto store-owned products would be cross-tenant; same-store validations on both joins; Admin API scoped via `current_store`.
+3. **Born-correct custom-field naming** (2026-07-27): the join model/table/FK/API surface use custom-field vocabulary from birth; the 5.5 constant alias makes this implementable before the 6.0 rename wave.
+4. **This plan owns the `fulfillment_types` column** (2026-07-27): previously orphaned between this plan and the fulfillment plan; now in Phase 1.
-4. **Store API filtering by ProductType.** Should `GET /api/v3/store/products?filter[product_type_id]=pt_xxx` be a first-class filter? Useful for storefronts that want to show type-specific browse pages.
+## Open Questions
-5. **Option type removal safety.** When removing an option type from a ProductType, the current design skips products whose variants use values from that option type. Should the admin API return a list of blocked products so the admin can resolve them, or should it hard-block the removal entirely until all variants are cleaned up?
+1. **Shared value pools for faceted filtering.** Custom-field values are per-resource strings today; efficient faceted navigation ("count products by Color = Red") needs shared value rows for choice-type fields. Future phase here, or separate plan?
+2. **Variant-level definitions on ProductType.** Should `ProductTypeCustomFieldDefinition` carry a `level` column (`:product` / `:variant`)? OptionTypes already own variant identity; variant-level custom fields would be descriptive metadata. Defer or include?
+3. **Store API filtering by ProductType.** Should `GET /api/v3/store/products?filter[product_type_id]=pt_xxx` be first-class? Useful for type-specific browse pages.
+4. **Option type removal UX.** When removal is blocked per-product (variants use its values), should the Admin API return the blocked-product list for resolution, or hard-block until variants are cleaned up?
## References
-- Current Prototype model: `spree/core/app/models/spree/prototype.rb`
-- Current Metafield system: `spree/core/app/models/spree/metafield.rb`, `spree/core/app/models/spree/metafield_definition.rb`
+- Current Prototype model: `spree/core/app/models/spree/prototype.rb` (15 lines; consumers: `product.rb:137, 485, 868-873`, `permitted_attributes.rb:188`, `prototype_factory.rb`, dangling `api/lib/spree/api/dependencies.rb:301`)
+- Current custom-field system: `spree/core/app/models/spree/metafield.rb`, `metafield_definition.rb` (aliased as `Spree::CustomField`/`CustomFieldDefinition` since 5.5)
- Legacy Product Properties (extracted): [github.com/spree/spree_legacy_product_properties](https://github.com/spree/spree_legacy_product_properties)
-- Architecture review: Spree core model analysis (2026-03-16)
-- Related plan: `6.0-cart-order-split.md`
+- Related plans: `6.0-fulfillment-and-delivery.md` (hard consumer of `fulfillment_types`), `5.4-6.0-custom-fields-rename.md`, `6.0-store-scoped-custom-field-definitions.md`, `6.0-replace-taxons-with-categories.md` (pre-approves `ProductTypeCategory`; owns the `class_name` flip and the migrated-taxon join cleanup), `5.5-6.0-resource-translations-api.md`, `6.0-admin-api.md` (reserves `/product_types` + `pt_`)
+- Architecture review: Spree core model analysis (2026-03-16); plan verification review (2026-07-27)
diff --git a/docs/plans/6.0-replace-taxons-with-categories.md b/docs/plans/6.0-replace-taxons-with-categories.md
index 0882b88100..2f27ae1d3b 100644
--- a/docs/plans/6.0-replace-taxons-with-categories.md
+++ b/docs/plans/6.0-replace-taxons-with-categories.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.0 (5.5 ships the `Spree::Category` alias + Category API surface; 6.0 renames the table and adds `Collection`)
**Depends on:** API v3 conventions, ProductType plan (6.0-product-types.md)
**Author:** Damian + Claude
-**Last updated:** 2026-05-20
+**Last updated:** 2026-07-27
## Summary
@@ -398,8 +398,15 @@ end
# - Root category keeps the taxonomy name
# - Remove taxonomy_id column references
# 4. Drop taxonomy_id from categories
+# 5. Clean spree_product_type_categories (6.0-product-types.md): delete or
+# re-point rows whose taxon moved to spree_collections or was a deleted
+# taxonomy root — otherwise dangling category_id FKs survive the split
```
+Also owned by this plan's rename wave: flip `Spree::ProductTypeCategory`'s
+`belongs_to :category, class_name: 'Spree::Taxon'` to `'Spree::Category'`
+(the product-types plan ships before this rename and cannot do it itself).
+
### Phase 3: Model renames + deprecation aliases
- `Spree::Taxon` → `Spree::Category` (alias `Spree::Taxon = Spree::Category` for one release)
diff --git a/docs/plans/6.0-store-scoped-custom-field-definitions.md b/docs/plans/6.0-store-scoped-custom-field-definitions.md
index 5116f8ba6d..721e266caf 100644
--- a/docs/plans/6.0-store-scoped-custom-field-definitions.md
+++ b/docs/plans/6.0-store-scoped-custom-field-definitions.md
@@ -84,6 +84,7 @@ misalign:
| `Spree::Metafields.ensure_metafield_definition_exists!` | auto-creates — needs a store |
| `Spree::Metafields#resolve_metafield_definition_id_from_string` | auto-creates via the `"namespace.key"` form |
| `Api::V3::Admin::CustomFieldDefinitionsController#scope` | currently unscoped — cross-store read/write |
+| `Spree::ProductTypeCustomFieldDefinition` (`6.0-product-types.md`) | the ProductType↔definition join validates same-store (`definition.store_id == product_type.store_id`) — ProductType is store-owned in the same release |
### Backfill