# frozen_string_literal: true class User < ApplicationRecord has_secure_password has_many :candidates, foreign_key: :recruiter_id has_many :reviewer_to_quizzes has_many :quizzes, through: :reviewer_to_quizzes has_many :votes, class_name: 'ReviewerVote' has_many :quiz_comments has_many :reviewees, through: :quizzes, source: :candidates validates :email, presence: true, uniqueness: true validates :name, presence: true validates :role, presence: true validates :reset_token, uniqueness: true, allow_nil: true def setup_reset gen_reset_token save end def commented_on? test_hash quiz_comments.where(test_hash: test_hash).count.positive? end # Voting # TODO: Refactor this out of User, belongs on ReviewerVote # ie: cast_yea(candidate, user) def cast_yea_on candidate vote = votes.find_by(candidate_id: candidate.to_i) vote.vote = :yea vote.save end def cast_nay_on candidate vote = votes.find_by(candidate_id: candidate.to_i) vote.vote = :nay vote.save end def review_candidate candidate, parms_hash candidate = Candidate.find(candidate.to_i) vote = votes.find_by(candidate_id: candidate.to_i) vote.veto = parms_hash[:review_status] if vote.save # skipping validations on candidate because that's not the managers responsibility candidate.review_comments = parms_hash[:review_comments] candidate.update_attribute(:review_status, parms_hash[:review_status]) end end def my_vote candidate candidate = Candidate.find(candidate.to_i) my_vote = votes.find_by(candidate_id: candidate.id) my_vote.vote unless my_vote.nil? end # Roles def admin? 'admin' == role end def acts_as_admin? 'admin' == role end def manager? 'manager' == role end def acts_as_manager? %w(admin manager).include? role end def recruiter? 'recruiter' == role end def acts_as_recruiter? %w(admin recruiter).include? role end def reviewer? 'reviewer' == role end def acts_as_reviewer? %w(admin manager reviewer).include? role end private def gen_reset_token loop do self[:reset_token] = SecureRandom.urlsafe_base64(10) self[:reset_timestamp] = DateTime.current break unless User.exists?(reset_token: self[:reset_token]) end end end