diff --git a/app/models/enterprise.rb b/app/models/enterprise.rb index 17c9380097..af56a6c638 100644 --- a/app/models/enterprise.rb +++ b/app/models/enterprise.rb @@ -19,6 +19,15 @@ class Enterprise < ActiveRecord::Base scope :is_distributor, where(:is_distributor => true) scope :with_distributed_active_products_on_hand, lambda { joins(:distributed_products).where('spree_products.deleted_at IS NULL AND spree_products.available_on <= ? AND spree_products.count_on_hand > 0', Time.now).select('distinct(enterprises.*)') } + scope :active_distributors_for_product_distributions, is_distributor.with_distributed_active_products_on_hand.by_name + scope :active_distributors_for_order_cycles, + joins('LEFT INNER JOIN exchanges ON (exchanges.receiver_id = enterprises.id)'). + joins('LEFT INNER JOIN order_cycles ON (order_cycles.id = exchanges.order_cycle.id)'). + merge(OrderCycle.active). + select('DISTINCT enterprises.*') + + scope :active_distributors, joins(:distributed_products) + def has_supplied_products_on_hand? self.supplied_products.where('count_on_hand > 0').present? diff --git a/spec/models/enterprises_spec.rb b/spec/models/enterprises_spec.rb index 051533144e..18eedec60a 100644 --- a/spec/models/enterprises_spec.rb +++ b/spec/models/enterprises_spec.rb @@ -18,6 +18,21 @@ describe Enterprise do end describe "scopes" do + describe "active_distributors" do + it "finds active distributors by product distributions" do + d = create(:distributor_enterprise) + create(:product, :distributors => [d]) + Enterprise.active_distributors.should == [d] + end + + it "finds active distributors by order cycles" + it "doesn't show distributors of deleted products" + it "doesn't show distributors of unavailable products" + it "doesn't show distributors of out of stock products" + it "doesn't show distributors from inactive order cycles" + end + + it "returns distributors with products in stock" do d1 = create(:distributor_enterprise) d2 = create(:distributor_enterprise)