From fc5795173e62f0eb3f5f6c9851ac36c1f2c9fa38 Mon Sep 17 00:00:00 2001 From: Rohan Mitchell Date: Sun, 24 Jun 2012 12:56:47 +1000 Subject: [PATCH] Do not add the product to cart if the user specifies a distributor that the product is not available at --- .../spree/orders_controller_decorator.rb | 23 ++++++++++++++++--- spec/controllers/orders_controller_spec.rb | 12 +++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/app/controllers/spree/orders_controller_decorator.rb b/app/controllers/spree/orders_controller_decorator.rb index bb2d2be1aa..d9cdc8bebe 100644 --- a/app/controllers/spree/orders_controller_decorator.rb +++ b/app/controllers/spree/orders_controller_decorator.rb @@ -3,9 +3,26 @@ Spree::OrdersController.class_eval do def populate_order_distributor @distributor = Spree::Distributor.find params[:distributor_id] - if @distributor.nil? - return false - end + redirect_to cart_path unless populate_valid? @distributor + end + + private + def populate_valid? distributor + # -- Distributor must be specified + return false if distributor.nil? + + # -- All products must be available under that distributor + params[:products].each do |product_id, variant_id| + product = Spree::Product.find product_id + return false unless product.distributors.include? distributor + end if params[:products] + + params[:variants].each do |variant_id, quantity| + variant = Spree::Variant.find variant_id + return false unless variant.product.distributors.include? distributor + end if params[:variants] + + true end end diff --git a/spec/controllers/orders_controller_spec.rb b/spec/controllers/orders_controller_spec.rb index b78ab3b034..9d500062a4 100644 --- a/spec/controllers/orders_controller_spec.rb +++ b/spec/controllers/orders_controller_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' describe Spree::OrdersController do context "adding the first product to the cart" do - it "does nothing if the user does not specify a distributor" do + it "does not add the product if the user does not specify a distributor" do create(:distributor) p = create(:product) @@ -10,5 +10,15 @@ describe Spree::OrdersController do spree_put :populate, :variants => {p.id => 1} end.to change(Spree::LineItem, :count).by(0) end + + it "does not add the product if the user specifies a distributor that the product is not available at" do + distributor_product = create(:distributor) + distributor_no_product = create(:distributor) + p = create(:product, :distributors => [distributor_product]) + + expect do + spree_put :populate, :variants => {p.id => 1}, :distributor_id => distributor_no_product.id + end.to change(Spree::LineItem, :count).by(0) + end end end