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.

Open source new Taxon model (#12243)

Damian Legawiec55e8780bc4a5
diff --git a/admin/spec/spec_helper.rb b/admin/spec/spec_helper.rb
index cf30bb8800..e9df6fe1c5 100644
--- a/admin/spec/spec_helper.rb
+++ b/admin/spec/spec_helper.rb
@@ -38,6 +38,7 @@ require 'ffaker'
require 'spree/testing_support/authorization_helpers'
require 'spree/testing_support/factories'
require 'spree/testing_support/preferences'
+require 'spree/testing_support/jobs'
require 'spree/testing_support/controller_requests'
require 'spree/testing_support/url_helpers'
require 'spree/testing_support/order_walkthrough'
@@ -67,8 +68,6 @@ RSpec.configure do |config|
Capybara.default_max_wait_time = 10
Capybara.raise_server_errors = false
DatabaseCleaner.clean_with :truncation
- # Force jobs to be executed in a synchronous way
- ActiveJob::Base.queue_adapter = :inline
end
config.before do
diff --git a/api/app/serializers/spree/api/v2/platform/taxon_serializer.rb b/api/app/serializers/spree/api/v2/platform/taxon_serializer.rb
index 4b25e3c785..0b0d7034c2 100644
--- a/api/app/serializers/spree/api/v2/platform/taxon_serializer.rb
+++ b/api/app/serializers/spree/api/v2/platform/taxon_serializer.rb
@@ -7,6 +7,14 @@ module Spree
attributes :pretty_name, :seo_title
+ attribute :description do |taxon|
+ taxon.description.to_plain_text
+ end
+
+ attribute :header_url do |taxon|
+ taxon.image.attachment&.url
+ end
+
attribute :is_root do |taxon|
taxon.root?
end
diff --git a/api/app/serializers/spree/v2/storefront/taxon_serializer.rb b/api/app/serializers/spree/v2/storefront/taxon_serializer.rb
index 0c4292ac28..e9b1a13316 100644
--- a/api/app/serializers/spree/v2/storefront/taxon_serializer.rb
+++ b/api/app/serializers/spree/v2/storefront/taxon_serializer.rb
@@ -4,9 +4,21 @@ module Spree
class TaxonSerializer < BaseSerializer
set_type :taxon
- attributes :name, :pretty_name, :permalink, :seo_title, :description, :meta_title, :meta_description,
+ attributes :name, :pretty_name, :permalink, :seo_title, :meta_title, :meta_description,
:meta_keywords, :left, :right, :position, :depth, :updated_at, :public_metadata
+ attribute :description do |taxon|
+ taxon.description.to_plain_text
+ end
+
+ attribute :has_products do |taxon|
+ taxon.active_products_with_descendants.exists?
+ end
+
+ attribute :header_url do |taxon|
+ taxon.image.attachment&.url
+ end
+
attribute :is_root do |taxon|
taxon.root?
end
diff --git a/api/lib/spree/api/testing_support/caching.rb b/api/lib/spree/api/testing_support/caching.rb
deleted file mode 100644
index 550a646f11..0000000000
--- a/api/lib/spree/api/testing_support/caching.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-RSpec.configure do |config|
- config.before(:each, caching: true) do
- ActionController::Base.perform_caching = true
- end
-
- config.after(:each, caching: true) do
- ActionController::Base.perform_caching = false
- Rails.cache.clear
- end
-end
diff --git a/api/lib/spree/api/testing_support/jobs.rb b/api/lib/spree/api/testing_support/jobs.rb
deleted file mode 100644
index 2964951978..0000000000
--- a/api/lib/spree/api/testing_support/jobs.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-RSpec.configure do |config|
- # Force jobs to be executed in a synchronous way (see http://archive.today/xcb1E)
- config.around do |example|
- (ActiveJob::Base.descendants << ActiveJob::Base).each(&:disable_test_adapter)
- ActiveJob::Base.queue_adapter = :inline
- example.run
- (ActiveJob::Base.descendants << ActiveJob::Base).each { |a| a.enable_test_adapter(ActiveJob::QueueAdapters::TestAdapter.new) }
- ActiveJob::Base.queue_adapter = :test
- end
-
- config.before(:each, :job) do
- ActiveJob::Base.queue_adapter = :test
- end
-
- config.after(:each, :job) do
- ActiveJob::Base.queue_adapter = :inline
- end
-end
diff --git a/api/spec/requests/spree/api/v2/storefront/taxons_spec.rb b/api/spec/requests/spree/api/v2/storefront/taxons_spec.rb
index e8cac17cb7..c77aafa007 100644
--- a/api/spec/requests/spree/api/v2/storefront/taxons_spec.rb
+++ b/api/spec/requests/spree/api/v2/storefront/taxons_spec.rb
@@ -168,12 +168,12 @@ describe 'Taxons Spec', type: :request do
end
context 'by taxonomy' do
- before { get "/api/v2/storefront/taxons?taxonomy_id=#{taxonomy.id}" }
+ before { get "/api/v2/storefront/taxons?filter[taxonomy_id]=#{taxonomy.id}" }
it_behaves_like 'returns 200 HTTP status'
it 'returns taxons by taxonomy' do
- expect(json_response['data'].size).to eq(taxonomy.taxons.count + 1) # taxons + root
+ expect(json_response['data'].size).to eq(taxonomy.taxons.count)
expect(json_response['data'][0]).to have_relationship(:taxonomy).with_data('id' => taxonomy.id.to_s, 'type' => 'taxonomy')
expect(json_response['data'][1]).to have_relationship(:taxonomy).with_data('id' => taxonomy.id.to_s, 'type' => 'taxonomy')
expect(json_response['data'][2]).to have_relationship(:taxonomy).with_data('id' => taxonomy.id.to_s, 'type' => 'taxonomy')
diff --git a/api/spec/serializers/spree/api/v2/platform/taxon_serializer_spec.rb b/api/spec/serializers/spree/api/v2/platform/taxon_serializer_spec.rb
index 346ec54af2..28ead6aa4a 100644
--- a/api/spec/serializers/spree/api/v2/platform/taxon_serializer_spec.rb
+++ b/api/spec/serializers/spree/api/v2/platform/taxon_serializer_spec.rb
@@ -6,7 +6,7 @@ describe Spree::Api::V2::Platform::TaxonSerializer do
subject { described_class.new(taxon.reload, params: serializer_params).serializable_hash }
let(:taxonomy) { create(:taxonomy, store: store) }
- let(:taxon) { create(:taxon, taxonomy: taxonomy, products: create_list(:product, 2, stores: [store])) }
+ let(:taxon) { create(:taxon, :with_description, taxonomy: taxonomy, products: create_list(:product, 2, stores: [store])) }
let!(:children) { create_list(:taxon, 2, taxonomy: taxonomy, parent: taxon) }
it { expect(subject).to be_kind_of(Hash) }
@@ -24,7 +24,7 @@ describe Spree::Api::V2::Platform::TaxonSerializer do
permalink: taxon.permalink,
lft: taxon.lft,
rgt: taxon.rgt,
- description: taxon.description,
+ description: taxon.description.to_plain_text,
created_at: taxon.created_at,
updated_at: taxon.updated_at,
meta_title: taxon.meta_title,
@@ -36,6 +36,10 @@ describe Spree::Api::V2::Platform::TaxonSerializer do
is_root: taxon.root?,
is_child: taxon.child?,
is_leaf: taxon.leaf?,
+ automatic: taxon.automatic?,
+ sort_order: taxon.sort_order,
+ rules_match_policy: taxon.rules_match_policy,
+ header_url: taxon.image.attachment&.url,
public_metadata: {},
private_metadata: {}
},
@@ -94,7 +98,7 @@ describe Spree::Api::V2::Platform::TaxonSerializer do
permalink: taxon.permalink,
lft: taxon.lft,
rgt: taxon.rgt,
- description: taxon.description,
+ description: taxon.description.to_plain_text,
created_at: taxon.created_at,
updated_at: taxon.updated_at,
meta_title: taxon.meta_title,
@@ -106,6 +110,10 @@ describe Spree::Api::V2::Platform::TaxonSerializer do
is_root: taxon.root?,
is_child: taxon.child?,
is_leaf: taxon.leaf?,
+ automatic: taxon.automatic?,
+ sort_order: taxon.sort_order,
+ rules_match_policy: taxon.rules_match_policy,
+ header_url: taxon.image.attachment&.url,
public_metadata: {},
private_metadata: {}
},
diff --git a/api/spec/services/spree/webhooks/subscribers/handle_request_spec.rb b/api/spec/services/spree/webhooks/subscribers/handle_request_spec.rb
index 62d909aed4..2b3995f324 100644
--- a/api/spec/services/spree/webhooks/subscribers/handle_request_spec.rb
+++ b/api/spec/services/spree/webhooks/subscribers/handle_request_spec.rb
@@ -185,16 +185,18 @@ describe Spree::Webhooks::Subscribers::HandleRequest do
end
it 'adds the event data to the body' do
- with_webhooks_enabled do
- allow(Spree::Webhooks::Subscribers::MakeRequest).to receive(:new).and_call_original
- order.finalize!
- expect(Spree::Webhooks::Subscribers::MakeRequest).to \
- have_received(:new).
- with(
- signature: event_signature,
- url: url,
- webhook_payload_body: body_with_event_metadata
- )
+ perform_enqueued_jobs do
+ with_webhooks_enabled do
+ allow(Spree::Webhooks::Subscribers::MakeRequest).to receive(:new).and_call_original
+ order.finalize!
+ expect(Spree::Webhooks::Subscribers::MakeRequest).to \
+ have_received(:new).
+ with(
+ signature: event_signature,
+ url: url,
+ webhook_payload_body: body_with_event_metadata
+ )
+ end
end
end
end
diff --git a/api/spec/spec_helper.rb b/api/spec/spec_helper.rb
index 12af8095fa..4adde95705 100644
--- a/api/spec/spec_helper.rb
+++ b/api/spec/spec_helper.rb
@@ -37,13 +37,12 @@ require 'i18n/tasks'
Dir[File.dirname(__FILE__) + '/support/**/*.rb'].each { |f| require f }
require 'spree/testing_support/factories'
+require 'spree/testing_support/jobs'
require 'spree/testing_support/preferences'
require 'spree/testing_support/image_helpers'
require 'spree/testing_support/next_instance_of'
require 'spree/testing_support/rspec_retry_config'
-require 'spree/api/testing_support/caching'
-require 'spree/api/testing_support/jobs'
require 'spree/api/testing_support/serializers'
require 'spree/api/testing_support/spree_webhooks'
require 'spree/api/testing_support/matchers/webhooks'
diff --git a/core/app/jobs/spree/products/auto_match_taxons_job.rb b/core/app/jobs/spree/products/auto_match_taxons_job.rb
new file mode 100644
index 0000000000..f4fa7f1e2a
--- /dev/null
+++ b/core/app/jobs/spree/products/auto_match_taxons_job.rb
@@ -0,0 +1,14 @@
+module Spree
+ module Products
+ class AutoMatchTaxonsJob < ::Spree::BaseJob
+ queue_as Spree.queues.taxons
+
+ def perform(product_id)
+ product = Spree::Product.find_by(id: product_id)
+ return unless product.present?
+
+ Spree::Products::AutoMatchTaxons.call(product: product)
+ end
+ end
+ end
+end
diff --git a/core/app/models/spree/price.rb b/core/app/models/spree/price.rb
index 00d65c65d5..e6f5b7c540 100644
--- a/core/app/models/spree/price.rb
+++ b/core/app/models/spree/price.rb
@@ -31,6 +31,8 @@ module Spree
less_than_or_equal_to: MAXIMUM_AMOUNT
}
+ validates :currency, presence: true
+
scope :with_currency, ->(currency) { where(currency: currency) }
scope :non_zero, -> { where.not(amount: [nil, 0]) }
scope :discounted, -> { where('compare_at_amount > amount') }
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rb
index 98aee9ada6..39ddc1a081 100644
--- a/core/app/models/spree/product.rb
+++ b/core/app/models/spree/product.rb
@@ -77,7 +77,7 @@ module Spree
has_many :menu_items, as: :linked_resource
- has_many :classifications, dependent: :delete_all, inverse_of: :product
+ has_many :classifications, -> { order(created_at: :asc) }, dependent: :delete_all, inverse_of: :product
has_many :taxons, through: :classifications, before_remove: :remove_taxon
has_many :taxonomies, through: :taxons
@@ -119,6 +119,11 @@ module Spree
has_many :variant_images, -> { order(:position) }, source: :images, through: :variants_including_master
has_many :variant_images_without_master, -> { order(:position) }, source: :images, through: :variants
+ has_many :option_value_variants, class_name: 'Spree::OptionValueVariant', through: :variants
+ has_many :option_values, class_name: 'Spree::OptionValue', through: :variants
+
+ has_many :prices_including_master, -> { non_zero }, through: :variants_including_master, source: :prices
+
has_many :store_products, class_name: 'Spree::StoreProduct'
has_many :stores, through: :store_products, class_name: 'Spree::Store'
has_many :digitals, through: :variants_including_master
@@ -136,6 +141,8 @@ module Spree
after_save :reset_nested_changes
after_touch :touch_taxons
+ after_commit :auto_match_taxons, if: :eligible_for_taxon_matching?
+
before_validation :downcase_slug
before_validation :normalize_slug, on: :update
before_validation :validate_master
@@ -157,6 +164,12 @@ module Spree
scope :draft, -> { where(status: 'draft') }
scope :archived, -> { where(status: 'archived') }
scope :not_archived, -> { where.not(status: 'archived') }
+ scope :on_sale, lambda { |currency = nil|
+ currency ||= Spree::Store.default.default_currency
+ joins(:prices_including_master).with_currency(currency).
+ where.not(spree_prices: { compare_at_amount: [nil, 0] }).
+ where("#{Spree::Price.table_name}.compare_at_amount > #{Spree::Price.table_name}.amount")
+ }
attr_accessor :option_values_hash
@@ -215,6 +228,10 @@ module Spree
default_variant.backorderable? || variants.any?(&:backorderable?)
end
+ def on_sale?(currency)
+ prices_including_master.find_all { |p| p.currency == currency }.any?(&:discounted?)
+ end
+
def find_or_build_master
master || build_master
end
@@ -463,6 +480,16 @@ module Spree
shipping_category&.shipping_methods&.any? { |method| method.calculator.is_a?(Spree::Calculator::Shipping::DigitalDelivery) }
end
+ def auto_match_taxons
+ return if deleted?
+ return if archived?
+
+ store = stores.find_by(default: true) || stores.first
+ return if store.nil? || store.taxons.automatic.none?
+
+ Spree::Products::AutoMatchTaxonsJob.perform_later(id)
+ end
+
def to_csv(store = nil)
store ||= stores.default || stores.first
properties_for_csv ||= Spree::Property.order(:position).flat_map do |property|
@@ -647,6 +674,10 @@ module Spree
true
end
+ def eligible_for_taxon_matching?
+ previously_new_record? || tag_list_previously_changed? || available_on_previously_changed?
+ end
+
def downcase_slug
slug&.downcase!
end
diff --git a/core/app/models/spree/store.rb b/core/app/models/spree/store.rb
index 9c15148a0e..48cad5d71a 100644
--- a/core/app/models/spree/store.rb
+++ b/core/app/models/spree/store.rb
@@ -119,6 +119,7 @@ module Spree
before_save :ensure_default_exists_and_is_unique
before_save :ensure_supported_currencies, :ensure_supported_locales
after_create :ensure_default_taxonomies_are_created
+ after_create :ensure_default_automatic_taxons
before_destroy :validate_not_last, unless: :skip_validate_not_last
before_destroy :pass_default_flag_to_other_store
@@ -305,7 +306,26 @@ module Spree
def ensure_default_taxonomies_are_created
taxonomies.find_or_create_by(name: I18n.t('spree.taxonomy_categories_name', default: I18n.t('spree.taxonomy_categories_name', locale: :en)))
taxonomies.find_or_create_by(name: I18n.t('spree.taxonomy_brands_name', default: I18n.t('spree.taxonomy_brands_name', locale: :en)))
+ taxonomies.find_or_create_by(name: I18n.t('spree.taxonomy_collections_name', default: I18n.t('spree.taxonomy_collections_name', locale: :en)))
rescue ActiveRecord::NotNullViolation
end
+
+ def ensure_default_automatic_taxons
+ collections_taxonomy = taxonomies.find_by(name: Spree.t(:taxonomy_collections_name))
+
+ if collections_taxonomy.present?
+ on_sale_taxon = collections_taxonomy.taxons.automatic.where(name: Spree.t('automatic_taxon_names.on_sale')).first_or_create! do |taxon|
+ taxon.parent = collections_taxonomy.root
+ taxon.rules.new(type: 'Spree::TaxonRules::Sale', value: 'true')
+ end
+
+ new_arrivals_taxon = collections_taxonomy.taxons.automatic.where(name: Spree.t('automatic_taxon_names.new_arrivals')).first_or_create! do |taxon|
+ taxon.parent = collections_taxonomy.root
+ taxon.rules.new(type: 'Spree::TaxonRules::AvailableOn', value: 30)
+ end
+
+ [on_sale_taxon, new_arrivals_taxon]
+ end
+ end
end
end
diff --git a/core/app/models/spree/taxon.rb b/core/app/models/spree/taxon.rb
index 78b017d986..e7a81dab77 100644
--- a/core/app/models/spree/taxon.rb
+++ b/core/app/models/spree/taxon.rb
@@ -3,6 +3,18 @@ require 'stringex'
module Spree
class Taxon < Spree::Base
+ RULES_MATCH_POLICIES = %w[all any].freeze
+ SORT_ORDERS = %w[
+ manual
+ best-selling
+ name-a-z
+ name-z-a
+ price-high-to-low
+ price-low-to-high
+ newest-first
+ oldest-first
+ ]
+
include Spree::TranslatableResource
include Spree::TranslatableResourceSlug
include Spree::Metadata
@@ -10,17 +22,21 @@ module Spree
include Spree::Webhooks::HasWebhooks
end
+ #
+ # Magic methods
+ #
extend FriendlyId
friendly_id :permalink, slug_column: :permalink, use: :history
- before_validation :set_permalink, on: :create, if: :name
-
acts_as_nested_set dependent: :destroy
+ #
+ # Associations
+ #
belongs_to :taxonomy, class_name: 'Spree::Taxonomy', inverse_of: :taxons
- has_many :classifications, -> { order(:position) }, dependent: :delete_all, inverse_of: :taxon
+ has_one :store, through: :taxonomy
+ has_many :classifications, -> { order(:position) }, dependent: :destroy_async, inverse_of: :taxon
has_many :products, through: :classifications
-
- delegate :store, to: :taxonomy
+ has_one :icon, as: :viewable, dependent: :destroy, class_name: 'Spree::TaxonImage' # TODO: remove this as this is deprecated
has_many :menu_items, as: :linked_resource
has_many :cms_sections, as: :linked_resource
@@ -31,6 +47,15 @@ module Spree
has_many :promotion_rule_taxons, class_name: 'Spree::PromotionRuleTaxon', dependent: :destroy
has_many :promotion_rules, through: :promotion_rule_taxons, class_name: 'Spree::PromotionRule'
+ #
+ # Attachments
+ #
+ has_one_attached :image, service: Spree.public_storage_service_name
+ has_one_attached :square_image, service: Spree.public_storage_service_name
+
+ #
+ # Validations
+ #
validates :name, presence: true, uniqueness: { scope: [:parent_id, :taxonomy_id], case_sensitive: false }
validates :taxonomy, presence: true
validates :permalink, uniqueness: { case_sensitive: false, scope: [:parent_id, :taxonomy_id] }
@@ -43,7 +68,12 @@ module Spree
validates :meta_description
validates :meta_title
end
+ validates :image, :square_image, content_type: Rails.application.config.active_storage.web_image_content_types
+ #
+ # Callbacks
+ #
+ before_validation :set_permalink, on: :create, if: :name
before_validation :copy_taxonomy_from_parent
before_save :set_pretty_name
before_save :set_permalink
@@ -54,20 +84,128 @@ module Spree
after_move :regenerate_pretty_name_and_permalink
after_move :regenerate_translations_pretty_name_and_permalink
- has_one :store, through: :taxonomy
-
- has_one :icon, as: :viewable, dependent: :destroy, class_name: 'Spree::TaxonImage'
-
+ #
+ # Scopes
+ #
scope :for_store, ->(store) { joins(:taxonomy).where(spree_taxonomies: { store_id: store.id }) }
+ scope :for_stores, ->(stores) { joins(:taxonomy).where(spree_taxonomies: { store_id: stores.ids }) }
+ scope :for_taxonomy, lambda { |taxonomy_name|
+ if Spree.use_translations?
+ joins(:taxonomy).
+ join_translation_table(Taxonomy).
+ where(["LOWER(#{Taxonomy.translation_table_alias}.name) = ?", taxonomy_name.downcase.strip])
+ else
+ joins(:taxonomy).where(["LOWER(#{Spree::Taxonomy.table_name}.name) = ?", taxonomy_name.downcase.strip])
+ end
+ }
- self.whitelisted_ransackable_associations = %w[taxonomy]
- self.whitelisted_ransackable_attributes = %w[name permalink]
+ #
+ # Search
+ #
+ if defined?(PgSearch)
+ include PgSearch::Model
+ pg_search_scope :search_by_name, against: :name, using: { tsearch: { any_word: true, prefix: true } }
+ else
+ def self.search_by_name(query)
+ i18n { name.lower.matches("%#{query.downcase}%") }
+ end
+ end
- scope :for_stores, ->(stores) { joins(:taxonomy).where(spree_taxonomies: { store_id: stores.ids }) }
+ #
+ # Ransack
+ #
+ self.whitelisted_ransackable_associations = %w[taxonomy]
+ self.whitelisted_ransackable_attributes = %w[name permalink automatic]
+ #
+ # Translations
+ #
TRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freeze
translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ #
+ # Action Text
+ #
+ translates :description, backend: :action_text
+
+ # Automatic taxons
+ validates :rules_match_policy, inclusion: { in: RULES_MATCH_POLICIES }, presence: true
+ validates :sort_order, inclusion: { in: SORT_ORDERS }, presence: true
+
+ has_many :taxon_rules, class_name: 'Spree::TaxonRule', dependent: :destroy
+ accepts_nested_attributes_for :taxon_rules, allow_destroy: true, reject_if: proc { |attributes| attributes['value'].blank? }
+ alias rules taxon_rules
+
+ scope :manual, -> { where.not(automatic: true) }
+ scope :automatic, -> { where(automatic: true) }
+
+ after_commit :regenerate_taxon_products, on: [:update], if: -> { automatic? && saved_change_to_rules_match_policy? }
+ attribute :marked_for_regenerate_taxon_products, :boolean, default: true
+
+ def manual?
+ !automatic?
+ end
+
+ def manual_sort_order?
+ sort_order == 'manual'
+ end
+
+ def active_products_with_descendants
+ @active_products_with_descendants ||= store.products.
+ joins(:classifications).
+ active.
+ where(
+ Spree::Classification.table_name => {
+ taxon_id: descendants.ids + [id]
+ }
+ )
+ end
+
+ def products_matching_rules(opts = {})
+ return Spree::Product.none if manual? || rules.empty?
+
+ storefront = opts[:storefront] || false
+ currency = opts[:currency] || store.default_currency
+
+ all_products = store.products.not_archived
+
+ products_matcher_cache_key = [
+ 'products_matching_rules',
+ cache_key_with_version,
+ storefront,
+ currency,
+ all_products.cache_key_with_version
+ ]
+
+ 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
+ # it's safer to use this approach with ids as it will not break if the rule is not a simple where clause
+ # and we will avoid `ArgumentError (Relation passed to #or must be structurally compatible. Incompatible values: [:group, :order, :joins, :readonly])` error
+ products = products.or(all_products.where(id: product_ids)) if product_ids.any?
+ else
+ products = rule.apply(products)
+ end
+ end
+
+ products
+ end
+
+ # we need to create a new taxon product (classification) record for each product that matches the rules
+ # so we can later use them for product filtering and so on
+ # if we want to fire the service once during object lifecycle - pass only_once: true
+ def regenerate_taxon_products(only_once: false)
+ if marked_for_regenerate_taxon_products?
+ Spree::Taxons::RegenerateProducts.call(taxon: self)
+ self.marked_for_regenerate_taxon_products = false if !frozen? && only_once
+ end
+ end
+
def slug
permalink
end
diff --git a/core/app/models/spree/taxon_rule.rb b/core/app/models/spree/taxon_rule.rb
new file mode 100644
index 0000000000..079834c59d
--- /dev/null
+++ b/core/app/models/spree/taxon_rule.rb
@@ -0,0 +1,25 @@
+module Spree
+ class TaxonRule < Base
+ MATCH_POLICIES = %w[
+ is_equal_to
+ is_not_equal_to
+ contains
+ does_not_contain
+ ].freeze
+
+ belongs_to :taxon, class_name: 'Spree::Taxon', inverse_of: :taxon_rules, touch: true
+
+ validates :taxon, :type, :value, presence: true
+ validates :match_policy, inclusion: { in: MATCH_POLICIES }, presence: true
+
+ after_commit :regenerate_taxon_products, if: -> { saved_change_to_value? || destroyed? || saved_change_to_match_policy? }
+
+ delegate :store, to: :taxon
+
+ private
+
+ def regenerate_taxon_products
+ taxon.regenerate_taxon_products(only_once: true)
+ end
+ end
+end
diff --git a/core/app/models/spree/taxon_rules/available_on.rb b/core/app/models/spree/taxon_rules/available_on.rb
new file mode 100644
index 0000000000..3a458cfc5b
--- /dev/null
+++ b/core/app/models/spree/taxon_rules/available_on.rb
@@ -0,0 +1,20 @@
+module Spree
+ module TaxonRules
+ class AvailableOn < Spree::TaxonRule
+ def apply(scope)
+ # value here is no of weeks
+ # eg. return products that become available in the last 2 weeks
+ timezone = taxon.store.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
+end
diff --git a/core/app/models/spree/taxon_rules/sale.rb b/core/app/models/spree/taxon_rules/sale.rb
new file mode 100644
index 0000000000..dc67ee5992
--- /dev/null
+++ b/core/app/models/spree/taxon_rules/sale.rb
@@ -0,0 +1,16 @@
+module Spree
+ module TaxonRules
+ class Sale < Spree::TaxonRule
+ 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
+end
diff --git a/core/app/models/spree/taxon_rules/tag.rb b/core/app/models/spree/taxon_rules/tag.rb
new file mode 100644
index 0000000000..b907d2597a
--- /dev/null
+++ b/core/app/models/spree/taxon_rules/tag.rb
@@ -0,0 +1,19 @@
+module Spree
+ module TaxonRules
+ class Tag < Spree::TaxonRule
+ 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
+end
diff --git a/core/app/models/spree/variant.rb b/core/app/models/spree/variant.rb
index bdec90ca3d..57ec634ebc 100644
--- a/core/app/models/spree/variant.rb
+++ b/core/app/models/spree/variant.rb
@@ -96,7 +96,7 @@ module Spree
scope :for_currency_and_available_price_amount, ->(currency = nil) do
currency ||= Spree::Store.default.default_currency
- joins(:prices).where('spree_prices.currency = ?', currency).where('spree_prices.amount IS NOT NULL').distinct
+ joins(:prices).where("#{Spree::Price.table_name}.currency = ?", currency).where("#{Spree::Price.table_name}.amount IS NOT NULL").distinct
end
scope :active, ->(currency = nil) do
diff --git a/core/app/services/spree/products/auto_match_taxons.rb b/core/app/services/spree/products/auto_match_taxons.rb
new file mode 100644
index 0000000000..aaabbb4b91
--- /dev/null
+++ b/core/app/services/spree/products/auto_match_taxons.rb
@@ -0,0 +1,67 @@
+module Spree
+ module Products
+ class AutoMatchTaxons
+ prepend ::Spree::ServiceModule::Base
+
+ def call(product:)
+ return unless product.present?
+
+ taxons_to_remove = []
+ taxons_to_add = []
+
+ # we need to check if existing taxons still match
+ product.taxons.automatic.includes(:taxon_rules).each do |taxon|
+ # products shouldn't be part of the taxon anymore
+ # eg. product tags or category was changed
+ taxons_to_remove << taxon unless taxon.products_matching_rules.ids.include?(product.id)
+ end
+
+ Spree::Classification.where(taxon: taxons_to_remove, product: product).delete_all if taxons_to_remove.any?
+
+ # we need to check if product matches any existing taxons
+ Spree::Taxon.automatic.includes(:taxon_rules, :products).each do |taxon|
+ taxons_to_add << taxon if taxon.products.exclude?(product) && taxon.products_matching_rules.ids.include?(product.id)
+ end
+
+ if taxons_to_add.any?
+ products_counts = Spree::Taxon.where(id: taxons_to_add.pluck(:id)).
+ joins(:classifications).
+ reorder('').
+ group(:taxon_id).
+ count(:product_id)
+
+ Spree::Classification.insert_all(
+ taxons_to_add.map do |taxon|
+ position = products_counts[taxon.id].to_i + 1
+ classification_attributes(taxon, product, position)
+ end
+ )
+ end
+
+ all_affected_taxons = (taxons_to_remove + taxons_to_add).uniq
+
+ if all_affected_taxons.any?
+ if defined?(Spree::Taxons::TouchFeaturedSections)
+ Spree::Taxons::TouchFeaturedSections.call(taxon_ids: all_affected_taxons.pluck(:id))
+ end
+
+ product.touch
+ end
+
+ success(product)
+ end
+
+ private
+
+ def classification_attributes(taxon, product, position)
+ {
+ taxon_id: taxon.id,
+ product_id: product.id,
+ position: position,
+ created_at: Time.current,
+ updated_at: Time.current
+ }
+ end
+ end
+ end
+end
diff --git a/core/app/services/spree/taxons/regenerate_products.rb b/core/app/services/spree/taxons/regenerate_products.rb
new file mode 100644
index 0000000000..ebc995de42
--- /dev/null
+++ b/core/app/services/spree/taxons/regenerate_products.rb
@@ -0,0 +1,53 @@
+module Spree
+ module Taxons
+ class RegenerateProducts
+ prepend ::Spree::ServiceModule::Base
+
+ def call(taxon:)
+ return if taxon.nil?
+ return if taxon.manual?
+
+ previous_products_ids = taxon.classifications.order(position: :asc).pluck(:product_id)
+
+ # https://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html#method-i-delete_all
+ # we don't want to run destroy_all here to avoid callbacks
+ # default dependent value is nullify and that won't work for us
+ taxon.classifications.delete_all(:delete_all)
+
+ products_matching_rules = taxon.products_matching_rules
+ product_ids_to_insert = products_matching_rules.ids
+
+ previous_filtered_products_ids = previous_products_ids & product_ids_to_insert
+ max_products_position = previous_filtered_products_ids.size || 0
+
+ if product_ids_to_insert.any?
+ records_to_insert = product_ids_to_insert.map do |product_id|
+ position = previous_filtered_products_ids.index(product_id)
+ position = position.present? ? position + 1 : max_products_position += 1
+
+ classification_attributes(product_id, taxon, position)
+ end
+
+ Spree::Classification.insert_all(records_to_insert)
+
+ # expire product cache
+ Spree::Product.where(id: (previous_products_ids + product_ids_to_insert).uniq).touch_all
+ end
+
+ success(taxon)
+ end
+
+ private
+
+ def classification_attributes(product_id, taxon, position)
+ {
+ product_id: product_id,
+ taxon_id: taxon.id,
+ position: position,
+ created_at: Time.current,
+ updated_at: Time.current
+ }
+ end
+ end
+ end
+end
diff --git a/core/config/locales/en.yml b/core/config/locales/en.yml
index 42e7d84155..83d777d727 100644
--- a/core/config/locales/en.yml
+++ b/core/config/locales/en.yml
@@ -1706,10 +1706,14 @@ en:
taxonomy: Taxonomy
taxonomy_brands_name: Brands
taxonomy_categories_name: Categories
+ taxonomy_collections_name: Collections
taxonomy_edit: Edit taxonomy
taxonomy_tree_error: The requested change has not been accepted and the tree has been returned to its previous state, please try again.
taxonomy_tree_instruction: ! '* Right click (or double tap on iOS device) a child in the tree to access the menu for adding, deleting or sorting a child.'
taxons: Taxons
+ automatic_taxon_names:
+ on_sale: On sale
+ new_arrivals: New arrivals
test: Test
test_mailer:
test_email:
diff --git a/core/db/migrate/20241127193411_create_spree_taxon_rules.rb b/core/db/migrate/20241127193411_create_spree_taxon_rules.rb
new file mode 100644
index 0000000000..f7e04f1a3e
--- /dev/null
+++ b/core/db/migrate/20241127193411_create_spree_taxon_rules.rb
@@ -0,0 +1,13 @@
+class CreateSpreeTaxonRules < ActiveRecord::Migration[6.1]
+ def change
+ create_table :spree_taxon_rules do |t|
+ t.belongs_to :taxon, null: false, index: true
+
+ t.string :type, null: false
+ t.string :value, null: false
+ t.string :match_policy, null: false, default: 'is_equal_to'
+
+ t.timestamps
+ end
+ end
+end
diff --git a/core/db/migrate/20241127223627_add_rules_match_policy_and_sort_order_to_spree_taxons.rb b/core/db/migrate/20241127223627_add_rules_match_policy_and_sort_order_to_spree_taxons.rb
new file mode 100644
index 0000000000..5e18c61ce1
--- /dev/null
+++ b/core/db/migrate/20241127223627_add_rules_match_policy_and_sort_order_to_spree_taxons.rb
@@ -0,0 +1,6 @@
+class AddRulesMatchPolicyAndSortOrderToSpreeTaxons < ActiveRecord::Migration[6.1]
+ def change
+ add_column :spree_taxons, :rules_match_policy, :string, default: 'all', null: false
+ add_column :spree_taxons, :sort_order, :string, default: 'manual', null: false
+ end
+end
diff --git a/core/db/migrate/20241128103947_add_automatic_to_spree_taxons.rb b/core/db/migrate/20241128103947_add_automatic_to_spree_taxons.rb
new file mode 100644
index 0000000000..cdcdffe737
--- /dev/null
+++ b/core/db/migrate/20241128103947_add_automatic_to_spree_taxons.rb
@@ -0,0 +1,5 @@
+class AddAutomaticToSpreeTaxons < ActiveRecord::Migration[6.1]
+ def change
+ add_column :spree_taxons, :automatic, :boolean, default: false, null: false
+ end
+end
diff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rb
index 9e7c5c8ccc..edf78bdb66 100644
--- a/core/lib/spree/core.rb
+++ b/core/lib/spree/core.rb
@@ -81,6 +81,7 @@ module Spree
default: :default,
exports: :default,
variants: :default,
+ taxons: :default,
stock_location_stock_items: :default,
coupon_codes: :default
)
diff --git a/core/lib/spree/testing_support/factories/taxon_factory.rb b/core/lib/spree/testing_support/factories/taxon_factory.rb
index f33c944f77..c2d6817867 100644
--- a/core/lib/spree/testing_support/factories/taxon_factory.rb
+++ b/core/lib/spree/testing_support/factories/taxon_factory.rb
@@ -5,5 +5,18 @@ FactoryBot.define do
association :taxonomy, strategy: :create
association :icon, factory: :taxon_image
parent_id { taxonomy.root.id }
+
+ trait :with_description do
+ description { '<div>Test <strong>description</strong></div>' }
+ end
+ end
+
+ factory :automatic_taxon, parent: :taxon do
+ automatic { true }
+ rules_match_policy { :all }
+
+ trait :any_match_policy do
+ rules_match_policy { :any }
+ end
end
end
diff --git a/core/lib/spree/testing_support/factories/taxon_rule_factory.rb b/core/lib/spree/testing_support/factories/taxon_rule_factory.rb
new file mode 100644
index 0000000000..fca4a525e1
--- /dev/null
+++ b/core/lib/spree/testing_support/factories/taxon_rule_factory.rb
@@ -0,0 +1,38 @@
+FactoryBot.define do
+ factory :sale_taxon_rule, class: Spree::TaxonRules::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_taxon_rule, class: Spree::TaxonRules::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
+end
diff --git a/core/lib/spree/testing_support/factories/variant_factory.rb b/core/lib/spree/testing_support/factories/variant_factory.rb
index c9aca8a764..01f66c4961 100644
--- a/core/lib/spree/testing_support/factories/variant_factory.rb
+++ b/core/lib/spree/testing_support/factories/variant_factory.rb
@@ -19,7 +19,11 @@ FactoryBot.define do
before(:create) { create(:stock_location) unless Spree::StockLocation.any? }
after(:create) do |variant|
- Spree::StockLocation.all.each { |stock_location| stock_location.propagate_variant(variant) }
+ Spree::StockLocation.all.each do |stock_location|
+ next if stock_location.stock_item(variant).present?
+
+ stock_location.propagate_variant(variant)
+ end
end
factory :variant do
diff --git a/core/lib/spree/testing_support/jobs.rb b/core/lib/spree/testing_support/jobs.rb
index 311dddab6d..d8026ba90b 100644
--- a/core/lib/spree/testing_support/jobs.rb
+++ b/core/lib/spree/testing_support/jobs.rb
@@ -1,9 +1,3 @@
RSpec.configure do |config|
- config.before(:each, :job) do
- ActiveJob::Base.queue_adapter = :test
- end
-
- config.after(:each, :job) do
- ActiveJob::Base.queue_adapter = :inline
- end
+ config.include ActiveJob::TestHelper
end
diff --git a/core/spec/models/spree/customer_return_spec.rb b/core/spec/models/spree/customer_return_spec.rb
index 78283a39d3..95f210e802 100644
--- a/core/spec/models/spree/customer_return_spec.rb
+++ b/core/spec/models/spree/customer_return_spec.rb
@@ -210,7 +210,11 @@ describe Spree::CustomerReturn, type: :model do
end
context 'to a different stock location' do
- let(:new_stock_location) { create(:stock_location, name: 'other', propagate_all_variants: true) }
+ let!(:new_stock_location) { create(:stock_location, name: 'other', propagate_all_variants: true) }
+
+ before do
+ perform_enqueued_jobs
+ end
it 'updates the stock item counts in new stock location' do
expect do
diff --git a/core/spec/models/spree/product_spec.rb b/core/spec/models/spree/product_spec.rb
index e44f1dadc4..14c1936b4f 100644
--- a/core/spec/models/spree/product_spec.rb
+++ b/core/spec/models/spree/product_spec.rb
@@ -10,7 +10,7 @@ end
describe Spree::Product, type: :model do
it_behaves_like 'metadata'
- let!(:store) { create(:store) }
+ let!(:store) { Spree::Store.default }
context 'product instance' do
let(:product) { create(:product, stores: [store]) }
@@ -1115,4 +1115,27 @@ describe Spree::Product, type: :model do
end
end
end
+
+ describe '#on_sale?' do
+ subject { product.on_sale?(currency) }
+
+ let(:product) { create(:product) }
+ let(:currency) { 'EUR' }
+ let(:variant_1) { create(:variant, product: product) }
+ let(:variant_2) { create(:variant, product: product) }
+
+ context 'when at least one variant is on sale' do
+ let!(:eur_price_1) { create(:price, variant: variant_1, currency: 'EUR', compare_at_amount: 200.00) }
+
+ it 'returns true' do
+ expect(subject).to be true
+ end
+ end
+
+ context 'when no variant is on sale' do
+ it 'returns false' do
+ expect(subject).to be false
+ end
+ end
+ end
end
diff --git a/core/spec/models/spree/shipment_spec.rb b/core/spec/models/spree/shipment_spec.rb
index 032639b7a2..326e3dd342 100644
--- a/core/spec/models/spree/shipment_spec.rb
+++ b/core/spec/models/spree/shipment_spec.rb
@@ -789,10 +789,11 @@ describe Spree::Shipment, type: :model do
context '#transfer_to_location' do
# Order with 2 line items in order to be able to split one shipment into 2
let(:order) { create(:completed_order_with_totals, line_items_count: 2) }
- let(:stock_location) { create(:stock_location, propagate_all_variants: true, backorderable_default: true) }
+ let!(:stock_location) { create(:stock_location, propagate_all_variants: true, backorderable_default: true) }
let(:variant) { order.line_items.first.variant }
before do
+ perform_enqueued_jobs
shipping_method = order.shipments.first.shipping_method
shipping_method.calculator.preferences[:amount] = order.shipments.first.cost
shipping_method.calculator.save!
diff --git a/core/spec/models/spree/stock/quantifier_spec.rb b/core/spec/models/spree/stock/quantifier_spec.rb
index ca28da6f1e..96522d752d 100644
--- a/core/spec/models/spree/stock/quantifier_spec.rb
+++ b/core/spec/models/spree/stock/quantifier_spec.rb
@@ -80,6 +80,7 @@ module Spree
let!(:stock_location_3) { create :stock_location, active: false, propagate_all_variants: true }
before do
+ perform_enqueued_jobs
stock_location_2.stock_items.where(variant_id: stock_item.variant).update_all(count_on_hand: 5, backorderable: false)
stock_location_3.stock_items.where(variant_id: stock_item.variant).update_all(count_on_hand: 5, backorderable: false)
end
diff --git a/core/spec/models/spree/stock_item_spec.rb b/core/spec/models/spree/stock_item_spec.rb
index cd94318913..ac784e8255 100644
--- a/core/spec/models/spree/stock_item_spec.rb
+++ b/core/spec/models/spree/stock_item_spec.rb
@@ -252,7 +252,7 @@ describe Spree::StockItem, type: :model do
context 'when a new stock location is added' do
it 'touches its variant' do
expect do
- create(:stock_location, propagate_all_variants: true)
+ perform_enqueued_jobs { create(:stock_location, propagate_all_variants: true) }
end.to change { subject.variant.reload.updated_at }
end
end
diff --git a/core/spec/models/spree/stock_location_spec.rb b/core/spec/models/spree/stock_location_spec.rb
index 4a6c9dab66..bbee4f3aea 100644
--- a/core/spec/models/spree/stock_location_spec.rb
+++ b/core/spec/models/spree/stock_location_spec.rb
@@ -14,7 +14,7 @@ module Spree
it 'creates stock_items for all variants' do
expect do
- create(:stock_location, propagate_all_variants: true)
+ perform_enqueued_jobs { create(:stock_location, propagate_all_variants: true) }
end.to(
change { Variant.count }.by(0).and(
change { described_class.count }.from(0).to(1).and(
diff --git a/core/spec/models/spree/store_spec.rb b/core/spec/models/spree/store_spec.rb
index 840fd13094..be1a356a9a 100644
--- a/core/spec/models/spree/store_spec.rb
+++ b/core/spec/models/spree/store_spec.rb
@@ -116,9 +116,27 @@ describe Spree::Store, type: :model do
let(:store) { build(:store) }
it 'creates default taxonomies' do
- expect { store.save! }.to change(Spree::Taxonomy, :count).by(2)
- expect(store.taxonomies.count).to eq(2)
- expect(store.taxonomies.pluck(:name)).to include(Spree.t(:taxonomy_categories_name), Spree.t(:taxonomy_brands_name))
+ expect { store.save! }.to change(Spree::Taxonomy, :count).by(3)
+
+ expect(store.taxonomies.count).to eq(3)
+ expect(store.taxonomies.pluck(:name)).to contain_exactly(
+ Spree.t(:taxonomy_categories_name),
+ Spree.t(:taxonomy_brands_name),
+ Spree.t(:taxonomy_collections_name)
+ )
+ end
+ end
+
+ describe '#ensure_default_automatic_taxons' do
+ let(:store) { build(:store) }
+ let(:collections_taxonomy) { store.taxonomies.find_by(name: Spree.t(:taxonomy_collections_name)) }
+
+ it 'creates automatic taxons on the collections taxonomy' do
+ expect { store.save! }.to change(Spree::Taxon.automatic, :count).by(2)
+
+ expect(store.reload.taxons.automatic.count).to eq(2)
+ expect(store.taxons.automatic.pluck(:name)).to contain_exactly('New arrivals', 'On sale')
+ expect(store.taxons.automatic.pluck(:taxonomy_id).uniq).to contain_exactly(collections_taxonomy.id)
end
end
end
diff --git a/core/spec/models/spree/taxon_spec.rb b/core/spec/models/spree/taxon_spec.rb
index 2eb08c9931..d553aa87e9 100644
--- a/core/spec/models/spree/taxon_spec.rb
+++ b/core/spec/models/spree/taxon_spec.rb
@@ -1,7 +1,8 @@
require 'spec_helper'
describe Spree::Taxon, type: :model do
- let(:taxonomy) { create(:taxonomy) }
+ let(:store) { Spree::Store.default }
+ let(:taxonomy) { create(:taxonomy, store: store) }
let(:taxon) { build(:taxon, name: 'Ruby on Rails', parent: nil) }
it_behaves_like 'metadata'
@@ -12,9 +13,9 @@ describe Spree::Taxon, type: :model do
it { is_expected.to eql taxon.permalink }
end
- context 'validations' do
+ context 'Validations' do
describe '#check_for_root' do
- let(:valid_taxon) { build(:taxon, name: 'Vaild Rails', parent_id: 1, taxonomy: taxonomy) }
+ let(:valid_taxon) { build(:taxon, name: 'Vaild Rails', parent_id: taxonomy.root.id, taxonomy: taxonomy) }
it 'does not validate the taxon' do
expect(taxon.valid?).to eq false
@@ -27,7 +28,7 @@ describe Spree::Taxon, type: :model do
describe '#parent_belongs_to_same_taxonomy' do
let(:valid_parent) { create(:taxon, name: 'Valid Parent', taxonomy: taxonomy) }
- let(:invalid_parent) { create(:taxon, name: 'Invalid Parent', taxonomy: create(:taxonomy)) }
+ let(:invalid_parent) { create(:taxon, name: 'Invalid Parent', taxonomy: create(:taxonomy, store: store)) }
it 'does not validate the taxon' do
expect(build(:taxon, taxonomy: taxonomy, parent: invalid_parent).valid?).to eq false
@@ -39,6 +40,92 @@ describe Spree::Taxon, type: :model do
end
end
+ context 'Scopes' do
+ describe '.for_taxonomy' do
+ let!(:categories_taxonomy) { store.taxonomies.find_by(name: 'Categories') || create(:taxonomy, name: 'Categories') }
+ let!(:root_category) { create(:taxon, taxonomy: categories_taxonomy) }
+
+ context 'when translations are disabled' do
+ it 'returns the correct taxon' do
+ expect(described_class.for_taxonomy('Categories')).to contain_exactly(
+ root_category,
+ root_category.parent
+ )
+ end
+ end
+
+ context 'when translations are enabled' do
+ before do
+ taxonomy
+
+ Spree::Config.always_use_translations = true
+ I18n.locale = :de
+
+ categories_taxonomy.name = "Kategorien"
+ categories_taxonomy.save!
+ end
+
+ after do
+ Spree::Config.always_use_translations = false
+ I18n.locale = :en
+ end
+
+ it 'returns the correct taxon' do
+ expect(described_class.for_taxonomy('Kategorien')).to contain_exactly(
+ root_category,
+ root_category.parent
+ )
+ end
+ end
+ end
+ end
+
+ describe 'callbacks' do
+ describe 'regenerate_taxon_products' do
+ let!(:taxon) { create(:automatic_taxon) }
+
+ before { taxon.reload }
+
+ context "when taxon's rules_match_policy changes" do
+ it 'calls #regenerate_taxon_products' do
+ expect(taxon).to receive(:regenerate_taxon_products).and_call_original
+
+ taxon.update!(rules_match_policy: :any)
+ end
+ end
+
+ context 'when taxon\'s rule changes' do
+ let!(:tag_rule) { create(:tag_taxon_rule, taxon: taxon, value: 'tag') }
+
+ it 'calls #regenerate_taxon_products' do
+ tag_rule.reload
+ expect(tag_rule).to receive(:regenerate_taxon_products).and_call_original
+
+ tag_rule.update!(value: 'new tag')
+ end
+ end
+
+ context 'when rule is destroyed' do
+ let!(:tag_rule) { create(:tag_taxon_rule, taxon: taxon, value: 'tag') }
+
+ it 'calls #regenerate_taxon_products' do
+ tag_rule.reload
+ expect(tag_rule).to receive(:regenerate_taxon_products).and_call_original
+
+ tag_rule.destroy!
+ end
+ end
+
+ context 'when rule is created' do
+ it 'calls #regenerate_taxon_products' do
+ expect(taxon).to receive(:regenerate_taxon_products).and_call_original
+
+ create(:tag_taxon_rule, taxon: taxon, value: 'tag')
+ end
+ end
+ end
+ end
+
context 'when using another locale' do
before do
root_taxon = taxon.taxonomy.root
@@ -52,6 +139,8 @@ describe Spree::Taxon, type: :model do
description: 'PL description'
)
end
+
+ taxon.reload
end
let(:taxon_pl_translation) { taxon.translations.find_by(locale: 'pl') }
@@ -62,7 +151,8 @@ describe Spree::Taxon, type: :model do
expect(taxon_pl_translation).to be_present
expect(taxon_pl_translation.name).to eq('PL name')
expect(taxon_pl_translation.permalink).to eq('pl-taxonomy/pl-name')
- expect(taxon_pl_translation.description).to eq('PL description')
+
+ expect(taxon.description_pl.to_plain_text).to eq('PL description')
end
end
@@ -129,7 +219,7 @@ describe Spree::Taxon, type: :model do
# Regression test for #2620
context 'creating a child node using first_or_create' do
- let!(:taxonomy) { create(:taxonomy) }
+ let!(:taxonomy) { create(:taxonomy, store: store) }
it 'does not error out' do
expect { taxonomy.root.children.unscoped.where(name: 'Some name', parent_id: taxonomy.taxons.first.id).first_or_create }.not_to raise_error
@@ -153,7 +243,7 @@ describe Spree::Taxon, type: :model do
end
describe '#sync_taxonomy_name' do
- let!(:taxonomy) { create(:taxonomy, name: 'Soft Goods') }
+ let!(:taxonomy) { create(:taxonomy, name: 'Soft Goods', store: store) }
let!(:taxon) { create(:taxon, taxonomy: taxonomy, name: 'Socks' ) }
context 'when none root taxon name is updated' do
@@ -459,11 +549,208 @@ describe Spree::Taxon, type: :model do
end
describe '#store' do
- let(:taxonomy) { create(:taxonomy) }
+ let(:taxonomy) { create(:taxonomy, store: store) }
let(:taxon) { build(:taxon, taxonomy: taxonomy) }
it 'returns the store from the taxonomy' do
- expect(taxon.store).to eq(taxonomy.store)
+ expect(taxon.store).to eq(store)
+ end
+ end
+
+ describe '#active_products_with_descendants' do
+ let(:root_category) { create(:taxon, taxonomy: taxonomy) }
+
+ context 'when category has products' do
+ let!(:product) { create(:product, taxons: [root_category]) }
+
+ it 'returns true' do
+ expect(root_category.reload.active_products_with_descendants.exists?).to be true
+ end
+
+ it 'returns true when products aren\'t active' do
+ product.update(status: 'draft')
+
+ expect(root_category.reload.products.exists?).to be true
+ end
+ end
+
+ context 'when only children categories have products' do
+ let(:parent_category) { create(:taxon, taxonomy: taxonomy, parent: root_category) }
+ let(:child_category) { create(:taxon, taxonomy: taxonomy, parent: parent_category) }
+ let!(:product) { create(:product, taxons: [child_category]) }
+
+ it 'returns true' do
+ expect(root_category.reload.active_products_with_descendants.exists?).to be true
+ end
+
+ it 'returns false when products aren\'t active' do
+ product.update(status: 'draft')
+
+ expect(root_category.reload.active_products_with_descendants.exists?).to be false
+ end
+ end
+
+ context 'when category has no products' do
+ it 'returns false' do
+ expect(root_category.reload.active_products_with_descendants.exists?).to be false
+ end
+ end
+
+ context 'when category has products but children categories have no products' do
+ let(:parent_category) { create(:taxon, taxonomy: taxonomy, parent: root_category) }
+ let!(:child_category) { create(:taxon, taxonomy: taxonomy, parent: parent_category) }
+ let!(:product) { create(:product, taxons: [root_category]) }
+
+ it 'returns true' do
+ expect(root_category.reload.active_products_with_descendants.exists?).to be true
+ end
+
+ it 'returns false when products aren\'t active' do
+ product.update(status: 'draft')
+
+ expect(root_category.reload.active_products_with_descendants.exists?).to be false
+ end
+ end
+
+ context 'when children categories also have no products' do
+ let(:parent_category) { create(:taxon, taxonomy: taxonomy, parent: root_category) }
+ let!(:child_category) { create(:taxon, taxonomy: taxonomy, parent: parent_category) }
+
+ it 'returns false' do
+ expect(root_category.reload.active_products_with_descendants.exists?).to be false
+ end
+ end
+ end
+
+ describe '#products_matching_rules' do
+ context 'when the taxon is manual' do
+ let(:taxon) { create(:taxon) }
+
+ it 'returns an empty taxon' do
+ expect(taxon.reload.products_matching_rules).to be_empty
+ end
+ end
+
+ context 'when the taxon is automatic' do
+ let(:taxon) { create(:automatic_taxon) }
+
+ context 'when the taxon has no rules' do
+ it 'returns an empty taxon' do
+ expect(taxon.reload.products_matching_rules).to be_empty
+ end
+ end
+
+ context 'when the taxon has rules' do
+ context 'when the rule is a tag rule' do
+ let(:cruelty_free_tag) { ActsAsTaggableOn::Tag.create(name: 'cruelty-free') }
+ let(:discounted_tag) { ActsAsTaggableOn::Tag.create(name: 'discounted') }
+ let(:other_tag) { ActsAsTaggableOn::Tag.create(name: 'other') }
+ let!(:cruelty_free_product) { create(:product, tags: [cruelty_free_tag]) }
+ let!(:discounted_product) { create(:product, tags: [discounted_tag]) }
+ let!(:both_tags_product) { create(:product, tags: [cruelty_free_tag, discounted_tag]) }
+ let!(:other_product) { create(:product, tags: [other_tag]) }
+
+ context 'when the match policy is is_equal_to' do
+ it 'returns products that match cruelty-free tag' do
+ create(:tag_taxon_rule, taxon: taxon, value: cruelty_free_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(cruelty_free_product, both_tags_product)
+ end
+
+ it 'returns products that match discounted tag' do
+ create(:tag_taxon_rule, taxon: taxon, value: discounted_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(discounted_product, both_tags_product)
+ end
+
+ context 'with all rules match policy' do
+ it 'returns products that match both tags' do
+ create(:tag_taxon_rule, taxon: taxon, value: cruelty_free_tag.name)
+ create(:tag_taxon_rule, taxon: taxon, value: discounted_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(both_tags_product)
+ end
+ end
+
+ context 'with any rules match policy' do
+ let(:taxon) { create(:automatic_taxon, :any_match_policy) }
+
+ it 'returns products that match any tag' do
+ create(:tag_taxon_rule, taxon: taxon, value: cruelty_free_tag.name)
+ create(:tag_taxon_rule, taxon: taxon, value: discounted_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(cruelty_free_product, discounted_product, both_tags_product)
+ end
+ end
+ end
+
+ context 'when the match policy is is_not_equal_to' do
+ it 'returns products that do not match cruelty-free tag' do
+ create(:tag_taxon_rule, :is_not_equal_to, taxon: taxon, value: cruelty_free_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(discounted_product, other_product)
+ end
+
+ it 'returns products that do not match discounted tag' do
+ create(:tag_taxon_rule, :is_not_equal_to, taxon: taxon, value: discounted_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(cruelty_free_product, other_product)
+ end
+
+ context 'with all rules match policy' do
+ it 'returns products that do not match both tags' do
+ create(:tag_taxon_rule, :is_not_equal_to, taxon: taxon, value: cruelty_free_tag.name)
+ create(:tag_taxon_rule, :is_not_equal_to, taxon: taxon, value: discounted_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(other_product)
+ end
+ end
+
+ context 'with any rules match policy' do
+ let(:taxon) { create(:automatic_taxon, :any_match_policy) }
+
+ it 'returns products that do not match any tag' do
+ create(:tag_taxon_rule, :is_not_equal_to, taxon: taxon, value: cruelty_free_tag.name)
+ create(:tag_taxon_rule, :is_not_equal_to, taxon: taxon, value: discounted_tag.name)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(cruelty_free_product, discounted_product, other_product)
+ end
+ end
+ end
+ end
+
+ context 'when the rule is a sale rule' do
+ let!(:product_with_master_on_sale) { create(:product, price: 10, compare_at_price: 12) }
+ let!(:product_with_one_variant_on_sale) do
+ create(:product).tap do |p|
+ create(:variant, product: p, price: 10, compare_at_price: 12)
+ create(:variant, product: p, price: 10)
+ end
+ end
+ let!(:product_on_sale_with_different_currency) do
+ create(:product, price: 10).tap do |p|
+ p.master.prices.create(amount: 10, compare_at_amount: 12, currency: 'PLN')
+ end
+ end
+ let!(:product_not_on_sale) { create(:product, price: 10) }
+
+ context 'when the match policy is is_equal_to' do
+ it 'matches products that are on sale in store\'s currency' do
+ create(:sale_taxon_rule, taxon: taxon)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(product_with_master_on_sale, product_with_one_variant_on_sale)
+ end
+ end
+
+ context 'when the match policy is in_not_equal_to' do
+ it 'matches products that aren\'t on sale and have price in store\'s currency' do
+ create(:sale_taxon_rule, :is_not_equal_to, taxon: taxon)
+
+ expect(taxon.reload.products_matching_rules).to contain_exactly(product_not_on_sale, product_on_sale_with_different_currency)
+ end
+ end
+ end
+ end
end
end
end
diff --git a/core/spec/models/spree/variant_spec.rb b/core/spec/models/spree/variant_spec.rb
index f0e32fad12..dfd1dfaacc 100644
--- a/core/spec/models/spree/variant_spec.rb
+++ b/core/spec/models/spree/variant_spec.rb
@@ -1,8 +1,8 @@
require 'spec_helper'
describe Spree::Variant, type: :model do
- let!(:store) { create(:store) }
- let!(:variant) { create(:variant) }
+ let!(:store) { Spree::Store.default }
+ let!(:variant) { create(:variant, product: create(:base_product, stores: [store])) }
let(:master_variant) { create(:master_variant) }
it_behaves_like 'default_price'
@@ -1174,7 +1174,9 @@ describe Spree::Variant, type: :model do
let!(:line_item) { create(:line_item, order: order, variant: variant, quantity: 2) }
let!(:line_item_2) { create(:line_item, order: order, variant: variant, quantity: 3) }
- before { variant.update(track_inventory: false) }
+ before do
+ variant.update(track_inventory: false)
+ end
it 'schedules RemoveFromIncompleteOrdersJob' do
expect(Spree::Variants::RemoveFromIncompleteOrdersJob).to receive(:perform_later).with(variant)
@@ -1182,8 +1184,8 @@ describe Spree::Variant, type: :model do
end
it 'deletes the line items from the order' do
- variant.destroy
- expect(order.reload.line_items).to be_empty
+ perform_enqueued_jobs { variant.destroy }
+ expect(order.line_items.reload).to be_empty
expect(order.total).to eq(0)
end
end
diff --git a/core/spec/services/spree/products/auto_match_taxons_spec.rb b/core/spec/services/spree/products/auto_match_taxons_spec.rb
new file mode 100644
index 0000000000..bda6e4f4ed
--- /dev/null
+++ b/core/spec/services/spree/products/auto_match_taxons_spec.rb
@@ -0,0 +1,48 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Products::AutoMatchTaxons do
+ subject { described_class.call(product: product) }
+
+ let(:product) { create(:product) }
+
+ context 'when product matches new taxon' do
+ let!(:taxon) { create(:automatic_taxon) }
+
+ before do
+ create(:tag_taxon_rule, taxon: taxon, value: 'cruelty-free')
+
+ product.tag_list.add('cruelty-free')
+ product.save
+ end
+
+ it 'should be added to the taxon' do
+ subject
+ expect(taxon.products.reload).to include(product)
+ end
+
+ it "doesn't do circular call" do
+ product.tag_list.add('cruelty-free')
+ product.save
+
+ subject
+
+ expect(product).not_to receive(:auto_match_taxons)
+ end
+ end
+
+ context 'when product no longer matches taxon' do
+ let!(:taxon) { create(:automatic_taxon) }
+
+ before do
+ create(:tag_taxon_rule, taxon: taxon, value: 'cruelty-free')
+ taxon.products << product
+ end
+
+ it 'should be removed from the taxon' do
+ expect(taxon.products.reload).to include(product)
+ subject
+
+ expect(taxon.products.reload).not_to include(product)
+ end
+ end
+end
diff --git a/core/spec/services/spree/taxons/regenerate_products_spec.rb b/core/spec/services/spree/taxons/regenerate_products_spec.rb
new file mode 100644
index 0000000000..1de5a0e89b
--- /dev/null
+++ b/core/spec/services/spree/taxons/regenerate_products_spec.rb
@@ -0,0 +1,105 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Taxons::RegenerateProducts do
+ subject(:regenerate_products) { described_class.call(taxon: taxon) }
+
+ let!(:taxon) { create(:automatic_taxon, :any_match_policy, products: tagged_products) }
+ let!(:tag_taxon_rule) { create(:tag_taxon_rule, taxon: taxon, value: 'tag') }
+
+ let(:tagged_products) { create_list(:product_in_stock, 2, tag_list: 'tag') }
+
+ let(:all_products) { tagged_products }
+
+ context 'after changing rules' do
+ let!(:other_tag_taxon_rule) { create(:tag_taxon_rule, :is_equal_to, taxon: taxon, value: 'other') }
+ let!(:other_tagged_product) { create(:product_in_stock, tag_list: 'other') }
+
+ let(:all_products) { [*tagged_products, other_tagged_product] }
+
+ before do
+ tag_taxon_rule.destroy!
+ taxon.reload
+ end
+
+ it 're-matches products for an automatic taxon' do
+ expect { regenerate_products }.to change(taxon.products, :count).from(2).to(1)
+ expect(taxon.reload.products).to contain_exactly(other_tagged_product)
+ end
+ end
+
+ context 'when nothing changed' do
+ before do
+ taxon.reload
+ end
+
+ it "doesn't change the taxon" do
+ expect { regenerate_products }.to_not change(taxon.products, :count)
+ expect(taxon.reload.products).to contain_exactly(*tagged_products)
+ end
+ end
+
+ context 'with manual order' do
+ context 'when nothing changed' do
+ it 'keeps products positions' do
+ regenerate_products
+ expect(taxon.reload.classifications.order(:position).pluck(:position)).to eq([1, 2])
+ end
+ end
+
+ context 'when products added' do
+ let!(:new_product) { create(:product) }
+
+ let(:matching_rules_products) { double(ids: ([new_product] + taxon.products).map(&:id)) }
+
+ before do
+ allow(taxon).to receive(:products_matching_rules).and_return(matching_rules_products)
+ taxon.classifications.order(position: :asc).last.move_to_top
+ end
+
+ it 'keeps products positions' do
+ old_positions = taxon.classifications.reload.order(position: :asc).pluck(:product_id, :position)
+ regenerate_products
+ expect(taxon.products.order(position: :asc).limit(2).pluck(:id, :position)).to eq(old_positions)
+ expect(taxon.reload.classifications.pluck(:position)).to match_array([1, 2, 3])
+ end
+ end
+
+ context 'when some one product removed and 2 added' do
+ let(:tagged_products) { create_list(:product_in_stock, 3, tag_list: 'tag') }
+ let(:new_tagged_products) { create_list(:product_in_stock, 2, tag_list: 'tag') }
+
+ let(:matching_rules_products) { double(ids: new_tagged_products.map(&:id) + [tagged_products.first.id] ) }
+
+ before do
+ allow(taxon).to receive(:products_matching_rules).and_return(matching_rules_products)
+ end
+
+ it 'keeps products positions' do
+ old_positions = taxon.classifications.reload.order(position: :asc).limit(1).pluck(:product_id, :position)
+ regenerate_products
+ expect(taxon.products.order(position: :asc).limit(1).pluck(:id, :position)).to eq(old_positions)
+ expect(taxon.reload.classifications.pluck(:position)).to match_array([1, 2, 3])
+ end
+ end
+
+ context 'when some one product removed from middle of list and 2 added' do
+ let(:tagged_products) { create_list(:product_in_stock, 3, tag_list: 'tag') }
+ let(:new_tagged_products) { create_list(:product_in_stock, 2, tag_list: 'tag') }
+
+ let(:current_taxon_products) { taxon.classifications.reload.order(position: :asc) }
+ let(:matching_rules_products) { double(ids: (new_tagged_products.map(&:id) + [current_taxon_products.first.product_id, current_taxon_products.last.product_id]).shuffle ) }
+
+ before do
+ allow(taxon).to receive(:products_matching_rules).and_return(matching_rules_products)
+ end
+
+ it 'keeps products positions' do
+ product_1 = current_taxon_products.first.product
+ product_3 = current_taxon_products.third.product
+ regenerate_products
+ expect(taxon.classifications.reload.order(position: :asc).where(product: [product_1, product_3]).pluck(:position)).to eq([1,2])
+ expect(taxon.reload.classifications.pluck(:position)).to match_array([1, 2, 3, 4])
+ end
+ end
+ end
+end
diff --git a/core/spec/spec_helper.rb b/core/spec/spec_helper.rb
index b2b7ef286d..a3f559d3e6 100644
--- a/core/spec/spec_helper.rb
+++ b/core/spec/spec_helper.rb
@@ -66,8 +66,6 @@ RSpec.configure do |config|
# Clean out the database state before the tests run
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
- # Force jobs to be executed in a synchronous way
- ActiveJob::Base.queue_adapter = :inline
end
config.around(:each) do |example|