diff --git a/app/helpers/shared_helper.rb b/app/helpers/shared_helper.rb index 8ddad2524f..48e38fcfb4 100644 --- a/app/helpers/shared_helper.rb +++ b/app/helpers/shared_helper.rb @@ -11,7 +11,7 @@ module SharedHelper # all suppliers of current distributor's products def current_producers - Exchange.where(receiver_id: current_distributor.id).map{ |ex| ex.variants.map {|v| v.product.supplier }}.flatten.uniq + variants = current_order_cycle.variants_distributed_by(current_distributor) + Enterprise.supplying_variant_in(variants) end end - diff --git a/app/models/enterprise.rb b/app/models/enterprise.rb index 9d63cdd25a..ca31f5bc8c 100644 --- a/app/models/enterprise.rb +++ b/app/models/enterprise.rb @@ -32,6 +32,7 @@ class Enterprise < ActiveRecord::Base scope :by_name, order('name') scope :is_primary_producer, where(:is_primary_producer => true) scope :is_distributor, where(:is_distributor => true) + scope :supplying_variant_in, lambda { |variants| joins(:supplied_products => :variants_including_master).where('spree_variants.id IN (?)', variants).select('DISTINCT enterprises.*') } scope :with_supplied_active_products_on_hand, lambda { joins(:supplied_products) .where('spree_products.deleted_at IS NULL AND spree_products.available_on <= ? AND spree_products.count_on_hand > 0', Time.now) diff --git a/spec/models/enterprise_spec.rb b/spec/models/enterprise_spec.rb index 8f562b947b..5288101752 100644 --- a/spec/models/enterprise_spec.rb +++ b/spec/models/enterprise_spec.rb @@ -159,6 +159,40 @@ describe Enterprise do end end + describe "supplying_variant_in" do + it "finds producers by supply of master variant" do + s = create(:supplier_enterprise) + p = create(:simple_product, supplier: s) + + Enterprise.supplying_variant_in([p.master]).should == [s] + end + + it "finds producers by supply of variant" do + s = create(:supplier_enterprise) + p = create(:simple_product, supplier: s) + v = create(:variant, product: p) + + Enterprise.supplying_variant_in([v]).should == [s] + end + + it "returns multiple enterprises when given multiple variants" do + s1 = create(:supplier_enterprise) + s2 = create(:supplier_enterprise) + p1 = create(:simple_product, supplier: s1) + p2 = create(:simple_product, supplier: s2) + + Enterprise.supplying_variant_in([p1.master, p2.master]).sort.should == [s1, s2].sort + end + + it "does not return duplicates" do + s = create(:supplier_enterprise) + p1 = create(:simple_product, supplier: s) + p2 = create(:simple_product, supplier: s) + + Enterprise.supplying_variant_in([p1.master, p2.master]).should == [s] + end + end + describe "distributing_product" do it "returns enterprises distributing via a product distribution" do d = create(:distributor_enterprise)