2015-09-08 11:44:40 +02:00
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: users
|
|
|
|
#
|
|
|
|
# id :integer not null, primary key
|
|
|
|
# name :string
|
|
|
|
# balance :integer default(0), not null
|
|
|
|
# penning :boolean default(FALSE), not null
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
|
|
|
#
|
|
|
|
|
2015-09-08 11:30:11 +02:00
|
|
|
class User < ActiveRecord::Base
|
2015-09-11 14:51:35 +02:00
|
|
|
include FriendlyId
|
|
|
|
friendly_id :name, use: :finders
|
2018-03-21 19:40:03 +01:00
|
|
|
devise :timeoutable, :omniauthable, :omniauth_providers => [:zeuswpi]
|
2015-09-08 12:11:48 +02:00
|
|
|
has_many :incoming_transactions,
|
|
|
|
class_name: 'Transaction', foreign_key: 'creditor_id'
|
|
|
|
has_many :outgoing_transactions,
|
|
|
|
class_name: 'Transaction', foreign_key: 'debtor_id'
|
2017-01-09 15:46:43 +01:00
|
|
|
has_many :incoming_requests,
|
|
|
|
class_name: 'Request', foreign_key: 'debtor_id'
|
|
|
|
has_many :outgoing_requests,
|
2017-01-14 23:12:45 +01:00
|
|
|
class_name: 'Request', foreign_key: 'creditor_id'
|
2017-01-09 16:22:58 +01:00
|
|
|
has_many :notifications
|
2019-05-08 21:46:17 +02:00
|
|
|
has_many :android_device_registration_tokens, class_name: 'AndroidDeviceRegistrationToken', foreign_key: 'user_id'
|
2015-09-08 12:45:11 +02:00
|
|
|
|
2015-09-09 12:49:24 +02:00
|
|
|
has_many :issued_transactions, as: :issuer, class_name: 'Transaction'
|
|
|
|
|
2015-09-08 15:51:23 +02:00
|
|
|
validates :name, presence: true, uniqueness: true
|
|
|
|
|
2018-03-21 19:40:03 +01:00
|
|
|
scope :humans, -> { where.not(id: self.zeus) }
|
2015-09-14 17:21:53 +02:00
|
|
|
|
2015-09-08 12:45:11 +02:00
|
|
|
def transactions
|
|
|
|
Transaction.where("creditor_id = ? OR debtor_id = ?", id, id)
|
|
|
|
end
|
2015-09-08 13:34:29 +02:00
|
|
|
|
2015-09-08 13:09:34 +02:00
|
|
|
def calculate_balance!
|
|
|
|
balance = incoming_transactions.sum(:amount) -
|
|
|
|
outgoing_transactions.sum(:amount)
|
|
|
|
self.update_attribute :balance, balance
|
|
|
|
end
|
2015-09-08 13:36:16 +02:00
|
|
|
|
2018-03-21 19:40:03 +01:00
|
|
|
def self.from_omniauth(auth)
|
|
|
|
where(name: auth.uid).first_or_create do |user|
|
|
|
|
user.name = auth.uid
|
|
|
|
end
|
2015-09-08 13:34:29 +02:00
|
|
|
end
|
2015-09-08 21:38:29 +02:00
|
|
|
|
2018-03-21 19:40:03 +01:00
|
|
|
def self.zeus
|
|
|
|
@@zeus ||= find_or_create_by name: 'Zeus'
|
2015-09-08 21:38:29 +02:00
|
|
|
end
|
2018-03-21 19:40:03 +01:00
|
|
|
|
2018-06-20 18:51:17 +02:00
|
|
|
def generate_key
|
2018-06-20 19:28:01 +02:00
|
|
|
set_key unless self.key
|
|
|
|
end
|
|
|
|
|
|
|
|
def generate_key!
|
|
|
|
set_key
|
|
|
|
self.save
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
def set_key
|
|
|
|
self.key = SecureRandom.base64(16)
|
2018-06-20 18:51:17 +02:00
|
|
|
end
|
2015-09-08 11:30:11 +02:00
|
|
|
end
|