diff --git a/app/controllers/homies_controller.rb b/app/controllers/homies_controller.rb index 18e71f4..51f1b35 100644 --- a/app/controllers/homies_controller.rb +++ b/app/controllers/homies_controller.rb @@ -11,7 +11,12 @@ class HomiesController < ApplicationController error_response(:bad_request) end end + + def cash + json_response(Homie.cash(params[:importance])) + end + private def homie_params params.require(:homie).permit( :name, @@ -19,4 +24,5 @@ class HomiesController < ApplicationController :about ) end + end diff --git a/app/models/homie.rb b/app/models/homie.rb index 867a8b2..81e6bfa 100644 --- a/app/models/homie.rb +++ b/app/models/homie.rb @@ -1,4 +1,15 @@ class Homie < ApplicationRecord has_many :money_moves_from, class_name: 'MoneyMove', foreign_key: :from_homie_id has_many :money_moves_to, class_name: 'MoneyMove', foreign_key: :to_homie_id + + def self.cash(importance) + got = Homie.all.joins(:money_moves_to).group(:id).order(:id).sum(:amount) + owe = Homie.all.joins(:money_moves_from).group(:id).order(:id).sum(:amount) + + result = [] + Homie.where(["importance > ?", importance]).map do |homie| + total = got.fetch(homie.id, 0) - owe.fetch(homie.id,0) + { homie: homie, amount: total } + end + end end diff --git a/config/routes.rb b/config/routes.rb index f4c6135..89da8c0 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,7 +1,12 @@ Rails.application.routes.draw do constraints format: :json do - resources :money_moves - resources :homies + resources :money_moves + resources :homies do + collection do + get 'cash' + end + end + end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end