Skip to content
This repository has been archived by the owner on Jan 19, 2024. It is now read-only.

Commit

Permalink
feat: add validation errors on update psychologists (#193)
Browse files Browse the repository at this point in the history
  • Loading branch information
rap2hpoutre authored May 30, 2022
1 parent 42cf9fb commit 37cdf92
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 28 deletions.
50 changes: 33 additions & 17 deletions src/__tests__/psychologists-update.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,39 @@ describe("updateIfExists", () => {
expect(exception.details.length).toEqual(9);
expect(exception.details[0].message).toEqual('"address" is required');
});
it("should fail when address is invalid", async () => {
let exception;
getAddressCoordinatesStub.returns(null);
await updateIfExists("1", "01", {
...valideInput,
address: "invalid address",
}).catch((e) => (exception = e));
expect(exception.details[0].message).toMatch(/adresse/);
});
it("should fail when secondAddress is invalid", async () => {
let exception;
getAddressCoordinatesStub
.onFirstCall()
.returns({
latitude: 456,
longitude: 123,
})
.onSecondCall()
.returns(null);
await updateIfExists("1", "01", {
...valideInput,
secondAddress: "invalid address",
}).catch((e) => (exception = e));
expect(exception.details[0].message).toMatch(/adresse/);
});
it("should fail when url is not http or https", async () => {
let exception;
await updateIfExists("1", "01", {
...valideInput,
website: "website invalid",
}).catch((e) => (exception = e));
expect(exception.details[0].message).toMatch(/https/);
});
it("update should update psy in db", async () => {
let exception;
getAddressCoordinatesStub.returns({ latitude: 456, longitude: 123 });
Expand Down Expand Up @@ -78,21 +111,4 @@ describe("updateIfExists", () => {
// @ts-ignore
expect(updatedPsy.shouldBeIgnored).toEqual(undefined);
});
it("update should coordinate with null if API returns null", async () => {
let exception;
getAddressCoordinatesStub.returns(null);

const result = await updateIfExists("1", "01", valideInput).catch(
(e) => (exception = e)
);
expect(exception).toEqual(undefined);
expect(result).toEqual([1]);

// @ts-ignore
const updatedPsy: Psychologist = await models.Psychologist.findOne({
raw: true,
where: { email: valideInput.email },
});
expect(updatedPsy.coordinates).toEqual(null);
});
});
19 changes: 13 additions & 6 deletions src/components/Admin/PsychologistForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const editableFields = [
label: "Informations complémentaires (second lieu)",
},
{ field: "phone", label: "Téléphone", required: true },
// Todo: add type email to input when it's supported by @dataesr/react-dsfr.
{ field: "email", label: "Email" },
{
field: "displayEmail",
Expand Down Expand Up @@ -105,7 +106,11 @@ const PsychologistForm = ({
psychologist: Psychologist;
isSuperAdmin: boolean;
}) => {
const [result, setResult] = useState<{ type: string; text: string }>();
const [result, setResult] = useState<{
type: "success" | "error";
text: string;
title: string;
}>();
const [sending, setSending] = useState(false);

const [modifiedPsychologist, setModifiedPsychologist] =
Expand Down Expand Up @@ -137,14 +142,16 @@ const PsychologistForm = ({
)
.then(() => {
setResult({
text: "Psychologue correctement mis à jour",
title: "Psychologue correctement mis à jour",
type: "success",
text: "",
});
})
.catch(() => {
.catch((e) => {
setResult({
text: "Une erreur est survenue, veuillez réessayer",
title: "Une erreur est survenue, veuillez réessayer",
type: "error",
text: e.response?.data || "",
});
})
.finally(() => {
Expand Down Expand Up @@ -273,9 +280,9 @@ const PsychologistForm = ({
<Alert
data-test-id="alert"
className="fr-mt-4w"
//@ts-ignore
type={result.type}
title={result.text}
title={result.title}
description={result.text}
/>
)}
</form>
Expand Down
37 changes: 32 additions & 5 deletions src/pages/api/admin/psychologists/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import {
const updateSchema = Joi.object({
address: Joi.string().required(),
coordinates: Joi.object().allow(null),
addressAdditional: Joi.string().allow("").allow(null),
addressAdditional: Joi.string().allow("", null),
secondAddress: Joi.string().allow(""),
secondAddressCoordinates: Joi.object().allow(null),
secondAddressAdditional: Joi.string().allow("").allow(null),
secondAddressAdditional: Joi.string().allow("", null),
cdsmsp: Joi.string().allow(""),
displayEmail: Joi.boolean().required(),
email: Joi.string().email(),
Expand All @@ -30,19 +30,46 @@ const updateSchema = Joi.object({
.required(),
teleconsultation: Joi.boolean().required(),
visible: Joi.boolean().required(),
website: Joi.string().allow("").allow(null),
website: Joi.string()
.uri({ scheme: ["http", "https"] })
.allow("", null)
.messages({
"string.uriCustomScheme":
"L'adresse du site web doit commencer par http:// ou https://",
}),
}).messages({
"string.empty": "{{#label}} ne peut pas être vide",
"string.email": "L'email doit être valide. Exemple : test@example.org",
});

const coordinatesSchema = Joi.array().length(2).items(Joi.number()).required();

const coordinatesErrorMessage =
"L'adresse postale du cabinet principal semble invalide. Veuillez la vérifier ou contacter l'équipe du support.";
const secondAddressCoordinatesErrorMessage =
"L'adresse postale du second lieu d'exercice semble invalide. Veuillez la vérifier ou contacter l'équipe du support.";

export const updateIfExists = async (id: string, department: string, body) => {
const existingPsychologist = await getOne(id, department);
if (!existingPsychologist) return;

const psy = await formatPsychologist(filterAllowedKeys(body));
const psy = filterAllowedKeys(body);
await updateSchema.validateAsync(psy, {
abortEarly: false,
});
const formattedPsy = await formatPsychologist(psy);
// Fails when address was not empty and the given address did not return
// coordinates on format (this validation is done after API address call).
await coordinatesSchema
.messages({ "any.required": coordinatesErrorMessage })
.validateAsync(formattedPsy.coordinates?.coordinates);
if (psy.secondAddress) {
await coordinatesSchema
.messages({ "any.required": secondAddressCoordinatesErrorMessage })
.validateAsync(formattedPsy.secondAddressCoordinates?.coordinates);
}

return await update(id, psy);
return await update(id, formattedPsy);
};

const updatePsy = async (req: NextApiRequest, res: NextApiResponse) => {
Expand Down

0 comments on commit 37cdf92

Please sign in to comment.