diff --git a/app/models/variant_override.rb b/app/models/variant_override.rb index dd3b22a5e0..355a46d1db 100644 --- a/app/models/variant_override.rb +++ b/app/models/variant_override.rb @@ -57,9 +57,15 @@ class VariantOverride < ActiveRecord::Base end def stock_overridden? + # If count_on_hand is present, it means on_demand is false + # See StockSettingsOverrideValidation for details count_on_hand.present? end + def use_producer_stock_settings? + on_demand.nil? + end + def decrement_stock!(quantity) if stock_overridden? decrement! :count_on_hand, quantity diff --git a/lib/open_food_network/scope_variant_to_hub.rb b/lib/open_food_network/scope_variant_to_hub.rb index bc2afa63da..a721505f7f 100644 --- a/lib/open_food_network/scope_variant_to_hub.rb +++ b/lib/open_food_network/scope_variant_to_hub.rb @@ -29,20 +29,18 @@ module OpenFoodNetwork end def count_on_hand - @variant_override.andand.count_on_hand || super + if @variant_override.present? && @variant_override.stock_overridden? + @variant_override.count_on_hand + else + super + end end def on_demand - if @variant_override.andand.on_demand.nil? - if @variant_override.andand.count_on_hand.present? - # If we're overriding the stock level of an on_demand variant, show it as not - # on_demand, so our stock control can take effect. - false - else - super - end + if @variant_override.present? && !@variant_override.use_producer_stock_settings? + @variant_override.on_demand else - @variant_override.andand.on_demand + super end end diff --git a/spec/lib/open_food_network/scope_variant_to_hub_spec.rb b/spec/lib/open_food_network/scope_variant_to_hub_spec.rb index aa5ce4b317..4f0ec5f13e 100644 --- a/spec/lib/open_food_network/scope_variant_to_hub_spec.rb +++ b/spec/lib/open_food_network/scope_variant_to_hub_spec.rb @@ -1,3 +1,4 @@ +require 'spec_helper' require 'open_food_network/scope_variant_to_hub' module OpenFoodNetwork @@ -81,13 +82,6 @@ module OpenFoodNetwork context "without an on_demand set" do before { vo.update_column(:on_demand, nil) } - context "when count_on_hand is set" do - it "returns false" do - scoper.scope v - expect(v.on_demand).to be false - end - end - context "when count_on_hand is not set" do before { vo.update_column(:count_on_hand, nil) } @@ -96,6 +90,13 @@ module OpenFoodNetwork expect(v.on_demand).to be true end end + + context "when count_on_hand is set" do + it "should return validation error on save" do + scoper.scope v + expect{ vo.save! }.to raise_error ActiveRecord::RecordInvalid + end + end end end