diff --git a/app/controllers/checkout_controller.rb b/app/controllers/checkout_controller.rb index a63d1db998..4cedfbbac9 100644 --- a/app/controllers/checkout_controller.rb +++ b/app/controllers/checkout_controller.rb @@ -25,7 +25,7 @@ class CheckoutController < Spree::StoreController before_action :ensure_order_not_completed before_action :ensure_checkout_allowed - before_action :ensure_sufficient_stock_lines + before_action :handle_insufficient_stock before_action :associate_user before_action :check_authorization diff --git a/app/controllers/concerns/order_stock_check.rb b/app/controllers/concerns/order_stock_check.rb index 1578677fd4..2adfaf67be 100644 --- a/app/controllers/concerns/order_stock_check.rb +++ b/app/controllers/concerns/order_stock_check.rb @@ -3,10 +3,16 @@ module OrderStockCheck extend ActiveSupport::Concern - def ensure_sufficient_stock_lines - return true if @order.insufficient_stock_lines.blank? + def handle_insufficient_stock + return if sufficient_stock? flash[:error] = Spree.t(:inventory_error_flash_for_insufficient_quantity) redirect_to main_app.cart_path end + + private + + def sufficient_stock? + @sufficient_stock ||= @order.insufficient_stock_lines.blank? + end end diff --git a/app/controllers/spree/paypal_controller_decorator.rb b/app/controllers/spree/paypal_controller_decorator.rb index f28c75a761..9d20713efa 100644 --- a/app/controllers/spree/paypal_controller_decorator.rb +++ b/app/controllers/spree/paypal_controller_decorator.rb @@ -58,9 +58,10 @@ Spree::PaypalController.class_eval do def confirm @order = current_order || raise(ActiveRecord::RecordNotFound) + # At this point the user has come back from the Paypal form, and we get one # last chance to interact with the payment process before the money moves... - return unless ensure_sufficient_stock_lines + return handle_insufficient_stock unless sufficient_stock? @order.payments.create!({ source: Spree::PaypalExpressCheckout.create({ diff --git a/spec/controllers/spree/paypal_controller_spec.rb b/spec/controllers/spree/paypal_controller_spec.rb index 9f630e892d..3182048ed4 100644 --- a/spec/controllers/spree/paypal_controller_spec.rb +++ b/spec/controllers/spree/paypal_controller_spec.rb @@ -27,6 +27,20 @@ module Spree spree_post :confirm, payment_method_id: payment_method.id expect(session[:access_token]).to eq(controller.current_order.token) end + + context "if the stock ran out whilst the payment was being placed" do + before do + allow(controller.current_order).to receive(:insufficient_stock_lines).and_return(true) + end + + it "redirects to the cart with out of stock error" do + expect(spree_post(:confirm, payment_method_id: payment_method.id)). + to redirect_to cart_path + + # And does not complete processing of the payment + expect(controller.current_order.reload.payments.count).to eq 0 + end + end end describe '#expire_current_order' do