From 3dc7c2bf56c38767c1f98fcf06fecfaad271b7cc Mon Sep 17 00:00:00 2001 From: Gaetan Craig-Riou Date: Sun, 26 May 2024 14:16:38 +1000 Subject: [PATCH] Fix spree product touch supplier Take into account import product scenario, in this case the variant doesn't have an assigned supplier yet. --- app/models/spree/product.rb | 8 +++++++- spec/models/spree/product_spec.rb | 8 ++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/app/models/spree/product.rb b/app/models/spree/product.rb index 56e6150621..5c7d55e1bd 100755 --- a/app/models/spree/product.rb +++ b/app/models/spree/product.rb @@ -77,6 +77,7 @@ module Spree after_update :touch_supplier, if: :saved_change_to_primary_taxon_id? around_destroy :destruction after_save :update_units + after_touch :touch_supplier # -- Scopes scope :with_properties, ->(*property_ids) { @@ -333,7 +334,12 @@ module Spree # Assume the product supplier is the supplier of the first variant # Will breack if product has mutiple variants with different supplier - variants.first.supplier.touch + first_variant = variants.first + + # The variant is invalid if no supplier is present, but this method can be triggered when + # importing product. In this scenario the variant has not been updated with the supplier yet + # hence the check. + first_variant.supplier.touch if first_variant.supplier.present? end def touch_distributors diff --git a/spec/models/spree/product_spec.rb b/spec/models/spree/product_spec.rb index 1106ecd92c..fbe396b709 100644 --- a/spec/models/spree/product_spec.rb +++ b/spec/models/spree/product_spec.rb @@ -334,6 +334,14 @@ module Spree expect { product.touch } .to change { supplier.reload.updated_at } end + + context "when the first variant is missing supplier" do + it "doesn't blow up" do + product.variants.first.update_attribute(:supplier_id, nil) + + expect { product.touch }.to_not raise_error + end + end end it "updates units when saved change to variant unit" do