From 8848af15ee4eeaa03c2b19258b0620155de57199 Mon Sep 17 00:00:00 2001 From: Pau Perez Date: Tue, 4 Sep 2018 13:26:42 +0200 Subject: [PATCH] Raise when a variant has more than a stock item This means we violated the business rules of having a single stock location for the OFN instance and hence a single stock item per variant. Although it is too late to preserve the data integrity we can know data needs to be cleaned up. --- lib/open_food_network/variant_stock.rb | 6 ++++++ spec/lib/open_food_network/variant_stock_spec.rb | 15 +++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/lib/open_food_network/variant_stock.rb b/lib/open_food_network/variant_stock.rb index 0b2773542d..98bde544f7 100644 --- a/lib/open_food_network/variant_stock.rb +++ b/lib/open_food_network/variant_stock.rb @@ -98,6 +98,7 @@ module OpenFoodNetwork warn_deprecation(__method__, 'Spree::Config[:track_inventory_levels]') raise_error_if_no_stock_item_available + raise_error_if_multiple_stock_items # There should be only one at the default stock location. # @@ -125,6 +126,11 @@ module OpenFoodNetwork raise message if stock_items.empty? end + def raise_error_if_multiple_stock_items + message = 'A variant cannot have more than a stock item.' + raise message if stock_items.size > 1 + end + # Backwards compatible setting of stock levels in Spree 2.0. # It would be better to use `Spree::StockItem.adjust_count_on_hand` which # takes a value to add to the current stock level and uses proper locking. diff --git a/spec/lib/open_food_network/variant_stock_spec.rb b/spec/lib/open_food_network/variant_stock_spec.rb index 1c3efb88ca..b0818f6690 100644 --- a/spec/lib/open_food_network/variant_stock_spec.rb +++ b/spec/lib/open_food_network/variant_stock_spec.rb @@ -129,6 +129,21 @@ describe OpenFoodNetwork::VariantStock do end describe '#on_demand=' do + context 'when the variant has multiple stock items' do + let(:variant) { create(:variant) } + + before do + # Spree creates a stock_item for each variant when creating a stock + # location by means of #propagate_variant + create(:stock_location, name: 'location') + create(:stock_location, name: 'another location') + end + + it 'raises' do + expect { variant.on_demand = true }.to raise_error(StandardError) + end + end + context 'when the variant has a stock item' do let(:variant) { create(:variant, on_demand: true) }