ingang/app/controllers/votes_controller.rb

82 lines
2.2 KiB
Ruby

class VotesController < ApplicationController
http_basic_authenticate_with name: Rails.application.config.admin_name,
password: Rails.application.config.admin_password
before_action :set_room, only: [:index, :bulk, :destroy_for_room]
before_action :set_votes, only: [:index, :bulk, :destroy_for_room]
# GET /rooms/:room_id/votes
# GET /rooms/:room_id/votes.json
def index
respond_to do |format|
format.html { render :index }
# let's protect voter credentials
format.json { render json: [], status: :unauthorized }
end
end
# GET /rooms/:room_id/votes/bulk
def bulk
@sample = "info@bij1.org,mijn-stemming,1,abcdABCD1234"
end
# POST /rooms/:room_id/votes/bulk
# POST /rooms/:room_id/votes/bulk.json
def create_bulk
room_id = params[:room_id]
votes_csv = params[:votes_csv]
require 'csv'
headers = %i[
voter_email
short_name
voter_login_id
voter_password
]
votes = CSV.parse(votes_csv, headers: headers).map { |row|
csv_fields = row.to_hash
email = csv_fields[:voter_email]
user = User.find_by(room_id: room_id, email: email)
{
:room_id => room_id,
:user_id => user.id,
:election_slug => csv_fields[:short_name],
:voter_login_id => csv_fields[:voter_login_id],
:voter_password => csv_fields[:voter_password],
}
}
Vote.upsert_all(votes, unique_by: [:user_id, :election_slug])
respond_to do |format|
format.html { redirect_to room_users_url(room_id), notice: 'Votes were successfully created.' }
format.json { render :show, status: :created, location: @room }
end
end
# DELETE /rooms/:room_id/votes
# DELETE /rooms/:room_id/votes.json
def destroy_for_room
@votes.each do |vote|
vote.destroy
end
respond_to do |format|
format.html { redirect_to room_users_url(@room.id), notice: 'Votes were successfully destroyed.' }
format.json { render :show, status: :created, location: @room }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_room
@room = Room.find(params[:room_id])
end
def set_votes
@votes = Vote.where(room_id: @room.id)
end
end