Current sync

This commit is contained in:
Senad Uka
2020-05-18 11:35:34 +02:00
parent 41b5ebb5d7
commit fb0a6c7dfd
11 changed files with 170 additions and 90 deletions

View File

@@ -4,7 +4,7 @@ class MoneyMovesController < ApplicationController
end
def create
money_move = MoneyMove.new(money_move_params)
money_move = MoneyMove.create_move(money_move_params)
if money_move.save
json_response(money_move)
else

View File

@@ -1,14 +1,12 @@
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
has_many :money_moves
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)
totals = Homie.all.joins(:money_moves).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)
total = totals.fetch(homie.id, 0)
{ homie: homie, amount: total }
end
end

View File

@@ -1,4 +1,25 @@
class MoneyMove < ApplicationRecord
belongs_to :from_homie, class_name: 'Homie'
belongs_to :to_homie, class_name: 'Homie'
belongs_to :homie
def create_move(params)
common_params = { description: params[:description] }
move_from = MoneyMove.new(
common_params + {
homie_id: params[:from_homie_id],
amount: -BigDecimal.new(params[:amount])
}
)
move_to = MoneyMove.new(
common_params + {
homie_id: params[:from_homie_id],
amount: BigDecimal.new(params[:amount])
}
)
MoneyMove.transaction do
move_from.save!
move_to.save!
end
end
end