import React, {useContext, useEffect, useMemo, useState} from "react"; import SearchBar from "../../SearchBar"; import {toast} from "react-toastify"; import {createElementAlert} from "../../Alert"; import PromotionForm from "../../Forms/PromotionForm"; import {Link} from "react-router-dom"; import {useHistory} from "react-router-dom"; import PromotionApi from "../../../Services/API/PromotionApi"; import {confirmAlert} from "react-confirm-alert"; import {checkUserIsConnectedOnError} from "../../../Services/API/errorsManager"; import {useTranslation} from "react-i18next"; import AddButton from "../../AddButton"; import {usePaginatedFetch} from "../../../Hooks/useFetch"; import Modal from "../../Modal"; import {checkRights} from "../../../Services/Functions/Rights/Rights"; import AtoUserRightsContext from "../../../Context/AtoUserRightsContext"; import LoadingModal from "../../LoadingModal"; import {getIri} from "../../../Services/Functions/functions"; const PromotionRow = ({promotion, onDelete, onEdit}) => { const {atoUserRights} = useContext(AtoUserRightsContext); const {t} = useTranslation("promotionList"); const getStatus = (promotionFormation) => { switch (promotionFormation.status) { case "active": return
{t("En cours")}
; break; case "suspended": return
{t("Suspendue")}
; break; case "archived": return
{t("Archivée")}
; break; } } function handleDelete(e) { e.preventDefault(); confirmAlert({ title: t("Suppression de la promotion {{promotion.name}}", {promotion}), message: t( "Êtes-vous sûr(e) de vouloir supprimer la promotion ? \n Toutes les données seront supprimées. Cette action est irréversible." ), buttons: [ { className: "btnDelete", label: t("Supprimer la promotion"), onClick: () => onDelete(promotion), }, { label: t("Annuler"), }, ], }); } function handleClickEdit(e) { e.preventDefault(); onEdit(promotion); } return ( {(checkRights(atoUserRights, "students:view") && ( {promotion.name} )) || promotion.name} {(promotion?.formation && ( {promotion?.formation.formation.name} )) || {t("Aucune formation")}} {new Date(promotion.createdAt).toLocaleString()} {promotion.students.length} {getStatus(promotion)}
{checkRights(atoUserRights, "students:view") && ( )}
{promotion.status !== 'archived' && ( )}
{" "} {(!promotion.formation || !promotion.formation.formation.hasSession) && promotion.status !== 'archived' ? ( ) : <>}
); }; const PromotionList = ({ato, updateAto, userConnected, isAppAdmin}) => { const {t} = useTranslation("promotionList"); const access = userConnected.appRoles[0].name; /* Load contexts */ const {atoUserRights} = useContext(AtoUserRightsContext); /* States definition */ const [filter, setFilter] = useState(""); const [modalContent, setModalContent] = useState(null); const history = useHistory(); const { loading, load, items: promotionList, setItems: setPromotionList, errors, clearAllErrors, } = usePaginatedFetch(PromotionApi.findByAto(ato.id, true)); // Handlers async function handleSubmitPromotion(promotion) { // Check if promotion name doesn't already exists if (promotionList.find((pl) => pl.name === promotion.name && (getIri(promotion) === null || getIri(promotion) !== getIri(pl)))) { toast.error(t("Une promotion avec ce nom existe déjà")); return; } try { if (promotion["@id"]) { promotion.ato = getIri(promotion.ato); if (!promotion.formation) { delete promotion.formation; } else { promotion.formation = getIri(promotion.formation); } promotion.students = promotion.students.map((s) => getIri(s)); const editedPromotion = await PromotionApi.edit(promotion); const updatedPromotionList = [...promotionList]; updatedPromotionList.splice( updatedPromotionList.findIndex( (searchPromotion) => searchPromotion["@id"] === editedPromotion["@id"] ), 1, editedPromotion ); setPromotionList(updatedPromotionList); toast.success( t("La promotion {{promotion.name}} a bien été modifiée.", { ns: "notification", promotion, }) ); } else { promotion.ato = promotion.ato["@id"]; const newPromotion = await PromotionApi.create(promotion); setPromotionList((prevPromotionList) => [ ...prevPromotionList, ...[newPromotion], ]); toast.success( t("La promotion {{promotion.name}} a bien été créée.", { ns: "notification", promotion, }) ); } setModalContent(null); } catch (e) { toast.error( t("Erreur lors de la création de la promotion.", {ns: "notification"}) ); console.error(e.response); } } function handleClickPromotionCreate(e) { e.preventDefault(); setModalContent(); } function handlePromotionEdit(promotion) { setModalContent( ); } async function handleDeleteClick(promotion) { const promotionListBackUp = [...promotionList]; try { setPromotionList(promotionList.filter((p) => p.id !== promotion.id)); if (await PromotionApi.remove(promotion)) { toast.success( t("La promotion {{promotion.name}} a bien été supprimée.", { promotion, }) ); } } catch (e) { checkUserIsConnectedOnError( history, e, t("Erreur lors de la suppression de la promotion.", { ns: "notification", }) ); setPromotionList(promotionListBackUp); } } // Memoized value const promotionsFilteredList = useMemo(() => { if (filter) { return promotionList.filter((p) => p.name.toLowerCase().includes(filter.toLowerCase()) ); } return promotionList; }, [filter, promotionList]); /* Effects */ useEffect(() => { load(); }, [load]); useEffect(() => { if (access !== 'admin') { if (!checkRights(atoUserRights, 'All users:list')) { toast.error(t('Accès interdit', {ns: 'notification'})); history.goBack(); } } }, [atoUserRights]); /* Check user rights */ // Render return (
{t("Chargement des promotions")} {errors && (

{t("Erreur lors du chargement des promotions")}

{errors["hydra:description"]}

)} {modalContent && ( setModalContent(null)} > {modalContent} )}
{(isAppAdmin || ((checkRights(atoUserRights, 'All users:create') || access === 'admin') && ato.status === 'active')) && (
)}
{(promotionsFilteredList.length > 0 && promotionsFilteredList.sort((a, b) => { // Sort array by Active / Suspended / Archived if (a.status === "active" && b.status !== "active") { return -1 } if (a.status === "suspended" && b.status !== "archived") { return 0; } return 1; }).map((p) => ( ))) || ( )}
{t("Promotion")} {t("Formation rattachée")} {t("Date de création")} {t("Nombre d'élèves")} {t("Statut")} {t("Options")}
{t("Aucune promotion dans votre base.")}
); }; export default PromotionList;