Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
docs(plans): reconcile taxons→categories plan and scope the Collection stack
Łukasz Adamczykfaef21747270
diff --git a/CLAUDE.md b/CLAUDE.mdindex 128d6c822d..f9a8244f58 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -27,7 +27,7 @@ Active plans (6.0 target, work pending):- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider, replaces Estimator + Calculator, DeliveryZone with postal code support- `6.0-rich-text-descriptions.md` — Drop ActionText storage, store HTML in text columns, sanitize on write, serve `description` + `description_html` in API (description_html serializer field shipped in 5.4)- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Vendor` replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.-- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). `Spree::Category < Spree::Taxon` alias + Category API surface shipped in 5.5; table rename + Collection pending.+- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). Category surface shipped (5.5–5.6): `Spree::Category < Spree::Taxon` scoped subclass, direct `store_id` ownership + backfill, full Admin Categories API, counter caches (`products_count`), dashboard UI. Pending 6.0: table rename + inheritance flip, the `Collection` stack, model-level removal of automatic/rules from Category, and dropping `Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.Multi-version plans (some phases shipped, some pending):- `5.4-store-api-naming-standardization.md` — Standardize API naming against industry (address fields, discounts, customer_note, label, brand/last4, etc.). 5.4 model/API aliases shipped; 6.0 column/table renames pending.diff --git a/docs/plans/6.0-admin-spa.md b/docs/plans/6.0-admin-spa.mdindex 8e38753c42..b52e4a85e6 100644--- a/docs/plans/6.0-admin-spa.md+++ b/docs/plans/6.0-admin-spa.md@@ -4,7 +4,7 @@**Target:** Spree 6.0**Depends on:** `6.0-admin-api.md`, `6.0-platform-auth.md`**Author:** damian-**Last updated:** 2026-04-30+**Last updated:** 2026-07-08## Summary@@ -873,7 +873,7 @@ Build remaining resource pages on top of the chrome and Tier 3 form primitives (- ⏳ Orders list + detail/edit- ⏳ Customers- ⏳ Promotions-- ⏳ Stock, categories, store settings, admin users, roles+- ⏳ Stock, categories, collections, store settings, admin users, roles- ⏳ Reports, exports, imports, dashboard### Phase 5 — bulk + power-user (Tiers 4 + 5)diff --git a/docs/plans/6.0-replace-taxons-with-categories.md b/docs/plans/6.0-replace-taxons-with-categories.mdindex 0882b88100..78656591df 100644--- a/docs/plans/6.0-replace-taxons-with-categories.md+++ b/docs/plans/6.0-replace-taxons-with-categories.md@@ -1,10 +1,10 @@# Replace Taxons with Categories & Add Collections-**Status:** API/serializer bridge shipped in 5.5 (`Spree::Category < Spree::Taxon` constant alias + `categories` controllers/serializers/associations); table rename + `Collection` split + rule engine pending in 6.0-**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)+**Status:** Category read/write surface shipped (5.5–5.6): `Spree::Category < Spree::Taxon` scoped subclass, direct `store_id` ownership + backfill, full Admin Categories API (CRUD + `reposition` + nested products/custom_fields/translations), and counter caches (`products_count`). **Remaining for 6.0:** table rename, the `Collection` stack (model + join + rules + API), model-level removal of automatic/rules from Category, and dropping `Taxonomy`.+**Target:** Spree 6.0 (Category surface landed in 5.5–5.6; 6.0 renames the table, splits out `Collection`, and drops `Taxonomy`)+**Depends on:** API v3 conventions, ProductType plan (6.0-product-types.md), Rich Text Descriptions plan (6.0-rich-text-descriptions.md), Admin SPA plan (6.0-admin-spa.md — dashboard UI)**Author:** Damian + Claude-**Last updated:** 2026-05-20+**Last updated:** 2026-07-08## Summary@@ -25,23 +25,41 @@ This also renames `Classification` to `ProductCategory` and `TaxonRule` to `Coll- Categories are **hierarchical**, **manual**, and define a product's **primary classification**- Collections are **flat**, often **automatic** (rule-based), and used for **merchandising** (seasonal campaigns, "on sale", "new arrivals")-3. **Taxonomy adds indirection without value.** `Taxonomy` is essentially a named container for a tree of Taxons, scoped to a Store. The root Taxon mirrors the Taxonomy name (kept in sync via callbacks). In practice, merchants have 2-3 taxonomies ("Categories", "Brands", "Collections"). This grouping can be replaced by a `kind` column on the category tree root or by separating Collections entirely.+3. **Taxonomy adds indirection without value.** `Taxonomy` is essentially a named container for a tree of Taxons, scoped to a Store. The root Taxon mirrors the Taxonomy name (kept in sync via callbacks). In practice, merchants have 2-3 taxonomies ("Categories", "Brands", "Collections"). This grouping is replaced by separating Collections out entirely; brands are out of scope (see Key Decisions → Brands).4. **`Classification` tells you nothing.** The Product↔Taxon join model name gives no hint about what it joins.## Current State-| Current | API name | Prefix | Notes |+Much of the **Category** half has already shipped (5.5–5.6). What exists today:++| Model | API name | Prefix | Notes ||---------|----------|--------|-------|-| `Spree::Taxonomy` | n/a (internal) | `txnmy_` | Container for taxon trees, scoped to store |-| `Spree::Taxon` | `categories` | `ctg_` | Nested set tree, has `automatic` flag + `TaxonRule` |+| `Spree::Taxonomy` | n/a (internal) | `txnmy_` | Container for taxon trees, scoped to store. Being dropped. |+| `Spree::Taxon` | `categories` | `ctg_` | Nested set tree on `spree_taxons`; still carries `automatic` + `TaxonRule` (Collection's future home) |+| `Spree::Category` | `categories` | `ctg_` | `class Category < Taxon` with `default_scope { manual }` + `requires_taxonomy? = false`. **Not STI** — there is no `type` column; it shares `spree_taxons` rows with `Taxon` and is a scoped view whose ownership is driven by `store_id` instead of `taxonomy_id`. || `Spree::Classification` | n/a | n/a | Product↔Taxon join (table: `spree_products_taxons`) || `Spree::TaxonRule` | n/a | `txrule_` | STI: AvailableOn, Sale, Tag |-| `Spree::Category` | `categories` | `ctg_` | Already exists as `< Taxon` alias |-The API v3 already exposes taxons as `categories` via the `CategorySerializer`. The `Spree::Category` class already exists as a subclass alias. The prefix `ctg_` is already in use.+**Already shipped:**+- **`store_id` on `spree_taxons`** (nullable) + backfill task `spree:taxons:backfill_store_id`; `Spree::Category` owns via `store_id` directly (no taxonomy required, through `SingleStoreResource`/`ensure_store`).+- **Counter caches** on `spree_taxons`: `children_count`, `classification_count` (direct), and `products_count` (descendant-inclusive, deduped — recomputed, not a Rails counter_cache).+- **Store API**: read-only `categories` controller + `CategorySerializer` (product exposes `taxons` under the `categories` key, expand-gated).+- **Admin API**: full CRUD `categories` controller + `reposition` + nested `products` / `custom_fields` / `translations`; `Admin::CategorySerializer < CategorySerializer`.+- **Promotion rules** already speak `category` on the wire (`Promotion::Rules::Taxon#api_type => 'category'`, permits `category_ids`); the model rename is still pending.++**No longer true:** default taxonomies ("Categories", "Brands", "Collections") and automatic taxons ("On Sale", "New Arrivals") are **no longer auto-created per store** — `Store#ensure_default_taxonomies_are_created` / `ensure_default_automatic_taxons` were deprecated (2026-03-10) and removed in 5.5 (PR #14020, 2026-05-11). New stores get no taxonomies; categories are created on demand. The `taxonomy_*_name` locale keys remain (only `brand_taxon` still reads `taxonomy_brands_name`).++**Known gap — "manual" sort in the v3 Store API.** "Manual" sort means ordering products by their hand-set position *within the grouping* (`Classification.position` → `ProductCategory.position`). Today it works only in the admin nested products controller and the legacy `Spree::Products::Find` finder — it is **not** implemented in the v3 search-provider path: `SearchProvider::Database#apply_sort` has no `'manual'` branch and never receives the category/collection context, and the Meilisearch provider indexes no position and can't sort by a per-grouping (many-valued) join position. So a category page's default "manual" sort does not currently reflect the merchant's hand-ordering on the v3 API. This affects **collections too**: their dedicated endpoint still lists through the provider (the collection is applied as a filter, not an AR pre-scope), so it can't bypass the provider to order by position. The fix is provider-level and shared by both — see Open Questions.++## Remaining for 6.0++The Category read/write surface is done. What's left:-Default taxonomies created per store: "Categories", "Brands", "Collections". Automatic taxons ("On Sale", "New Arrivals") live under the "Collections" taxonomy.+1. **Table rename** — `spree_taxons` → `spree_categories`, `spree_products_taxons` → `spree_product_categories` (+ FK columns), plus the inheritance flip (Category becomes the base class, `Taxon` becomes a deprecation alias). `spree_taxon_rules` is dropped (not renamed) — `spree_collection_rules` is a new table.+2. **The full `Collection` stack** — `Spree::Collection`, `Spree::ProductCollection` join, `Spree::CollectionRule` (STI), and the Store + Admin API. Nothing exists yet. (Dashboard UI is tracked in `6.0-admin-spa.md`.)+3. **Model-level split** — move `automatic`, `rules_match_policy`, `sort_order`, and `taxon_rules` off Category onto Collection (today they still live on `Taxon`/`Category` and are only excluded at the API layer).+4. **Drop `Taxonomy`** — remove the model, table, and the `taxonomy_id` column. Also removes `Product#brand_taxon` / `#brand_name` (brands are out of scope for 6.0 — see Key Decisions → Brands).## Key Decisions (do not deviate without discussion)@@ -56,6 +74,20 @@ Default taxonomies created per store: "Categories", "Brands", "Collections". Aut- **`pretty_name` and hierarchical `permalink` stay.** These are valuable for breadcrumbs and SEO.- **`hide_from_nav` stays** on Category — useful for categories that exist for organization but shouldn't appear in navigation.+### Counter caches++Two product-count concepts, named consistently across grouping models. `products_count` means "products in this grouping, including descendants" — for a flat Collection that's just its direct members, so the name means the same thing on both models.++| Model | Column | Meaning | Maintained by |+|-------|--------|---------|---------------|+| Category | `products_count` | descendant-inclusive, deduped (self + subtree) | recompute (`recalculate_products_count`) |+| Collection | `products_count` | direct (flat) | Rails `counter_cache` on `ProductCollection` |+| Product | `categories_count` | # categories the product is in | Rails `counter_cache` on `ProductCategory` |+| Product | `collections_count` | # collections the product is in | Rails `counter_cache` on `ProductCollection` |++- **Drop `classification_count`** on both `spree_categories` (only the legacy Rails admin reads it; the dashboard/API use `products_count`) and `spree_products` (renamed to `categories_count`).+- The category's `products_count` is **not** a Rails counter_cache — it's recomputed on classification change / node move, so `ProductCategory` carries no category-side count counter.+### Collection- **New model `Spree::Collection`** — flat (no tree), store-scoped@@ -68,9 +100,17 @@ Default taxonomies created per store: "Categories", "Brands", "Collections". Aut### Taxonomy → dropped-- **No replacement model.** The "kind" of category tree (Categories vs Brands) is handled by the root category's name, or by a simple `kind` string column on Category if explicit grouping is needed.+- **No replacement model, and no `kind` column.** Taxonomy simply goes away. With brands out of scope (see below), there's no remaining need to distinguish "kinds" of trees — a store has one category tree plus flat collections.- **Store scoping moves to Category directly.** Every category has `store_id` (required). Children auto-copy from parent on create. Simple `where(store_id:)` scoping, no joins needed.+### Brands → out of scope (no brand feature in 6.0)++**Decision:** Spree 6.0 ships **no brand-specific construct** — no `Spree::Brand` model, no brand attribute/column, no `:brands` tag context, no category `kind` column. The going-forward model is just **Category** (hierarchy) + **Collection** (curated/rule-based); a store that wants to group products by brand models it as a regular Category or Collection like any other grouping.++- The existing `Product#brand_taxon` / `#brand_name` and the "Brands" taxonomy convention are **removed along with `Taxonomy`**, with no replacement. The brand lookup was the only remaining `Taxonomy`-dependent runtime path, so removing it is what unblocks dropping `Taxonomy`.+- The `taxonomy_brands_name` locale key is removed.+- Rationale: none of the surveyed platforms model brand as a category, and a proper first-class brand is a larger feature than 6.0 warrants. Rather than ship a half-measure (brand-as-category or brand-as-tag), 6.0 ships nothing brand-specific — a dedicated `Spree::Brand` can be designed later (core or extension) without a rushed decision here.+## Design Details### Category model@@ -87,10 +127,10 @@ class Spree::Category < Spree.base_classacts_as_nested_set dependent: :destroy, counter_cache: :children_count- # Every category has store_id — children copy from parent on create- belongs_to :store, class_name: 'Spree::Store'- validates :store, presence: true- before_validation :copy_store_from_parent, if: -> { store_id.blank? && parent.present? }+ # Store ownership via the shared concern — provides belongs_to :store, presence,+ # and ensure_store (children inherit the parent's store). Replaces the old+ # hand-rolled copy_store_from_parent; Taxon#set_store is deprecated for 6.0.+ include Spree::SingleStoreResource# Productshas_many :product_categories, class_name: 'Spree::ProductCategory', dependent: :destroy_async@@ -115,6 +155,9 @@ class Spree::Category < Spree.base_class# TranslationsTRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freezetranslates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)+ # Interim: description via ActionText (current behavior — same as Collection).+ # 6.0-rich-text-descriptions.md owns migrating BOTH Category and Collection off+ # ActionText to sanitized HTML text columns; this plan does not change description storage.translates :description, backend: :action_text# Scopes@@ -124,6 +167,8 @@ class Spree::Category < Spree.base_classend```+> **Interim state:** today `Spree::Category < Spree::Taxon` (shares `spree_taxons`, no `type` column). The rename **flips** this — Category becomes the base class on `spree_categories` and `Spree::Taxon` becomes a deprecation alias (see Migration Phase 4). The design above is the post-rename target.+### Collection model```ruby@@ -137,16 +182,19 @@ class Spree::Collection < Spree.base_classinclude Spree::MetadataRULES_MATCH_POLICIES = %w[all any].freeze- SORT_ORDERS = %w[- manual best_selling- price_asc price_desc- available_on_desc available_on_asc- name_asc name_desc+ # Space format (same values as Spree::Taxon::SORT_ORDERS) — required by the sort+ # pipeline: FiltersAggregator#to_api_sort splits on a space ('price asc' -> 'price'),+ # and apply_sort maps to 'price'/'-price'/'best_selling'. Underscores would break default_sort.+ SORT_ORDERS = [+ 'manual', 'best_selling',+ 'price asc', 'price desc',+ 'available_on desc', 'available_on asc',+ 'name asc', 'name desc'].freezeacts_as_list scope: :store_id- belongs_to :store, class_name: 'Spree::Store'+ # store ownership (belongs_to :store + presence) comes from SingleStoreResource# Productshas_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async@@ -161,15 +209,19 @@ class Spree::Collection < Spree.base_classhas_one_attached :imagehas_one_attached :square_image- # Validations+ # Validations (store presence comes from SingleStoreResource)validates :name, presence: true- validates :store, presence: truevalidates :rules_match_policy, inclusion: { in: RULES_MATCH_POLICIES }, presence: truevalidates :sort_order, inclusion: { in: SORT_ORDERS }, presence: true# TranslationsTRANSLATABLE_FIELDS = %i[name description permalink].freezetranslates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)+ # Interim: mirror the current Category — description via ActionText. This overrides the+ # "text column per 6.0-rich-text-descriptions.md" target for the initial build (those+ # primitives aren't shipped yet); that plan migrates BOTH Category and Collection off+ # ActionText together.+ translates :description, backend: :action_textscope :manual, -> { where.not(automatic: true) }scope :automatic, -> { where(automatic: true) }@@ -195,8 +247,10 @@ class Spree::ProductCategory < Spree.base_classself.table_name = 'spree_product_categories'acts_as_list scope: :category- belongs_to :product, class_name: 'Spree::Product', counter_cache: :category_count, touch: true- belongs_to :category, class_name: 'Spree::Category', counter_cache: :product_count, touch: true+ # Product side is a Rails counter_cache (categories_count). Category side has+ # NO counter_cache — its products_count is descendant-inclusive and recomputed.+ belongs_to :product, class_name: 'Spree::Product', counter_cache: :categories_count, touch: true+ belongs_to :category, class_name: 'Spree::Category', touch: truevalidates :category, :product, presence: truevalidates :category_id, uniqueness: { scope: :product_id }@@ -207,8 +261,8 @@ class Spree::ProductCollection < Spree.base_classself.table_name = 'spree_product_collections'acts_as_list scope: :collection- belongs_to :product, class_name: 'Spree::Product', touch: true- belongs_to :collection, class_name: 'Spree::Collection', touch: true+ belongs_to :product, class_name: 'Spree::Product', counter_cache: :collections_count, touch: true+ belongs_to :collection, class_name: 'Spree::Collection', counter_cache: :products_count, touch: truevalidates :collection, :product, presence: truevalidates :collection_id, uniqueness: { scope: :product_id }@@ -238,8 +292,20 @@ end# Spree::CollectionRules::Tag — products with matching tags```+### Automatic collection regeneration++Automatic membership is materialized into `ProductCollection` rows (as today's `Classification` is for automatic taxons). It regenerates on **events** — a `CollectionRule` change, a `rules_match_policy` change, or a product save. Event-driven regeneration has **no clock**, so time-relative rules drift: a product that ages past an `AvailableOn` window stays in the collection until some unrelated write re-triggers evaluation.++A scheduled job closes that gap for **time-based** rules:++- **Registry** — `config.spree.time_based_collection_rules = [Spree::CollectionRules::AvailableOn]` in `engine.rb` (mirrors the `collection_rules` registry; apps/plugins append their own).+- **Job** — `Spree::Collections::RegenerateTimeBasedJob < Spree::BaseJob` (`queue_as Spree.queues.collections`): selects automatic collections that have a rule whose `type` is registered as time-based and calls `Spree::Collections::RegenerateProducts` on each.+- **Cadence** — not hardcoded in the gem; wired by the host app's scheduler (sidekiq-cron / solid_queue recurring), the same pattern as `Spree::StockReservations::ExpireJob`. Hourly/daily is enough (`AvailableOn` windows are day-granular).+### Product changes+**Already shipped:** `has_many :categories, through: :classifications` and a `category_ids=` setter that maps the API name to the underlying `taxon_ids` (accepting prefixed IDs, scoped to the product's store); `main_taxon` still exists. Still to add: `primary_category`, the `collections` association, and the `collections_count` counter. **To remove:** `brand_taxon` / `brand_name` (brands out of scope — see Key Decisions → Brands).+```rubyclass Spree::Product < Spree.base_class# Categories (renamed from taxons/classifications)@@ -258,8 +324,8 @@ class Spree::Product < Spree.base_class@primary_category ||= categories.firstend- # brand_taxon → brand (lookup by taxonomy name replaced by category kind or brand association)- # See Open Questions for brand handling+ # brand_taxon / brand_name are REMOVED — no replacement. Brands are out of scope+ # for 6.0 (see Key Decisions → Brands); group by brand via a Category or Collection.end```@@ -281,22 +347,30 @@ endStore API already uses `categories` naming. Changes:```-# Categories (existing endpoints, just renamed internally)+# Categories — SHIPPED (read-only in Store API)GET /api/v3/store/categories # was taxonsGET /api/v3/store/categories/:idGET /api/v3/store/products/:id?expand=categories-# Collections (new)+# Collections — PENDING (6.0)GET /api/v3/store/collectionsGET /api/v3/store/collections/:id-GET /api/v3/store/collections/:id/products+GET /api/v3/store/collections/:id/products # dedicated PLP (in_collection filter) — see note below+GET /api/v3/store/products/filters?collection_id=coll_… # facets/sort metadata (existing endpoint + new param)-# Admin API+# Admin API — categories SHIPPED (5.6)GET /api/v3/admin/categoriesPOST /api/v3/admin/categoriesPATCH /api/v3/admin/categories/:idDELETE /api/v3/admin/categories/:id-+PATCH /api/v3/admin/categories/:id/reposition+GET /api/v3/admin/categories/:id/products+POST /api/v3/admin/categories/:id/products+DELETE /api/v3/admin/categories/:id/products/:product_id+PATCH /api/v3/admin/categories/:id/products/:product_id/reposition+# (+ nested custom_fields and translations via concerns)++# Admin API — collections PENDING (6.0)GET /api/v3/admin/collectionsPOST /api/v3/admin/collectionsPATCH /api/v3/admin/collections/:id@@ -320,33 +394,29 @@ Collection response:}```-## Migration Path+### Collection product listing (Store API)-### Phase 1: Table renames + new Collection table+Products in a collection are served by a **dedicated endpoint**, not a filter on `/products`. This follows the Shopify Storefront GraphQL model (`collection { products }`) where the collection is the path context and filters/sort layer on top. (Most REST APIs — WooCommerce, Medusa, commercetools, BigCommerce — use a `?collection_id=` filter instead; we deliberately choose the nested style for cleaner requests and to apply the collection's own default sort automatically. `in_collection` is still kept as a Ransack scope for composite queries.)-Single migration:+- `GET /api/v3/store/collections/:id/products` — a thin controller that resolves the collection and **delegates to the same search-provider flow** as `/products` (query, Ransack filters, pagination, serializer). `def scope` stays the **base visibility scope** (`available` + `accessible_by`) — it is **not** pre-scoped to the collection. Instead the controller injects `in_collection: collection.id` into the filters, and each provider applies it: the DB provider via the `in_collection` Ransack scope, Meilisearch via the `collection_ids` filter. Collection scoping has to be a provider filter (not an AR pre-scope) because Meilisearch does its own filtering/counting/pagination and treats the AR scope only as a post-search visibility guard. No logic duplication.+- **Sort precedence.** Effective sort = the request's `sort` param if present, otherwise the collection's `sort_order`. Position ordering (`ProductCollection.position`) applies **only when the effective sort is `manual`**; any dynamic sort — whether from the collection's own default or a shopper override — dismisses it. Because the listing runs through the provider (for the `in_collection` filter, pagination, and faceting), manual sort **cannot** be handled by bypassing the provider with a direct AR query — it must be implemented *in* the provider. That's the same provider-level manual-sort fix categories need, which is **unresolved** (Open Question #1, approach TBD); until it lands, a `sort_order: 'manual'` collection falls back to default order. The dedicated endpoint does **not** sidestep the v3 manual-sort gap.+- **Facets/sort metadata** reuse the existing `GET /api/v3/store/products/filters` with a new **`collection_id`** param (parallel to `category_id`): it resolves the collection, scopes `in_collection`, and passes **only the collection's `sort_order`** to `FiltersAggregator` — via a `sort_order:` string param, **not** the `Collection` object (the aggregator stays decoupled from the model). No child facet (collections are flat).+- **Model:** `Spree::Product.in_collection` / `in_collections` scopes (flat join to `spree_product_collections`, no descendants), whitelisted as ransackable scopes.+- **Meilisearch:** index `collection_ids` (flat, no ancestors) on the product document, add it to `filterable_attributes` / `facet_attributes`, and handle `in_collection` in `build_filter_condition`. Kept fresh by `RegenerateProducts` (touches products + `enqueue_search_index`).-```ruby-class RenameTaxonsToCategories < ActiveRecord::Migration[7.2]- def change- # Rename core tables- rename_table :spree_taxons, :spree_categories- rename_table :spree_products_taxons, :spree_product_categories- rename_table :spree_taxon_rules, :spree_collection_rules+Membership is materialized in `ProductCollection` for both manual and automatic collections, so read-time is always a plain join filter — rules are never evaluated per request.- # Rename FK columns- rename_column :spree_product_categories, :taxon_id, :category_id- rename_column :spree_collection_rules, :taxon_id, :collection_id+## Migration Path++### Phase 1: Collection stack — schema + models (additive, no renames)- # Add store_id to categories (replacing taxonomy_id)- add_column :spree_categories, :store_id, :bigint- add_index :spree_categories, :store_id+New tables **first** (so the models are testable in RSpec), then the models/code built on them. This ships **alongside** the untouched Taxon/automatic-taxon setup — nothing is renamed yet.- # Rename counter caches- rename_column :spree_categories, :classification_count, :product_count- rename_column :spree_products, :classification_count, :category_count+**1a. Schema** (new tables, additive):- # Create collections table+```ruby+class CreateSpreeCollections < ActiveRecord::Migration[7.2]+ def changecreate_table :spree_collections do |t|t.string :name, null: falset.text :description@@ -365,55 +435,139 @@ class RenameTaxonsToCategories < ActiveRecord::Migration[7.2]t.jsonb :private_metadatat.timestampsend-add_index :spree_collections, [:store_id, :permalink], unique: true- # Create product_collections join tablecreate_table :spree_product_collections do |t|t.references :product, null: falset.references :collection, null: falset.integer :positiont.timestampsend-add_index :spree_product_collections, [:collection_id, :product_id], unique: true++ # NEW table — NOT a rename of spree_taxon_rules (that stays live for automatic+ # taxons until Phase 4). STI: type = Spree::CollectionRules::{AvailableOn,Sale,Tag}.+ create_table :spree_collection_rules do |t|+ t.references :collection, null: false+ t.string :type, null: false+ t.string :value+ t.string :match_policy, null: false, default: 'is_equal_to'+ t.timestamps+ end+ add_index :spree_collection_rules, [:collection_id, :type]++ # Counter for ProductCollection membership (additive; the category-side+ # counter renames happen in Phase 2).+ add_column :spree_products, :collections_count, :integer, null: false, default: 0++ # Mobility table-backend translations (mirrors spree_taxon_translations) for the+ # table-backed translatable fields. NOT ActionText-specific: `description` uses the+ # ActionText backend and is stored in the shared global `action_text_rich_texts` table.+ create_table :spree_collection_translations do |t|+ t.string :name+ t.string :permalink+ t.string :meta_title+ t.string :meta_description+ t.string :meta_keywords+ t.string :locale, null: false+ t.references :spree_collection, null: false, index: false+ t.timestamps null: false+ end+ add_index :spree_collection_translations, :locale+ add_index :spree_collection_translations, [:spree_collection_id, :locale], unique: true,+ name: 'index_collection_translations_on_collection_and_locale'+ end+end+```++**1b. Models + code** (built on 1a, fully spec'd before any rename):+- `Spree::Collection`, `Spree::ProductCollection`, `Spree::CollectionRule` + STI `CollectionRules::{AvailableOn,Sale,Tag}`+- `Spree::Collections::RegenerateProducts`; `RegenerateTimeBasedJob` + `time_based_collection_rules` registry (see Design Details → Automatic collection regeneration)+- Product: `in_collection`/`in_collections` scopes (+ ransack whitelist), `collections`/`collections_count`, `primary_category`+- Store + Admin Collection API: `collections` controllers + serializers; dedicated `collections/:id/products`; admin nested curation + `reposition`; `/products/filters` `collection_id` param + `FiltersAggregator` `sort_order:` change (see API → Collection product listing)+- Meilisearch: index `collection_ids` + filterable/facet attrs + `build_filter_condition` + reindex++**Not in scope of this phase (or plan):**+- **Dashboard Collection UI** — all dashboard work lives in `6.0-admin-spa.md` (the Category admin UI is already there; Collection is added to its resource list).+- **Manual sort** for a collection's `sort_order: 'manual'` is deferred to Open Question #1 (provider-level manual/position sort — approach TBD). Until it's resolved, a manual collection falls back to default order on the storefront; all dynamic sorts work.++### Phase 2: Table renames (Taxon → Category)++```ruby+class RenameTaxonsToCategories < ActiveRecord::Migration[7.2]+ def change+ rename_table :spree_taxons, :spree_categories+ rename_table :spree_products_taxons, :spree_product_categories+ rename_column :spree_product_categories, :taxon_id, :category_id++ # store_id already exists on spree_taxons (shipped 5.6) and carries over on+ # the rename — do NOT re-add it. Backfill first:+ # bundle exec rake spree:taxons:backfill_store_id++ # Counter caches (category side): keep products_count (descendant-inclusive,+ # already present); drop the direct classification_count (only the legacy Rails+ # admin read it). collections_count was added additively in Phase 1.+ remove_column :spree_categories, :classification_count, :integer+ rename_column :spree_products, :classification_count, :categories_countendend```-### Phase 2: Data migration (rake task)+**Transitional tweak.** The tables are renamed here but the classes aren't renamed until Phase 4, so point the existing models at the renamed tables — otherwise the app and the Phase 3 rake task break in the middle state:++```ruby+class Spree::Taxon < Spree.base_class+ self.table_name = 'spree_categories' # Spree::Category < Spree::Taxon inherits it+end++class Spree::Classification < Spree.base_class+ self.table_name = 'spree_product_categories'+ belongs_to :taxon, class_name: 'Spree::Taxon', foreign_key: :category_id # column was renamed+end+```++`spree_taxon_rules` is **not** renamed — the new `spree_collection_rules` already exists (Phase 1); the old table is migrated in Phase 3 and dropped in Phase 4.++### Phase 3: Data migration (rake task)++Runs after the Phase 2 rename, so it reads the automatic rows from `spree_categories`. Classify by **structure, not taxonomy name.** Taxonomy names are Mobility-translated/localized and freely renamed, and default taxonomies are no longer auto-seeded (removed in 5.5, PR #14020) — so name matching is unreliable across upgraded and new stores alike. The real Category/Collection signal is already in the data: whether a taxon is rule-based.```ruby# rake spree:migrate_taxons_to_categories_and_collections#-# For each Taxonomy:-# 1. Set store_id on all its root + descendant taxons (now categories)-# 2. If taxonomy is "Collections" (by name):-# - Move its automatic child taxons to spree_collections-# - Move their TaxonRules to CollectionRules-# - Move their Classifications to ProductCollections-# - Move manual child taxons to ProductCollections-# - Delete the taxonomy root category-# 3. For other taxonomies ("Categories", "Brands"):-# - Root category keeps the taxonomy name-# - Remove taxonomy_id column references-# 4. Drop taxonomy_id from categories+# For every store, using store_id (backfill first — spree:taxons:backfill_store_id):+# 1. Automatic taxons (automatic: true OR any taxon_rules) -> Spree::Collection+# - copy their TaxonRules -> new CollectionRules (remap collection_id, rewrite STI type)+# - copy their ProductCategories -> ProductCollections+# (regardless of which taxonomy / name they lived under)+# then delete the automatic rows from spree_categories+# 2. Manual taxons -> Spree::Category (the nested-set tree, owned via store_id)+# - manual taxons that happened to live under a "Collections" tree stay as+# categories; merchants re-file them as collections via the new UI+# (safe, reversible — no name-based guessing)+# 3. Drop the now-empty taxonomy roots and the taxonomy_id references+#+# Handles both upgraded stores (may have localized/renamed standard trees) and+# new 5.5+ stores (arbitrary or zero taxonomies).```-### Phase 3: Model renames + deprecation aliases+### Phase 4: Class renames + deprecation aliases-- `Spree::Taxon` → `Spree::Category` (alias `Spree::Taxon = Spree::Category` for one release)+Now that Collections exist (Phase 1), the tables are renamed (Phase 2), and the automatic data is migrated (Phase 3), rename the remaining classes and drop the transitional `self.table_name` tweaks from Phase 2. The inheritance is inverted today — `Spree::Category < Spree::Taxon`; the rename **flips it**: `Spree::Category` becomes the base class on `spree_categories`, and `Spree::Taxon` becomes the deprecation alias (removed in 6.1).++- `Spree::Taxon` → `Spree::Category` (keep `Spree::Taxon` as a deprecation alias of `Spree::Category` for one release)- `Spree::Taxonomy` → deprecated, no replacement- `Spree::Classification` → `Spree::ProductCategory` (alias for one release)-- `Spree::TaxonRule` → `Spree::CollectionRule`-- `Spree::TaxonRules::*` → `Spree::CollectionRules::*`-- Update all serializers, controllers, services, factories, specs+- `Spree::PromotionRuleTaxon` → `Spree::PromotionRuleCategory`; `Spree::Promotion::Rules::Taxon` → `Spree::Promotion::Rules::Category` (wire format is already `category` — `api_type` / `category_ids` — so the API contract is unchanged)+- **Drop `spree_taxon_rules` + `Spree::TaxonRule` / `TaxonRules::*`** (in 6.0, not the 6.1 cleanup) — rows were copied to `spree_collection_rules` in Phase 3, and `CollectionRule` is net-new (not a rename), so there's no deprecation alias to keep.+- Downstream shim: `alias_attribute :classification_count, :categories_count` on Product for the deprecation window (any app reading the old column keeps working)+- Update all serializers, controllers, services, factories, specs for the rename-### Phase 4: Cleanup (6.1)+### Phase 5: Cleanup (6.1)-- Remove all aliases and deprecation shims+- Remove all aliases and deprecation shims (incl. the `Spree::Taxon` alias and the `classification_count` `alias_attribute`)- Remove `taxonomy_id` column from categories-- Remove `spree_taxonomies` table+- Remove `spree_taxonomies` table, plus `Product#brand_taxon` / `#brand_name` and the `taxonomy_brands_name` locale key (brands out of scope — no replacement)- Remove `automatic`, `rules_match_policy`, `sort_order` columns from categories (moved to collections)## Constraints on Current Work@@ -424,23 +578,21 @@ end- **Don't add new Taxonomy-dependent features.** Taxonomy is going away.- **Keep the `ctg_` prefix.** Already in use, will carry over.- **New "collection-like" features go on Taxon's automatic path for now** — they'll migrate cleanly to Collection.-- **`ProductTypeCategory` join table** (from 6.0-product-types.md) should be named anticipating the Category rename — use `category_id` column, not `taxon_id`.+- **`ProductTypeCategory` join table** (from 6.0-product-types.md) should be named anticipating the Category rename — use `category_id` column, not `taxon_id`. (Already satisfied: `6.0-product-types.md` specifies `category_id`.)+- **Counter reads use the new names.** New code reads `products_count` (inclusive) on Category / `categories_count` on Product — not `classification_count` (being dropped/renamed).+- **No brand-specific features.** Brands are out of scope for 6.0 (see Key Decisions → Brands). Don't add a `Spree::Brand`, a brand column, a `:brands` tag context, or a category `kind` column; model brand grouping as a Category or Collection.## Open Questions-1. **Brand handling.** Currently `brand_taxon` looks up a taxon under the "Brands" taxonomy. Options:- - (a) Keep brands as a category tree root named "Brands" — simplest, brands are just categories- - (b) Add a dedicated `Spree::Brand` model — cleaner but more migration work- - (c) Brand as a metafield — too unstructured- - Leaning toward (a): brands are categories under a "Brands" root. `product.brand` resolves to the first category under the Brands root.--2. **Category kind/type column.** Should root categories have a `kind` column (e.g., `categories`, `brands`) to replace the Taxonomy name as a semantic grouping? This would make "find the brands root" a query on `kind` rather than a string match on `name`. Low cost, high value.--3. **Collection pagination of products.** Should `GET /collections/:id/products` support full Ransack filtering and Pagy pagination, or should it return the collection's pre-sorted product list? Probably both — Ransack filters scoped to the collection's product set.--4. **Automatic collection scheduling.** Current `AvailableOn` rule regenerates on product changes. Should collections support scheduled regeneration (e.g., daily cron) for time-based rules? The current `after_commit` approach may miss edge cases.+> **Resolved:**+> - *Brand handling* & *Category kind/type column* — 6.0 ships no brand feature and no `kind` column; brands are modeled as a regular Category or Collection, and `brand_taxon`/`brand_name` are removed with `Taxonomy`. See Key Decisions → Brands.+> - *Collection product listing* — a dedicated `GET /collections/:id/products` (base visibility scope + an injected `in_collection` filter, delegating to the shared search flow; default sort from the collection's `sort_order`), with facets via the existing `/products/filters` + a new `collection_id` param. See API → Collection product listing.+> - *Automatic collection scheduling* — a `RegenerateTimeBasedJob` scoped to a `time_based_collection_rules` registry, scheduled by the host app (the `ExpireJob` pattern). See Design Details → Automatic collection regeneration.+> - *Collection nesting* — collections stay **flat**; hierarchy lives in Category (matches Shopify and keeps the Category/Collection split clean).-5. **Collection nesting.** The plan says collections are flat. Should we support one level of nesting (parent collection)? Some platforms support hierarchical collections with filter inheritance. Could be a future enhancement.+1. **"Manual" sort in the v3 Store API (categories *and* collections).** Manual/position ordering isn't implemented in the v3 search-provider path (see Current State → Known gap) — only in the admin controller and the legacy `Products::Find` finder. Both category pages and the collection endpoint list through the search provider, so neither can bypass it; the fix is provider-level and shared. Collections can ship without it (dynamic sorts all work; a `sort_order: 'manual'` collection just falls back to default order until this lands). The open part is the exact approach:+ - **DB provider:** add a `'manual'` branch to `SearchProvider::Database#apply_sort` that orders by the grouping's min join-position (`ascend_by_taxons_min_position` for a category; an `ascend_by_collections_min_position` twin for a collection), and thread the category/collection context into `search_and_filter` / `apply_sort` (they don't receive it today).+ - **Meilisearch:** fall back to the DB for the manual case (resolve ordered ids via the min-position scope, bypassing MS sort); native per-grouping position sort isn't feasible (position is a many-valued join property; MS sorts only on fixed scalar attributes).## References