From 1c7e9923f963e2b6506219b49b1eaa607c7fc181 Mon Sep 17 00:00:00 2001 From: Rob Harrington Date: Sun, 13 Nov 2016 11:22:40 +1100 Subject: [PATCH] Checking for sufficient stock takes variant overrides into account --- app/models/spree/line_item_decorator.rb | 12 ++++++++++ spec/models/spree/line_item_spec.rb | 31 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/app/models/spree/line_item_decorator.rb b/app/models/spree/line_item_decorator.rb index de9dffbcc4..a15c5bf43e 100644 --- a/app/models/spree/line_item_decorator.rb +++ b/app/models/spree/line_item_decorator.rb @@ -125,6 +125,18 @@ Spree::LineItem.class_eval do Spree::InventoryUnit.decrease(order, variant, quantity) end + # MONKEYPATCH of Spree method + # Enables scoping of variant to hub/shop, so we check stock against relevant overrides if they exist + def sufficient_stock? + scoper.scope(variant) # This line added + return true if Spree::Config[:allow_backorders] + if new_record? || !order.completed? + variant.on_hand >= quantity + else + variant.on_hand >= (quantity - self.changed_attributes['quantity'].to_i) + end + end + private def scoper diff --git a/spec/models/spree/line_item_spec.rb b/spec/models/spree/line_item_spec.rb index 00e2077dc9..f669c08f92 100644 --- a/spec/models/spree/line_item_spec.rb +++ b/spec/models/spree/line_item_spec.rb @@ -140,6 +140,37 @@ module Spree end end + describe "determining if sufficient stock is present" do + let!(:v) { create(:variant, on_demand: false, on_hand: 10) } + let!(:li) { create(:line_item, variant: v, quantity: 5, max_quantity: 5) } + let!(:hub) { create(:distributor_enterprise) } + + before do + Spree::Config.set allow_backorders: false + li.order.update_attributes(distributor_id: hub.id) + end + + context "when no variant override is in place" do + it "uses stock level on the variant" do + expect(li.sufficient_stock?).to be_true + v.update_attributes(on_hand: 4) + expect(li.sufficient_stock?).to be_false + end + end + + context "when a variant override is in place" do + let!(:vo) { create(:variant_override, hub: hub, variant: v, count_on_hand: 5) } + + it "uses stock level on the override" do + expect(li.sufficient_stock?).to be_true + v.update_attributes(on_hand: 4) + expect(li.sufficient_stock?).to be_true + vo.update_attributes(count_on_hand: 4) + expect(li.sufficient_stock?).to be_false + end + end + end + describe "calculating price with adjustments" do it "does not return fractional cents" do li = LineItem.new