Skip to content

Commit

Permalink
Raise when a variant has more than a stock item
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
sauloperez committed Sep 6, 2018
1 parent acce7e3 commit 2cdcd22
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/open_food_network/variant_stock.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ def on_demand
# @raise [StandardError] when the variant has no stock item yet
def on_demand=(new_value)
warn_deprecation(__method__)

raise_error_if_no_stock_item_available
raise_error_if_multiple_stock_items

# There should be only one at the default stock location.
#
Expand Down Expand Up @@ -117,6 +119,11 @@ def raise_error_if_no_stock_item_available
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.
Expand Down
15 changes: 15 additions & 0 deletions spec/lib/open_food_network/variant_stock_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,21 @@
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) }

Expand Down

0 comments on commit 2cdcd22

Please sign in to comment.