From 0ecfee79d455a800a8a0b2a7a99222244dfb1dc5 Mon Sep 17 00:00:00 2001 From: Rohan Mitchell Date: Fri, 11 Jul 2014 12:33:25 +1000 Subject: [PATCH] Add Spree::Variant.in_distributor --- app/models/spree/variant_decorator.rb | 9 +++++++++ spec/models/spree/variant_spec.rb | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/app/models/spree/variant_decorator.rb b/app/models/spree/variant_decorator.rb index 12593215ba..69da9d5740 100644 --- a/app/models/spree/variant_decorator.rb +++ b/app/models/spree/variant_decorator.rb @@ -18,8 +18,17 @@ Spree::Variant.class_eval do before_validation :update_weight_from_unit_value after_save :update_units + scope :with_order_cycles_outer, joins('LEFT OUTER JOIN exchange_variants AS o_exchange_variants ON (o_exchange_variants.variant_id = spree_variants.id)'). + joins('LEFT OUTER JOIN exchanges AS o_exchanges ON (o_exchanges.id = o_exchange_variants.exchange_id)'). + joins('LEFT OUTER JOIN order_cycles AS o_order_cycles ON (o_order_cycles.id = o_exchanges.order_cycle_id)') + scope :not_deleted, where(deleted_at: nil) scope :in_stock, where('spree_variants.count_on_hand > 0 OR spree_variants.on_demand=?', true) + scope :in_distributor, lambda { |distributor| + with_order_cycles_outer. + where('o_exchanges.incoming = ? AND o_exchanges.receiver_id = ?', false, distributor). + select('DISTINCT spree_variants.*') + } def price_with_fees(distributor, order_cycle) diff --git a/spec/models/spree/variant_spec.rb b/spec/models/spree/variant_spec.rb index 0abf9ea431..e01c637616 100644 --- a/spec/models/spree/variant_spec.rb +++ b/spec/models/spree/variant_spec.rb @@ -28,6 +28,24 @@ module Spree Variant.where(is_master: false).in_stock.sort.should == [@v_in_stock, @v_on_demand].sort end end + + describe "finding variants in a distributor" do + let!(:d1) { create(:distributor_enterprise) } + let!(:d2) { create(:distributor_enterprise) } + let!(:p1) { create(:simple_product) } + let!(:p2) { create(:simple_product) } + let!(:oc1) { create(:simple_order_cycle, distributors: [d1], variants: [p1.master]) } + let!(:oc2) { create(:simple_order_cycle, distributors: [d2], variants: [p2.master]) } + + it "shows variants in an order cycle distribution" do + Variant.in_distributor(d1).should == [p1.master] + end + + it "doesn't show duplicates" do + oc_dup = create(:simple_order_cycle, distributors: [d1], variants: [p1.master]) + Variant.in_distributor(d1).should == [p1.master] + end + end end describe "calculating the price with enterprise fees" do