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 a3b0ba7
Show file tree
Hide file tree
Showing 10 changed files with 548 additions and 46 deletions.
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
158 changes: 139 additions & 19 deletions packages/backend/src/services/Hebergement.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* 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 @@ -14,19 +15,91 @@ const query = {
informations_locaux,
informations_transport,
created_at,
edited_at
edited_at,
HEBERGEMENT_ID,
CURRENT,
CREATED_BY,
EDITED_BY,
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()
(SELECT org_id FROM front.user_organisme WHERE use_id = $1), --organisme_id,
$2, --nom,
$3, --coordonnees,
$4, --informations_locaux,
$5, --informations_transport,
NOW(), --created_at,
NOW(), --edited_at,
gen_random_uuid(), --HEBERGEMENT_ID,
TRUE, --CURRENT,
$1, --CREATED_BY,
$1, --EDITED_BY,
$6, --EMAIL,
$7, --ADRESSE_ID,
$8, --TELEPHONE_1,
$9, --TELEPHONE_2,
$10, --NOM_GESTIONNAIRE,
(SELECT ID FROM FRONT.HEBERGEMENT_TYPE WHERE VALUE = $11), --TYPE_ID,
(SELECT ID FROM FRONT.HEBERGEMENT_TYPE_PENSION WHERE VALUE = $12), --TYPE_PENSION_ID,
$13, --NOMBRE_LITS,
$14, --LIT_DESSUS,
$15, --NOMBRE_LITS_SUPERPOSES,
$16, --NOMBRE_MAX_PERSONNES_COUCHAGE,
$17, --VISITE_LOCAUX,
(SELECT ID FROM FRONT.HEBERGEMENT_ACCESSIBILITE WHERE VALUE = $18), --ACCESSIBILITE_ID,
$19, --CHAMBRES_DOUBLES,
$20, --CHAMBRES_UNISEXES,
$21, --REGLEMENTATION_ERP,
$22, --COUCHAGE_INDIVIDUEL,
$23, --RANGEMENT_INDIVIDUEL,
$24, --AMENAGEMENTS_SPECIFIQUES,
$25, --DESCRIPTION_LIEU_HEBERGEMENT,
$26, --EXCURSION_DESCRIPTION,
$27, --DEPLACEMENT_PROXIMITE_DESCRIPTION,
$28, --VEHICULES_ADAPTES,
$29, --FILE_REPONSE_EXPLOITANT_OU_PROPRIETAIRE,
$30, --FILE_DERNIER_ARRETE_AUTORISATION_MAIRE,
$31 --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 @@ -121,17 +194,64 @@ module.exports.create = async (
{ nom, coordonnees, informationsLocaux, informationsTransport },
) => {
log.i("create - IN");
const {
rows: [{ id }],
} = await pool.query(query.create, [
userId,
nom,
coordonnees,
informationsLocaux,
informationsTransport,
]);
log.d("create - DONE", { id });
return id;

const client = await pool.connect();

let hebergementId;

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

hebergementId = rows[0].id;
const prestationsHotelieres = informationsLocaux.prestationsHotelieres;
await pool.query(query.associatePrestation(prestationsHotelieres.length), [
hebergementId,
...prestationsHotelieres,
]);
await client.query("COMMIT");
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}

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

module.exports.update = async (
Expand Down
75 changes: 75 additions & 0 deletions packages/backend/src/services/adresse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const pool = require("../utils/pgpool").getPool();

const query = {
editCleInsee: `
UPDATE FRONT.ADRESSE
SET
CLE_INSEE = $2
WHERE
ID = $1
RETURNING id
`,
getByCleInseeOrLabel: `
SELECT
ID, CLE_INSEE as "cleInsee"
FROM
FRONT.ADRESSE
WHERE
CLE_INSEE = $1
OR LABEL = $2
`,
insert: `
INSERT INTO
FRONT.ADRESSE (
CLE_INSEE,
LABEL,
CODE_INSEE,
CODE_POSTAL,
LONG,
LAT,
DEPARTEMENT
)
VALUES
($1, $2, $3, $4, $5, $6, $7)
RETURNING id
`,
};

const getByCleInseeOrLabel = async ({ cleInsee, label }) => {
const { rows } = await pool.query(query.getByCleInseeOrLabel, [
cleInsee,
label,
]);
return rows?.[0] ?? null;
};

module.exports.saveAdresse = async (adresse) => {
const existingAdresse = await getByCleInseeOrLabel({
cleInsee: adresse.cleInsee,
label: adresse.label,
});

if (existingAdresse && !existingAdresse.cleInsee && adresse.cleInsee) {
const { rows } = await pool.query(query.editCleInsee, [
existingAdresse.id,
adresse.cleInsee,
]);
return rows[0].id;
}

if (!existingAdresse) {
const { rows } = await pool.query(query.insert, [
adresse.cleInsee,
adresse.label,
adresse.codeInsee,
adresse.codePostal,
adresse.coordinates[0],
adresse.coordinates[1],
adresse.departement,
]);

return rows[0].id;
}

return existingAdresse.id;
};
3 changes: 2 additions & 1 deletion packages/frontend-usagers/src/components/search-address.vue
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const searchAddressDebounced = debounce(async function (queryString) {
options.value = adresses.map((address) => {
return {
label: address.properties.label,
cleInsee: address.properties.id,
codeInsee: address.properties.citycode,
codePostal: address.properties.postcode,
coordinates: address.geometry.coordinates,
Expand Down Expand Up @@ -122,7 +123,7 @@ function select(_value, option) {
:is-pointed="isPointed(option)"
/>
</template>
<template #no-result> Pas de résultat </template>
<template #no-result> Pas de résultat</template>
</Multiselect>
<div v-if="message" class="fr-messages-group">
<p :class="messageClass">
Expand Down
19 changes: 0 additions & 19 deletions packages/frontend-usagers/src/utils/adresse.js

This file was deleted.

6 changes: 3 additions & 3 deletions packages/frontend-usagers/src/utils/organisme.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as yup from "yup";
import dayjs from "dayjs";
import regex from "./regex";
import adresse from "./adresse";
import personne from "./personne";
import protocoleTransport from "./protocoleTransport";
import protocoleSanitaire from "./protocoleSanitaire";
import { adresseSchema } from "@vao/shared/src/schema/adresse";

const types = [
{
Expand Down Expand Up @@ -225,8 +225,8 @@ const personnePhysiqueSchema = {
regex.numTelephoneRegex.test(tel),
),
adresseIdentique: yup.boolean().required(),
adresseDomicile: yup.object({ ...adresse.schema(true) }).required(),
adresseSiege: yup.object({ ...adresse.schema(true) }).required(),
adresseDomicile: yup.object({ ...adresseSchema(true) }).required(),
adresseSiege: yup.object({ ...adresseSchema(true) }).required(),
};
const agrementSchema = (regions) => ({
file: yup.mixed().required(),
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend-usagers/src/utils/personne.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as yup from "yup";
import dayjs from "dayjs";
import regex from "./regex";
import adresse from "./adresse";
import { informationsPersonnelListe } from "#imports";
import { adresseSchema } from "@vao/shared/src/schema/adresse";

const schema = ({
showAdresse,
Expand Down Expand Up @@ -60,7 +60,7 @@ const schema = ({

...(showAdresse && {
adresse: yup.object({
...adresse.schema(),
...adresseSchema(),
}),
}),
...(showAttestation && {
Expand Down
4 changes: 2 additions & 2 deletions packages/frontend-usagers/src/utils/prestataireUtils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as yup from "yup";
import dayjs from "dayjs";
import regex from "./regex";
import adresse from "./adresse";
import { adresseSchema } from "@vao/shared/src/schema/adresse";

const typePrestataireOptions = [
{
Expand Down Expand Up @@ -53,7 +53,7 @@ const schema = {
.required(),
adresse: yup.object().when("typePrestataire", {
is: (val) => val === "personne_morale",
then: () => yup.object(adresse.schema()),
then: () => yup.object(adresseSchema()),
otherwise: (val) => val.nullable().strip(),
}),
competence: yup.string().when("typePrestataire", {
Expand Down
Loading

0 comments on commit a3b0ba7

Please sign in to comment.