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.

71.2 KB
Raw Blame

Replace Taxons with Categories & Add Collections

Status: Implemented (PR #14302, 2026-07-19). The Category read/write surface landed earlier (5.5–5.6); PR #14302 completed the 6.0 core: the spree_taxons → spree_categories table rename + inheritance flip (Spree::Category < Spree.base_class, Spree::Taxon retained as a deprecation alias), the full Collection stack (model + join + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data-migration task, and de-ruling Category. Remaining (all 6.1): the channel-aware reimplementation of CollectionRules::AvailableOn — Phase 5, which ships now with an interim legacy-available_on apply and rides with 6.0-channels-catalogs-b2b.md; and dropping spree_taxon_rules + Spree::TaxonRule/TaxonRules::* + the Taxonomy model and table (Phase 6). Taxonomy became data-only in 6.0 — Phase 5b removed every runtime path that created, touched or validated one, leaving only the upgrade task's reader and the pre-upgrade store-resolution fallbacks. Nothing 6.0-blocking is left. 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), Channels/Publications plan (6.0-channels-catalogs-b2b.md — the CollectionRules::AvailableOn rule's channel-aware implementation depends on its available_on → ProductPublication#published_at migration; see Migration Phase 5) Author: Damian + Claude Last updated: 2026-07-28

Summary

Split the overloaded Taxon model into two distinct concepts that every modern commerce platform separates:

  • Category — hierarchical product classification (Men > Clothing > T-Shirts). A product's primary organizational home. Manual membership only.
  • Collection — flat, curated or rule-based product groupings ("Summer Sale", "New Arrivals", "Best Sellers"). Supports both manual curation and automatic rules.

Drop the Taxonomy model entirely — it's a grouping layer that adds indirection without value. Categories become a single tree per store (rooted, nested set). Collections are flat, store-scoped, and own the current automatic/rule-based functionality.

This also renames Classification to ProductCategory and TaxonRule to CollectionRule.

Problem

  1. "Taxon" and "Taxonomy" are jargon. No other commerce platform uses these terms. Every new developer has to learn what they mean. The industry-standard separation is Category (hierarchical) + Collection (flat/curated).

  2. Taxon is overloaded. The same model serves as both hierarchical categories AND flat collections (via the "Collections" taxonomy with automatic rules). These have fundamentally different semantics:

    • 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 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

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. 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

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).

"Manual" (position) sort in the v3 Store API — implemented for both providers. "Manual" sort orders products by their hand-set position within the grouping (ProductCategory.position / ProductCollection.position). The DB provider infers the grouping from the applied in_category/in_collection filter, defaults a grouping page's blank sort to manual, and orders by ProductCollection.position (flat, for collections) or MIN(ProductCategory.position) collapsed per product (subtree, for categories) — reusing the join the filter already made. The Meilisearch provider reaches the same result natively via single index + distinct: ProductPresenter emits per-grouping membership docs (shared scalar grouping_id + position), a manual grouping page filters grouping_id and sorts position:asc, and distinctAttribute = product_id collapses the duplicates on non-grouping queries (facet counts/totals accurate on MS ≥ 1.40). See Open Questions (resolved).

Remaining for 6.0

The Category read/write surface is done. What's left:

  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 (6.1). The brand methods Product#brand_taxon / #brand_name (the only remaining Taxonomy-dependent runtime path) are removed in 6.0 (Phase 3); brands are out of scope with no replacement (see Key Decisions → Brands).

Key Decisions (do not deviate without discussion)

Category

  • Spree::Taxon renamed to Spree::Category, spree_taxons renamed to spree_categories
  • Spree::Taxonomy dropped. Categories are a single nested set per store. The taxonomy_id column becomes store_id directly on the category.
  • Spree::Classification renamed to Spree::ProductCategory, table spree_products_taxons renamed to spree_product_categories, columns taxon_id → category_id
  • Categories are manual only. The automatic flag, rules_match_policy, sort_order, and taxon_rules association move to Collection.
  • Prefix stays ctg_ (already in use)
  • Nested set stays. awesome_nested_set with parent_id, lft, rgt, depth, children_count. Proven, no reason to change.
  • pretty_name and hierarchical permalink stay. These are valuable for breadcrumbs and SEO.
  • hide_from_nav is removed (reversal, 2026-08-05 — it previously "stayed"). Nothing ever read it: no serializer exposed it, no scope or query filtered on it, and no storefront or dashboard consumed it, so it was a write-only flag an API client could set to no effect. The Ruby surface (validation, Ransack entry, permitted attributes, admin param) and the SDK params are gone; the column drops in 6.1 with the other dead columns. Collections never had it — the column in this plan's Phase 1 migration was specified but never implemented, and is not being added.

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
  • New join table Spree::ProductCollection (replaces the automatic taxon's use of Classification)
  • Owns automatic/rule-based membership — the automatic flag, rules_match_policy, and rules association move here from Taxon
  • Spree::TaxonRule renamed to Spree::CollectionRule — STI subtypes Tag, Sale, AvailableOn, all registered in config.spree.collection_rules (which mirrors the existing config.spree.taxon_rules). AvailableOn ships with an interim legacy-column implementation; its channel-aware behavior depends on 6.0-channels-catalogs-b2b.md (see Design Details → Automatic collection regeneration; Migration Phase 5)
  • Prefix: coll_
  • Both manual and automatic collections. Manual collections have ProductCollection records managed by admins. Automatic collections have CollectionRule records that regenerate membership.
  • Sort order on Collection, not Category. The SORT_ORDERS constant (manual, best_selling, price asc, etc.) moves to Collection.

Taxonomy → dropped

  • 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 with no replacement. The brand methods go in 6.0 (Phase 3) — they were the only remaining Taxonomy-dependent runtime path, so removing them is what unblocks dropping Taxonomy itself (model/table) in 6.1.
  • 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

class Spree::Category < Spree.base_class
  has_prefix_id :ctg

  include Spree::TranslatableResource
  include Spree::TranslatableResourceSlug
  include Spree::Metafields
  include Spree::Metadata
  include Spree::MemoizedData

  acts_as_nested_set dependent: :destroy, counter_cache: :children_count

  # 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

  # Products
  has_many :product_categories, class_name: 'Spree::ProductCategory', dependent: :destroy_async
  has_many :products, through: :product_categories

  # ProductType integration (from 6.0-product-types.md)
  has_many :product_type_categories, class_name: 'Spree::ProductTypeCategory', dependent: :destroy
  has_many :product_types, through: :product_type_categories

  # Promotions
  has_many :promotion_rule_categories, class_name: 'Spree::PromotionRuleCategory', dependent: :destroy
  has_many :promotion_rules, through: :promotion_rule_categories

  # Attachments
  has_one_attached :image
  has_one_attached :square_image

  # Validations
  validates :name, presence: true, uniqueness: { scope: %i[parent_id store_id], case_sensitive: false }

  # Translations
  TRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freeze
  translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
  # description rides the table backend above — NOT action_text. The old
  # `translates :description, backend: :action_text` line is removed by
  # 6.0-rich-text-descriptions.md Phase 3, which runs BEFORE this plan's
  # table rename (its rake task is table-name-agnostic either way).

  # Scopes
  scope :for_store, ->(store) { where(store_id: store.id) }

  # No automatic/rules — that's Collection's job
end

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 3). The design above is the post-rename target.

Collection model

class Spree::Collection < Spree.base_class
  has_prefix_id :coll

  include Spree::SingleStoreResource
  include Spree::TranslatableResource
  include Spree::TranslatableResourceSlug
  include Spree::Metafields
  include Spree::Metadata

  # FriendlyId with history, mirroring Category/Taxon. `use: :history` records superseded
  # permalinks in the shared `friendly_id_slugs` table (polymorphic, scoped by sluggable_type)
  # so old collection URLs keep resolving after a RENAME — a deliberate SEO requirement.
  # No new table (friendly_id_slugs already exists for Taxon). Within-store uniqueness is
  # enforced separately by `validates :permalink, uniqueness: { scope: :store_id }` + the DB
  # index: a collision ERRORS (exactly as Taxon does — friendly_id is not scoped and does not
  # auto-suffix here). Generation mirrors Taxon's dual set_permalink — a model-level
  # `before_validation` (so the column_fallback base column is populated for the default
  # locale, which the Translation `before_save` alone misses) plus a Translation-level
  # `before_save` — but flat: `generate_slug` is `name.to_url` with no parent prefix.
  extend FriendlyId
  friendly_id :permalink, slug_column: :permalink, use: :history
  before_validation :set_permalink, if: :name

  RULES_MATCH_POLICIES = %w[all any].freeze
  # Space format — required by the sort pipeline (FiltersAggregator splits on a space).
  # Owned by Collection (Category is manual-only and no longer defines SORT_ORDERS).
  # 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'
  ].freeze

  acts_as_list scope: :store_id

  # store ownership (belongs_to :store + presence) comes from SingleStoreResource

  # Products
  has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async
  has_many :products, through: :product_collections

  # Automatic rules. The association is named `rules` (not `collection_rules`) so the
  # Admin API's write key equals the serializer's read key: ParamsNormalizer derives the
  # flat nested-attributes key from the association name (`rules` → `rules_attributes`),
  # so a `rules: [...]` payload routes correctly (read/write symmetry — see CLAUDE.md).
  has_many :rules, class_name: 'Spree::CollectionRule', dependent: :destroy
  accepts_nested_attributes_for :rules, allow_destroy: true,
    reject_if: proc { |attrs| attrs['value'].blank? }

  # Attachments
  has_one_attached :image
  has_one_attached :square_image

  # Validations (store presence comes from SingleStoreResource)
  validates :name, presence: true
  validates :permalink, uniqueness: { scope: :store_id, case_sensitive: false, allow_blank: true }
  validates :rules_match_policy, inclusion: { in: RULES_MATCH_POLICIES }, presence: true
  validates :sort_order, inclusion: { in: SORT_ORDERS }, presence: true

  # Translations
  TRANSLATABLE_FIELDS = %i[name description permalink].freeze
  translates(*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_text

  scope :manual, -> { where.not(automatic: true) }
  scope :automatic, -> { where(automatic: true) }

  # Regenerate product membership from rules (moved from Taxon)
  def regenerate_products
    return unless automatic?
    Spree::Collections::RegenerateProducts.call(collection: self)
  end

  def products_matching_rules(opts = {})
    return Spree::Product.none unless automatic? && rules.any?
    # Same logic as current Taxon#products_matching_rules
  end
end

Join tables

# Renamed from Spree::Classification
class Spree::ProductCategory < Spree.base_class
  self.table_name = 'spree_product_categories'
  acts_as_list scope: :category

  # 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: true

  validates :category, :product, presence: true
  validates :category_id, uniqueness: { scope: :product_id }
end

# New
class Spree::ProductCollection < Spree.base_class
  self.table_name = 'spree_product_collections'
  acts_as_list scope: :collection

  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: true

  validates :collection, :product, presence: true
  validates :collection_id, uniqueness: { scope: :product_id }
end

CollectionRule (renamed from TaxonRule)

class Spree::CollectionRule < Spree.base_class
  has_prefix_id :crule

  MATCH_POLICIES = %w[is_equal_to is_not_equal_to contains does_not_contain].freeze

  belongs_to :collection, class_name: 'Spree::Collection', inverse_of: :rules, touch: true

  validates :collection, :type, :value, presence: true
  validates :match_policy, inclusion: { in: MATCH_POLICIES }, presence: true

  after_commit :regenerate_collection_products,
    if: -> { saved_change_to_value? || destroyed? || saved_change_to_match_policy? }
end

# STI subtypes (all registered in config.spree.collection_rules, which mirrors config.spree.taxon_rules):
# Spree::CollectionRules::Tag         — products with matching tags
# Spree::CollectionRules::Sale        — products currently on sale
# Spree::CollectionRules::AvailableOn — products created/available within N days.
#   Ships with the interim legacy-column `apply`; channel-aware reimplementation
#   (against ProductPublication#published_at) is Migration Phase 5.

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 (via AutoMatchCollections). 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, net-new (no taxon_rules equivalent — taxons ship no scheduled refresh, hence their drift). This is a separate axis from the config.spree.collection_rules rule registry (which mirrors config.spree.taxon_rules); 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).

AvailableOn ships fully now, but its implementation is interim. The STI class ships in Phase 1 (registered in collection_rules alongside Tag/Sale) so the Phase 4 rake migrates TaxonRules::AvailableOn → CollectionRules::AvailableOn 1:1 (value + match_policy preserved) rather than dropping the data. Its apply is the same legacy spree_products.available_on query the taxon rule already runs — a faithful, zero-behavior-change carry-over (the taxon rule was equally channel-unaware), which keeps migrated automatic collections computing correct membership and lets the scheduled job above refresh them. One caveat holds until the reimplementation (Migration Phase 5):

  • Channel-unaware + on a doomed column. The available_on column is superseded by the channel-scoped ProductPublication#published_at and is removed by 6.0-channels-catalogs-b2b.md (its Phase 3 — "6.0 cleanup"). So AvailableOn is a new reader of a column another 6.0 plan drops. Migration Phase 5 reimplements apply against published_at and — as a hard cross-plan ordering constraint — must land before the channels plan drops the column.

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).

class Spree::Product < Spree.base_class
  # Categories (renamed from taxons/classifications). `manual`-scoped during the
  # transition — automatic categories are migrated to Collections in Phase 4, after
  # which the scope is a no-op; it (and `taxons`) are dropped in 6.1.
  has_many :product_categories, dependent: :delete_all, inverse_of: :product
  has_many :categories, -> { manual }, through: :product_categories, source: :category
  # Deprecation period (removed in 6.1). `taxons` stays a *real* association (not an
  # alias_method) because it is Ransack-whitelisted (`taxons_id_in`) and Ransack
  # needs a reflectable association; it lists every category via the join.
  # `classifications` is a plain method alias (it is not Ransack-whitelisted).
  has_many :taxons, through: :product_categories, source: :category, before_remove: :remove_category
  alias_method :classifications, :product_categories

  # Collections (new)
  has_many :product_collections, dependent: :delete_all, inverse_of: :product
  has_many :collections, through: :product_collections

  # main_taxon → primary_category
  def primary_category
    @primary_category ||= categories.first
  end

  # 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

Store changes

class Spree::Store < Spree.base_class
  # Drop: has_many :taxonomies
  # Drop: has_many :taxons, through: :taxonomies

  has_many :categories, class_name: 'Spree::Category'
  has_many :root_categories, -> { roots }, class_name: 'Spree::Category'
  has_many :collections, class_name: 'Spree::Collection'
end

API

Store API already uses categories naming. Changes:

# Categories — SHIPPED (read-only in Store API)
GET    /api/v3/store/categories          # was taxons
GET    /api/v3/store/categories/:id
GET    /api/v3/store/products/:id?expand=categories

# Collections — PENDING (6.0)
GET    /api/v3/store/collections
GET    /api/v3/store/collections/:id
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 — categories SHIPPED (5.6)
GET    /api/v3/admin/categories
POST   /api/v3/admin/categories
PATCH  /api/v3/admin/categories/:id
DELETE /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/collections
POST   /api/v3/admin/collections
PATCH  /api/v3/admin/collections/:id            # reorder via `position` (acts_as_list reorders on save) — no separate reposition action
DELETE /api/v3/admin/collections/:id
GET    /api/v3/admin/collections/:id/products
POST   /api/v3/admin/collections/:id/products
DELETE /api/v3/admin/collections/:id/products/:product_id
PATCH  /api/v3/admin/collections/:id/products/:product_id/reposition
# (+ nested custom_fields and translations via concerns)
#
# Bulk product membership (mirrors the category bulk endpoints):
POST   /api/v3/admin/products/bulk_add_to_collections       # { ids: [...], collection_ids: [...] }
POST   /api/v3/admin/products/bulk_remove_from_collections  # { ids: [...], collection_ids: [...] }

Unlike categories (a nested set that needs an explicit reposition with a target parent + index), collections are a flat acts_as_list, so the collection's own order is reordered by sending position on PATCH /collections/:id — matching the SPA <ResourceTable reorder> convention and the sibling flat resource (payment_methods). Only the nested membership (ProductCollection.position) keeps a dedicated reposition. Admin collection endpoints require the new read_collections / write_collections API-key scopes (JWT admins use CanCanCan as usual). Membership is deliberately not gated behind write_collections: collection_ids on a product write and the /products/bulk_*_collections endpoints are reachable with write_products, because filing a product into its groupings is part of maintaining the product — the same rule category_ids has always followed. Creating or configuring a collection (its rules, sort order, name) still requires write_collections.

Nested rules are written through a model-level sync setter (Spree::Collection#rules=), mirroring Spree::OptionType#option_values=: the client sends the full desired rule set under rules (prefixed crule_ ids update, id-less entries create, omitted rules are destroyed), decoded and applied in the parent's save transaction. normalize_params is deliberately not called on this controller so rules reaches the setter rather than being rewritten to rules_attributes.

Collection response (Admin — the Store serializer omits the merchandising config automatic, rules_match_policy, and rules; that's back-office state, not customer-facing). rules is expand-gated (?expand=rules), like custom_fields: a listing would otherwise serialize every collection's full rule set for callers that only need the basics, and the only consumer that needs them is the edit form. The shape below is the expanded one:

{
  "id": "coll_k5nR8xLq",
  "name": "Summer Sale",
  "automatic": true,
  "sort_order": "best_selling",
  "rules_match_policy": "all",
  "rules": [
    { "id": "crule_abc", "type": "Spree::CollectionRules::Tag", "value": "summer", "match_policy": "contains" }
  ],
  "image_url": "https://...",
  "products_count": 42,
  "slug": "summer-sale"
}

The Store response is the customer-facing subset — id, name, slug/permalink, description/description_html, image_url/square_image_url, sort_order, position, meta_*, products_count (+ custom_fields on expand) — with no automatic/rules_match_policy/rules (internal merchandising state stays out of the Store API, per the store-vs-admin serializer rule).

Collection product listing (Store API)

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.)

  • 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.prefixed_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 is implemented in the provider, not by bypassing it with a direct AR query. Both providers implement it — the DB provider orders by ProductCollection.position; the Meilisearch provider queries per-grouping membership docs (single index + distinct) sorted by position:asc. All dynamic sorts work on both.
  • 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 scope (flat join to spree_product_collections, no descendants), whitelisted as a ransackable scope. (No in_collections plural — the collection surface is single-collection; add it only if a real multi-collection filter appears.)
  • 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).

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.

Migration Path

Phase 1: Collection stack — schema + models (additive, no renames)

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.

1a. Schema (new tables, additive):

class CreateSpreeCollections < ActiveRecord::Migration[7.2]
  def change
    create_table :spree_collections do |t|
      t.string :name, null: false
      t.text :description
      t.string :permalink
      t.boolean :automatic, null: false, default: false
      t.string :rules_match_policy, null: false, default: 'all'
      t.string :sort_order, null: false, default: 'manual'
      t.integer :position
      t.integer :products_count, null: false, default: 0
      t.references :store, null: false
      t.string :meta_title
      t.string :meta_description
      t.string :meta_keywords
      t.jsonb :public_metadata
      t.jsonb :private_metadata
      t.timestamps
    end
    add_index :spree_collections, [:store_id, :permalink], unique: true

    create_table :spree_product_collections do |t|
      t.references :product, null: false
      t.references :collection, null: false
      t.integer :position
      t.timestamps
    end
    add_index :spree_product_collections, [:collection_id, :product_id], unique: true

    # NEW table — NOT a rename of spree_taxon_rules (kept data-only for the Phase 4
    # migration, dropped in 6.1). STI type: Spree::CollectionRules::{Tag,Sale,AvailableOn}
    # (AvailableOn ships with an interim apply — see Automatic collection regeneration;
    # no schema change when its Phase 5 channel-aware reimplementation lands).
    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::{Tag,AvailableOn,Sale}, all registered in config.spree.collection_rules (mirrors the existing config.spree.taxon_rules, engine.rb). AvailableOn ships with the interim legacy-column apply; channel-aware reimplementation is Phase 5
  • Spree::Collections::RegenerateProducts; AutoMatchCollections (+ job) for event-driven regeneration on product save; RegenerateTimeBasedJob + time_based_collection_rules = [AvailableOn] registry (net-new — no taxon_rules equivalent; taxons ship no scheduled refresh) for time-relative rules — all on the collections queue (see Design Details → Automatic collection regeneration)
  • Product: in_collection scope (+ ransack whitelist), collections/collections_count, primary_category
  • Store + Admin Collection API: collections controllers + serializers; dedicated collections/:id/products; admin nested curation + nested reposition (the collection's own order reorders via position on update, no top-level reposition action); read_collections/write_collections API-key scopes; /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 — implemented for both providers: DB (position ordering for category + collection groupings) and Meilisearch (single index + distinct over per-grouping membership docs). All dynamic sorts work on both. (Was Open Question #1, now resolved.)
  • CollectionRules::AvailableOn's channel-aware reimplementation — the model, its interim (legacy-column) apply, and the scheduled refresh (RegenerateTimeBasedJob + time_based_collection_rules) all ship in this phase; only rewriting apply against ProductPublication#published_at is Migration Phase 5, a dependency on 6.0-channels-catalogs-b2b.md.

Phase 2: Table renames (Taxon → Category)

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

    # Promotion↔category join + Mobility translations rename now too, so no class
    # needs a table_name/foreign_key pin. (spree_taxon_rules + spree_prototype_taxons
    # keep taxon_id — dropped in 6.1 / renamed by 6.0-product-types respectively.)
    rename_table :spree_promotion_rule_taxons, :spree_promotion_rule_categories
    rename_column :spree_promotion_rule_categories, :taxon_id, :category_id
    rename_table :spree_taxon_translations, :spree_category_translations
    rename_column :spree_category_translations, :spree_taxon_id, :spree_category_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_count
  end
end

Transitional tweak. The tables are renamed here but the classes aren't renamed until Phase 3, so point the existing models at the renamed tables — otherwise the app and the Phase 4 rake task break in the middle state:

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 4 and dropped in 6.1 (Phase 6), not 6.0 (see Phase 3 for why).

Additional Phase 2 decisions (implemented):

  • classification_count is dropped now (not deferred). The direct taxon-side Rails counter was only read by the legacy spree/admin engine; the descendant-inclusive products_count is kept. The product-side counter is renamed classification_count → categories_count. Classification's counter_cache follows to categories_count; the three taxon bulk services recompute products_count via recalculate_products_count instead of the removed counter. Legacy spree/admin views that read taxon.classification_count are not fixed (that engine is being replaced by the SPA) — the specs they break are marked pending.
  • Mobility translation table is renamed here too (spree_taxon_translations → spree_category_translations, spree_taxon_id → spree_category_id), for consistency with the other table renames. Once the class is renamed to Spree::Category (Phase 3), Mobility derives spree_category_translations / spree_category_id naturally, so no translates pin is needed in delivered 6.0. (A Phase-2-only intermediate — class still Spree::Taxon, table already renamed — would need a transient pin to the new table, but 6.0 ships all phases together.)
  • Automatic-taxon matching code is removed here (see Phase 3 rationale). Because 6.0 is single-delivery, the taxon auto-match path doesn't need to survive the rename: removed Product#auto_match_taxons + after_commit, Product.bulk_auto_match_taxons, Taxon#regenerate_taxon_products + after_commit, and the TaxonRule regeneration callback. Rule-based membership now lives on Collection. Price re-match + the bulk-tags API endpoint now trigger auto_match_collections / Product.bulk_auto_match_collections; the bulk-category endpoints no longer re-match (category membership never affected rule matching). The service/job classes Products::AutoMatchTaxons (+ its job) and Taxons::RegenerateProducts are retained as deprecating aliases (see Phase 3's "Deprecation aliases" note), not deleted.
  • eligible_for_taxon_matching? → eligible_for_collection_matching? (the Product predicate + the Price attribute).

Phase 3: Class renames + deprecation aliases

Now that Collections exist (Phase 1) and the tables are renamed (Phase 2), rename the remaining classes and drop the transitional self.table_name tweaks from Phase 2. This runs before the data migration (Phase 4) so the migration script is written against the final model names (Spree::Category, Spree::ProductCategory, Spree::Collection) rather than the transitional ones. 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::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)
  • The rename is Ruby-level, not just class names: associations and methods go to category now. The join models expose belongs_to :category (ProductCategory, PromotionRuleCategory), Category/Product expose has_many :product_categories, and the promotion rule exposes has_many :promotion_rule_categories + has_many :categories with category-named internals (eligible_category_ids, category_ids_in_order_including_ancestors, add_categories, category_ids_to_add). Because Phase 2 renames the join tables too (spree_product_categories, spree_promotion_rule_categories, spree_category_translations + their category_id/spree_category_id columns), no foreign_key/table_name/translates pins are needed — the natural category_id is used everywhere and Mobility derives spree_category_translations on its own. Pins remain only for the join tables that are not renamed in this plan: Category#has_many :prototype_taxons, foreign_key: :taxon_id (spree_prototype_taxons is renamed by 6.0-product-types.md) and Category#has_many :taxon_rules, foreign_key: :taxon_id (spree_taxon_rules is dropped in 6.1). A belongs_to :taxon, foreign_key: :category_id — new name paired with a renamed column — is the exact backwards state to avoid.
  • Product/Store keep categories as the one real, canonical association (-> { manual }); taxons is a deprecated method alias of categories, not a real association (removed in 6.1). taxons is therefore dropped from the Product Ransack whitelist — filter by categories_id_in (the v3 API uses the in_taxon/in_category scopes, not taxons_ ransack). Other deprecated method aliases bridge old names for one release: taxon/taxon= on the join models; taxons/taxon_ids/eligible_taxon_ids/taxon_ids_to_add on the rule; classifications on Product/Category.
  • Automatic-taxon matching code was removed in Phase 2, not here — since 6.0 ships all phases at once (no released intermediate state), the taxon auto-match services + triggers were deleted in Phase 2 and rule-based membership moved to Collection. Spree::TaxonRule / TaxonRules::* remain as data-only models.
  • Dropping spree_taxon_rules + Spree::TaxonRule / TaxonRules::* + the config.spree.taxon_rules registry is deferred to 6.1 (Phase 6), NOT 6.0. The Phase 4 data migration reads spree_taxon_rules to build CollectionRules, but schema migrations (db:migrate) run automatically at deploy while the data migration is a manual rake task run afterward — a same-release drop_table would wipe the source before the data task runs. So the table + models are retained through 6.0 and dropped in 6.1.
  • 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
  • Stored class-name strings become 'Spree::Category' — the metafield/translation resource_type registries move to 'Spree::Category', and renamed classes write the new name into polymorphic/STI/slug columns. Existing rows still hold 'Spree::Taxon*'; they're backfilled by the Phase 4 data migration (see its step 4). This is a deliberate reversal of the Phase 2 pin-the-old-name approach — 6.0 does NOT keep using 'Spree::Taxon' in data.
  • De-rule Spree::Category at the model level (the automatic/rules_match_policy/sort_order columns + spree_taxon_rules table stay for the Phase 4 migration, dropped in 6.1): remove products_matching_rules, the taxon_rules association + accepts_nested_attributes_for + rules alias, the rules_match_policy/sort_order validations, scope :automatic, and manual_sort_order?. SORT_ORDERS + RULES_MATCH_POLICIES move to Spree::Collection (its rightful owner); FiltersAggregator reads Spree::Collection::SORT_ORDERS. scope :manual + the manual?/automatic? column readers stay (the manual scope guards the category surfaces). TaxonRule#belongs_to :taxon drops its now-dangling inverse_of: :taxon_rules.
  • Brand removal (moved here from 6.1): delete Product#brand_taxon / #brand_name (+ the MEMOIZED_METHODS entry), the brand field on the Products Performance report, and the brand_name column from the product CSV export — brands are out of scope with no replacement (see Key Decisions → Brands). The spree_taxonomies table + taxonomy_brands_name locale key still drop in 6.1 with Taxonomy; only the brand methods/fields go now.
  • Wording sweep (Ruby names → category): Product#main_taxon → #primary_category (deprecated delegate), touch_taxons → touch_categories, Spree::Products::TouchTaxonsJob → TouchCategoriesJob (both jobs later removed in 6.0 — see the deprecation shims below) + Spree.queues.taxons → categories (with a deprecation alias), taxon_and_ancestors → category_and_ancestors, remove_taxon → remove_category, the grouped_taxon_ids_for_products scope → grouped_category_ids_for_products, and recalculate_products_count's param; delete the dead, buggy Product#taxons_for_store. Comments/param names across Category/Product de-taxoned.
  • Remove the deprecated taxon-tied Product scopes marked remove-in-6.0: in_taxons, for_filters, taxons_name_eq, plus their now-orphaned private helpers prepare_taxon_conditions / get_taxons. The active scopes stay (in_taxon, in_category, in_categories, in_collection, ascend_by_taxons_min_position). Non-taxon deprecated scopes (master-price, option, name, etc.) are left for their own plans.
  • Rename the manual-membership services Spree::Taxons::AddProducts / RemoveProducts → Spree::Categories::AddProducts / RemoveProducts (param taxons: → categories:, matching Spree::Collections::*). All monorepo callers move to the new names, but the old classes are kept as deprecating aliases (see "Deprecation aliases" below). The optional Spree::Taxons::TouchFeaturedSections hook (guarded by defined?, its namespace owned by another gem) is left untouched.
  • Deprecation aliases (kept for one release, removed in 6.1). Every renamed/moved taxon name keeps working with a runtime deprecation warning:
    • Model constants (Spree::Taxon, Spree::Classification, Spree::PromotionRuleTaxon, Spree::Promotion::Rules::Taxon) stay true constant aliases — not DeprecatedConstantProxy, which silently breaks is_a?/case/STI/polymorphic-constantize. Each calls Spree::Deprecation.warn in the alias's module body, so the notice fires through Spree's deprecator when the file loads (at boot under eager load, on first reference otherwise). Since a plain alias is the same object as the canonical class, a reliable per-reference warning isn't achievable without a proxy (breaks is_a?) or const_missing (breaks defined?), so the load-time notice is the deliberate trade-off.
    • Service/job classes are resurrected as thin deprecating wrappers that Spree::Deprecation.warn on invocation and delegate: Taxons::AddProducts/RemoveProducts translate taxons: → categories:; Products::AutoMatchTaxons (+ AutoMatchTaxonsJob) delegate to their *Collections* counterparts (Products::TouchTaxonsJob was removed outright with TouchCategoriesJob in 6.0 — the Store API caches on product timestamps, so products no longer touch their categories); Taxons::RegenerateProducts warns and no-ops (categories are manual in 6.0 — its behavior only survives for Collection, keyed on a collection rather than a taxon, so there is no faithful delegate).
    • Spree.queues.taxons is restored as a singleton method that warns and returns Spree.queues.categories.
    • Method bridges (Product#taxons/taxon_ids/main_taxon/classifications, Store#taxons, the join models' #taxon, the rule's #taxons/#taxon_ids/#eligible_taxon_ids/#taxon_ids_to_add/#taxon_ids_string) each Spree::Deprecation.warn and delegate. Internal core callers were repointed to the canonical names so the warnings only fire for external code. (Spree::Taxonomy and Spree::Taxons::Find are themselves legacy/dropped in 6.1 and keep referencing the Taxon constant internally.)

Phase 4: Data migration (rake task)

Runs after the Phase 2 rename and the Phase 3 class rename — so the script reads via the final models (Spree::Category, Spree::ProductCategory) and writes the final Collection classes, with everything in place. 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 category is rule-based.

# rake spree:migrate_taxons_to_categories_and_collections
#
# For every store, using store_id (backfill first — spree:taxons:backfill_store_id):
#   1. Automatic categories (automatic: true OR any taxon_rules) -> Spree::Collection
#      - copy their TaxonRules       -> new CollectionRules (remap collection_id, rewrite STI type)
#        Maps ALL types 1:1 — Tag, Sale, AND AvailableOn. AvailableOn's CollectionRule
#        model ships in Phase 1 (interim legacy-column apply), so its rows migrate cleanly
#        with value + match_policy preserved; they go channel-aware once Phase 5 reimplements apply.
#      - copy their ProductCategories -> ProductCollections
#      - copy columns + metadata + table translations; MOVE the ActionText description,
#        ActiveStorage image/square_image, metafields, and friendly_id slugs onto the
#        collection (else category.destroy purges/destroys them). Match both
#        'Spree::Taxon' and 'Spree::Category' record_type/sluggable_type (deploy window).
#      (regardless of which taxonomy / name they lived under)
#      then delete the automatic rows from spree_categories (one txn per category, idempotent)
#   2. Manual categories stay as Spree::Category (the nested-set tree, owned via store_id)
#      - manual categories 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. Sever the taxonomy structure from the survivors: drop taxonomy roots left
#      childless after step 1 (keep non-empty roots as top-level categories), then
#      null taxonomy_id on all remaining categories — they are store-owned now.
#      The taxonomy_id COLUMN + spree_taxonomies + the Taxonomy model drop in 6.1.
#   4. Backfill stored class-name strings 'Spree::Taxon*' -> 'Spree::Category*'
#      (Phase 3 renamed the classes and writes the new names; existing rows still
#      hold the old ones, so migrate them here):
#        - spree_metafields.resource_type
#        - spree_metafield_definitions.resource_type
#        - friendly_id_slugs.sluggable_type
#        - active_storage_attachments.record_type   (taxon image / square_image)
#        - action_text_rich_texts.record_type       (description — translates :description, backend: :action_text)
#        - spree_promotion_rules.type               (Promotion::Rules::Taxon -> Category, STI)
#      Direct FK columns (taxon_id/category_id) and the pinned translation table
#      need no change. Same rake run as above, so no additional upgrade window.
#   5. Clean spree_product_type_categories (6.0-product-types.md): delete or
#      re-point rows whose category moved to spree_collections or was a deleted
#      taxonomy root — otherwise dangling category_id FKs survive the split
#
# Handles both upgraded stores (may have localized/renamed standard trees) and
# new 5.5+ stores (arbitrary or zero taxonomies).

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).

Status: implemented as spree/core/lib/tasks/categories_and_collections.rake (spec: spec/lib/tasks/categories_and_collections_spec.rb). Each automatic category migrates in its own transaction — a partial failure rolls back and a re-run skips what's already gone, so the task is idempotent. Automatic categories with child categories are skipped (automatic taxons are leaves; the task refuses to destroy a subtree). After the automatic pass it severs the taxonomy structure (backfill store_id from taxonomy → drop childless taxonomy roots → null taxonomy_id on the rest), then runs the string backfills once for the surviving (manual) category rows.

Phase 5: Reintroduce channel-aware AvailableOn (after 6.0-channels-catalogs-b2b.md)

Gated on the channels plan finishing the available_on → ProductPublication#published_at migration. Until then, CollectionRules::AvailableOn runs the interim legacy-column query shipped in Phase 1.

  • Reimplement CollectionRules::AvailableOn#apply against spree_product_publications.published_at (join), replacing the raw spree_products.available_on query. Decide which channel a store-owned collection's availability rule evaluates against — the store's default channel, or any publication with published_at in the window — and document it (a collection has no channel of its own).
  • No data migration, no registry change — AvailableOn is already registered (Phase 1) and its CollectionRule rows already carry the right value/match_policy from Phase 4; only apply changes.
  • Cross-plan ordering constraint (hard). CollectionRules::AvailableOn is a reader of spree_products.available_on, which 6.0-channels-catalogs-b2b.md Phase 3 ("6.0 cleanup") drops. This phase must land before that column drop — the channels plan's cleanup is blocked on this reimplementation.

Phase 5b: Taxonomy runtime removal (6.0) — shipped

Taxonomy is data-only from 6.0. Nothing creates, touches, or manages a taxonomy at runtime; the model and table survive purely so the 5.6 → 6.0 upgrade task can read existing rows (and so an interrupted upgrade can roll back). What landed:

  • Imports::CreateCategoriesJob builds store-owned categories — a CSV import no longer creates a taxonomy per path root. Every A -> B -> C segment is a category, the first one top-level, which matches what the data migration produces.

  • Taxonomy timestamp touching removed — Product#taxonomies (the has_many through:) and the taxonomy_ids memoized method are gone; product-to-category touching was later removed altogether, along with TouchCategoriesJob.

  • Taxonomy write-back callbacks removed — Taxonomy#set_root / #set_root_taxon_name and Category#sync_taxonomy_name. Renaming a category no longer rewrites a taxonomy's name.

  • Category#requires_taxonomy? and the taxonomy presence validation removed. The method always returned false, so the taxonomy-scoped uniqueness branches were dead code — uniqueness is now unconditionally store-scoped, and check_for_root and parent_belongs_to_same_taxonomy are gone. copy_taxonomy_from_parent stays: a category created under an un-migrated parent still inherits its taxonomy so #ensure_store and .for_store can resolve a store pre-upgrade.

    parent_belongs_to_same_taxonomy did carry one guarantee worth keeping, though — it stopped a category being nested under a parent from another store, as a side effect of taxonomies being store-owned. parent_belongs_to_same_store replaces it directly: a tree belongs to one store, and while the API scopes parents by store, imports, extensions and direct model calls do not. It reads #store rather than the raw column so legacy rows still resolving their store through a taxonomy compare correctly.

  • Unique indexes re-scoped to the store (20260807150001_reindex_spree_categories_by_store). The (name, parent_id, taxonomy_id) / (permalink, parent_id, taxonomy_id) indexes stop constraining anything once spree:migrate_taxons_to_categories_and_collections nulls taxonomy_id — SQL treats NULLs as distinct in unique indexes — and they never matched the store-scoped validation anyway.

    The replacement is a single unique index on (permalink, store_id), and name uniqueness is dropped entirely. The permalink is the category's full path (men/clothing/shirts, built by generate_slug from the parent chain), so it already encodes the hierarchy: scoping it by parent_id was always redundant, and two sibling categories that would clash are already caught because their paths are identical. Names need no constraint at all — the same name in two branches is legitimate, and the permalinks distinguish them.

    This also sidesteps the NULL problem that a parent_id-scoped index creates. Top-level categories have parent_id IS NULL, and unique indexes treat NULLs as distinct, so any index including parent_id silently fails to constrain roots — the common case in 6.0. Leaving parent_id out of the index removes the issue instead of working around it, so no partial indexes, no generated columns, and no per-adapter branching: one plain index behaves identically on PostgreSQL, SQLite, MySQL and MariaDB.

    Ordering is the normal one — migrations first, then rake tasks. That means the migration cannot depend on a rake task having cleaned the data for it; it resolves duplicate permalinks itself before adding the index (see below).

  • Duplicate permalinks are resolved by the migration itself (Spree::CategoryPermalinkDeduplicator, spree/core/lib/spree/). Store-scoped uniqueness surfaced a real data hazard: pre-6.0 permalinks were unique per taxonomy, so one store could legally hold the same permalink under two taxonomies.

    This cannot be left to the upgrade rake task. spree:taxons:backfill_store_id already runs in the 5.5 -> 5.6 upgrade, so a 5.6 store reaches 6.0's db:migrate with store_id populated — a collision would fail index creation and block the deploy before any rake task could run. The migration therefore deduplicates before adding the index.

    The deduplicator works on raw SQL, not Spree::Category: a migration cannot assume the model's callbacks, validations and default scopes match the schema on disk. It groups by the store a category belongs to or resolves through its taxonomy, so rows still awaiting the backfill are covered too — which is why spree:migrate_taxons_to_categories_and_collections still calls it (its own backfill is what gives those rows a store, and assignment would otherwise trip the index row by row). The first category of each group keeps its permalink; the rest get their taxonomy's name appended, then a numeric suffix. Rewriting a permalink re-prefixes the whole subtree, so a child of catalog follows its parent to catalog-shop-b/kids rather than keeping a path its parent no longer has. Idempotent — a second run is a no-op.

  • Taxonomy deregistered from translatable_resources and metafields.enabled_resources, and dropped from the three permission sets — a model being removed shouldn't carry a user-manageable custom-field/translation surface.

  • PermittedAttributes: taxonomy_attributes deleted (unused); taxon_attributes renamed to category_attributes with a deprecated taxon_attributes reader delegating to it (removed 6.1). The taxonomy_id and taxon_rules_attributes keys are gone from it.

  • Factories split — :category is now its own store-owned factory that creates no taxonomy; :taxon remains the legacy taxonomy-backed factory (it builds its own root, since the model no longer does) for the upgrade-path specs.

No NULL-store_id fallbacks. Every category has a store_id: spree:taxons:backfill_store_id runs in the 5.5 -> 5.6 manifest, and #ensure_store — which landed in the same commit that made taxonomy optional — stamps one on create, so no row predates both. #store's taxonomy fallback, the .for_store taxonomy join, the [:taxonomy] preload and the serializers' c.taxonomy&.store_id filter were all written for a state that cannot occur, and are gone. This is what lets acts_as_nested_set be scoped by store (see above).

What deliberately stays until 6.1: the Taxonomy model + table (the upgrade task's source and rollback path), Category#taxonomy, and copy_taxonomy_from_parent, which keeps taxonomy_id consistent for that task. All three go with the column.

Phase 6: Cleanup (6.1)

  • Remove all aliases and deprecation shims (incl. the Spree::Taxon alias, the classification_count alias_attribute, and PermittedAttributes.taxon_attributes)
  • Remove taxonomy_id column from categories
  • Remove spree_taxonomies table + the taxonomy_id column + the taxonomy_brands_name locale key (brands out of scope — no replacement; Product#brand_taxon/#brand_name were already removed in 6.0/Phase 3)
  • Remove automatic, rules_match_policy, sort_order columns from categories (moved to collections), plus the dead hide_from_nav column (its Ruby/SDK surface went in 6.0 — see Key Decisions → Category)
  • Drop spree_taxon_rules + Spree::TaxonRule / TaxonRules::* + the config.spree.taxon_rules registry (retained data-only through 6.0 so the Phase 4 data migration can read them; rows were copied to spree_collection_rules, and CollectionRule is net-new so there's no alias to keep)
  • Remove the deprecated Ruby-level aliases kept through 6.0: the taxons and classifications method aliases on Product/Category/Store, the taxon/taxon= readers on the join models, and the rule's taxons/taxon_ids/eligible_taxon_ids/taxon_ids_to_add aliases
  • Remove the deprecated constant + service/job/queue aliases kept through 6.0: Spree::Taxon, Spree::Classification, Spree::PromotionRuleTaxon, Spree::Promotion::Rules::Taxon (constant aliases + their load-time Spree::Deprecation.warn); the Spree::Taxons::AddProducts/RemoveProducts/RegenerateProducts, Spree::Products::AutoMatchTaxons/AutoMatchTaxonsJob wrappers; and the Spree.queues.taxons singleton method
  • Rename spree_prototype_taxons (with 6.0-product-types.md), dropping the foreign_key: :taxon_id pin on Category#prototype_taxons (the #taxon_rules pin goes away with the spree_taxon_rules drop above)

Constraints on Current Work

  • Use categories in all new API code. The Store API already does this. Don't introduce new taxon references in API v3.
  • Use Spree::Category in new code. It is the canonical class now; Spree::Taxon is a deprecation alias (removed in 6.1).
  • Don't add new TaxonRule subtypes. TaxonRule is data-only from 6.0 (matching removed); new rule types go on CollectionRule.
  • Don't add new Taxonomy-dependent features. Taxonomy is data-only from 6.0 (see Phase 5b) and dropped in 6.1 — don't read it, write it, or register it anywhere. The only permitted references are the upgrade rake tasks and the pre-upgrade store-resolution fallbacks.
  • Keep the ctg_ prefix. Already in use, will carry over.
  • New "collection-like" (rule-based) features go on Spree::Collection — the taxon automatic-match path was removed in Phase 2.
  • 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

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). Ships in Phase 1 with AvailableOn as its one registered rule (interim legacy-column implementation; channel-aware reimplementation in Phase 5). See Design Details → Automatic collection regeneration.
  • Collection nesting — collections stay flat; hierarchy lives in Category (matches Shopify and keeps the Category/Collection split clean).
  • "Manual" (position) sort in the v3 Store API — resolved for both providers.
    • DB provider (shipped): SearchProvider::Database infers the grouping from the applied in_category/in_collection filter (manual_sort_grouping), defaults a grouping page's blank sort to manual, and orders by ProductCollection.position (flat) for collections or MIN(ProductCategory.position) grouped per product (subtree collapse) for categories — reusing the join the filter already made, so no extra query.
    • Meilisearch provider — single index + distinct (Algolia's "duplicate records" recipe). ProductPresenter emits, alongside each base doc, one membership doc per grouping (each collection + each category ancestor-or-self) carrying a shared scalar grouping_id + position; a manual grouping page filters grouping_id and sorts position:asc, while an index-level distinctAttribute = product_id collapses the duplicates on shop-all/search/non-manual queries. Facet counts + totals stay accurate under distinct (verified on MS ≥ 1.40, incl. 1.42.1 and 1.49.0). Rejected alternatives: a two-index "membership index B" (extra index + dual-write; deferred as premature optimization — the escape hatch if the distinct tax hurts) and per-grouping nested sortable attributes (unbounded sortable list + reindex-per-grouping anti-pattern).

No open questions remain — all resolved above.

References

  • Industry pattern: hierarchical Category + flat Collection (manual and/or rule-based) is the standard across modern headless commerce platforms
  • Current Spree API: already uses categories naming in Store API v3
  • Related plan: 6.0-product-types.md (ProductTypeCategory join table)