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.

Rescope ProductType to a creation-time template

Damian Legawiec391a84eda5e5
diff --git a/CLAUDE.md b/CLAUDE.md
index 3775964f61..bfd00d670a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,7 +16,7 @@ Active plans (6.0 target, work pending):
- `6.0-cart-order-split.md` — Cart/Order model separation, dual-FK owner everywhere (`cart_id`/`order_id` exactly-one, `#owner` as method — NOT polymorphic), idempotent copy-on-completion (`Order#cart_id` unique, order-before-payment), Order state machine removed (Checkout::Requirements for steps; payment/fulfillment statuses derived-then-persisted via one recompute service). **Shipped to 6-0-dev (feature/6-0-core-rewrite Waves 1+5):** Cart owns checkout end to end, machine + `spree_orders.state` gone, `Carts::Complete` three-phase pipeline live, `Orders::UpdateStatuses` sole status writer; only Wave 7 data migration (incomplete orders → carts) remains
- `6.0-admin-api.md` — Admin REST API conventions, auth, endpoint list (~300 endpoints)
- `6.0-admin-spa.md` — React admin architecture, extension points, table registry, i18n + server-error mapping
-- `6.0-product-types.md` — Prototype → ProductType rename, MetafieldDefinition schema enforcement
+- `6.0-product-types.md` — Prototype → ProductType rename, custom-field schema enforcement. **Creation-time template (2026-08-06):** type edits never mutate existing products (custom-field form/validation + `fulfillment_types` are live by reference; option types/categories seed additively at attach; explicit previewed `ApplyToProducts` job is the only bulk path); per-product type detach/reassign allowed (non-destructive), required fields validate at activation only, no Store API exposure. **Shipped:** Phases 1+3, most of 4; Phase 2 (rescoped) is the delivery checklist in the plan
- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product. **Shipped to 6-0-dev (PR #14265):** is_master removed from all models, default_variant_id + `spree:remove_master_variant` data-migration rake landed; only the physical is_master column drop remains (6.1 cleanup).
- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs
- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard
diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.md
index c5b9476b62..545814fe3c 100644
--- a/docs/plans/6.0-fulfillment-and-delivery.md
+++ b/docs/plans/6.0-fulfillment-and-delivery.md
@@ -100,6 +100,8 @@ Replacement semantics:
**Modality vs segment.** New fulfillment types are for genuinely new delivery *modalities* (need provider code anyway — the initializer is the smallest part of the work). Product *segments* ("oversized", "fragile") should NOT become custom types: model them with `DeliveryMethodRule` (weight/item-total/excluded-products — merchant-manageable in the dashboard, registry `Spree.delivery_method_rules` for custom rules; the former `Product#excluded_delivery_method_ids` column is gone per the 2026-08-06 decision — one-off subtractions are `ExcludedProductsRule`). The Wave 7 shipping→delivery data migration MAY mint custom tokens for 5.x shipping categories whose method bindings actually narrow (a category not served by all methods) — flattening those to `'shipping'` would silently widen eligibility — but that token-minting is a compatibility measure, not recommended modeling; the migration task must print the `Spree.fulfillment_types += [...]` initializer line for every token it mints.
+**Named delivery groups — the if-needed 6.1 successor to profiles (2026-08-06).** ShippingCategory stays removed even though the removal is unreleased. Competitor context, stated honestly: Medusa's ShippingProfile and Shopify's shipping profiles are the same design as ShippingCategory (product-level FK to a named group, options scoped to the group, carts split per group) — so per-product delivery grouping entities are common; what the 6.0 stack replaces them with covers all three of the category's jobs (eligibility via `fulfillment_types` matching, splitting via `Splitter::FulfillmentType`, per-product restrictions via `excluded_delivery_method_ids`). The one genuine loss is the *named grouping as a management surface*: tagging 1,000 products "Oversized" once beats maintaining a per-product exclusion denylist (inverted logic, worse ergonomics at scale). If real merchant demand materializes, the comeback is NOT the old category (mandatory column, join table to methods, digital-via-calculator hack) but an additive construct in existing machinery — a named eligibility/exclusion set that products reference, or a `DeliveryMethodRule` kind matching a product group. 6.1-if-needed, evidence first. Also clarified 2026-08-06: dropping the category loses nothing at the variant level — Spree never had a variant-level shipping category (`spree_variants` has no such column back through the consolidated 4.3 schema; `Variant#shipping_category` was pure product delegation; Solidus is the fork that added one). Mixed physical/digital within one product is a pre-existing gap, with the reserved relief valve recorded in `6.0-product-types.md` (per-product/per-variant `fulfillment_types` override, 6.1-if-needed).
+
### FulfillmentProvider is a strategy (not a DB model)
```ruby
diff --git a/docs/plans/6.0-product-types.md b/docs/plans/6.0-product-types.md
index 0779bd6561..40de3537d9 100644
--- a/docs/plans/6.0-product-types.md
+++ b/docs/plans/6.0-product-types.md
@@ -1,26 +1,35 @@
# ProductType (Prototype → ProductType)
-**Status:** Phases 1 and 3 shipped, Phase 4 partly; Phase 2 pending — see "Implementation status"
+**Status:** Phases 1 and 3 shipped, Phase 4 partly; Phase 2 (rescoped 2026-08-06) pending — see "Implementation status"
**Target:** Spree 6.0
**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
+**Last updated:** 2026-08-06
## Summary
-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.
+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 **creation-time template with live-by-reference schema** (semantics revised 2026-08-06, replacing the earlier "live template" design):
-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").
+- **Live by reference (no sync, no copies):** the custom-field form the dashboard renders, the required-field validation, and `fulfillment_types` delivery eligibility are all read from the type *at use time*. Editing the type's custom-field definitions updates every product form on next load with zero product rows touched.
+- **Seeded at attach time (additive, one-shot):** option types and categories are materialized state (join rows that variants and navigation hang off), so the type seeds them additively when a product is created with the type or a type is assigned later. Editing a type **never mutates existing products**; the only path from a type edit to existing products is the explicit, previewed, additive-only **"Apply to existing products"** action.
-This closes Spree's biggest functional gap in catalog modeling, while building on existing infrastructure rather than starting from scratch.
+This is the Shopify-shaped behavior (category changes affect nothing retroactively) with Saleor's schema value (type-driven forms and validation), and it closes Spree's biggest functional gap in catalog modeling while building on existing infrastructure rather than starting from scratch.
-## Implementation status (verified 2026-08-05)
+## Implementation status (verified 2026-08-05; semantics rescoped 2026-08-06)
-**Shipped:** Phase 1 (the `Spree::ProductType` model, both join models, `fulfillment_types` with registry-backed validation, `Product#product_type` + `#fulfillment_types` + `#digital?`), Phase 3 (admin API controller, Store + Admin serializers), and most of Phase 4 (dashboard settings page, product-types table, `product_type_id` on the product form).
+**Shipped:** Phase 1 (the `Spree::ProductType` model, both join models, `fulfillment_types` with registry-backed validation, `Product#product_type` + `#fulfillment_types` + `#digital?`), Phase 3 (admin API controller, Store + Admin serializers — the base `V3::ProductTypeSerializer` exists only as the admin serializer's parent class per house convention; it is not wired to any store endpoint), and most of Phase 4 (dashboard settings page, product-types table, `product_type_id` on the product form).
-**Pending:** Phase 2 — the `ProductTypeCustomFieldDefinition` join and everything resting on it, which is the schema-enforcement half of the plan: locked type-defined option types, the type-driven custom-field form, and required-field validation on activation.
+**Pending — the delivery checklist (Phase 2 as rescoped):**
-**ShippingCategory is fully retired from behavior (2026-08-05).** `ProductType#fulfillment_types` is the sole delivery-eligibility input — `Stock::Package#eligible_delivery_methods` reads it and nothing consults the category for routing. The CSV `shipping_category` column was cut outright rather than bridged (see `6.0-fulfillment-and-delivery.md`); `Product#shipping_category` survives only as a deprecated association, dropping with the table in 6.1.
+1. **Fix the seeding trigger (shipped-code gap).** `sync_associations_from_product_type` runs only `after_create` (`product.rb:162`) — assigning a type to an existing typeless product, or reassigning, silently skips the option-type/category seeding. Move to `after_save, if: :saved_change_to_product_type_id?` (covers create, later assignment, and reassignment; guard on `product_type` presence).
+2. **`ProductTypeCustomFieldDefinition` join** — migration + model (unchanged from the original Phase 2 design; no `level` column, see Key Decisions).
+3. **Required-field validation at activation only** — validate the type's required custom fields when a product transitions into `active`, never on ordinary saves of an already-active product.
+4. **`Apply to existing products`** — `POST /api/v3/admin/product_types/:id/apply_to_products`, additive-only service + background job, dashboard confirm dialog showing `products_count`.
+5. **Admin controller write surface** — permit `option_type_ids`, `category_ids`, and the nested `custom_field_definitions` payload (today only `name` + `fulfillment_types` are permitted). Replace-set writes on the type are safe: they edit the template only and never touch products.
+6. **Dashboard** — type-driven custom-field form on the product page (rendered from the type's definition list, `sort_order`, required indicators), the apply-action confirm, and "type edits affect new products only" messaging on the type edit page.
+7. **No immutability guard to remove** — the model-level type-change block from the superseded 2026-07-27 decision was never shipped; do not add it. Add specs covering detach/reassign being additive and non-destructive instead.
+
+**ShippingCategory is fully retired from behavior (2026-08-05).** `ProductType#fulfillment_types` is the sole delivery-eligibility input — `Stock::Package#eligible_delivery_methods` reads it and nothing consults the category for routing. The CSV `shipping_category` column was cut outright rather than bridged (see `6.0-fulfillment-and-delivery.md`); `Product#shipping_category` survives only as a deprecated association, dropping with the table in 6.1. The removal is unreleased but stays (2026-08-06 decision) — see the fulfillment plan's "named delivery groups" note for the if-needed 6.1 successor to profile-style grouping.
## Problem
@@ -37,14 +46,19 @@ This closes Spree's biggest functional gap in catalog modeling, while building o
- **Rename only, no new table.** `Spree::Prototype` → `Spree::ProductType`, `spree_prototypes` → `spree_product_types`. Existing join tables renamed accordingly. No data loss.
- **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`.
+- **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 seeding 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.
+- **Creation-time template, not a live sync** (2026-08-06, reversing the 2026-07-27 "live template" decision after competitor review — Saleor is the only platform with live propagation, and only because attributes there have no existence outside the type; Shopify deliberately made category changes affect nothing retroactively). Two regimes by data nature:
+ - **Live by reference:** custom-field form generation, required-field validation, and `fulfillment_types` read the type at use time — they need no propagation to be "live".
+ - **Seeded additively at attach:** option types and categories are copied (additively) when a product gets the type — at creation or a later assignment. Editing a type never mutates existing products; there are **no propagation callbacks** on the join models, no locked option types, and no provenance tracking to maintain. Products manage their option types freely after seeding; the type is a template, not a contract.
+ - **Explicit apply action:** `ProductTypes::ApplyToProducts` (additive-only, idempotent, background job, previewed with the affected count) is the sole sanctioned path from a type edit to existing products — a deliberate bulk edit the merchant asks for by name, categorically different from a standing invariant mutating products as a side effect.
+- **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. **No `level` column** — variant-level definitions are deferred to 6.1 (2026-08-06); option types already own variant identity, and the column would be speculative schema.
+- **Required fields are enforced at activation only** (2026-08-06). The validation runs when a product transitions into `active`, never on ordinary saves of an already-active product — otherwise adding a required definition to a type instantly makes every existing active product of that type fail on its next save (the latent mass-mutation the live-by-reference half would otherwise reintroduce). Shopify precedent: definition validations apply to new writes only.
- **Prefix ID: `pt_`.** Replaces `proto_`.
-- **No shared value pools in this phase.** Custom-field values remain per-resource strings. Faceted filtering via shared pools stays in Open Questions.
+- **No shared value pools — ever, for custom fields** (2026-08-06, closing the former open question). Custom-field values remain per-resource strings. The split of roles, stated precisely: **predicate** search/sort/filter on those strings already ships storefront-side (5.6 — per-definition `searchable?`/`sortable?` flags, `SearchProvider::MetafieldSchema`, `with_metafield_filters` with Ransack-style predicates, in both Database and Meilisearch providers) and continues unchanged. **Faceted navigation over canonical values with counts** ("Color: Red (42)") is the OptionType/OptionValue role — value rows already shared, translatable, disjunctive facet counting shipped in 5.4 — and a value pool on custom fields would duplicate it. If demand for product-level descriptive facets emerges (the Vendure Facet / Saleor non-variant-attribute case), that is a new dedicated plan, not a custom-fields extension.
- **ProductType is optional.** Products without a type work exactly as today. Type enforcement is additive, not breaking.
-- **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.
+- **A product's type is changeable: explicit detach and reassign are allowed** (2026-08-06, reversing the 2026-07-27 hard-immutability decision — which was never shipped). Both are per-product, non-destructive operations: detach (type → nil) removes nothing — custom-field values survive as unstructured values, option types and categories stay; reassign is detach + attach — the new type's option types/categories seed additively and its required fields are checked at the next activation. Nothing in the system ever changes a product's type automatically. Deletion still honors the safe path: `has_many :products, dependent: :restrict_with_error` blocks deleting a type that products still use (reassign first). One-time exception: the 6.0 data migrations may assign an initial type to products that have none (see fulfillment-types addendum).
+- **ProductType is a back-office concept — no Store API exposure at all** (2026-08-06). Storefront navigation and filtering use categories and collections only. No store endpoint, no `expand=product_type`, no store filter param. The base `V3::ProductTypeSerializer` exists solely as the admin serializer's parent class (house convention).
- **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.)
@@ -79,7 +93,8 @@ class Spree::ProductType < Spree.base_class
dependent: :destroy
has_many :custom_field_definitions, through: :product_type_custom_field_definitions
- # restrict, not nullify — deletion honors the immutability invariant and keeps products_count honest
+ # restrict, not nullify — a type in use cannot be deleted (reassign products first);
+ # also 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 }
@@ -118,37 +133,14 @@ end
```
```ruby
-# Renamed from Spree::OptionTypePrototype
+# Renamed from Spree::OptionTypePrototype — a plain join. NO propagation
+# callbacks (2026-08-06): editing a type's option types edits the template only.
class Spree::OptionTypeProductType < Spree.base_class
belongs_to :option_type, class_name: 'Spree::OptionType'
belongs_to :product_type, class_name: 'Spree::ProductType'
validates :product_type, :option_type, presence: true
validates :product_type_id, uniqueness: { scope: :option_type_id }
-
- # Live template: propagate to all products of this type
- after_create :add_option_type_to_products
- after_destroy :remove_option_type_from_products
-
- private
-
- 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 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)
- .where(spree_option_values: { option_type_id: option_type.id })
- .exists?
- next if has_variants_using
-
- product.option_types.delete(option_type)
- end
- end
end
```
@@ -173,36 +165,28 @@ class Spree::Product < Spree.base_class
# 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
- validate :required_custom_fields_present, if: :active?
- validate :type_option_types_present, if: :product_type
+ # Seeds fire on create AND on any later assignment or reassignment —
+ # detach (nil) is a no-op, reassign seeds the new type additively.
+ after_save :sync_associations_from_product_type, if: :saved_change_to_product_type_id?
- def type_option_type?(option_type)
- product_type&.option_types&.include?(option_type)
- end
-
- def extra_option_types
- return option_types unless product_type
-
- option_types - product_type.option_types
- end
+ # Activation-only: never fails an ordinary save of an already-active product
+ validate :required_custom_fields_present, if: :becoming_active?
private
- # ADDITIVE — deliberately unlike today's prototype callback, which REPLACES
- # option_types/taxons by assignment (product.rb:870-871)
+ # ADDITIVE — deliberately unlike the legacy prototype callback, which REPLACED
+ # option_types/taxons by assignment. Never removes anything; a product that
+ # already has the option type or category is untouched.
def sync_associations_from_product_type
return unless product_type
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) }
+ product_type.categories.each { |cat| categories << cat unless categories.include?(cat) }
end
- def type_option_types_present
- (product_type.option_types - option_types).each do |ot|
- errors.add(:option_types, "cannot remove type-defined option type: #{ot.name}")
- end
+ def becoming_active?
+ active? && status_changed?
end
def required_custom_fields_present
@@ -217,6 +201,26 @@ class Spree::Product < Spree.base_class
end
```
+There is **no** `type_option_types_present` validation, no `type_option_type?`/`extra_option_types` helpers, and no locked rows — all artifacts of the superseded live-template design. After seeding, a product's option types are its own.
+
+### Apply to existing products
+
+```ruby
+# app/services — Tier 1 per 6.0-service-workflows.md. The ONLY path by which a
+# type edit reaches existing products. Additive and idempotent: safe to re-run,
+# never removes anything, never touches variants or option values.
+class Spree::ProductTypes::ApplyToProducts
+ def call(product_type:)
+ product_type.products.find_each do |product|
+ (product_type.option_types - product.option_types).each { |ot| product.option_types << ot }
+ (product_type.categories - product.categories).each { |cat| product.categories << cat }
+ end
+ end
+end
+```
+
+Invoked from the Admin API via a background job (`ProductTypes::ApplyToProductsJob`); the dashboard confirms with the type's `products_count` before enqueueing. Adding an option type to a product is safe by construction: existing variants simply have no values for it yet — no validation starts failing.
+
### Admin API
```
@@ -224,7 +228,8 @@ 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 # 422 while products still use the type (restrict_with_error)
+DELETE /api/v3/admin/product_types/:id # 422 while products still use the type (restrict_with_error)
+POST /api/v3/admin/product_types/:id/apply_to_products # 202; additive-only background job
```
Scoped through `current_store.product_types`. Response shape (flat, real prefixed IDs — OptionType is `opt_`, definitions are `cfdef_`):
@@ -244,35 +249,32 @@ Scoped through `current_store.product_types`. Response shape (flat, real prefixe
}
```
-`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:
+`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, and replace-set semantics are safe here because they edit the template only (no propagation):
```json
PATCH /api/v3/admin/product_types/:id
{ "custom_field_definitions": [ { "id": "cfdef_123", "required": true, "sort_order": 0 } ] }
```
-### Store API
+`apply_to_products` responds `202` with `{ "products_count": <n> }` so the client can message the scope of the job it just confirmed.
-Read-only `product_type` expand on products:
+### Store API
-```
-GET /api/v3/store/products/:id?expand=product_type
-→ "product_type": { "id": "pt_k5nR8xLq", "name": "T-Shirt" }
-```
+None (2026-08-06). ProductType is a back-office concept; storefront navigation and filtering use categories and collections only. No endpoint, no expand, no filter param. The base `V3::ProductTypeSerializer` exists solely as the parent class of `Admin::ProductTypeSerializer` (house convention: admin extends store-namespace base) and is not wired to any store surface.
### Admin surface (React dashboard — no Rails admin in 6.0)
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).
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).
+1. Option types and categories seeded by the type render like any others — nothing is locked; the merchant may remove or add freely after seeding.
+2. Custom-field form fields render from the type's **current** definition list in `sort_order`, grouped by namespace, with required indicators; required fields validated on activation only.
+3. Creating a product: optional ProductType selector; selecting a type seeds its option types and categories additively. Changing or clearing the type later is allowed (explicit, non-destructive; the form re-renders custom fields from the new type).
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).
+1. The edit page states plainly that changes affect **new products only** (plus the custom-field form/validation, which are live by reference).
+2. "Apply to existing products" is a separate explicit action with a confirm dialog showing `products_count` ("This adds this type's missing option types and categories to 1,204 products. Nothing is removed."), then enqueues the job.
+3. Deletion is refused while products use the type (reassign first); the UI shows `products_count` on the delete confirm.
### Fulfillment types (addendum 2026-07-27)
@@ -280,9 +282,10 @@ ProductType editing:
- `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.
+- 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.
- `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.
+- **Granularity (clarified 2026-08-06): product-level is not a regression.** Spree never had a variant-level shipping category — `spree_variants` has no `shipping_category_id` (verified back through the consolidated 4.3 schema); `Variant#shipping_category` was a pure delegation to the product. (Solidus is the fork that added a real variant-level column.) Mixed physical/digital within one product (hardcover + ebook) is a **pre-existing gap**, shared with Saleor, that Shopify/BigCommerce close at the variant level. The reserved relief valve, 6.1-if-needed: a nullable per-product (or per-variant) `fulfillment_types` override with the type as default — `Product#fulfillment_types`' reading chain already ends in a fallback, so the override slots in without breaking anything. Do not build it speculatively.
## Migration Path
@@ -336,7 +339,9 @@ Code changes:
- 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
+### Phase 2: Schema enforcement (rescoped 2026-08-06)
+
+The custom-field-definition join, plus the seeding/validation/apply work from the delivery checklist (Implementation status items 1–7):
```ruby
class CreateSpreeProductTypeCustomFieldDefinitions < ActiveRecord::Migration[7.2]
@@ -357,17 +362,19 @@ class CreateSpreeProductTypeCustomFieldDefinitions < ActiveRecord::Migration[7.2
end
```
-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.
+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. No `level` column (variant-level definitions deferred to 6.1).
+
+Also in this phase: the seeding-trigger fix (`after_create` → `after_save` on `saved_change_to_product_type_id?`), activation-only required validation, `ProductTypes::ApplyToProducts` + job + endpoint, and the admin controller's full write surface (`option_type_ids`, `category_ids`, nested `custom_field_definitions`).
### Phase 3: Admin API + serializers + SDK
-- `ProductTypeSerializer` (Store + Admin), `ProductTypeCustomFieldDefinitionSerializer`, `product_type` expand on `ProductSerializer`
-- Admin CRUD controller (store-scoped), nested `custom_field_definitions` write payload
+- `ProductTypeSerializer` (base + Admin), `ProductTypeCustomFieldDefinitionSerializer` — **no store-facing surface** (2026-08-06)
+- Admin CRUD controller (store-scoped), nested `custom_field_definitions` write payload, `apply_to_products` action
- `@spree/admin-sdk` `productTypes` resource; typelizer → Zod → OpenAPI pipeline
### Phase 4: React dashboard
-- 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.
+- ProductType list + edit pages (with the "affects new products only" messaging and the apply-action confirm); product form integration (seeded option types render as ordinary removable rows, dynamic custom-field form from the type definition, required-field validation surfaced at activation); i18n in all locale files.
### Rake task: backfill product_type_id (advisory)
@@ -385,26 +392,29 @@ Advisory, not automatic — `product_type_id` stays nullable. (Realistically a s
- **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.
+- **Editing a ProductType must never mutate existing products** except through the explicit `ApplyToProducts` action (additive-only, previewed, background job). No propagation callbacks on the join models — ever.
+- **Required-field validation runs at activation only.** Nothing may make an already-active product fail an ordinary save because its type gained a required definition.
+- **No Store API exposure of ProductType** — no endpoint, no expand, no filter. Storefronts see categories and collections only.
## Resolved Questions
-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.
+1. ~~**Immutability is enforced at the model level, including deletion** (2026-07-27)~~ — **superseded 2026-08-06** (see 5). Deletion handling survives: `dependent: :restrict_with_error` blocks deletion while products use the type; migrations keep 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.
+5. **Creation-time template semantics; type changes allowed** (2026-08-06, competitor review vs Saleor/Shopify/Medusa/Vendure): the type seeds option types/categories additively at attach and is live-by-reference for custom fields and fulfillment; editing a type never mutates existing products; the explicit `ApplyToProducts` action (shipping in 6.0 Phase 2) is the sole bulk path; per-product detach and reassign are explicit, non-destructive operations. This dissolves the former open question on option-type removal UX — removing an option type from a type no longer touches any product, so there is nothing to block or report.
+6. **Variant-level custom-field definitions deferred to 6.1** (2026-08-06): no `level` column in the 6.0 join — option types own variant identity, and speculative schema is against house rules. Unblocked by: concrete demand for templated variant metadata (revisit with the 6.1 catalog work).
+7. **No Store API exposure** (2026-08-06): ProductType is back-office vocabulary; storefront filtering/browse pages use categories and collections. The formerly planned `expand=product_type` on store products was never implemented and is cancelled.
+8. **No shared value pools for custom fields** (2026-08-06, closing the last open question): the question conflated two roles that are both already served. Predicate search/sort/filter on custom-field strings shipped in 5.6 (`SearchProvider::MetafieldSchema` + `with_metafield_filters`, storefront included) and stays string-based; faceted navigation over canonical values with counts is the OptionType/OptionValue role (disjunctive faceting shipped 5.4). Custom fields stay unstructured per-resource strings. Product-level descriptive facets (Vendure Facet / Saleor non-variant attributes), if ever demanded, get their own plan.
## Open Questions
-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?
+None — all settled; see Resolved Questions.
## References
- 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)
-- 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)
+- Related plans: `6.0-fulfillment-and-delivery.md` (hard consumer of `fulfillment_types`; owns the "named delivery groups" 6.1-if-needed note), `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); competitor review of template semantics — Saleor/Shopify/Medusa/Vendure (2026-08-06, recorded in `decisions.md`)
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index d4b24108ed..ba13fab77a 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,65 @@
+## 2026-08-06: ProductType is a creation-time template, not a live sync; type changes are allowed; no Store API exposure
+
+Competitor review (Saleor / Shopify / Medusa / Vendure) reversed the
+2026-07-27 "live template" and hard-immutability decisions in
+`6.0-product-types.md` before the unshipped Phase 2 built them. Saleor
+is the only platform with live propagation, and only because its
+attributes have no existence outside the type; Shopify — the largest
+merchant base on this problem — made category changes affect nothing
+retroactively. The settled semantics:
+
+- **Two regimes by data nature.** Custom-field form generation,
+ required-field validation, and `fulfillment_types` are **live by
+ reference** (read from the type at use time — no sync needed to be
+ "live"). Option types and categories are **seeded additively at
+ attach** (creation or later assignment); editing a type never mutates
+ existing products. No propagation callbacks, no locked option types,
+ no provenance tracking.
+- **One explicit bulk path:** `ProductTypes::ApplyToProducts` —
+ additive-only, idempotent, previewed with `products_count`, run as a
+ background job, shipping in 6.0 Phase 2. A deliberate bulk edit the
+ merchant asks for by name, never a side effect of editing a type.
+- **Required fields validate at activation only** — never on ordinary
+ saves of an already-active product, otherwise adding a required
+ definition to a type bricks every active product of that type on next
+ save (Shopify precedent: definition validations gate new writes only).
+- **A product's type is changeable**: explicit per-product detach and
+ reassign, both non-destructive (nothing deleted; custom-field values
+ survive as unstructured values; the new type seeds additively and its
+ required fields are checked at next activation). The immutability
+ guard was never shipped and will not be. Deleting a type in use stays
+ `restrict_with_error`.
+- **ProductType is back-office vocabulary — no Store API surface at
+ all** (no endpoint, no expand, no filter). Storefronts see categories
+ and collections only. The planned `expand=product_type` was never
+ implemented and is cancelled.
+- **Variant-level custom-field definitions deferred to 6.1** (no
+ speculative `level` column in the join).
+- **No shared value pools for custom fields — the plan's last open
+ question, closed.** Both roles it conflated are already served:
+ predicate search/sort/filter on custom-field strings shipped in 5.6
+ (`SearchProvider::MetafieldSchema` + `with_metafield_filters`,
+ storefront included) and stays string-based; faceted navigation over
+ canonical values with counts is the OptionType/OptionValue role
+ (disjunctive faceting shipped 5.4). Product-level descriptive facets
+ (Vendure Facet / Saleor non-variant attributes), if ever demanded,
+ get their own dedicated plan — never a custom-fields extension.
+
+Adjacent, same review: **ShippingCategory stays removed** despite the
+removal being unreleased. Medusa's ShippingProfile / Shopify's shipping
+profiles are the same design as the category, but the 6.0 stack already
+covers all three of its jobs (fulfillment-type eligibility matching,
+`Splitter::FulfillmentType`, `excluded_delivery_method_ids`). The one
+real loss — a *named* product grouping for delivery management — gets an
+if-needed 6.1 successor as a named eligibility set or a
+`DeliveryMethodRule` kind, recorded in `6.0-fulfillment-and-delivery.md`
+("Named delivery groups"). Also on record: Spree never had a
+variant-level shipping category (Solidus did), so product-level
+`fulfillment_types` granularity is not a regression; the mixed
+physical/digital product gap keeps a reserved relief valve (per-product
+or per-variant `fulfillment_types` override, 6.1-if-needed).
+
+
## 2026-08-06: All three reason vocabularies are store-owned
`ReturnReason`, `ClaimReason` and now `RefundReason` include