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
feat(core): add Collection stack models
Łukasz Adamczyk2652c1d39fe0
diff --git a/spree/core/app/models/spree/collection.rb b/spree/core/app/models/spree/collection.rbnew file mode 100644index 0000000000..3948b5b606--- /dev/null+++ b/spree/core/app/models/spree/collection.rb@@ -0,0 +1,188 @@+# frozen_string_literal: true++require 'stringex'++module Spree+ class Collection < Spree.base_class+ include Spree::SingleStoreResource++ has_prefix_id :coll++ RULES_MATCH_POLICIES = %w[all any].freeze+ # Same values/format as Spree::Taxon::SORT_ORDERS — required by the search sort+ # pipeline (FiltersAggregator#to_api_sort splits on a space; apply_sort maps to 'price'/etc.).+ SORT_ORDERS = Spree::Taxon::SORT_ORDERS++ include Spree::TranslatableResource+ include Spree::TranslatableResourceSlug+ include Spree::Metafields+ include Spree::Metadata++ #+ # Slug / permalink — FriendlyId with history (mirrors Spree::Taxon; flat, no hierarchy).+ # `use: :history` keeps old permalinks resolving via the shared friendly_id_slugs table+ # after a rename. Declared before `translates` (as in Taxon). Within-store uniqueness is+ # still enforced by the validation + DB index below — a collision errors (as in Taxon),+ # it does not auto-suffix.+ #+ extend FriendlyId+ friendly_id :permalink, slug_column: :permalink, use: :history++ TRANSLATABLE_FIELDS = %i[name description permalink].freeze+ translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)++ #+ # Action Text+ #+ # Interim: description via ActionText (mirrors Spree::Taxon). 6.0-rich-text-descriptions.md+ # migrates both Category and Collection off ActionText later.+ translates :description, backend: :action_text++ #+ # Associations+ #+ belongs_to :store, class_name: 'Spree::Store'++ has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async, inverse_of: :collection+ has_many :products, through: :product_collections++ has_many :collection_rules, class_name: 'Spree::CollectionRule', dependent: :destroy, inverse_of: :collection+ accepts_nested_attributes_for :collection_rules, allow_destroy: true, reject_if: proc { |attributes|+ attributes['value'].blank?+ }+ alias rules collection_rules++ #+ # Attachments+ #+ has_one_attached :image, service: Spree.public_storage_service_name+ has_one_attached :square_image, service: Spree.public_storage_service_name++ #+ # Positioning (flat, store-scoped)+ #+ acts_as_list scope: :store_id++ #+ # Validations+ #+ 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+ validates :hide_from_nav, inclusion: { in: [true, false] }++ before_validation :set_permalink, if: :name++ #+ # Scopes+ #+ scope :manual, -> { where.not(automatic: true) }+ scope :automatic, -> { where(automatic: true) }++ #+ # Automatic (rule-based) membership+ #+ after_commit :regenerate_products, on: [:update], if: -> { automatic? && saved_change_to_rules_match_policy? }+ attribute :marked_for_regenerate_products, :boolean, default: true++ def manual?+ !automatic?+ end++ def manual_sort_order?+ sort_order == 'manual'+ end++ def slug+ permalink+ end++ def slug=(value)+ self.permalink = value+ end++ # Rebuild the materialized ProductCollection membership from the rules.+ # Pass only_once: true to fire at most once per object lifecycle.+ #+ # @param only_once [Boolean]+ # @return [void]+ def regenerate_products(only_once: false)+ return unless marked_for_regenerate_products?++ Spree::Collections::RegenerateProducts.call(collection: self)+ self.marked_for_regenerate_products = false if !frozen? && only_once+ end++ # Products matching the automatic rules (mirrors Spree::Taxon#products_matching_rules).+ #+ # @return [ActiveRecord::Relation]+ def products_matching_rules(opts = {})+ return Spree::Product.none if manual? || rules.empty?++ currency = opts[:currency] || store.default_currency+ storefront = opts[:storefront] || false++ all_products = store.products.not_archived+ all_products = all_products.active(currency: currency) if storefront++ any_rules_match_policy = rules_match_policy == 'any'+ products = any_rules_match_policy ? Spree::Product.none : all_products++ rules.each do |rule|+ if any_rules_match_policy+ product_ids = rule.apply(all_products).ids+ products = products.or(all_products.where(id: product_ids)) if product_ids.any?+ else+ products = rule.apply(products)+ end+ end++ products+ end++ # Slug generation, flat (no parent hierarchy). Mirrors Spree::Taxon's dual set_permalink:+ # with translations off, the model writes the base permalink column directly (which+ # column_fallback routes the default locale to, bypassing the Translation before_save);+ # with translations on, each Translation generates its own. An existing permalink is+ # sticky — renaming the collection does not rewrite it (set permalink explicitly to change).+ def set_permalink+ if Spree.use_translations?+ translations.each(&:set_permalink)+ else+ self.permalink = generate_slug+ end+ end++ def generate_slug+ permalink.blank? ? name.to_url : permalink.to_url+ end++ # Per-locale slug accessors + generation on the Mobility translation.+ self::Translation.class_eval do+ before_save :set_permalink++ def slug+ permalink+ end++ def slug=(value)+ self.permalink = value+ end++ def set_permalink+ self.permalink = generate_slug+ end++ def name_with_fallback+ name.blank? ? translated_model[:name] : name+ end++ private++ def generate_slug+ permalink.blank? ? name_with_fallback.to_url : permalink.to_url+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/collection_rule.rb b/spree/core/app/models/spree/collection_rule.rbnew file mode 100644index 0000000000..e864717fcb--- /dev/null+++ b/spree/core/app/models/spree/collection_rule.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++module Spree+ class 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: :collection_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? }++ delegate :store, to: :collection++ private++ def regenerate_collection_products+ collection.regenerate_products(only_once: true)+ end+ end+enddiff --git a/spree/core/app/models/spree/collection_rules/available_on.rb b/spree/core/app/models/spree/collection_rules/available_on.rbnew file mode 100644index 0000000000..b9091741c4--- /dev/null+++ b/spree/core/app/models/spree/collection_rules/available_on.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module Spree+ module CollectionRules+ class AvailableOn < Spree::CollectionRule+ # value is the number of days; matches products created/available within that window.+ def apply(scope)+ timezone = collection.store.preferred_timezone+ date = value.to_i.days.ago.beginning_of_day.in_time_zone(timezone)++ if match_policy == 'is_equal_to'+ scope.where(['spree_products.created_at >= ?', date]).or(+ scope.where(['spree_products.available_on >= ?', date])+ )+ else+ scope+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/collection_rules/sale.rb b/spree/core/app/models/spree/collection_rules/sale.rbnew file mode 100644index 0000000000..f695e4558b--- /dev/null+++ b/spree/core/app/models/spree/collection_rules/sale.rb@@ -0,0 +1,18 @@+# frozen_string_literal: true++module Spree+ module CollectionRules+ class Sale < Spree::CollectionRule+ def apply(scope)+ case match_policy+ when 'is_equal_to' || 'contains'+ scope.on_sale(store.default_currency)+ when 'is_not_equal_to' || 'does_not_contain'+ scope.where.not(id: scope.on_sale(store.default_currency))+ else+ scope+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/collection_rules/tag.rb b/spree/core/app/models/spree/collection_rules/tag.rbnew file mode 100644index 0000000000..8307eae502--- /dev/null+++ b/spree/core/app/models/spree/collection_rules/tag.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module Spree+ module CollectionRules+ class Tag < Spree::CollectionRule+ def apply(scope)+ if match_policy == 'is_equal_to'+ scope.tagged_with(value)+ elsif match_policy == 'is_not_equal_to'+ scope.tagged_with(value, exclude: true)+ elsif match_policy == 'contains'+ scope.tagged_with(value, any: true)+ elsif match_policy == 'does_not_contain'+ scope.tagged_with(value, any: true, exclude: true)+ else+ scope+ end+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/product_collection.rb b/spree/core/app/models/spree/product_collection.rbnew file mode 100644index 0000000000..bd94c19f20--- /dev/null+++ b/spree/core/app/models/spree/product_collection.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module Spree+ class ProductCollection < Spree.base_class+ self.table_name = 'spree_product_collections'++ acts_as_list scope: :collection++ # products_count is a plain Rails counter_cache on the collection (collections are+ # flat, so — unlike Classification — there is no descendant-inclusive recompute).+ 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,+ inverse_of: :product_collections++ validates :product, :collection, presence: true+ validates :position, numericality: { only_integer: true, allow_blank: true, allow_nil: true }+ validates :collection_id, uniqueness: { scope: :product_id, message: :already_linked, allow_blank: true }++ self.whitelisted_ransackable_attributes = %w[collection_id product_id]+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/collection_factory.rb b/spree/core/lib/spree/testing_support/factories/collection_factory.rbnew file mode 100644index 0000000000..64a0b46493--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/collection_factory.rb@@ -0,0 +1,25 @@+FactoryBot.define do+ factory :collection, class: Spree::Collection do+ sequence(:name) { |n| "collection_#{n}" }+ store { Spree::Store.default }++ trait :with_description do+ description { '<div>Test <strong>description</strong></div>' }+ end++ trait :with_image do+ after(:create) do |collection|+ collection.image.attach(io: File.new(Spree::Core::Engine.root.join('spec', 'fixtures', 'thinking-cat.jpg')), filename: 'thinking-cat.jpg')+ end+ end+ end++ factory :automatic_collection, parent: :collection do+ automatic { true }+ rules_match_policy { 'all' }++ trait :any_match_policy do+ rules_match_policy { 'any' }+ end+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/collection_rule_factory.rb b/spree/core/lib/spree/testing_support/factories/collection_rule_factory.rbnew file mode 100644index 0000000000..0c79800987--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/collection_rule_factory.rb@@ -0,0 +1,47 @@+FactoryBot.define do+ factory :sale_collection_rule, class: Spree::CollectionRules::Sale do+ value { true }++ trait :is_equal_to do+ match_policy { 'is_equal_to' }+ end++ trait :is_not_equal_to do+ match_policy { 'is_not_equal_to' }+ end++ trait :contains do+ match_policy { 'contains' }+ end++ trait :does_not_contain do+ match_policy { 'does_not_contain' }+ end+ end++ factory :tag_collection_rule, class: Spree::CollectionRules::Tag do+ trait :is_equal_to do+ match_policy { 'is_equal_to' }+ end++ trait :is_not_equal_to do+ match_policy { 'is_not_equal_to' }+ end++ trait :contains do+ match_policy { 'contains' }+ end++ trait :does_not_contain do+ match_policy { 'does_not_contain' }+ end+ end++ factory :available_on_collection_rule, class: Spree::CollectionRules::AvailableOn do+ value { 30 }++ trait :is_equal_to do+ match_policy { 'is_equal_to' }+ end+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/product_collection_factory.rb b/spree/core/lib/spree/testing_support/factories/product_collection_factory.rbnew file mode 100644index 0000000000..01ba194520--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/product_collection_factory.rb@@ -0,0 +1,8 @@+FactoryBot.define do+ factory :product_collection, class: Spree::ProductCollection do+ product+ collection++ position { 1 }+ end+enddiff --git a/spree/core/spec/models/spree/collection_rule_spec.rb b/spree/core/spec/models/spree/collection_rule_spec.rbnew file mode 100644index 0000000000..e044fc58d3--- /dev/null+++ b/spree/core/spec/models/spree/collection_rule_spec.rb@@ -0,0 +1,66 @@+require 'spec_helper'++RSpec.describe Spree::CollectionRule, type: :model do+ let(:store) { @default_store }+ let(:collection) { create(:automatic_collection, store: store) }++ describe 'validations' do+ it 'rejects an unknown match_policy' do+ rule = build(:tag_collection_rule, collection: collection, value: 'sale', match_policy: 'nonsense')++ expect(rule).not_to be_valid+ expect(rule.errors[:match_policy]).to be_present+ end++ it 'requires a value' do+ rule = build(:tag_collection_rule, :is_equal_to, collection: collection, value: nil)++ expect(rule).not_to be_valid+ expect(rule.errors[:value]).to be_present+ end+ end++ # Assert the callback reaches the collection's regeneration; stub only the+ # effect (the 1c service that fulfills it).+ describe 'regeneration callback' do+ before { allow(collection).to receive(:regenerate_products) }++ it 'regenerates the collection products when a rule is created' do+ expect(collection).to receive(:regenerate_products).with(only_once: true)++ create(:tag_collection_rule, :is_equal_to, collection: collection, value: 'sale')+ end++ it 'regenerates when the value changes' do+ rule = create(:tag_collection_rule, :is_equal_to, collection: collection, value: 'sale')++ expect(collection).to receive(:regenerate_products).with(only_once: true)+ rule.update!(value: 'new-sale')+ end++ it 'regenerates when the rule is destroyed' do+ rule = create(:tag_collection_rule, :is_equal_to, collection: collection, value: 'sale')++ expect(collection).to receive(:regenerate_products).with(only_once: true)+ rule.destroy!+ end+ end++ # Tag and Sale rule application is covered via Collection#products_matching_rules;+ # AvailableOn is exercised directly here.+ describe Spree::CollectionRules::AvailableOn do+ let!(:recent_product) { create(:product).tap { |p| p.update_columns(available_on: 1.day.ago) } }+ let!(:old_product) do+ create(:product).tap { |p| p.update_columns(available_on: 90.days.ago, created_at: 90.days.ago) }+ end++ it 'matches products created or available within the window' do+ rule = build(:available_on_collection_rule, :is_equal_to, collection: collection, value: 30)++ result = rule.apply(store.products.not_archived)++ expect(result).to include(recent_product)+ expect(result).not_to include(old_product)+ end+ end+enddiff --git a/spree/core/spec/models/spree/collection_spec.rb b/spree/core/spec/models/spree/collection_spec.rbnew file mode 100644index 0000000000..0f3453a6e3--- /dev/null+++ b/spree/core/spec/models/spree/collection_spec.rb@@ -0,0 +1,173 @@+require 'spec_helper'++RSpec.describe Spree::Collection, type: :model do+ let(:store) { @default_store }++ it_behaves_like 'metadata'++ describe 'permalink generation' do+ it 'derives a url-safe permalink from the name' do+ expect(create(:collection, name: 'Summer Sale').permalink).to eq('summer-sale')+ end++ it 'keeps an explicit permalink' do+ expect(create(:collection, name: 'Summer Sale', permalink: 'custom').permalink).to eq('custom')+ end++ it 'supports non-latin characters' do+ expect(create(:collection, name: '你好').permalink).to eq('ni-hao')+ end+ end++ describe 'permalink uniqueness + slug history (FriendlyId)' do+ it 'allows the same permalink in different stores' do+ other = create(:store)+ create(:collection, name: 'Summer', store: store)++ expect(build(:collection, name: 'Summer', store: other)).to be_valid+ end++ it 'rejects a duplicate permalink within the same store (errors, does not auto-suffix)' do+ create(:collection, name: 'Summer', store: store)+ duplicate = build(:collection, name: 'Summer', store: store)++ expect(duplicate).not_to be_valid+ expect(duplicate.errors[:permalink]).to be_present+ end++ it 'keeps an old permalink resolving after a rename (use: :history)' do+ collection = create(:collection, name: 'Summer', store: store)+ old_permalink = collection.permalink+ collection.update!(permalink: 'winter')++ expect(described_class.friendly.find(old_permalink)).to eq(collection)+ expect(collection.reload.permalink).to eq('winter')+ end+ end++ describe 'validations' do+ it 'rejects an unknown sort_order' do+ collection = build(:collection, sort_order: 'nonsense')++ expect(collection).not_to be_valid+ expect(collection.errors[:sort_order]).to be_present+ end++ it 'rejects an unknown rules_match_policy' do+ collection = build(:collection, rules_match_policy: 'nonsense')++ expect(collection).not_to be_valid+ expect(collection.errors[:rules_match_policy]).to be_present+ end+ end++ describe '#manual? / #manual_sort_order?' do+ it { expect(build(:collection).manual?).to be(true) }+ it { expect(build(:automatic_collection).manual?).to be(false) }+ it { expect(build(:collection, sort_order: 'manual').manual_sort_order?).to be(true) }+ it { expect(build(:collection, sort_order: 'price asc').manual_sort_order?).to be(false) }+ end++ describe 'scopes' do+ let!(:manual) { create(:collection) }+ let!(:automatic) { create(:automatic_collection) }++ it 'partitions manual and automatic collections' do+ expect(described_class.manual).to include(manual)+ expect(described_class.manual).not_to include(automatic)+ expect(described_class.automatic).to include(automatic)+ expect(described_class.automatic).not_to include(manual)+ end+ end++ describe 'description (ActionText)' do+ it 'round-trips rich text' do+ collection = create(:collection, description: '<p>Hello <strong>world</strong></p>')++ expect(collection.reload.description.to_plain_text).to eq('Hello world')+ end+ end++ describe 'automatic regeneration callback' do+ let(:collection) { create(:automatic_collection) }++ it 'regenerates products when the match policy changes' do+ expect(collection).to receive(:regenerate_products)++ collection.update!(rules_match_policy: 'any')+ end++ it 'does not regenerate a manual collection on an unrelated change' do+ manual = create(:collection)+ expect(manual).not_to receive(:regenerate_products)++ manual.update!(name: 'Renamed')+ end+ end++ describe '#products_matching_rules' do+ context 'when the collection is manual' do+ let(:collection) { create(:collection) }++ it 'returns nothing' do+ expect(collection.products_matching_rules).to be_empty+ end+ end++ context 'when the collection is automatic with no rules' do+ let(:collection) { create(:automatic_collection) }++ it 'returns nothing' do+ expect(collection.products_matching_rules).to be_empty+ end+ end++ # Stub only the regeneration effect (the 1c service that wires it) so real+ # rules can persist and be read back through the association.+ context 'when the collection has tag rules' do+ before { allow(collection).to receive(:regenerate_products) }++ let(:sale_tag) { ActsAsTaggableOn::Tag.create(name: 'sale') }+ let(:new_tag) { ActsAsTaggableOn::Tag.create(name: 'new') }+ let!(:sale_product) { create(:product, tags: [sale_tag]) }+ let!(:both_product) { create(:product, tags: [sale_tag, new_tag]) }+ let!(:new_product) { create(:product, tags: [new_tag]) }++ context 'with the "all" match policy' do+ let(:collection) { create(:automatic_collection) }++ it 'matches products carrying every tag' do+ create(:tag_collection_rule, :is_equal_to, collection: collection, value: 'sale')+ create(:tag_collection_rule, :is_equal_to, collection: collection, value: 'new')++ expect(collection.reload.products_matching_rules).to contain_exactly(both_product)+ end+ end++ context 'with the "any" match policy' do+ let(:collection) { create(:automatic_collection, :any_match_policy) }++ it 'matches products carrying any tag' do+ create(:tag_collection_rule, :is_equal_to, collection: collection, value: 'sale')+ create(:tag_collection_rule, :is_equal_to, collection: collection, value: 'new')++ expect(collection.reload.products_matching_rules).to contain_exactly(sale_product, both_product, new_product)+ end+ end+ end++ context 'when the collection has a sale rule' do+ before { allow(collection).to receive(:regenerate_products) }++ let(:collection) { create(:automatic_collection) }+ let!(:on_sale) { create(:product, price: 10, compare_at_price: 12) }+ let!(:not_on_sale) { create(:product, price: 10) }++ it 'matches products on sale in the store currency' do+ create(:sale_collection_rule, :is_equal_to, collection: collection)++ expect(collection.reload.products_matching_rules).to contain_exactly(on_sale)+ end+ end+ end+enddiff --git a/spree/core/spec/models/spree/product_collection_spec.rb b/spree/core/spec/models/spree/product_collection_spec.rbnew file mode 100644index 0000000000..77636f07fb--- /dev/null+++ b/spree/core/spec/models/spree/product_collection_spec.rb@@ -0,0 +1,38 @@+require 'spec_helper'++RSpec.describe Spree::ProductCollection, type: :model do+ let(:store) { @default_store }+ let(:collection) { create(:collection, store: store) }+ let(:product) { create(:product, store: store) }++ describe 'uniqueness' do+ it 'cannot link the same product to the same collection twice' do+ create(:product_collection, collection: collection, product: product)++ expect {+ create(:product_collection, collection: collection, product: product)+ }.to raise_error(ActiveRecord::RecordInvalid)+ end+ end++ describe 'counter caches' do+ it 'maintains products_count on the collection' do+ expect {+ create(:product_collection, collection: collection, product: product)+ }.to change { collection.reload.products_count }.from(0).to(1)+ end++ it 'maintains collections_count on the product' do+ expect {+ create(:product_collection, collection: collection, product: product)+ }.to change { product.reload.collections_count }.from(0).to(1)+ end++ it 'decrements both counters on destroy' do+ product_collection = create(:product_collection, collection: collection, product: product)++ expect { product_collection.destroy }.to change { collection.reload.products_count }.from(1).to(0).+ and change { product.reload.collections_count }.from(1).to(0)+ end+ end+end