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
Prevent NoMethodError in StoreProduct#refresh_metrics! when product is nil (#13531)
Damian Legawiec43abc97b4beb
diff --git a/core/app/models/spree/store_product.rb b/core/app/models/spree/store_product.rbindex cb3c7ed5b9..b10365e53a 100644--- a/core/app/models/spree/store_product.rb+++ b/core/app/models/spree/store_product.rb@@ -9,6 +9,8 @@ module Spreevalidates :store_id, uniqueness: { scope: :product_id }def refresh_metrics!+ return if product.nil?+completed_order_ids = product.completed_orders.where(store_id: store_id).select(:id)variant_ids = product.variants_including_master.idsdiff --git a/core/spec/models/spree/store_product_spec.rb b/core/spec/models/spree/store_product_spec.rbindex 81ffafe12a..2ebe9ffd0f 100644--- a/core/spec/models/spree/store_product_spec.rb+++ b/core/spec/models/spree/store_product_spec.rb@@ -121,5 +121,49 @@ RSpec.describe Spree::StoreProduct, type: :model doexpect(store_product.revenue).to eq(expected_revenue)endend++ context 'when product association is nil' do+ let(:store_product) { build(:store_product, store: store, product: nil) }++ it 'returns nil without errors' do+ result = nil+ expect { result = store_product.refresh_metrics! }.not_to raise_error+ expect(result).to be_nil+ end++ it 'does not update metrics' do+ original_units_sold_count = store_product.units_sold_count+ original_revenue = store_product.revenue++ store_product.refresh_metrics!++ expect(store_product.units_sold_count).to eq(original_units_sold_count)+ expect(store_product.revenue).to eq(original_revenue)+ end++ context 'when product_id points to non-existent product' do+ let(:store_product) { described_class.new(store: store, product_id: 999999) }++ it 'handles missing product gracefully' do+ expect(store_product.product).to be_nil+ expect { store_product.refresh_metrics! }.not_to raise_error+ end+ end++ context 'when product is destroyed after store_product creation' do+ let(:product) { create(:product, stores: [store]) }+ let(:store_product) { product.store_products.find_by(store: store) }++ it 'handles destroyed product gracefully' do+ original_product_id = store_product.product_id+ product.destroy+ store_product.reload++ expect(store_product.product_id).to eq(original_product_id)+ expect(store_product.product).to be_nil+ expect { store_product.refresh_metrics! }.not_to raise_error+ end+ end+ endendend