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
fix for product slug candidates and history (#12895)
Szymon Chorobskie0dba1b2798a
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rbindex eb6e4b456a..5bc225d20b 100644--- a/core/app/models/spree/product.rb+++ b/core/app/models/spree/product.rb@@ -20,14 +20,17 @@module Spreeclass Product < Spree.base_class- extend FriendlyId+ acts_as_paranoid+ acts_as_taggable_on :tags, :labels+ auto_strip_attributes :name+include Spree::ProductScopesinclude Spree::MultiStoreResourceinclude Spree::TranslatableResource- include Spree::TranslatableResourceSluginclude Spree::MemoizedDatainclude Spree::Metadatainclude Spree::Product::Webhooks+ include Spree::Product::Slugsif defined?(Spree::VendorConcern)include Spree::VendorConcernend@@ -52,33 +55,8 @@ module Spreepg_search_scope :search_by_name, against: { name: 'A', meta_title: 'B' }, using: { trigram: { threshold: 0.3, word_similarity: true } }end-- before_save :set_slug- acts_as_paranoid- # deleted translation values also need to be accessible for index views listing deleted resources- default_scope { unscope(where: :deleted_at) }- def set_slug- self.slug = generate_slug- end-- private-- def generate_slug- if name.blank? && slug.blank?- translated_model.name.to_url- elsif slug.blank?- name.to_url- else- slug.to_url- end- endend- friendly_id :slug_candidates, use: [:history, :scoped, :mobility], scope: spree_base_uniqueness_scope- acts_as_paranoid- auto_strip_attributes :name- acts_as_taggable_on :tags, :labels-# we need to have this callback before any dependent: :destroy associations# https://github.com/rails/rails/issues/3458before_destroy :ensure_not_in_complete_orders@@ -144,17 +122,12 @@ module Spreeafter_initialize :ensure_masterafter_initialize :assign_default_tax_category- before_validation :downcase_slug- before_validation :normalize_slug, on: :updatebefore_validation :validate_masterbefore_validation :ensure_default_shipping_categoryafter_create :add_associations_from_prototypeafter_create :build_variants_from_option_values_hash, if: :option_values_hash- after_destroy :punch_slug- after_restore :update_slug_history-after_save :save_masterafter_save :run_touch_callbacks, if: :anything_changed?after_save :reset_nested_changes@@ -172,7 +145,6 @@ module Spreevalidates :price, if: :requires_price?end- validates :slug, presence: true, uniqueness: { allow_blank: true, case_sensitive: true, scope: spree_base_uniqueness_scope }validate :discontinue_on_must_be_later_than_make_active_at, if: -> { make_active_at && discontinue_on }scope :for_store, ->(store) { joins(:store_products).where(StoreProduct.table_name => { store_id: store.id }) }@@ -511,17 +483,6 @@ module Spreewhere conditions.inject(:or)end- def self.slug_available?(slug, id)- !where(slug: slug).where.not(id: id).exists?- end-- def ensure_slug_is_unique(candidate_slug)- return slug if candidate_slug.blank? || slug.blank?- return candidate_slug if self.class.slug_available?(candidate_slug, id)-- normalize_friendly_id([candidate_slug, uuid_for_friendly_id])- end-# Suitable for displaying only variants that has at least one option value.# There may be scenarios where an option type is removed and along with it# all option values. At that point all variants associated with only those@@ -737,25 +698,6 @@ module Spreeself.tax_category = Spree::TaxCategory.default if new_record?end- def normalize_slug- self.slug = normalize_friendly_id(slug)- end-- def punch_slug- # punch slug with date prefix to allow reuse of original- return if frozen?-- update_column(:slug, "#{Time.current.to_i}_#{slug}"[0..254])-- translations.with_deleted.each do |t|- t.update_column :slug, "#{Time.current.to_i}_#{t.slug}"[0..254]- end- end-- def update_slug_history- save!- end-def anything_changed?saved_changes? || @nested_changesend@@ -811,14 +753,6 @@ module Spreeendend- # Try building a slug based on the following fields in increasing order of specificity.- def slug_candidates- [- :name,- [:name, :sku]- ]- end-def run_touch_callbacksrun_callbacks(:touch)end@@ -866,10 +800,6 @@ module Spreepreviously_new_record? || tag_list_previously_changed? || available_on_previously_changed?end- def downcase_slug- slug&.downcase!- end-def after_activate# Implement your logic hereenddiff --git a/core/app/models/spree/product/slugs.rb b/core/app/models/spree/product/slugs.rbnew file mode 100644index 0000000000..5b1b6e9a8d--- /dev/null+++ b/core/app/models/spree/product/slugs.rb@@ -0,0 +1,103 @@+module Spree+ class Product < Spree.base_class+ module Slugs+ extend ActiveSupport::Concern++ included do+ extend FriendlyId+ include Spree::TranslatableResourceSlug++ translates :slug+ friendly_id :slug_candidates, use: [:history, :slugged, :scoped, :mobility], scope: spree_base_uniqueness_scope, slug_limit: 255++ Product::Translation.class_eval do+ before_save :set_slug+ acts_as_paranoid+ # deleted translation values also need to be accessible for index views listing deleted resources+ default_scope { unscope(where: :deleted_at) }++ private++ def set_slug+ self.slug = generate_slug+ end++ def generate_slug+ if name.blank? && slug.blank?+ translated_model.name.to_url+ elsif slug.blank?+ name.to_url+ else+ slug.to_url+ end+ end+ end++ before_validation :downcase_slug+ before_validation :normalize_slug, on: :update+ after_destroy :punch_slugs+ after_restore :regenerate_slug++ validates :slug, presence: true, uniqueness: { allow_blank: true, case_sensitive: true, scope: spree_base_uniqueness_scope }++ def self.slug_available?(slug, id)+ !where(slug: slug).where.not(id: id).exists?+ end+ end++ def ensure_slug_is_unique(candidate_slug)+ return slug if candidate_slug.blank? || slug.blank?+ return candidate_slug if self.class.slug_available?(candidate_slug, id)++ normalize_friendly_id([candidate_slug, uuid_for_friendly_id])+ end++ private++ def slug_candidates+ if defined?(:deleted_at) && deleted_at.present?+ [+ ['deleted', :name],+ ['deleted', :name, :sku],+ ['deleted', :name, :uuid_for_friendly_id]+ ]+ else+ [+ [:name],+ [:name, :sku],+ [:name, :uuid_for_friendly_id]+ ]+ end+ end++ def downcase_slug+ slug&.downcase!+ end++ def normalize_slug+ self.slug = normalize_friendly_id(slug)+ end++ def regenerate_slug+ self.slug = nil+ save!+ end++ def punch_slugs+ return if new_record? || frozen?++ self.slug = nil++ set_slug+ update_column(:slug, slug)++ new_slug = ->(rec) { "deleted-#{rec.id}_#{rec.slug}"[..254] }++ translations.with_deleted.each { |rec| rec.update_columns(slug: new_slug.call(rec)) }+ slugs.with_deleted.each { |rec| rec.update_column(:slug, new_slug.call(rec)) }++ translations.find_by!(locale: I18n.locale).update_column(:slug, slug) if Spree.use_translations?+ end+ end+ end+enddiff --git a/core/spec/models/spree/product/slugs_spec.rb b/core/spec/models/spree/product/slugs_spec.rbnew file mode 100644index 0000000000..2f91940caf--- /dev/null+++ b/core/spec/models/spree/product/slugs_spec.rb@@ -0,0 +1,232 @@+require 'spec_helper'++describe Spree::Product::Slugs, type: :model do+ let(:store) { Spree::Store.default }++ let(:product) { create(:product, stores: [store], slug: product_slug) }+ let(:product_slug) { nil }++ context 'with not normalized slug' do+ let(:product_slug) { 'hey//joe' }++ it 'normalizes slug on update validation' do+ expect { product.valid? }.to change(product, :slug).to('hey-joe')+ end+ end++ context 'with slug history' do+ before do+ product.update!(name: 'ala', slug: nil)+ end++ it 'updates slugs withs deleted-{id} prefix to ensure uniqueness' do+ expect { product.destroy! }.to change { product.slugs.with_deleted.first.slug }.to a_string_matching(/deleted-\d+_.*/)+ end++ it 'soft deletes slug record' do+ expect { product.destroy! }.to change { product.slugs.with_deleted.first.deleted? }.to be_truthy+ end+ end++ describe 'ability to retake a slug of deleted record with the same name' do+ let(:another_product) { create(:product, name: name) }+ let(:product) { build(:product, name: name) }++ let(:name) { 'product-name' }++ it 'can use original slug' do+ original_slugs_slug = another_product.slugs.first.slug+ original_product_slug = another_product.slug++ another_product.destroy!+ product.save!++ expect(product.slugs.first.slug).to eq(original_slugs_slug)+ expect(product.slug).to eq(original_product_slug)+ end+ end++ it 'stores old slugs in FriendlyIds history' do+ expect(product).to receive(:create_slug)+ # Set it, otherwise the create_slug method avoids writing a new one+ product.slug = 'custom-slug'+ product.run_callbacks :save+ end++ context 'when product destroyed' do+ it 'renames slug' do+ product.destroy!+ expect(product.slug).to match(/deleted-product-[0-9]+/)+ end++ context 'when more than one translation exists' do+ before do+ product.set_friendly_id('french-slug', :fr)+ product.save!+ end++ it 'renames slug for all translations' do+ product.destroy!++ expect(product.slug).to match(/deleted-product-[0-9]+/)+ expect(product.translations.with_deleted.where(locale: :fr).first.slug).to match(/deleted-\d+_french-slug/)+ end+ end++ context 'when slug is already at or near max length' do+ before do+ product.slug = nil+ product.name = 'x' * 255+ product.save!+ product.translations.create!(slug: product.name, locale: 'de')+ end++ it 'truncates renamed slug to ensure it remains within length limit' do+ product.destroy!+ expect(product.slug.length).to eq(255)+ expect(product.slugs.with_deleted.first.slug.length).to eq(255)+ expect(product.translations.with_deleted.first.slug.length).to eq(255)+ end+ end+ end++ it 'validates slug uniqueness' do+ existing_product = product+ new_product = create(:product, stores: [store])+ new_product.slug = existing_product.slug++ expect(new_product.valid?).to be false+ end++ it "falls back to 'name-sku' for slug if regular name-based slug already in use" do+ product1 = build(:product, stores: [store])+ product1.name = 'test'+ product1.sku = '123'+ product1.save!++ product2 = build(:product, stores: [store])+ product2.name = 'test'+ product2.sku = '456'+ product2.save!++ expect(product2.slug).to eq 'test-456'+ end++ context 'history' do+ before do+ @product = create(:product, stores: [store])+ end++ it 'keeps the history when the product is destroyed' do+ @product.destroy++ expect(@product.slugs.with_deleted).not_to be_empty+ end++ it 'updates the history when the product is restored' do+ @product.destroy++ @product.restore(recursive: true)++ latest_slug = @product.slugs.find_by slug: @product.slug+ expect(latest_slug).not_to be_nil+ end+ end++ describe '#localized_slugs_for_store' do+ subject { product.localized_slugs_for_store(store) }++ let(:store) { create(:store, default_locale: 'fr', supported_locales: 'en,pl,fr') }+ let(:product) { create(:product, stores: [store], name: 'Test product', slug: 'test-slug-en') }+ let!(:product_translation_fr) { product.translations.create(slug: 'test_slug_fr', locale: 'fr') }++ before { Spree::Locales::SetFallbackLocaleForStore.new.call(store: store) }++ context 'when there are slugs in locales not supported by the store' do+ before do+ product.translations.create!(slug: 'test_slug_pl', locale: 'pl')+ product.translations.create!(slug: 'test_slug_de', locale: 'de')+ end++ let(:expected_slugs) do+ {+ 'en' => 'test-slug-en',+ 'fr' => 'test-slug-fr',+ 'pl' => 'test-slug-pl'+ }+ end++ it 'returns only slugs in locales supported by the store' do+ expect(subject).to match(expected_slugs)+ end+ end++ context 'when one of the supported locales does not have a translation' do+ let(:expected_slugs) do+ {+ 'en' => 'test-slug-en',+ 'fr' => 'test-slug-fr',+ 'pl' => 'test-slug-fr'+ }+ end++ it "falls back to store's default locale" do+ expect(subject).to match(expected_slugs)+ end+ end++ context 'the slugs are generated from name when slug field is empty' do+ before do+ product_translation_fr.update(slug: nil, name: 'slug from name')+ end++ let(:expected_slugs) do+ {+ 'en' => 'test-slug-en',+ 'fr' => 'slug-from-name',+ 'pl' => 'slug-from-name'+ }+ end++ it 'saves slugs generated from name' do+ expect(subject).to match(expected_slugs)+ end+ end++ context 'the slugs are generated from default locale name when name and slug for translation is empty' do+ before do+ product_translation_fr.update(slug: nil, name: nil)+ end++ let(:expected_slugs) do+ {+ 'en' => 'test-slug-en',+ 'fr' => 'test-product',+ 'pl' => 'test-product'+ }+ end++ it 'saves slugs generated from fallback name' do+ expect(subject).to match(expected_slugs)+ end+ end++ context 'the slugs are generated from invalid slug format' do+ before do+ product_translation_fr.update(slug: 'slug with_spaces')+ end++ let(:expected_slugs) do+ {+ 'en' => 'test-slug-en',+ 'fr' => 'slug-with-spaces',+ 'pl' => 'slug-with-spaces'+ }+ end++ it 'saves slugs in valid format' do+ expect(subject).to match(expected_slugs)+ end+ end+ end+enddiff --git a/core/spec/models/spree/product_spec.rb b/core/spec/models/spree/product_spec.rbindex bdd2764d9d..ad30a731fa 100644--- a/core/spec/models/spree/product_spec.rb+++ b/core/spec/models/spree/product_spec.rb@@ -302,75 +302,6 @@ describe Spree::Product, type: :model doendend- context 'slugs' do- it 'normalizes slug on update validation' do- product.slug = 'hey//joe'- product.valid?- expect(product.slug).not_to match '/'- end-- it 'stores old slugs in FriendlyIds history' do- expect(product).to receive(:create_slug)- # Set it, otherwise the create_slug method avoids writing a new one- product.slug = 'custom-slug'- product.run_callbacks :save- end-- context 'when product destroyed' do- it 'renames slug' do- product.destroy- expect(product.slug).to match(/[0-9]+_product-[0-9]+/)- end-- context 'when more than one translation exists' do- before {- product.send(:slug=, "french-slug", locale: :fr)- product.save!- }-- it 'renames slug for all translations' do- product.destroy- expect(product.slug).to match(/[0-9]+_product-[0-9]+/)- expect(product.translations.with_deleted.where(locale: :fr).first.slug).to match(/[0-9]+_french-slug/)- end- end-- context 'when slug is already at or near max length' do- before do- product.slug = 'x' * 255- product.save!- end-- it 'truncates renamed slug to ensure it remains within length limit' do- product.destroy- expect(product.slug.length).to eq 255- end- end- end-- it 'validates slug uniqueness' do- existing_product = product- new_product = create(:product, stores: [store])- new_product.slug = existing_product.slug-- expect(new_product.valid?).to eq false- end-- it "falls back to 'name-sku' for slug if regular name-based slug already in use" do- product1 = build(:product, stores: [store])- product1.name = 'test'- product1.sku = '123'- product1.save!-- product2 = build(:product, stores: [store])- product2.name = 'test'- product2.sku = '456'- product2.save!-- expect(product2.slug).to eq 'test-456'- end- end-describe '#discontinue_on_must_be_later_than_make_active_at' dobefore { product.make_active_at = Date.today }@@ -416,26 +347,11 @@ describe Spree::Product, type: :model do@product = create(:product, stores: [store])end- it 'keeps the history when the product is destroyed' do- @product.destroy-- expect(@product.slugs.with_deleted).not_to be_empty- end-it 'keeps translations when product is destroyed' do@product.destroyexpect(@product.name).not_to be_emptyend-- it 'updates the history when the product is restored' do- @product.destroy-- @product.restore(recursive: true)-- latest_slug = @product.slugs.find_by slug: @product.slug- expect(latest_slug).not_to be_nil- endendcontext 'memoized data' do@@ -1032,101 +948,6 @@ describe Spree::Product, type: :model doendend- describe '#localized_slugs_for_store' do- let(:store) { create(:store, default_locale: 'fr', supported_locales: 'en,pl,fr') }- let(:product) { create(:product, stores: [store], name: 'Test product', slug: 'test-slug-en') }- let!(:product_translation_fr) { product.translations.create(slug: 'test_slug_fr', locale: 'fr') }-- before { Spree::Locales::SetFallbackLocaleForStore.new.call(store: store) }-- subject { product.localized_slugs_for_store(store) }-- context 'when there are slugs in locales not supported by the store' do- let!(:product_translation_pl) { product.translations.create(slug: 'test_slug_pl', locale: 'pl') }- let!(:product_translation_de) { product.translations.create(slug: 'test_slug_de', locale: 'de') }-- let(:expected_slugs) do- {- 'en' => 'test-slug-en',- 'fr' => 'test-slug-fr',- 'pl' => 'test-slug-pl'- }- end-- it 'returns only slugs in locales supported by the store' do- expect(subject).to match(expected_slugs)- end- end-- context 'when one of the supported locales does not have a translation' do- let(:expected_slugs) do- {- 'en' => 'test-slug-en',- 'fr' => 'test-slug-fr',- 'pl' => 'test-slug-fr'- }- end-- it "falls back to store's default locale" do- expect(subject).to match(expected_slugs)- end- end-- context 'the slugs are generated from name when slug field is empty' do- before do- product_translation_fr.update(slug: nil, name: "slug from name")- end-- let(:expected_slugs) do- {- 'en' => 'test-slug-en',- 'fr' => 'slug-from-name',- 'pl' => 'slug-from-name'- }- end-- it "saves slugs generated from name" do- expect(subject).to match(expected_slugs)- end- end-- context 'the slugs are generated from default locale name when name and slug for translation is empty' do- before do- product_translation_fr.update(slug: nil, name: nil)- end-- let(:expected_slugs) do- {- 'en' => 'test-slug-en',- 'fr' => 'test-product',- 'pl' => 'test-product'- }- end-- it 'saves slugs generated from fallback name' do- expect(subject).to match(expected_slugs)- end- end-- context 'the slugs are generated from invalid slug format' do- before do- product_translation_fr.update(slug: "slug with_spaces")- end-- let(:expected_slugs) do- {- 'en' => 'test-slug-en',- 'fr' => 'slug-with-spaces',- 'pl' => 'slug-with-spaces'- }- end-- it 'saves slugs in valid format' do- expect(subject).to match(expected_slugs)- end- end- end-describe '#to_csv' dolet(:store) { Spree::Store.default }let(:product) { create(:product, stores: [store]) }