2018-10-31 14:56:01 +01:00
|
|
|
module CreateAvisConcern
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def create_avis_from_params(dossier, confidentiel = false)
|
|
|
|
confidentiel ||= create_avis_params[:confidentiel]
|
2018-10-31 16:21:16 +01:00
|
|
|
|
|
|
|
# Because of a limitation of the email_field rails helper,
|
|
|
|
# the :emails parameter is a 1-element array.
|
|
|
|
# Hence the call to first
|
|
|
|
# https://github.com/rails/rails/issues/17225
|
|
|
|
emails = create_avis_params[:emails].first.split(',').map(&:strip)
|
2018-10-31 14:56:01 +01:00
|
|
|
|
2018-10-31 16:09:11 +01:00
|
|
|
create_results = Avis.create(
|
|
|
|
emails.map do |email|
|
|
|
|
{
|
|
|
|
email: email,
|
|
|
|
introduction: create_avis_params[:introduction],
|
|
|
|
claimant: current_gestionnaire,
|
|
|
|
dossier: dossier,
|
|
|
|
confidentiel: confidentiel
|
|
|
|
}
|
|
|
|
end
|
|
|
|
)
|
|
|
|
|
2018-10-31 20:38:32 +01:00
|
|
|
persisted, failed = create_results.partition(&:persisted?)
|
|
|
|
|
|
|
|
if persisted.any?
|
|
|
|
sent_emails_addresses = persisted.map(&:email_to_display).join(", ")
|
2018-10-31 16:09:11 +01:00
|
|
|
flash.notice = "Une demande d'avis a été envoyée à #{sent_emails_addresses}"
|
2018-10-31 20:38:32 +01:00
|
|
|
end
|
2018-10-31 14:56:01 +01:00
|
|
|
|
2018-10-31 20:38:32 +01:00
|
|
|
if failed.any?
|
|
|
|
flash.now.alert = failed
|
|
|
|
.select { |avis| avis.errors.present? }
|
|
|
|
.map { |avis| "#{avis.email} : #{avis.errors.full_messages.join(', ')}" }
|
2018-10-31 14:56:01 +01:00
|
|
|
|
|
|
|
# When an error occurs, return the avis back to the controller
|
|
|
|
# to give the user a chance to correct and resubmit
|
2018-10-31 20:38:32 +01:00
|
|
|
Avis.new(create_avis_params.merge(emails: [failed.map(&:email).join(", ")]))
|
|
|
|
else
|
|
|
|
nil
|
2018-10-31 14:56:01 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def create_avis_params
|
2018-10-31 16:21:16 +01:00
|
|
|
params.require(:avis).permit(:introduction, :confidentiel, emails: [])
|
2018-10-31 14:56:01 +01:00
|
|
|
end
|
|
|
|
end
|