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.

Added `Category#products_count`

Damian Legawiecc4a423f96eae
diff --git a/packages/admin-sdk/src/types/generated/Category.ts b/packages/admin-sdk/src/types/generated/Category.ts
index d98e0ee5dc..f2247de17e 100644
--- a/packages/admin-sdk/src/types/generated/Category.ts
+++ b/packages/admin-sdk/src/types/generated/Category.ts
@@ -1,4 +1,4 @@
-// Typelizer digest d6f9417c8877ac349d6c73e2fda11bb1
+// Typelizer digest 6c717d21c07f4658e3af496b37777bc4
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CustomField} from '@/types'
@@ -30,6 +30,7 @@ interface Category {
pretty_name: string;
lft: number;
rgt: number;
+ products_count: number;
created_at: string;
updated_at: string;
}
diff --git a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
index 4d46421f0b..c36d93ab44 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/category_serializer.rb
@@ -7,11 +7,11 @@ module Spree
class CategorySerializer < V3::CategorySerializer
include Spree::Api::V3::Admin::Translatable
- typelize pretty_name: :string, lft: :number, rgt: :number, sort_order: :string,
+ typelize pretty_name: :string, lft: :number, rgt: :number, products_count: :number,
metadata: 'Record<string, unknown>'
- # Admin-only attributes
- attributes :metadata, :pretty_name, :lft, :rgt, created_at: :iso8601, updated_at: :iso8601
+ attributes :metadata, :pretty_name, :lft, :rgt, :products_count,
+ created_at: :iso8601, updated_at: :iso8601
# Override inherited associations to use admin serializers
one :parent,
diff --git a/spree/core/app/models/spree/classification.rb b/spree/core/app/models/spree/classification.rb
index d55c4a64e0..fc0347ff77 100644
--- a/spree/core/app/models/spree/classification.rb
+++ b/spree/core/app/models/spree/classification.rb
@@ -13,6 +13,12 @@ module Spree
# For #3494
validates :taxon_id, uniqueness: { scope: :product_id, message: :already_linked, allow_blank: true }
+ # Keep the taxon's descendant-inclusive products_count (and its ancestors')
+ # in sync on direct create/destroy. Bulk Taxons::AddProducts/RemoveProducts
+ # skip these callbacks and recompute explicitly.
+ after_create :recalculate_taxon_products_count
+ after_destroy :recalculate_taxon_products_count
+
self.whitelisted_ransackable_attributes = ['taxon_id', 'product_id']
scope :by_best_selling, lambda { |order_direction = :desc|
@@ -36,5 +42,11 @@ module Spree
end
end
}
+
+ private
+
+ def recalculate_taxon_products_count
+ Spree::Taxon.recalculate_products_count(taxon_id)
+ end
end
end
diff --git a/spree/core/app/models/spree/taxon.rb b/spree/core/app/models/spree/taxon.rb
index 186297f7ff..5b2ab962f2 100644
--- a/spree/core/app/models/spree/taxon.rb
+++ b/spree/core/app/models/spree/taxon.rb
@@ -83,6 +83,11 @@ module Spree
after_commit :regenerate_pretty_name_and_permalink, on: :update, if: :should_regenerate_pretty_name_and_permalink?
after_move :regenerate_pretty_name_and_permalink
after_move :regenerate_translations_pretty_name_and_permalink
+ # Moving a subtree shifts its products under a new ancestor chain (and away
+ # from the old one), so recompute both branches' inclusive products_count.
+ # Capture the old parent before the move; recompute both chains after.
+ before_move :capture_parent_before_move
+ after_move :recalculate_products_count_after_move
#
# Scopes
@@ -131,7 +136,7 @@ module Spree
#
self.whitelisted_ransackable_associations = %w[taxonomy parent]
self.whitelisted_ransackable_attributes = %w[name permalink automatic depth is_root children_count
- classification_count hide_from_nav parent_id]
+ classification_count products_count pretty_name hide_from_nav parent_id]
#
# Translations
@@ -192,6 +197,26 @@ module Spree
)
end
+ # Recomputes the stored, descendant-inclusive +products_count+ for the given
+ # taxons AND all of their ancestors — the nodes whose inclusive count can
+ # shift when a classification changes. Counts unique products classified
+ # under each node or its descendants (a product reachable through several
+ # nodes is counted once per ancestor). Call after any classification change.
+ #
+ # @param taxon_ids [Array<Integer>] taxons whose branch counts changed
+ def self.recalculate_products_count(taxon_ids)
+ changed = unscoped.where(id: Array(taxon_ids).compact.uniq)
+
+ # The affected nodes are each changed taxon plus its ancestors.
+ affected = changed.flat_map { |taxon| taxon.self_and_ancestors.to_a }.uniq(&:id)
+
+ affected.each do |taxon|
+ count = Spree::Classification.where(taxon_id: taxon.self_and_descendants.select(:id))
+ .distinct.count(:product_id)
+ taxon.update_column(:products_count, count) if taxon.products_count != count
+ end
+ end
+
def products_matching_rules(opts = {})
return Spree::Product.none if manual? || rules.empty?
@@ -413,7 +438,16 @@ module Spree
# Touches all ancestors at once to avoid recursive taxonomy touch, and reduce queries.
ancestors.update_all(updated_at: Time.current)
# Have taxonomy touch happen in #touch_ancestors_and_taxonomy rather than association option in order for imports to override.
- taxonomy.try!(:touch)
+ taxonomy.touch if taxonomy.present?
+ end
+
+ # Recompute the inclusive products_count for the moved node's new ancestor
+ # chain and the previous parent's chain too (whose subtree just lost this
+ # node's products).
+ def recalculate_products_count_after_move
+ affected = [id, @parent_id_before_move].compact
+ @parent_id_before_move = nil
+ self.class.recalculate_products_count(affected)
end
def check_for_root
diff --git a/spree/core/app/services/spree/taxons/add_products.rb b/spree/core/app/services/spree/taxons/add_products.rb
index 88aa4f5a1c..4a6c941d21 100644
--- a/spree/core/app/services/spree/taxons/add_products.rb
+++ b/spree/core/app/services/spree/taxons/add_products.rb
@@ -33,6 +33,9 @@ module Spree
product_ids = products.pluck(:id)
taxon_ids.each { |id| Spree::Taxon.reset_counters(id, :classifications) }
product_ids.each { |id| Spree::Product.reset_counters(id, :classifications) }
+ # Recompute the descendant-inclusive products_count for the taxons and
+ # their ancestors (bulk insert skips Classification callbacks).
+ Spree::Taxon.recalculate_products_count(taxon_ids)
# clear cache & index products
Spree::Product.where(id: product_ids).touch_all
diff --git a/spree/core/app/services/spree/taxons/remove_products.rb b/spree/core/app/services/spree/taxons/remove_products.rb
index 26da0cad44..f277e5b2e9 100644
--- a/spree/core/app/services/spree/taxons/remove_products.rb
+++ b/spree/core/app/services/spree/taxons/remove_products.rb
@@ -48,6 +48,9 @@ module Spree
# update counter caches
taxon_ids.each { |id| Spree::Taxon.reset_counters(id, :classifications) }
product_ids.each { |id| Spree::Product.reset_counters(id, :classifications) }
+ # Recompute the descendant-inclusive products_count for the taxons and
+ # their ancestors (delete_all skips Classification callbacks).
+ Spree::Taxon.recalculate_products_count(taxon_ids)
# clear cache & index products
Spree::Product.where(id: product_ids).touch_all
diff --git a/spree/core/db/migrate/20260627000001_add_products_count_to_spree_taxons.rb b/spree/core/db/migrate/20260627000001_add_products_count_to_spree_taxons.rb
new file mode 100644
index 0000000000..378badb180
--- /dev/null
+++ b/spree/core/db/migrate/20260627000001_add_products_count_to_spree_taxons.rb
@@ -0,0 +1,6 @@
+class AddProductsCountToSpreeTaxons < ActiveRecord::Migration[7.2]
+ def change
+ add_column :spree_taxons, :products_count, :integer, default: 0, null: false, if_not_exists: true
+ add_index :spree_taxons, :products_count, if_not_exists: true
+ end
+end
diff --git a/spree/core/lib/tasks/taxons.rake b/spree/core/lib/tasks/taxons.rake
index d5f16c43f4..ce063525f0 100644
--- a/spree/core/lib/tasks/taxons.rake
+++ b/spree/core/lib/tasks/taxons.rake
@@ -1,6 +1,5 @@
namespace :spree do
namespace :taxons do
- desc 'Reset counter caches (children_count, classification_count) on taxons'
desc 'Backfill spree_taxons.store_id from each taxon\'s taxonomy'
task backfill_store_id: :environment do |_t, _args|
puts 'Backfilling taxon store_id from taxonomy...'
@@ -12,6 +11,24 @@ namespace :spree do
puts "\nDone!"
end
+
+ # Recomputes the descendant-inclusive products_count for every taxon, in
+ # batches. Shared by the dedicated task and reset_counter_caches.
+ backfill_products_count = lambda do
+ Spree::Taxon.unscoped.in_batches(of: 1000) do |batch|
+ Spree::Taxon.recalculate_products_count(batch.pluck(:id))
+ print '.'
+ end
+ end
+
+ desc 'Backfill the descendant-inclusive products_count on every taxon'
+ task backfill_products_count: :environment do |_t, _args|
+ puts 'Backfilling taxon products_count...'
+ backfill_products_count.call
+ puts "\nDone!"
+ end
+
+ desc 'Reset counter caches (children_count, classification_count, products_count) on taxons'
task reset_counter_caches: :environment do |_t, _args|
puts 'Resetting taxon counter caches...'
@@ -24,6 +41,9 @@ namespace :spree do
print '.'
end
+ puts "\nRecomputing products_count..."
+ backfill_products_count.call
+
puts "\nDone!"
end
end
diff --git a/spree/core/spec/models/spree/category_spec.rb b/spree/core/spec/models/spree/category_spec.rb
index 780d3aa4db..8d2c203ff2 100644
--- a/spree/core/spec/models/spree/category_spec.rb
+++ b/spree/core/spec/models/spree/category_spec.rb
@@ -87,4 +87,70 @@ RSpec.describe Spree::Category, type: :model do
expect(described_class.for_stores([store, other])).to include(mine, theirs)
end
end
+
+ describe 'products_count (descendant-inclusive)' do
+ let(:electronics) { described_class.create!(name: 'Electronics', store: store) }
+ let(:phones) { described_class.create!(name: 'Phones', parent: electronics) }
+ let(:laptops) { described_class.create!(name: 'Laptops', parent: electronics) }
+
+ def add(product, category)
+ Spree::Taxons::AddProducts.call(taxons: [category], products: [product])
+ end
+
+ it 'counts a directly-assigned product on the category' do
+ add(create(:product, stores: [store]), phones)
+
+ expect(phones.reload.products_count).to eq(1)
+ expect(phones.reload.classification_count).to eq(1)
+ end
+
+ it 'rolls subcategory products up to ancestors' do
+ add(create(:product, stores: [store]), phones)
+ add(create(:product, stores: [store]), laptops)
+
+ expect(electronics.reload.products_count).to eq(2) # inclusive
+ expect(electronics.reload.classification_count).to eq(0) # nothing direct
+ expect(phones.reload.products_count).to eq(1)
+ expect(laptops.reload.products_count).to eq(1)
+ end
+
+ it 'de-duplicates a product reachable through several nodes' do
+ product = create(:product, stores: [store])
+ add(product, phones)
+ add(product, electronics) # also directly on the ancestor
+
+ expect(electronics.reload.products_count).to eq(1) # counted once
+ end
+
+ it 'decrements ancestors when a product is removed' do
+ product = create(:product, stores: [store])
+ add(product, phones)
+ expect(electronics.reload.products_count).to eq(1)
+
+ Spree::Taxons::RemoveProducts.call(taxons: [phones], products: [product])
+
+ expect(electronics.reload.products_count).to eq(0)
+ expect(phones.reload.products_count).to eq(0)
+ end
+
+ it 'maintains the count on a direct Classification create/destroy' do
+ product = create(:product, stores: [store])
+ classification = Spree::Classification.create!(taxon: phones, product: product)
+ expect(electronics.reload.products_count).to eq(1)
+
+ classification.destroy
+ expect(electronics.reload.products_count).to eq(0)
+ end
+
+ it 'updates both ancestor chains when a subtree moves' do
+ other_root = described_class.create!(name: 'Office', store: store)
+ add(create(:product, stores: [store]), phones)
+ expect(electronics.reload.products_count).to eq(1)
+
+ phones.reload.move_to_child_of(other_root.reload)
+
+ expect(electronics.reload.products_count).to eq(0) # lost the subtree
+ expect(other_root.reload.products_count).to eq(1) # gained it
+ end
+ end
end