From 5e0186fa1ff4164781ab0781a1adee6f0c56ffcf Mon Sep 17 00:00:00 2001 From: Rob Harrington Date: Wed, 16 Nov 2016 12:00:33 +1100 Subject: [PATCH] Standing Order Placement Job: capping line items quantities to available stock level --- app/jobs/standing_order_placement_job.rb | 10 +++++++ .../jobs/standing_order_placement_job_spec.rb | 27 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/app/jobs/standing_order_placement_job.rb b/app/jobs/standing_order_placement_job.rb index 829b57b249..e9367556d2 100644 --- a/app/jobs/standing_order_placement_job.rb +++ b/app/jobs/standing_order_placement_job.rb @@ -33,4 +33,14 @@ class StandingOrderPlacementJob end end end + + def cap_quantity_and_store_changes(order) + insufficient_stock_lines = order.insufficient_stock_lines + return [] unless insufficient_stock_lines.present? + insufficient_stock_lines.map do |line_item| + quantity_was = line_item.quantity + line_item.cap_quantity_at_stock! + { line_item: line_item, quantity_was: quantity_was } + end + end end diff --git a/spec/jobs/standing_order_placement_job_spec.rb b/spec/jobs/standing_order_placement_job_spec.rb index 27805393d7..e1121bcca7 100644 --- a/spec/jobs/standing_order_placement_job_spec.rb +++ b/spec/jobs/standing_order_placement_job_spec.rb @@ -29,6 +29,33 @@ describe StandingOrderPlacementJob do end end + describe "processing an order containing items with insufficient stock" do + let(:order) { create(:order, order_cycle: order_cycle1) } + let(:variant1) { create(:variant, count_on_hand: 5) } + let(:variant2) { create(:variant, count_on_hand: 2) } + let(:variant3) { create(:variant, count_on_hand: 0) } + let(:line_item1) { create(:line_item, order: order, variant: variant1, quantity: 5) } + let(:line_item2) { create(:line_item, order: order, variant: variant2, quantity: 2) } + let(:line_item3) { create(:line_item, order: order, variant: variant3, quantity: 0) } + + before do + line_item1.update_attribute(:quantity, 3) + line_item2.update_attribute(:quantity, 3) + line_item3.update_attribute(:quantity, 3) + end + + it "caps quantity at the stock level, and reports the change" do + changes = job.send(:cap_quantity_and_store_changes, order.reload) + expect(line_item1.reload.quantity).to be 3 # not capped + expect(line_item2.reload.quantity).to be 2 # capped + expect(line_item3.reload.quantity).to be 0 # capped + expect(changes).to eq [ + { line_item: line_item2, quantity_was: 3}, + { line_item: line_item3, quantity_was: 3} + ] + end + end + describe "performing the job" do let(:order) { standing_order1.orders.first }