skill-assessment-app/app/models/reviewer_vote.rb

55 lines
1.8 KiB
Ruby
Raw Permalink Normal View History

2016-11-17 22:43:19 -06:00
# frozen_string_literal: true
class ReviewerVote < ApplicationRecord
belongs_to :candidate
belongs_to :user
2016-11-18 17:43:24 -06:00
validates :user_id, uniqueness: { scope: :candidate_id }
2017-02-09 16:26:33 -06:00
after_save :notify_manager
2016-11-17 22:43:19 -06:00
enum vote: {
undecided: 0,
yea: 1,
nay: 2
}
enum veto: {
approved: 1,
declined: 2
2016-11-17 22:43:19 -06:00
}
2017-02-09 16:26:33 -06:00
private
def notify_manager
ReviewerMailer.notify_manager(candidate_id).deliver_now if all_reviewers_voted?
end
def all_reviewers_voted? # rubocop:disable Metrics/MethodLength
sql = " select distinct rev.candidate_id
, full_votes.voters, full_votes.vote_count
, c.test_hash
from reviewer_votes rev
inner join users u on u.id = rev.user_id
inner join candidates c on c.id = rev.candidate_id
left join (
select candidate_id
from reviewer_votes
where veto > 0 or veto is null
) as vetos on vetos.candidate_id = rev.candidate_id
left join (
select candidate_id
, count(vote) voters
, sum(case when vote != 0 then 1 else 0 end) vote_count
from reviewer_votes
left join users on users.id = reviewer_votes.user_id
where users.role != 'manager'
group by candidate_id
) as full_votes on full_votes.candidate_id = rev.candidate_id
where vetos.candidate_id is null
and full_votes.voters = full_votes.vote_count
and rev.candidate_id = #{candidate_id};"
result = ActiveRecord::Base.connection.exec_query(sql)
result.count == 1
end # rubocop:enable Metrics/MethodLength
2016-11-17 22:43:19 -06:00
end