1class Admin::GovernmentResponseController < Admin::AdminController
 
2  before_action :fetch_petition
 
3  before_action :fetch_government_response
 
4
 
5  rescue_from ActiveRecord::RecordNotUnique do
 
6    @government_response = @petition.government_response(true) and update
 
7  end
 
8
 
 9  def show
 
10    render 'admin/petitions/show'
 
11  end
 
 
13  def update
 
14    if @government_response.update(government_response_params)
 
15      if send_email_to_petitioners?
 
16        EmailThresholdResponseJob.run_later_tonight(petition: @petition)
 
17        message = :email_sent_overnight
 
18      else
 
19        message = :government_response_updated
 
20      end
 
 
22      redirect_to [:admin, @petition], notice: message
 
23    else
 
24      render 'admin/petitions/show'
 
25    end
 
26  end
 
 
28  private
 
 
30  def fetch_petition
 
31    @petition = Petition.moderated.find(params[:petition_id])
 
32  end
 
 
34  def fetch_government_response
 
35    @government_response = @petition.government_response || @petition.build_government_response
 
36  end
 
 
38  def government_response_params
 
39    params.require(:government_response).permit(:responded_on, :summary, :details)
 
40  end
 
 
42  def send_email_to_petitioners?
 
43    params.key?(:save_and_email)
 
44  end
 
45end