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.

Improve performance of `Product#total_on_hand`

Damian Legawiec6db41942decc
diff --git a/core/app/models/spree/product.rb b/core/app/models/spree/product.rb
index b125c66e1a..bdeeabf010 100644
--- a/core/app/models/spree/product.rb
+++ b/core/app/models/spree/product.rb
@@ -390,13 +390,11 @@ module Spree
end
def total_on_hand
- @total_on_hand ||= Rails.cache.fetch(['product-total-on-hand', cache_key_with_version]) do
- if any_variants_not_track_inventory?
- BigDecimal::INFINITY
- else
- stock_items.sum(:count_on_hand)
- end
- end
+ @total_on_hand ||= if any_variants_not_track_inventory?
+ BigDecimal::INFINITY
+ else
+ stock_items.loaded? ? stock_items.sum(&:count_on_hand) : stock_items.sum(:count_on_hand)
+ end
end
# Master variant may be deleted (i.e. when the product is deleted)
diff --git a/core/spec/models/spree/store_product_spec.rb b/core/spec/models/spree/store_product_spec.rb
deleted file mode 100644
index 3246dac80b..0000000000
--- a/core/spec/models/spree/store_product_spec.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-require 'spec_helper'
-
-describe Spree::StoreProduct, type: :model do
- let!(:store) { create(:store) }
- let!(:another_store) { create(:store) }
- let!(:product) { create(:product, stores: [store]) }
-
- context 'assigning store' do
- subject(:assign_store) { product.stores << another_store }
-
- it 'touches product' do
- expect { assign_store }.to change(product, :updated_at)
- end
-
- it 'touches store' do
- expect { assign_store }.to change(another_store, :updated_at)
- end
-
- it 'increases Store Product count' do
- expect { assign_store }.to change(described_class, :count).from(1).to(2)
- end
- end
-
- context 'unassignes store' do
- subject(:unassign_store) { product.stores.destroy(another_store) }
-
- before { product.stores << another_store }
-
- it 'touches product' do
- expect { unassign_store }.to change(product, :updated_at)
- end
-
- it 'decreases Store Product count' do
- expect { unassign_store }.to change(described_class, :count).from(2).to(1)
- end
-
- it 'does not remove store' do
- expect { unassign_store }.not_to change { Spree::Store.count }
- end
- end
-end