Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
iNeoO committed Nov 13, 2024
1 parent 2c3975f commit ebedc96
Show file tree
Hide file tree
Showing 3 changed files with 150 additions and 7 deletions.
36 changes: 29 additions & 7 deletions packages/backend/src/controllers/demandeSejour/get.js
Original file line number Diff line number Diff line change
@@ -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);
Expand All @@ -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,
Expand All @@ -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);
Expand Down
79 changes: 79 additions & 0 deletions packages/backend/src/helpers/queryParams.js
Original file line number Diff line number Diff line change
@@ -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
: "",
};
},
};
42 changes: 42 additions & 0 deletions packages/backend/src/services/DemandeSejour.js
Original file line number Diff line number Diff line change
@@ -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");

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit ebedc96

Please sign in to comment.