Skip to content

Commit 280048c

Browse files
committed
check if stock_items are loaded before doing a SUM()
1 parent 75d3196 commit 280048c

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

core/app/models/spree/product.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,8 @@ def possible_promotions
289289
def total_on_hand
290290
if any_variants_not_track_inventory?
291291
Float::INFINITY
292+
elsif stock_items.loaded?
293+
stock_items.sum(&:count_on_hand)
292294
else
293295
stock_items.sum(:count_on_hand)
294296
end

core/spec/models/spree/product_spec.rb

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -550,6 +550,8 @@ class Extension < Spree::Base
550550
end
551551

552552
context '#total_on_hand' do
553+
let(:product) { create :product }
554+
553555
it 'should be infinite if track_inventory_levels is false' do
554556
stub_spree_preferences(track_inventory_levels: false)
555557
expect(build(:product, variants_including_master: [build(:master_variant)]).total_on_hand).to eql(Float::INFINITY)
@@ -561,17 +563,30 @@ class Extension < Spree::Base
561563
end
562564

563565
it 'should return sum of stock items count_on_hand' do
564-
product = create(:product)
565566
product.stock_items.first.set_count_on_hand 5
566567
product.variants_including_master.reload # force load association
567568
expect(product.total_on_hand).to eql(5)
568569
end
569570

570571
it 'should return sum of stock items count_on_hand when variants_including_master is not loaded' do
571-
product = create(:product)
572572
product.stock_items.first.set_count_on_hand 5
573573
expect(product.reload.total_on_hand).to eql(5)
574574
end
575+
576+
context 'when the stock items are loaded' do
577+
it 'returns the loaded count_on_hand instead of doing SUM(count_on_hand)' do
578+
product.stock_items.first.set_count_on_hand(5)
579+
580+
product = described_class.includes(:stock_items).find(product.id)
581+
582+
# Set the count on hand to a different number to highlight we loaded and
583+
# must be done from the class level so that we don't update the instance
584+
# product has loaded
585+
Spree::StockItem.find(product.stock_items.first.id).set_count_on_hand(7)
586+
587+
expect(product.total_on_hand).to eql 5
588+
end
589+
end
575590
end
576591

577592
# Regression spec for https://github.com/spree/spree/issues/5588

0 commit comments

Comments
 (0)