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

refactor(api, admin): Listes de volontaires - optimiser la récupération des labels de filtres #4709

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
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
44 changes: 7 additions & 37 deletions admin/src/scenes/volontaires/list.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useState } from "react";
import { useSelector } from "react-redux";
import { Link, useHistory } from "react-router-dom";

Expand All @@ -13,7 +13,7 @@ import Breadcrumbs from "../../components/Breadcrumbs";
import Loader from "../../components/Loader";
import { ExportComponent, Filters, ModalExport, ResultTable, Save, SelectedFilters, SortOption } from "../../components/filters-system-v2";
import { appURL } from "../../config";
import api from "../../services/api";
import useFilterLabels from "./useFilterLabels";
import plausibleEvent from "../../services/plausible";
import { ROLES, YOUNG_STATUS, YOUNG_STATUS_COLORS, getAge, translate, translatePhase1, translatePhase2 } from "../../utils";
import { Title } from "../pointDeRassemblement/components/common";
Expand All @@ -26,13 +26,11 @@ import { getCohortGroups } from "@/services/cohort.service";
export default function VolontaireList() {
const user = useSelector((state) => state.Auth.user);
const history = useHistory();
const { data: filterLabels, isPending, isError } = useFilterLabels("volontaires");
const { sessions, bus, classes, etablissements } = filterLabels || {};
if (user?.role === ROLES.ADMINISTRATEUR_CLE) return history.push("/mes-eleves");

const [volontaire, setVolontaire] = useState(null);
const [sessionsPhase1, setSessionsPhase1] = useState(null);
const [bus, setBus] = useState(null);
const [classes, setClasses] = useState(null);
const [etablissements, setEtablissements] = useState(null);
const [isExportOpen, setIsExportOpen] = useState(false);
const [size, setSize] = useState(10);

Expand All @@ -45,38 +43,10 @@ export default function VolontaireList() {
sort: { label: "Nom (A > Z)", field: "lastName.keyword", order: "asc" },
});

const filterArray = getFilterArray(user, bus, sessionsPhase1, classes, etablissements);
if (isPending) return <Loader />;
if (isError) return <div>Erreur lors de la récupération des filtres</div>;

useEffect(() => {
(async () => {
try {
const { data: sessions } = await api.post(`/elasticsearch/sessionphase1/export`, {
filters: {},
exportFields: ["codeCentre", "cohesionCenterId"],
});
const { data: bus } = await api.post(`/elasticsearch/lignebus/export`, {
filters: {},
exportFields: ["busId"],
});
const { data: classes } = await api.post(`/elasticsearch/cle/classe/export`, {
filters: {},
exportFields: ["name", "uniqueKeyAndId"],
});
const { data: etablissements } = await api.post(`/elasticsearch/cle/etablissement/export`, {
filters: {},
exportFields: ["name", "uai"],
});
setSessionsPhase1(sessions);
setBus(bus);
setClasses(classes);
setEtablissements(etablissements);
} catch (e) {
toastr.error("Oups, une erreur est survenue lors de la récupération des données");
}
})();
}, []);

if (!sessionsPhase1 || !bus || !classes || !etablissements) return <Loader />;
const filterArray = getFilterArray(user, bus, sessions, classes, etablissements);

return (
<>
Expand Down
22 changes: 22 additions & 0 deletions admin/src/scenes/volontaires/useFilterLabels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { buildRequest } from "@/utils/buildRequest";
import { useQuery } from "@tanstack/react-query";
import { FilterLabelDto, FilterLabelRoutes } from "snu-lib";

async function getFilterLabels(listType: string): Promise<FilterLabelDto> {
const { ok, code, data } = await buildRequest<FilterLabelRoutes["Get"]>({
path: "/filter-label/{listType}",
method: "GET",
params: { listType },
})();
if (!ok) throw new Error(code);
if (!data) throw new Error("No data");
return data;
}

export default function useFilterLabels(listType: string) {
return useQuery({
queryKey: ["filter-label", listType],
queryFn: () => getFilterLabels(listType),
refetchOnWindowFocus: false,
});
}
22 changes: 8 additions & 14 deletions admin/src/scenes/volontaires/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,8 @@ export const getFilterArray = (user, bus, session, classes, etablissements) => {
parentGroup: "Phase 1",
missingLabel: "Non renseigné",
translate: (item) => {
if (item === "N/A" || !classes.length) return item;
const res = classes.find((option) => option._id.toString() === item);
if (!res) return "N/A - Supprimé";
return res?.uniqueKeyAndId;
if (item === "N/A") return item;
return classes[item] || "N/A - Supprimé";
},
},
{
Expand All @@ -193,10 +191,8 @@ export const getFilterArray = (user, bus, session, classes, etablissements) => {
parentGroup: "Phase 1",
missingLabel: "Non renseigné",
translate: (item) => {
if (item === "N/A" || !etablissements.length) return item;
const res = etablissements.find((option) => option._id.toString() === item);
if (!res) return "N/A - Supprimé";
return res?.name;
if (item === "N/A") return item;
return etablissements[item] || "N/A - Supprimé";
},
},
{
Expand All @@ -205,10 +201,8 @@ export const getFilterArray = (user, bus, session, classes, etablissements) => {
parentGroup: "Phase 1",
missingLabel: "Non renseigné",
translate: (item) => {
if (item === "N/A" || !session.length) return item;
const res = session.find((option) => option._id.toString() === item);
if (!res) return "N/A - Supprimé";
return res?.codeCentre;
if (item === "N/A") return item;
return session[item] || "N/A - Supprimé";
},
},
{
Expand Down Expand Up @@ -273,8 +267,8 @@ export const getFilterArray = (user, bus, session, classes, etablissements) => {
parentGroup: "Phase 1",
missingLabel: "Non renseigné",
translate: (item) => {
if (item === "N/A" || !bus?.length) return item;
return bus.find((option) => option._id.toString() === item)?.busId || item;
if (item === "N/A") return item;
return bus[item] || item;
},
},
{
Expand Down
35 changes: 35 additions & 0 deletions api/src/filterLabel/filterLabelController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import Joi from "joi";
import { ERRORS } from "snu-lib";
import passport from "passport";
import express, { Response } from "express";
import { capture } from "../sentry";
import { UserRequest } from "../controllers/request";
import { getLabelVolontaires, listTypes } from "./filterLabelService";

const router = express.Router();

const validator = Joi.string().valid(listTypes.INSCRIPTION, listTypes.VOLONTAIRES).required();

router.get("/:list", passport.authenticate("referent", { session: false, failWithError: true }), GetFilterLabels);

async function GetFilterLabels(req: UserRequest, res: Response) {
try {
const { value, error } = validator.validate(req.params.list);
if (error) {
capture(error);
return res.status(400).send({ ok: false, code: ERRORS.INVALID_PARAMS });
}

if (value === listTypes.VOLONTAIRES) {
const data = await getLabelVolontaires();
return res.status(200).send({ ok: true, data });
}

// TODO: getLabelInscriptions
} catch (error) {
capture(error);
return res.status(500).send({ ok: false, code: ERRORS.SERVER_ERROR });
}
}

module.exports = router;
30 changes: 30 additions & 0 deletions api/src/filterLabel/filterLabelRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ClasseModel, EtablissementModel, LigneBusModel, SessionPhase1Model } from "../models";

function buildPipeline(key: string) {
return [
{ $project: { _id: 1, [key]: 1 } },
{ $group: { _id: null, keyValuePairs: { $push: { k: { $toString: "$_id" }, v: { $toString: `$${key}` } } } } },
{ $replaceRoot: { newRoot: { $arrayToObject: "$keyValuePairs" } } },
];
}

export async function getLigneLabelMap() {
const pipeline = buildPipeline("busId");
const data = await LigneBusModel.aggregate(pipeline);
return data[0];
}
export async function getClasseLabelMap() {
const pipeline = buildPipeline("uniqueKeyAndId");
const data = await ClasseModel.aggregate(pipeline);
return data[0];
}
export async function getEtablissementLabelMap() {
const pipeline = buildPipeline("name");
const data = await EtablissementModel.aggregate(pipeline);
return data[0];
}
export async function getSessionLabelMap() {
const pipeline = buildPipeline("codeCentre");
const data = await SessionPhase1Model.aggregate(pipeline);
return data[0];
}
11 changes: 11 additions & 0 deletions api/src/filterLabel/filterLabelService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { getClasseLabelMap, getEtablissementLabelMap, getLigneLabelMap, getSessionLabelMap } from "./filterLabelRepository";

export const listTypes = { INSCRIPTION: "inscription", VOLONTAIRES: "volontaires" };

export async function getLabelVolontaires() {
const sessions = await getSessionLabelMap();
const bus = await getLigneLabelMap();
const classes = await getClasseLabelMap();
const etablissements = await getEtablissementLabelMap();
return { sessions, bus, classes, etablissements };
}
1 change: 1 addition & 0 deletions api/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export function injectRoutes(app) {
app.use("/SNUpport", require("./controllers/SNUpport"));
app.use("/cle", require("./cle").default);
app.use("/preinscription", require("./preinscription/preinscriptionController"));
app.use("/filter-label", require("./filterLabel/filterLabelController"));

//services
app.use("/jeveuxaider", require("./services/jeveuxaider"));
Expand Down
1 change: 1 addition & 0 deletions packages/lib/src/dto/filterLabelDto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type FilterLabelDto = Record<string, string>;
1 change: 1 addition & 0 deletions packages/lib/src/dto/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export * from "./contactDto";
export * from "./taskDto";
export * from "./phase1";
export * from "./referentiel/ReferentielTaskDto";
export * from "./filterLabelDto";
13 changes: 13 additions & 0 deletions packages/lib/src/routes/filterLabel/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { FilterLabelDto } from "../../dto";
import { BasicRoute, RouteResponseBody } from "..";

interface GetFilterLabelRoute extends BasicRoute {
method: "GET";
path: "/filter-label/{listType}";
params: { listType: string };
response: RouteResponseBody<FilterLabelDto>;
}

export type FilterLabelRoutes = {
Get: GetFilterLabelRoute;
};
1 change: 1 addition & 0 deletions packages/lib/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,6 @@ export type { PreinscriptionRoutes } from "./preinscription";
export type { AffectationRoutes } from "./phase1/affectation";
export type { ReferentielRoutes } from "./referentiel";
export type { ReferentRoutes } from "./iam/referent";
export type { FilterLabelRoutes } from "./filterLabel";

export * from "./phase1";
Loading