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

Fix/#729 refacto de la table hebergement v 2 #617

Open
wants to merge 2 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
2 changes: 1 addition & 1 deletion packages/backend/src/controllers/demandeSejour/depose.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const dayjs = require("dayjs");
const yup = require("yup");

const DemandeSejour = require("../../services/DemandeSejour");
const Hebergement = require("../../services/Hebergement");
const Hebergement = require("../../services/hebergement/Hebergement");
const Send = require("../../services/mail").mailService.send;
const PdfDeclaration2Mois = require("../../services/pdf/declaration2mois/generate");
const PdfDeclaration8jours = require("../../services/pdf/declaration8jours/generate");
Expand Down
38 changes: 0 additions & 38 deletions packages/backend/src/controllers/demandeSejour/getHebergement.js

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ module.exports = async function get(req, res) {
sort: titleSorted ?? "nom",
},
);

return res.status(200).json({
count: data.total_count,
hebergements: data.hebergements || [],
Expand Down
1 change: 0 additions & 1 deletion packages/backend/src/controllers/demandeSejour/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ module.exports.get = require("./get");
module.exports.getAdminStats = require("./getAdminStats");
module.exports.getExtract = require("./getExtract");
module.exports.getExtractHebergement = require("./getExtractHebergement");
module.exports.getHebergement = require("./getHebergement");
module.exports.getHebergementsByDepartementCodes = require("./getHebergementsByDepartementCodes");
module.exports.getById = require("./getById");
module.exports.getByIdBo = require("./getByIdBo");
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/controllers/hebergement/get.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const Hebergement = require("../../services/Hebergement");
const Hebergement = require("../../services/hebergement/Hebergement");

const logger = require("../../utils/logger");

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const Hebergement = require("../../services/Hebergement");
const Hebergement = require("../../services/hebergement/Hebergement");

const logger = require("../../utils/logger");
const Sentry = require("@sentry/node");
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/controllers/hebergement/getById.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const Hebergement = require("../../services/Hebergement");
const Hebergement = require("../../services/hebergement/Hebergement");
const AppError = require("../../utils/error");

const logger = require("../../utils/logger");
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/controllers/hebergement/getExtract.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const Hebergement = require("../../services/Hebergement");
const Hebergement = require("../../services/hebergement/Hebergement");
const logger = require("../../utils/logger");
const dayjs = require("dayjs");

Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/controllers/hebergement/post.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const yup = require("yup");
const Hebergement = require("../../services/Hebergement");
const Hebergement = require("../../services/hebergement/Hebergement");
const HebergementSchema = require("../../schemas/hebergement");
const logger = require("../../utils/logger");
const ValidationAppError = require("../../utils/validation-error");
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/controllers/hebergement/update.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const yup = require("yup");

const Hebergement = require("../../services/Hebergement");
const Hebergement = require("../../services/hebergement/Hebergement");
const logger = require("../../utils/logger");
const ValidationAppError = require("../../utils/validation-error");
const HebergementSchema = require("../../schemas/hebergement");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,33 @@ async function checkPermissionDeclarationSejour(req, res, next) {

// Requête SQL simplifiée, ne récupérant que les informations brutes nécessaires
const query = `
SELECT ds.id, ds.hebergement, o.personne_morale, agr.region_obtention
SELECT ds.id, o.personne_morale, agr.region_obtention
FROM front.demande_sejour ds
INNER JOIN front.organismes o ON o.id = ds.organisme_id
LEFT JOIN front.agrements agr ON agr.organisme_id = ds.organisme_id
WHERE ds.id = $1
`;

const queryHebegements = `
SELECT DISTINCT
A.DEPARTEMENT AS DEPARTEMENT
Copy link
Contributor

Choose a reason for hiding this comment

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

Mettre au moins AS "departement" pour pas se trainer un truc bizarre dans le code

FROM
FRONT.DEMANDE_SEJOUR_TO_HEBERGEMENT DSTH
INNER JOIN FRONT.HEBERGEMENT H ON H.ID = DSTH.HEBERGEMENT_ID
INNER JOIN FRONT.ADRESSE A ON A.ID = H.ADRESSE_ID
WHERE
DEMANDE_SEJOUR_ID = $1
`;

let sejour;
let departementsHebergements;
try {
const { rows } = await pool.query(query, [declarationId]);
departementsHebergements =
(await pool.query(queryHebegements, [declarationId]))?.rows.map(
(r) => r.departement,
) ?? [];

if (!rows || rows.length === 0) {
return next(
new AppError(
Expand All @@ -54,14 +71,9 @@ async function checkPermissionDeclarationSejour(req, res, next) {
);
}

const { hebergement, personne_morale, region_obtention } = sejour;
const { personne_morale, region_obtention } = sejour;

// Traitement des données JSON pour vérifier les départements
const hebergements = hebergement?.hebergements || [];
const departementsHebergements = hebergements.map(
(h) => h.coordonnees?.adresse?.departement,
);

const hasValidDepartement = departements.some((dep) =>
departementsHebergements.includes(dep.value),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const request = require("supertest");
const app = require("../../../app"); // Chemin vers ton application Express
const Hebergement = require("../../../services/hebergement/Hebergement");
const CheckJWT = require("../../../middlewares/checkJWT");
const checkPermissionHebergement = require("../../../middlewares/checkPermissionHebergement");

// Mock des services et middlewares
jest.mock("../../../services/hebergement/Hebergement");
jest.mock("../../../middlewares/checkJWT");
jest.mock("../../../middlewares/checkPermissionHebergement");

describe("GET /hebergement/:id", () => {
const user = {
id: 1,
role: "admin",
};

beforeEach(() => {
jest.clearAllMocks();

// Mock des middlewares
CheckJWT.mockImplementation((req, res, next) => {
req.decoded = { ...user };
next();
});
checkPermissionHebergement.mockImplementation((req, res, next) => {
next();
});
});

it("devrait retourner un hébergement par ID avec succès", async () => {
const mockHebergement = {
id: "123",
};

// Mock de Hebergement.getById
Hebergement.getById.mockResolvedValue(mockHebergement);

const response = await request(app).get("/hebergement/123");

// Vérification des résultats
expect(response.status).toBe(200);
expect(Hebergement.getById).toHaveBeenCalledWith("123");
});

it("devrait retourner une erreur 400 si l'ID est manquant ou invalide", async () => {
CheckJWT.mockImplementationOnce((req, res, next) => {
req.decoded = { ...user };
req.params = {};
next();
});

const response = await request(app).get("/hebergement/2");
expect(response.status).toBe(400);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const request = require("supertest");
const app = require("../../../app"); // Chemin vers ton application Express
const Hebergement = require("../../../services/hebergement/Hebergement");
const boCheckJWT = require("../../../middlewares/bo-check-JWT");
const checkPermissionHebergement = require("../../../middlewares/checkPermissionHebergement");

// Mock des services et middlewares
jest.mock("../../../services/hebergement/Hebergement");
jest.mock("../../../middlewares/bo-check-JWT");
jest.mock("../../../middlewares/checkPermissionHebergement");

describe("GET /hebergement/admin/:id", () => {
const user = {
id: 1,
role: "admin",
};

beforeEach(() => {
jest.clearAllMocks();

// Mock des middlewares
boCheckJWT.mockImplementation((req, res, next) => {
req.decoded = { ...user };
next();
});
checkPermissionHebergement.mockImplementation((req, res, next) => {
next();
});
});

it("devrait retourner un hébergement par ID avec succès", async () => {
const mockHebergement = {
id: "123",
};

// Mock de Hebergement.getById
Hebergement.getById.mockResolvedValue(mockHebergement);

const response = await request(app).get("/hebergement/admin/123");

// Vérification des résultats
expect(response.status).toBe(200);
expect(Hebergement.getById).toHaveBeenCalledWith("123");
});

it("devrait retourner une erreur 400 si l'ID est manquant ou invalide", async () => {
boCheckJWT.mockImplementationOnce((req, res, next) => {
req.decoded = { ...user };
req.params = {};
next();
});

const response = await request(app).get("/hebergement/admin/2");
expect(response.status).toBe(400);
});
});
108 changes: 108 additions & 0 deletions packages/backend/src/routes/__tests__/hebergement/post.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
const request = require("supertest");
const app = require("../../../app");
const Hebergement = require("../../../services/hebergement/Hebergement");
const checkJWT = require("../../../middlewares/checkJWT");
const checkPermissionHebergement = require("../../../middlewares/checkPermissionHebergement");
const yup = require("yup");
const FOUser = require("../../../services/FoUser");

// Mock de la méthode Hebergement.update
jest.mock("../../../services/hebergement/Hebergement");
jest.mock("../../../middlewares/checkJWT");
jest.mock("../../../middlewares/checkPermissionHebergement");
jest.mock("../../../schemas/hebergement");
jest.mock("../../../services/FoUser");

describe("POST /", () => {
const user = {
id: 1,
};
beforeEach(() => {
jest.clearAllMocks();
checkJWT.mockImplementation((req, res, next) => {
req.decoded = { ...user };
next();
});
checkPermissionHebergement.mockImplementation((req, res, next) => {
next();
});
});

it("should return 400 if a required parameter is missing", async () => {
const res = await request(app)
.post("/hebergement")
.send({ nom: "Hébergement" }) // Paramètre manquant
.expect(400);
expect(res.statusCode).toBe(400);
});

it("should return 200 if the hebergement is posted successfully", async () => {
Hebergement.create.mockResolvedValueOnce(true);
FOUser.getUserOrganisme.mockResolvedValueOnce(1);

const body = {
nom: "Hébergement 1",
coordonnees: { lat: 10, lon: 20 },
informationsLocaux: {},
informationsTransport: {},
};

jest.spyOn(yup, "object").mockImplementationOnce(() => ({
validate: (parametre) => {
return parametre;
},
}));
const res = await request(app).post("/hebergement").send(body);

expect(res.status).toBe(200);
expect(Hebergement.create).toHaveBeenCalledWith(
1,
1,
expect.objectContaining(body),
);
});

it("should return 400 if validation fails with yup", async () => {
// Simule l'échec de la validation avec yup
jest.spyOn(yup, "object").mockImplementationOnce(() => ({
validate: () => {
throw new Error("error");
},
}));

const res = await request(app)
.post("/hebergement")
.send({
nom: "Hébergement",
coordonnees: {},
informationsLocaux: "Info",
informationsTransport: "Info",
})
.expect(400);

expect(res.status).toBe(400);
});

it("should return 404 if Hebergement.update throws an archive error", async () => {
const archiveError = new Error("Hebergement archived");
archiveError.cause = "archive";
Hebergement.update.mockRejectedValueOnce(archiveError);

jest.spyOn(yup, "object").mockImplementationOnce(() => ({
validate: (parametre) => {
return parametre;
},
}));

const res = await request(app)
.post("/hebergement/123")
.send({
nom: "Hébergement",
coordonnees: { lat: 10, lon: 20 },
informationsLocaux: "Info locaux",
informationsTransport: "Info transport",
});

expect(res.status).toBe(400);
});
});
Loading
Loading