Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactoring: améliore la gestion des erreurs des followups #4652

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 26 additions & 32 deletions backend/controllers/followups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import { SurveyType } from "../../lib/enums/survey.js"
import { FollowupFactory } from "../lib/followup-factory.js"
import { FetchSurvey } from "../../lib/types/survey.d.js"
import Request from "../types/express.d.js"
import { phoneNumberValidation } from "../../lib/phone-number.js"
import config from "../config/index.js"
import { sendSimulationResultsEmail } from "../lib/messaging/email/email-service.js"
import { sendSimulationResultsSms } from "../lib/messaging/sms/sms-service.js"
import { ErrorType, ErrorStatus, ErrorName } from "../../lib/enums/error.js"

export function followup(
req: Request,
Expand All @@ -39,23 +39,6 @@ export function followup(
})
}

async function sendFollowupNotifications(followup: Followup, res: Response) {
const { email, phone } = followup
if (phone) {
if (
phoneNumberValidation(phone, config.smsService.internationalDiallingCodes)
) {
await sendSimulationResultsSms(followup)
} else {
return res.status(422).send("Unsupported phone number format")
}
}
if (email) {
await sendSimulationResultsEmail(followup)
}
return res.send({ result: "OK" })
}

async function createSimulationRecapUrl(req: Request, res: Response) {
const followup = await FollowupFactory.create(req.simulation)
await followup.addSurveyIfMissing(
Expand All @@ -69,6 +52,7 @@ async function createSimulationRecapUrl(req: Request, res: Response) {
export async function persist(req: Request, res: Response) {
const { surveyOptin, email, phone } = req.body
const simulation = req.simulation

try {
if (email || phone) {
const followup = await FollowupFactory.createWithResults(
Expand All @@ -77,17 +61,27 @@ export async function persist(req: Request, res: Response) {
email,
phone
)
return sendFollowupNotifications(followup, res)
} else {
return createSimulationRecapUrl(req, res)
if (email) await sendSimulationResultsEmail(followup)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

J'aurais inversé, d'abord l'e-mail et ensuite le téléphone car plus de chance que le premier fonctionne.
On pourra aussi adapter le message en mode erreur avec le numéro de téléphone, l'email a bien été envoyer ressayer plus tard ou un truc du genre.

Copy link
Contributor Author

@Shamzic Shamzic Oct 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Peut-être dans un second temps, faire les deux envois séparément avec des messages dédiés à chaque service (ex: "l'email a bien été envoyé", puis "Le sms a bien été envoyé") ?

if (phone) await sendSimulationResultsSms(followup)
return res.send({ result: "OK" })
}

return createSimulationRecapUrl(req, res)
} catch (error: any) {
Sentry.captureException(error)
if (error.name === "ValidationError") {
return res.status(403).send(error.message)
} else {
return res.status(500).send(`Error while persisting followup`)

let status: number = ErrorStatus.InternalServerError

if (
error.name === ErrorName.ValidationError ||
error.message === ErrorType.UnsupportedPhoneNumberFormat
) {
status = ErrorStatus.UnprocessableEntity
}

return res
.status(status)
.send(error.message || ErrorType.PersistingFollowup)
}
}

Expand Down Expand Up @@ -117,7 +111,7 @@ export function showFollowup(req: Request, res: Response) {
})
.catch((error: Error) => {
console.error("error", error)
return res.sendStatus(400)
return res.sendStatus(ErrorStatus.BadRequest)
})
}

Expand All @@ -142,12 +136,13 @@ export function showSurveyResults(req: Request, res: Response) {
export function showSurveyResultByEmail(req: Request, res: Response) {
Followups.findByEmail(req.params.email)
.then((followups: Followup[]) => {
if (!followups || !followups.length) return res.sendStatus(404)
if (!followups || !followups.length)
return res.sendStatus(ErrorStatus.NotFound)
res.send(followups)
})
.catch((error: Error) => {
console.error("error", error)
return res.sendStatus(400)
return res.sendStatus(ErrorStatus.BadRequest)
})
}

Expand All @@ -160,7 +155,7 @@ export async function followupByAccessToken(
const followup: Followup | null = await Followups.findOne({
accessToken,
})
if (!followup) return res.sendStatus(404)
if (!followup) return res.sendStatus(ErrorStatus.NotFound)
req.followup = followup
next()
}
Expand Down Expand Up @@ -216,7 +211,7 @@ async function getRedirectUrl(req: Request) {
case SurveyType.TousABordNotification:
return "https://www.tadao.fr/713-Demandeur-d-emploi.html"
default:
throw new Error(`Unknown survey type: ${surveyType}`)
throw new Error(`${ErrorType.UnknownSurveyType} : ${surveyType}`)
}
}

Expand All @@ -227,7 +222,6 @@ export async function logSurveyLinkClick(req: Request, res: Response) {
res.redirect(redirectUrl)
} catch (error) {
Sentry.captureException(error)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

À postériori, je me demande si le captureException et le console error est pertinent, sachant qu'on ne retrouve plus le survey.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Le console.error c'est sûr qu'il n'est pas utile. Le captureException, comme tu avais pris l'initiative de l'ajouter, je te laisse décider si tu souhaites le retirer. Je l'aurais aussi enlevé de mon côté

console.error("error", error)
return res.sendStatus(404)
return res.sendStatus(ErrorStatus.NotFound)
}
}
3 changes: 2 additions & 1 deletion backend/lib/messaging/email/email-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ import { EmailType } from "../../../../lib/enums/messaging.js"
import { SurveyType } from "../../../../lib/enums/survey.js"
import { Survey } from "../../../../lib/types/survey.js"
import { Followup } from "../../../../lib/types/followup.js"
import { ErrorType } from "../../../../lib/enums/error.js"
import dayjs from "dayjs"

export async function sendSimulationResultsEmail(
followup: Followup
): Promise<Followup> {
if (!followup.email) {
throw new Error("Missing followup email")
throw new Error(ErrorType.MissingFollowupEmail)
}
const render: any = await emailRender(EmailType.SimulationResults, followup)
const sendEmailSmtpResponse = await sendEmailSmtp({
Expand Down
17 changes: 15 additions & 2 deletions backend/lib/messaging/sms/sms-service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import axios from "axios"
import config from "../../../config/index.js"
import { phoneNumberFormatting } from "./../../../../lib/phone-number.js"
import {
phoneNumberFormatting,
phoneNumberValidation,
} from "./../../../../lib/phone-number.js"
import { SmsType } from "../../../../lib/enums/messaging.js"
import { Followup } from "../../../../lib/types/followup.js"
import { Survey } from "../../../../lib/types/survey.d.js"
import { SurveyType } from "../../../../lib/enums/survey.js"
import { ErrorType } from "../../../../lib/enums/error.js"
import dayjs from "dayjs"
import Sentry from "@sentry/node"

Expand Down Expand Up @@ -69,7 +73,16 @@ export async function sendSimulationResultsSms(
): Promise<Followup> {
try {
if (!followup.phone) {
throw new Error("Missing followup phone")
throw new Error(ErrorType.MissingFollowupPhone)
}

if (
!phoneNumberValidation(
followup.phone,
config.smsService.internationalDiallingCodes
)
) {
throw new Error(ErrorType.UnsupportedPhoneNumberFormat)
}

const { username, password } = await getSMSConfig()
Expand Down
20 changes: 20 additions & 0 deletions lib/enums/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export enum ErrorType {
UnsupportedPhoneNumberFormat = "Unsupported phone number format",
PersistingFollowup = "Persisting followup error",
MissingFollowupPhone = "Missing followup phone",
MissingFollowupEmail = "Missing followup email",
UnknownSurveyType = "Unknown survey type",
}

export enum ErrorStatus {
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
UnprocessableEntity = 422,
NotFound = 404,
InternalServerError = 500,
}

export enum ErrorName {
ValidationError = "ValidationError",
}
Loading