volunteers_controller.rb 2.22 KB
Newer Older
1
class VolunteersController < ApplicationController
2
  include AvailabilityAttributes
3
  include NestedAttributes
4
  include ContactAttributes
5
  include VolunteerAttributes
6

7
  before_action :set_volunteer, only: [:show, :edit, :update, :destroy]
8
9

  def index
10
    authorize Volunteer
Kaspar Vollenweider's avatar
Kaspar Vollenweider committed
11
    @q = policy_scope(Volunteer).ransack(params[:q])
12
    respond_to do |format|
Kaspar Vollenweider's avatar
Kaspar Vollenweider committed
13
      format.xlsx do
14
        @volunteers = @q.result
Kaspar Vollenweider's avatar
Kaspar Vollenweider committed
15
16
      end
      format.html do
17
18
19
        @volunteers = @q.result.paginate(page: params[:page])
      end
    end
20
21
  end

22
  def show; end
23
24
25

  def new
    @volunteer = Volunteer.new
Chrysanthi Lagodimou's avatar
Chrysanthi Lagodimou committed
26
    authorize @volunteer
27
28
  end

29
  def edit; end
30
31
32

  def create
    @volunteer = Volunteer.new(volunteer_params)
33
    @volunteer.registrar = current_user
34
    authorize @volunteer
35
    if @volunteer.save
36
      redirect_to @volunteer, notice: t('volunteer_created')
37
38
    else
      render :new
39
40
41
42
    end
  end

  def update
43
44
45
46
    @volunteer.attributes = volunteer_params
    return render :edit unless @volunteer.valid?
    if handle_volunteer_update
      redirect_to volunteers_path, notice: t('invite_sent', email: @volunteer.primary_email)
47
    else
48
      redirect_to @volunteer, notice: t('volunteer_updated')
49
    end
50
51
52
53
  end

  def destroy
    @volunteer.destroy
54
    redirect_to volunteers_url, notice: t('volunteer_destroyed')
55
56
  end

57
  def seeking_clients
58
    authorize Volunteer
59
    @q = policy_scope(Volunteer).seeking_clients.ransack(params[:q])
60
    @seeking_clients = @q.result.paginate(page: params[:page])
61
62
  end

63
64
  private

65
66
67
68
69
70
71
72
73
  def handle_volunteer_update
    if @volunteer.acceptance_change == ['undecided', 'accepted'] && @volunteer.user_id.blank?
      @volunteer.save && invite_volunteer_user
    else
      @volunteer.save!
      false
    end
  end

74
  def invite_volunteer_user
75
76
77
78
79
80
    return false if @volunteer.external
    new_user = User.new(
      email: @volunteer.contact.primary_email, password: Devise.friendly_token,
      role: 'volunteer', volunteer: @volunteer
    )
    new_user.save && new_user.invite!
81
82
  end

83
84
  def set_volunteer
    @volunteer = Volunteer.find(params[:id])
85
    authorize @volunteer
86
87
88
  end

  def volunteer_params
89
90
    params.require(:volunteer).permit(volunteer_attributes, :bank, :iban, :waive, :acceptance,
      :take_more_assignments, :external)
91
92
  end
end