Skip to content

Commit

Permalink
fix(hebergement): refacto
Browse files Browse the repository at this point in the history
  • Loading branch information
benjaminDNUM committed Nov 13, 2024
1 parent 262f42e commit 40c9fb7
Show file tree
Hide file tree
Showing 13 changed files with 646 additions and 70 deletions.
6 changes: 4 additions & 2 deletions packages/backend/src/controllers/hebergement/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const HebergementSchema = require("../../schemas/hebergement");
const logger = require("../../utils/logger");
const ValidationAppError = require("../../utils/validation-error");
const AppError = require("../../utils/error");
const FOUser = require("../../services/FoUser");

const log = logger(module.filename);

Expand Down Expand Up @@ -44,11 +45,12 @@ module.exports = async function post(req, res, next) {
}

try {
const id = await Hebergement.create(userId, hebergement);
const organismeId = await FOUser.getUserOrganisme(userId);
const id = await Hebergement.create(userId, organismeId, hebergement);

return res.status(200).json({
id,
message: "sauvegarde organisme OK",
message: "sauvegarde hebegement OK",
});
} catch (error) {
log.w("DONE with error");
Expand Down
18 changes: 8 additions & 10 deletions packages/backend/src/controllers/hebergement/update.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,12 @@ const log = logger(module.filename);

module.exports = async function post(req, res, next) {
const hebergementId = req.params.id;
const { nom, coordonnees, informationsLocaux, informationsTransport } =
req.body;
log.i("IN", {
coordonnees,
hebergementId,
informationsLocaux,
informationsTransport,
nom,
});
const { body, decoded } = req;
const userId = decoded.id;

console.log(userId);

const { nom, coordonnees, informationsLocaux, informationsTransport } = body;

if (
!nom ||
Expand All @@ -36,6 +33,7 @@ module.exports = async function post(req, res, next) {
);
}
let hebergement;

try {
hebergement = await yup.object(HebergementSchema.schema()).validate(
{
Expand All @@ -54,7 +52,7 @@ module.exports = async function post(req, res, next) {
}

try {
await Hebergement.update(hebergementId, hebergement);
await Hebergement.update(userId, hebergementId, hebergement);
log.i("DONE");
return res.sendStatus(200);
} catch (error) {
Expand Down
1 change: 1 addition & 0 deletions packages/backend/src/schemas/parts/adresse.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const yup = require("yup");
const schema = ({ isFromAPIAdresse } = {}) => {
return isFromAPIAdresse
? {
cleInsee: yup.string().required("ce champ est obligatoire"),
codeInsee: yup.string().required("ce champ est obligatoire"),
codePostal: yup.string().required("ce champ est obligatoire"),
coordinates: yup.array().required("ce champ est obligatoire"),
Expand Down
6 changes: 6 additions & 0 deletions packages/backend/src/services/FoUser.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ ${additionalParamsQuery}
`,
additionalParams,
],
getUserOragnisme: `SELECT org_id as "organismeId" FROM front.user_organisme WHERE use_id = $1`,
};

module.exports.read = async ({
Expand Down Expand Up @@ -150,3 +151,8 @@ module.exports.readOne = async (id) => {
log.i("readOne - DONE");
return users[0];
};

module.exports.getUserOrganisme = async (userId) => {
const { rows } = await pool.query(query.getUserOragnisme, [userId]);
return rows[0]?.organismeId ?? null;
};
247 changes: 216 additions & 31 deletions packages/backend/src/services/Hebergement.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-param-reassign */
const AppError = require("../utils/error");
const logger = require("../utils/logger");
const { saveAdresse } = require("./adresse");
const pool = require("../utils/pgpool").getPool();

const log = logger(module.filename);
Expand All @@ -9,24 +9,96 @@ const query = {
create: `
INSERT INTO front.hebergement(
organisme_id,
CREATED_BY,
EDITED_BY,
created_at,
edited_at,
HEBERGEMENT_ID,
CURRENT,
nom,
coordonnees,
informations_locaux,
informations_transport,
created_at,
edited_at
EMAIL,
ADRESSE_ID,
TELEPHONE_1,
TELEPHONE_2,
NOM_GESTIONNAIRE,
TYPE_ID,
TYPE_PENSION_ID,
NOMBRE_LITS,
LIT_DESSUS,
NOMBRE_LITS_SUPERPOSES,
NOMBRE_MAX_PERSONNES_COUCHAGE,
VISITE_LOCAUX,
ACCESSIBILITE_ID,
CHAMBRES_DOUBLES,
CHAMBRES_UNISEXES,
REGLEMENTATION_ERP,
COUCHAGE_INDIVIDUEL,
RANGEMENT_INDIVIDUEL,
AMENAGEMENTS_SPECIFIQUES,
DESCRIPTION_LIEU_HEBERGEMENT,
EXCURSION_DESCRIPTION,
DEPLACEMENT_PROXIMITE_DESCRIPTION,
VEHICULES_ADAPTES,
FILE_REPONSE_EXPLOITANT_OU_PROPRIETAIRE,
FILE_DERNIER_ARRETE_AUTORISATION_MAIRE,
FILE_DERNIERE_ATTESTATION_SECURITE
)
VALUES (
(SELECT org_id FROM front.user_organisme WHERE use_id = $1),
$2,
$3,
$4,
$5,
NOW(),
NOW()
$1, --organisme_id,
$2, --CREATED_BY,
$3, --EDITED_BY,
$4, --created_at,
NOW(), --edited_at,
$5, --HEBERGEMENT_ID,
TRUE, --CURRENT,
$6, --nom,
$7, --coordonnees,
$8, --informations_locaux,
$9, --informations_transport,
$10, --EMAIL,
$11, --ADRESSE_ID,
$12, --TELEPHONE_1,
$13, --TELEPHONE_2,
$14, --NOM_GESTIONNAIRE,
(SELECT ID FROM FRONT.HEBERGEMENT_TYPE WHERE VALUE = $15), --TYPE_ID,
(SELECT ID FROM FRONT.HEBERGEMENT_TYPE_PENSION WHERE VALUE = $16), --TYPE_PENSION_ID,
$17, --NOMBRE_LITS,
$18, --LIT_DESSUS,
$19, --NOMBRE_LITS_SUPERPOSES,
$20, --NOMBRE_MAX_PERSONNES_COUCHAGE,
$21, --VISITE_LOCAUX,
(SELECT ID FROM FRONT.HEBERGEMENT_ACCESSIBILITE WHERE VALUE = $22), --ACCESSIBILITE_ID,
$23, --CHAMBRES_DOUBLES,
$24, --CHAMBRES_UNISEXES,
$25, --REGLEMENTATION_ERP,
$26, --COUCHAGE_INDIVIDUEL,
$27, --RANGEMENT_INDIVIDUEL,
$28, --AMENAGEMENTS_SPECIFIQUES,
$29, --DESCRIPTION_LIEU_HEBERGEMENT,
$30, --EXCURSION_DESCRIPTION,
$31, --DEPLACEMENT_PROXIMITE_DESCRIPTION,
$32, --VEHICULES_ADAPTES,
$33, --FILE_REPONSE_EXPLOITANT_OU_PROPRIETAIRE,
$34, --FILE_DERNIER_ARRETE_AUTORISATION_MAIRE,
$35 --FILE_DERNIERE_ATTESTATION_SECURITE
)
RETURNING id
`,
associatePrestation: (nbRows) => `
INSERT INTO
FRONT.HEBERGEMENT_TO_PRESTATION_RELATION (HEBERGEMENT_ID, PRESTATION_ID)
VALUES
${new Array(nbRows)
.fill(null)
.map(
(_, index) =>
`($1, (SELECT ID FROM FRONT.HEBERGEMENT_PRESTATIONS_HOTELIERES WHERE VALUE = $${index + 2}))`,
)
.join(",")}
`,
getByDepartementCodes: (
departementCodes,
{ search, limit, offset, order, sort },
Expand Down Expand Up @@ -104,6 +176,17 @@ const query = {
JOIN front.user_organisme uo ON uo.org_id = h.organisme_id
WHERE uo.use_id = $1
`,
getUnchangedValuesForHistory: `
SELECT
HEBERGEMENT_ID AS "hebergementUuid",
ORGANISME_ID as "organismeId",
CREATED_BY as "createdBy",
CREATED_AT as "createdAt"
FROM
FRONT.HEBERGEMENT
WHERE
ID = $1;
`,
update: `
UPDATE front.hebergement
SET
Expand All @@ -114,42 +197,144 @@ const query = {
edited_at = NOW()
WHERE id = $1
`,
historize: `
UPDATE front.hebergement
SET current = FALSE
WHERE id = $1
`,
};

module.exports.create = async (
userId,
const create = async (
client,
{ createdBy, createdAt, updatedBy, organismeId },
{ nom, coordonnees, informationsLocaux, informationsTransport },
hebergemenetUuid,
) => {
log.i("create - IN");
const {
rows: [{ id }],
} = await pool.query(query.create, [
userId,

await client.query("BEGIN");
const adresseId = await saveAdresse(coordonnees.adresse);
const { rows } = await pool.query(query.create, [
organismeId, // $1
createdBy,
updatedBy,
createdAt,
hebergemenetUuid ?? crypto.randomUUID(), // 5
nom,
coordonnees,
informationsLocaux,
informationsTransport,
coordonnees.email, // 10
adresseId,
coordonnees.numTelephone1,
coordonnees.numTelephone2,
coordonnees.nomGestionnaire,
informationsLocaux.type, // 15
informationsLocaux.pension,
informationsLocaux.nombreLits,
informationsLocaux.litsDessus,
informationsLocaux.nombreLitsSuperposes,
informationsLocaux.nombreMaxPersonnesCouchage, // 20
informationsLocaux.visiteLocaux,
informationsLocaux.accessibilite,
informationsLocaux.chambresDoubles,
informationsLocaux.chambresUnisexes,
informationsLocaux.reglementationErp, // 25
informationsLocaux.couchageIndividuel,
informationsLocaux.rangementIndividuel,
informationsLocaux.amenagementsSpecifiques,
informationsLocaux.descriptionLieuHebergement,
informationsTransport.excursion, // 30
informationsTransport.deplacementProximite,
informationsTransport.vehiculesAdaptes,
informationsLocaux.fileReponseExploitantOuProprietaire?.uuid ?? null,
informationsLocaux.fileDernierArreteAutorisationMaire?.uuid ?? null,
informationsLocaux.fileDerniereAttestationSecurite?.uuid ?? null,
]);
log.d("create - DONE", { id });
return id;
};

module.exports.update = async (
hebergementId,
{ nom, coordonnees, informationsLocaux, informationsTransport },
) => {
log.i("update - IN");
const { rowCount } = await pool.query(query.update, [
const hebergementId = rows[0].id;
const prestationsHotelieres = informationsLocaux.prestationsHotelieres;
await pool.query(query.associatePrestation(prestationsHotelieres.length), [
hebergementId,
nom,
coordonnees,
informationsLocaux,
informationsTransport,
...prestationsHotelieres,
]);
if (rowCount === 0) {
throw new AppError("hebergement " + hebergementId + " not found");
await client.query("COMMIT");

log.d("create - DONE", { hebergementId });
return hebergementId;
};

module.exports.create = async (userId, organismeId, hebergement) => {
const client = await pool.connect();

try {
await client.query("BEGIN");
create(
client,
{
createdAt: new Date(),
createdBy: userId,
updatedBy: userId,
organismeId,
},
hebergement,
);
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
};

module.exports.update = async (userId, hebergementId, hebergement) => {
log.i("update - IN");

await pool.query(query.historize, [hebergementId]);
const client = await pool.connect();

let newHebergementId;
try {
await client.query("BEGIN");

const {
rows: [{ hebergementUuid, organismeId, createdBy, createdAt }],
} = await client.query(query.getUnchangedValuesForHistory, [hebergementId]);

console.log(
hebergementUuid,
organismeId,
createdBy,
createdAt,
hebergementId,
);

await pool.query(query.historize, [hebergementId]);
console.log("laaaaaaa");

newHebergementId = await create(
client,
{
createdBy,
createdAt,
updatedBy: userId,
organismeId,
},
hebergement,
hebergementUuid,
);

await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
log.i("update - DONE");

return newHebergementId;
};

module.exports.getByDepartementCodes = async (departementsCodes, params) => {
Expand Down
Loading

0 comments on commit 40c9fb7

Please sign in to comment.