2015-09-08 11:44:40 +02:00
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: transactions
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# debtor_id :integer not null
|
|
|
|
# creditor_id :integer not null
|
2015-09-09 12:50:39 +02:00
|
|
|
# issuer_id :integer not null
|
|
|
|
# issuer_type :string not null
|
2015-09-08 11:44:40 +02:00
|
|
|
# amount :integer default(0), not null
|
|
|
|
# message :string
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
|
|
|
#
|
|
|
|
|
2015-09-08 11:30:11 +02:00
|
|
|
class Transaction < ActiveRecord::Base
|
2015-09-08 12:11:48 +02:00
|
|
|
belongs_to :debtor, class_name: 'User'
|
|
|
|
belongs_to :creditor, class_name: 'User'
|
2015-09-09 12:49:24 +02:00
|
|
|
belongs_to :issuer, polymorphic: true
|
2015-09-08 12:11:48 +02:00
|
|
|
|
2015-09-08 13:09:34 +02:00
|
|
|
after_save :recalculate_balances
|
|
|
|
after_destroy :recalculate_balances
|
|
|
|
|
2015-09-08 15:51:23 +02:00
|
|
|
validates :amount, numericality: { greater_than: 0 }
|
|
|
|
validate :different_debtor_creditor
|
|
|
|
|
2015-09-09 14:46:06 +02:00
|
|
|
def peer_of(user)
|
|
|
|
return creditor if user == debtor
|
|
|
|
return debtor if user == creditor
|
|
|
|
end
|
|
|
|
|
|
|
|
def signed_amount_for(user)
|
|
|
|
return -amount if user == debtor
|
|
|
|
return amount if user == creditor
|
|
|
|
end
|
|
|
|
|
2015-09-08 13:09:34 +02:00
|
|
|
private
|
2015-09-08 15:51:23 +02:00
|
|
|
|
2015-09-08 13:09:34 +02:00
|
|
|
def recalculate_balances
|
|
|
|
creditor.calculate_balance!
|
|
|
|
debtor.calculate_balance!
|
|
|
|
end
|
2015-09-08 15:51:23 +02:00
|
|
|
|
|
|
|
def different_debtor_creditor
|
2015-09-09 12:49:24 +02:00
|
|
|
if self.debtor == self.creditor
|
|
|
|
self.errors.add :base, "Can't write money to yourself"
|
|
|
|
end
|
2015-09-08 15:51:23 +02:00
|
|
|
end
|
2015-09-08 11:30:11 +02:00
|
|
|
end
|