diff --git a/app/models/spree/user_decorator.rb b/app/models/spree/user_decorator.rb index 9684e86371..17473fd521 100644 --- a/app/models/spree/user_decorator.rb +++ b/app/models/spree/user_decorator.rb @@ -51,24 +51,22 @@ Spree.user_class.class_eval do # Returns Enterprise IDs for distributors that the user has shopped at def enterprises_ordered_from - self.orders.where(state: :complete).map(&:distributor_id).uniq + orders.where(state: :complete).map(&:distributor_id).uniq end # Returns orders and their associated payments for all distributors that have been ordered from - def get_orders_by_distributor - Enterprise.includes(distributed_orders: { payments: :payment_method }) - .where(enterprises: { id: self.enterprises_ordered_from }, - spree_orders: { state: 'complete', user_id: self.id }) - .order('spree_orders.completed_at DESC') + def compelete_orders_by_distributor + Enterprise + .includes(distributed_orders: { payments: :payment_method }) + .where(enterprises: { id: enterprises_ordered_from }, + spree_orders: { state: 'complete', user_id: id }) + .order('spree_orders.completed_at DESC') end def orders_by_distributor # Remove uncompleted payments as these will not be reflected in order balance - data_array = self.get_orders_by_distributor.to_a.each do |enterprise| - enterprise.distributed_orders.each do |order| - order.payments.keep_if { |payment| payment.state == "completed" } - end - end + data_array = compelete_orders_by_distributor.to_a + remove_uncompleted_payments(data_array) data_array.sort! { |a, b| b.distributed_orders.length <=> a.distributed_orders.length } end @@ -79,4 +77,12 @@ Spree.user_class.class_eval do errors.add(:owned_enterprises, "^#{email} is not permitted to own any more enterprises (limit is #{enterprise_limit}).") end end + + def remove_uncompleted_payments(enterprises) + enterprises.each do |enterprise| + enterprise.distributed_orders.each do |order| + order.payments.keep_if { |payment| payment.state == "completed" } + end + end + end end