Skip to content

Commit

Permalink
apply Amines review 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Holist committed Oct 2, 2024
1 parent 089355e commit 3dbe8d1
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 46 deletions.
4 changes: 2 additions & 2 deletions app/controllers/invitations_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ def create # rubocop:disable Metrics/AbcSize
format.json do
render json: {
success: false,
payload: turbo_stream.replace("remote_modal", partial: "invitation_error_modal",
locals: { errors: invite_user.errors })
turbo_stream_html: turbo_stream.replace("remote_modal", partial: "common/custom_errors_modal",
locals: { errors: invite_user.errors })
}, status: :unprocessable_entity
end
end
Expand Down
2 changes: 1 addition & 1 deletion app/javascript/react/lib/handleUserInvitation.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const handleUserInvitation = async (
motifCategoryId
);
if (!result.success && options.raiseError) {
window.Turbo.renderStreamMessage(result.payload);
window.Turbo.renderStreamMessage(result.turbo_stream_html);
}
return result;
};
Expand Down
16 changes: 13 additions & 3 deletions app/services/base_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ def format_error(result, exception)
errors = result.errors
raise UnexpectedResultBehaviourError unless errors.is_a? Array

# we add the exception message only if it is a custom message
errors << exception.message if exception.message != exception.class.to_s
errors << ServiceError.new(exception.message) if exception.message != exception.class.to_s
result.errors = errors
result[:success?] = false
result[:failure?] = true
Expand All @@ -52,6 +51,14 @@ def call

private

def add_error(message)
result.errors << ServiceError.new(message)
end

def add_custom_error(message, type:, attributes: {})
result.errors << CustomServiceError.new(message, type: type, attributes: attributes)
end

def call_service!(service_class, **)
service_result = service_class.call(**)
return service_result if service_result.success?
Expand All @@ -63,11 +70,14 @@ def call_service!(service_class, **)
def save_record!(record)
return if record.save

result.errors << record.errors.full_messages.to_sentence
record.errors.full_messages.each do |message|
result.errors << ServiceError.new(message)
end
fail!
end

def fail!(error_message = nil)
result.errors << ServiceError.new(error_message) if error_message.present?
raise FailedServiceError, error_message
end
end
13 changes: 13 additions & 0 deletions app/services/custom_service_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class CustomServiceError < ServiceError
attr_reader :type, :attributes

def initialize(message, type:, attributes: {})
super(message)
@type = type
@attributes = attributes
end

def to_partial_path
"common/custom_errors/#{@type}"
end
end
5 changes: 2 additions & 3 deletions app/services/invitations/save_and_send.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ def send_invitation
def verify_creneaux_are_available
return if retrieve_creneau_availability.creneau_availability

result.errors << {
error_type: "no_creneau_available"
}
add_custom_error("Il n'y a plus de créneaux disponibles pour inviter cet usager",
type: "no_creneau_available")
fail!
end

Expand Down
45 changes: 15 additions & 30 deletions app/services/invitations/validate.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def validate_invitation_not_already_sent_today
return if invitation.format_postal?
return unless invitation_already_sent_today?

add_error(message: "Une invitation #{invitation.format} a déjà été envoyée aujourd'hui à cet usager")
add_error("Une invitation #{invitation.format} a déjà été envoyée aujourd'hui à cet usager")
end

def invitation_already_sent_today?
Expand All @@ -45,25 +45,25 @@ def invitation_already_sent_today?
def validate_user_title_presence
return if user.title?

add_error(message: "La civilité de la personne doit être précisée pour pouvoir envoyer une invitation")
add_error("La civilité de la personne doit être précisée pour pouvoir envoyer une invitation")
end

def validate_organisations_are_not_from_different_departments
return if organisations.map(&:department_id).uniq == [department_id]

add_error(message: "Les organisations ne peuvent pas être liés à des départements différents de l'invitation")
add_error("Les organisations ne peuvent pas être liés à des départements différents de l'invitation")
end

def validate_no_rdv_pending_taken_today
return if follow_up.participations.none?(&:pending?)

add_error(message: "Cet usager a déjà un rendez-vous à venir pour ce motif")
add_error("Cet usager a déjà un rendez-vous à venir pour ce motif")
end

def validate_it_expires_in_more_than_5_days
return if expires_at > 5.days.from_now

add_error(message: "La durée de validité de l'invitation pour un courrier doit être supérieure à 5 jours")
add_error("La durée de validité de l'invitation pour un courrier doit être supérieure à 5 jours")
end

def validate_user_belongs_to_an_org_linked_to_motif_category
Expand All @@ -78,27 +78,26 @@ def validate_user_belongs_to_an_org_linked_to_motif_category
def validate_motif_of_this_category_is_defined_in_organisations
return if organisations_motifs.map(&:motif_category).include?(motif_category)

add_error(message: "Aucun motif de la catégorie #{motif_category_name} n'est défini sur RDV-Solidarités")
add_error("Aucun motif de la catégorie #{motif_category_name} n'est défini sur RDV-Solidarités")
end

def validate_referents_are_assigned
return if user.referent_ids.any?

add_error(message: "Un référent doit être assigné au bénéficiaire pour les rdvs avec référents")
add_error("Un référent doit être assigné au bénéficiaire pour les rdvs avec référents")
end

def validate_follow_up_motifs_are_defined
return if organisations_motifs.any? do |motif|
motif.follow_up? && motif.motif_category == motif_category
end

add_error(
error_type: "no_follow_up_category",
attributes: {
organisation_id: organisations.first.id,
motif_category_name: motif_category_name
}
)
add_custom_error("Aucun motif de suivi n'a été défini pour la catégorie #{motif_category_name}",
type: "no_follow_up_category",
attributes: {
organisation_id: organisations.first.id,
motif_category_name: motif_category_name
})
end

def organisations_motifs
Expand All @@ -113,24 +112,10 @@ def validate_help_phone_number_presence

organisation_names = organisations_without_phone_number.map(&:name).to_sentence(last_word_connector: " et ")
if organisations_without_phone_number.size > 1
add_error(message: "Les téléphones de contact des organisations (#{organisation_names}) doivent être indiqués.")
add_error("Les téléphones de contact des organisations (#{organisation_names}) doivent être indiqués.")
elsif organisations_without_phone_number.size == 1
add_error(message: "Le téléphone de contact de l'organisation #{organisation_names} doit être indiqué.")
end
end

def add_error(error_type: "generic", message: nil, attributes: {})
# Attributes are used to build the error message in the view
# Error type is used to determine which custom message will be displayed in the view
if error_type == "generic" && message.blank?
raise ArgumentError, "Le message est requis pour les erreurs génériques"
add_error("Le téléphone de contact de l'organisation #{organisation_names} doit être indiqué.")
end

result.errors << {
error_type: error_type,
message: message,
attributes: attributes
}
end
end
end
11 changes: 11 additions & 0 deletions app/services/service_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class ServiceError
attr_reader :message

def initialize(message)
@message = message
end

def to_s
message
end
end
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
<%= render "common/remote_modal" do %>
<div>
<div class="text-center mb-3">
<%= image_tag "illustrations/error-line.svg", alt: "Illustration d'un message d'avertissement", class: "mb-3" %>
<%= image_tag "illustrations/error-line.svg", alt: "Illustration d'un message d'erreur", class: "mb-3" %>
</div>
<h4 class="text-center"><b>Impossible d'inviter l'usager</b></h4>
<div class="p-3">
<% errors.each_with_index do |error, index| %>
<% if error[:error_type] != "generic" %>
<%= render "invitations/custom_errors/#{error[:error_type]}", error: error %>
<% if error.is_a?(CustomServiceError) %>
<%= render error, locals: error.attributes %>
<% else %>
<p><%= error[:message] %></p>
<p><%= error.to_s %></p>
<% end %>
<% if index < errors.size - 1 %>
<hr class="mx-auto w-50">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<p>
La catégorie <%= error[:attributes][:motif_category_name] %> a été configurée en « RDV de suivi (avec référent) » sur rdv-insertion.
La catégorie <%= locals[:motif_category_name] %> a été configurée en « RDV de suivi (avec référent) » sur rdv-insertion.
</p>
<p>
Pour inviter des usagers à ces rendez-vous, créez un motif de suivi dans les <%= link_to("paramètres de votre organisation sur RDV-Solidarités",
"https://www.rdv-solidarites.fr/admin/organisations/#{error[:attributes][:organisation_id]}/motifs",
"https://www.rdv-solidarites.fr/admin/organisations/#{locals[:organisation_id]}/motifs",
target: "_blank", class: "text-decoration-underline") %>.
</p>
<p>
Expand Down
7 changes: 6 additions & 1 deletion spec/controllers/invitations_controller_spec.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
describe InvitationsController do
# TOCHECK
describe "#create" do
let!(:user_id) { "24213123" }
let!(:organisation_id) { "22232" }
Expand Down Expand Up @@ -158,6 +157,12 @@
expect(response).not_to be_successful
expect(response.parsed_body["success"]).to eq(false)
end

it "renders the errors" do
post :create, params: create_params
expect(response).not_to be_successful
expect(response.parsed_body["turbo_stream_html"]).to include('action="replace"')
end
end
end

Expand Down

0 comments on commit 3dbe8d1

Please sign in to comment.