From ebedc96af3057389fa7c32e7710cbe12b0ceb915 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Val=C3=A8re=20Pique?= Date: Wed, 13 Nov 2024 18:01:54 +0100 Subject: [PATCH] wip --- .../src/controllers/demandeSejour/get.js | 36 +++++++-- packages/backend/src/helpers/queryParams.js | 79 +++++++++++++++++++ .../backend/src/services/DemandeSejour.js | 42 ++++++++++ 3 files changed, 150 insertions(+), 7 deletions(-) create mode 100644 packages/backend/src/helpers/queryParams.js diff --git a/packages/backend/src/controllers/demandeSejour/get.js b/packages/backend/src/controllers/demandeSejour/get.js index 2d51a4fa0..c746ee78d 100644 --- a/packages/backend/src/controllers/demandeSejour/get.js +++ b/packages/backend/src/controllers/demandeSejour/get.js @@ -1,6 +1,9 @@ const DemandeSejour = require("../../services/DemandeSejour"); const Organisme = require("../../services/Organisme"); - +const { + sanityzePaginationParams, + sanityzeFiltersParams, +} = require("../../helpers/queryParams"); const logger = require("../../utils/logger"); const log = logger(module.filename); @@ -10,11 +13,23 @@ module.exports = async function get(req, res, next) { const { decoded } = req; const { id: userId } = decoded; log.d("userId", { userId }); - const { sortBy } = req.query; - const params = { - sortBy, - }; + const titles = [ + "idFonctionnelle", + "departementSuivi", + "libelle", + "periode", + "dateDebut", + "dateFin", + "editedAt", + "statut", + "periode", + ]; + + const paginationParams = sanityzePaginationParams(req.query, { + sortDirection: titles, + }); + const filterParams = sanityzeFiltersParams(req.query, titles); try { const organisme = await Organisme.getOne({ use_id: userId, @@ -28,9 +43,16 @@ module.exports = async function get(req, res, next) { } else { organismesId = [organisme.organismeId]; } - const demandes = await DemandeSejour.get(params, organismesId); + const demandes = await DemandeSejour.getNext( + organismesId, + paginationParams, + filterParams, + ); log.d(demandes); - return res.status(200).json({ demandes }); + return res.status(200).json({ + demandes: demandes.rows, + total: demandes.total, + }); } catch (error) { log.w("DONE with error"); return next(error); diff --git a/packages/backend/src/helpers/queryParams.js b/packages/backend/src/helpers/queryParams.js new file mode 100644 index 000000000..49a6e23fb --- /dev/null +++ b/packages/backend/src/helpers/queryParams.js @@ -0,0 +1,79 @@ +module.exports = { + applyFilters: (query, initialParams = [], filterParams) => { + const params = [...initialParams]; + if (Object.keys(filterParams).length === 0) { + return { + params: initialParams, + query, + }; + } + const filters = Object.entries(filterParams) + .map(([key, value], index) => { + params.push(filterParams); + if (Array.isArray(value)) { + return `${key} = ANY($${initialParams.length + index + 1})`; + } + return `${key} = $${initialParams.length + index + 1}`; + }) + .join(" AND "); + return { + params, + query: `${query} AND ${filters}`, + }; + }, + applyPagination: ( + query, + params, + limit = 10, + offset = 0, + sortBy = "", + sortDirection = "", + ) => { + const validSort = sortBy ? `"${sortBy}"` : ""; + + const paginatedQuery = ` + ${query} + ${validSort ? `ORDER BY ${validSort} ${sortDirection}` : ""} + LIMIT $${params.length + 1} + OFFSET $${params.length + 2}; + `; + + const countQuery = ` + SELECT COUNT(*) AS total FROM (${query}) AS subquery; + `; + + return { + countQuery, + countQueryParams: params, + params: [...params, limit, offset], + query: paginatedQuery, + }; + }, + sanityzeFiltersParams: (queryParams, availableParams) => + availableParams.reduce((acc, availableParam) => { + if (queryParams[availableParam]) { + acc[availableParam] = queryParams[availableParam]; + } + return acc; + }, {}), + sanityzePaginationParams: ( + { sortBy, sortDirection, limit, offset }, + defaultParams = {}, + ) => { + const defaultSortDirection = ["", "ASC", "DESC"]; + const defaultLimit = 10; + const defaultOffset = 0; + return { + limit: isNaN(parseInt(limit, 10)) + ? (defaultParams?.limit ?? defaultLimit) + : parseInt(limit, 10), + offset: isNaN(parseInt(offset, 10)) + ? (defaultParams?.offset ?? defaultOffset) + : parseInt(offset, 10), + sortBy: defaultParams?.sortBy?.includes(sortBy) ? sortBy : "", + sortDirection: defaultSortDirection.includes(sortDirection) + ? sortDirection + : "", + }; + }, +}; diff --git a/packages/backend/src/services/DemandeSejour.js b/packages/backend/src/services/DemandeSejour.js index 119d6e05b..036dfcf34 100644 --- a/packages/backend/src/services/DemandeSejour.js +++ b/packages/backend/src/services/DemandeSejour.js @@ -1,6 +1,7 @@ /* eslint-disable no-param-reassign */ const dayjs = require("dayjs"); const logger = require("../utils/logger"); +const { applyPagination } = require("../helpers/queryParams"); const pool = require("../utils/pgpool").getPool(); const dsStatus = require("../helpers/ds-statuts"); @@ -553,9 +554,28 @@ WHERE `, [departementCodes, search, limit, offset], ], + getNext: () => + // $1 organisationIds + `SELECT + ds.id as "declarationId", + ds.statut as "statut", + ds.id_fonctionnelle as "idFonctionnelle", + ds.departement_suivi as "departementSuivi", + ds.libelle as "libelle", + o.personne_morale->>'siret' as "siret", + ds.date_debut as "dateDebut", + ds.date_fin as "dateFin", + ds.periode as "periode", + ds.edited_at as "editedAt" + FROM front.demande_sejour ds + JOIN front.organismes o ON o.id = ds.organisme_id + WHERE + o.id = ANY ($1) + `, getNextIndex: ` SELECT nextval('front.seq_declaration_sejour') AS index `, + getOne: (criterias) => [ ` SELECT @@ -878,6 +898,28 @@ module.exports.cancel = async (declarationId, userId) => { log.i("cancel - DONE"); return rowCount; }; +module.exports.getNext = async ( + organismesId, + { sortBy, sortDirection, limit, offset }, +) => { + const queryGet = query.getNext(); + const paginatedQuery = applyPagination( + queryGet, + [organismesId], + limit, + offset, + sortBy, + sortDirection, + ); + const result = await Promise.all([ + pool.query(paginatedQuery.query, paginatedQuery.params), + pool.query(paginatedQuery.countQuery, paginatedQuery.countQueryParams), + ]); + return { + rows: result[0].rows, + total: parseInt(result[1].rows[0].total, 10), + }; +}; module.exports.get = async ({ sortBy }, organismesId) => { log.i("get - IN", { organismesId }); const queryGet = query.get(organismesId);