src/Controller/FormationSessionController.php line 334

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Doctrine\Persistence\ManagerRegistry;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use App\Entity\FormationSession;
  11. use App\Entity\FormationSessionMotivation;
  12. use App\Entity\FormationMotivationType;
  13. use App\Entity\FormationSessionDocument;
  14. use App\Entity\FormationType;
  15. use App\Entity\ParametrageTexte;
  16. use App\Entity\Utilisateur;
  17. use App\Entity\UtilisateurInformation;
  18. use App\Entity\Workflow;
  19. use App\Entity\RefRole;
  20. use App\Entity\RefGabarit;
  21. use App\Form\FormationSessionType;
  22. use App\Form\FormationTypeType;
  23. use App\Form\FormationSessionDocumentType;
  24. use App\Form\FormationSessionMotivationType;
  25. use App\Services\AccessRule;
  26. use App\Services\ExportFormation;
  27. use App\Services\Mailer;
  28. use App\Services\GeneratePdf;
  29. use Symfony\Component\Mailer\MailerInterface;
  30. use Symfony\Component\Mime\Email;
  31. use Twig\Environment;
  32. use App\Services\Lib\EmailSHDecision;
  33. use App\Entity\RFederation;
  34. class FormationSessionController extends AbstractController
  35. {
  36.     final public const ERROR_VALIDATION_FORM 'Erreur lors de la validation du formulaire';
  37.     final public const ERROR_OCCURED 'Une erreur est survenue';
  38.     final public const ERROR_FILE 'Fichier introuvable';
  39.     private ManagerRegistry $doctrine;
  40.     private AccessRule $accessRule;
  41.     private ExportFormation $exportFormation;
  42.     private MailerInterface $mailer;
  43.     private GeneratePdf $generatePdf;
  44.     private $twig;
  45.     private  $emailSHDecision;
  46.     public function __construct(ManagerRegistry $doctrineAccessRule $accessRuleExportFormation $exportFormationMailerInterface $mailerEnvironment $twigGeneratePdf $generatePdfEmailSHDecision $emailSHDecision)
  47.     {
  48.         $this->doctrine $doctrine;
  49.         $this->accessRule $accessRule;
  50.         $this->exportFormation $exportFormation;
  51.         $this->mailer $mailer;
  52.         $this->generatePdf $generatePdf;
  53.         $this->twig $twig;
  54.         $this->emailSHDecision $emailSHDecision;
  55.     }
  56.     private function arrayOfElement($fs)
  57.     {
  58.         $data = [];
  59.         if (isset($fs) && !empty($fs)) {
  60.             $data = [
  61.                 'id' => isset($fs['id_formation_session']) ? $fs['id_formation_session'] : "",
  62.                 'id_utilisateur' => isset($fs['id_utilisateur']) ? $fs['id_utilisateur'] : "",
  63.                 'civilite' => isset($fs['civilite']) ? $fs['civilite'] : "",
  64.                 'nom' => isset($fs['nom']) ? $fs['nom'] : "",
  65.                 'prenom' => isset($fs['prenom']) ? $fs['prenom'] : "",
  66.                 'affectation_id' => isset($fs['affectation_id']) ? $fs['affectation_id'] : "",
  67.                 'libelle_affectation' => isset($fs['libelle_affectation']) ? $fs['libelle_affectation'] : "",
  68.                 'id_federation' => isset($fs['id_federation']) ? $fs['id_federation'] : "",
  69.                 'r_ser_libl' => isset($fs['r_ser_libl']) ? $fs['r_ser_libl'] : "",
  70.                 'libelle_poste' => isset($fs['libelle_poste']) ? $fs['libelle_poste'] : "",
  71.                 'titre' => isset($fs['titre']) ? $fs['titre'] : "",
  72.                 'libelle_organisme' => isset($fs['libelle_organisme']) ? $fs['libelle_organisme'] : "",
  73.                 'titre_session' => isset($fs['titre_session']) ? $fs['titre_session'] : "",
  74.                 'type_formation' => isset($fs['libelle_formation']) ? $fs['libelle_formation'] : "",
  75.                 'id_formation_type' => isset($fs['id_formation_type']) ? $fs['id_formation_type'] : "",
  76.                 'id_workflow' => isset($fs['id_workflow']) ? $fs['id_workflow'] : "",
  77.                 'libelle_action' => isset($fs['libelle_action']) ? $fs['libelle_action'] : "",
  78.                 'date_debut' => isset($fs['date_debut']) ? $fs['date_debut'] : "",
  79.                 'date_fin' => isset($fs['date_fin']) ? $fs['date_fin'] : "",
  80.                 'nb_jours' => isset($fs['nb_jours']) ? $fs['nb_jours'] : "",
  81.                 'avis_dtn' => isset($fs['avis_dtn']) ? $fs['avis_dtn'] : "",
  82.                 'avis_sh' => isset($fs['avis_sh']) ? $fs['avis_sh'] : "",
  83.                 'lieu_formation' => isset($fs['lieu_formation']) ? $fs['lieu_formation'] : "",
  84.                 'responsable' => [
  85.                     'nom_responsable' => isset($fs['nom_responsable']) ? $fs['nom_responsable'] : "",
  86.                     'mail_responsable' => isset($fs['mail_responsable']) ? $fs['mail_responsable'] : "",
  87.                     'telephone_responsable' => isset($fs['telephone_responsable']) ? $fs['telephone_responsable'] : "",
  88.                 ],
  89.                 'presentation' => isset($fs['presentation']) ? $fs['presentation'] : "",
  90.                 'lien' => isset($fs['lien']) ? $fs['lien'] : "",
  91.                 'certification' => isset($fs['certification']) ? $fs['certification'] : null,
  92.                 'commentaire_dtn' => isset($fs['commentaire_dtn']) ? $fs['commentaire_dtn'] : "",
  93.                 'commentaire_sh' => isset($fs['commentaire_sh']) ? $fs['commentaire_sh'] : "",
  94.                 'date_avis_dtn' => isset($fs['date_avis_dtn']) ? $fs['date_avis_dtn'] : "",
  95.                 'date_sgn_sh' => isset($fs['date_sgn_sh']) ? $fs['date_sgn_sh'] : "",
  96.             ];
  97.         }
  98.         return $data;
  99.     }
  100.     private function fillSessions($sessions$sessions_motivations$number_of_motivation_types)
  101.     {
  102.         $toFill = [];
  103.         $accents = ['é' => 'e'];
  104.         if (isset($sessions) && !empty($sessions)) {
  105.             for ($i 0$i < (is_countable($sessions) ? count($sessions) : 0); $i++) {
  106.                 $motivations_array = [];
  107.                 if (!empty($sessions_motivations) && isset($sessions_motivations[$i])) {
  108.                     for (
  109.                         $j $i $number_of_motivation_types;
  110.                         $j $i $number_of_motivation_types $number_of_motivation_types && $j count($sessions_motivations);
  111.                         $j++
  112.                     ) {
  113.                         $motivation $sessions_motivations[$j];
  114.                         $libelle_motivation strtr(
  115.                             strtolower(str_replace(' ''_', (string) $motivation['libelle_motivation'])),
  116.                             $accents
  117.                         );
  118.                         $motivations_array[$libelle_motivation] = $motivation['valeur'];
  119.                     }
  120.                 }
  121.                 $session $this->arrayOfElement($sessions[$i]);
  122.                 $session['motivation'] = $motivations_array;
  123.                 $toFill[] = $session;
  124.             }
  125.         }
  126.         return $toFill;
  127.     }
  128.     /**
  129.      * @return JsonResponse
  130.      */
  131.     #[Route(path'/api/modifier-formation-types/{id}'name'ctsweb_modifier_formation_types')]
  132.     public function modifierFormationTypes(Request $requestFormationType $formationtype)
  133.     {
  134.         $form $this->handleRequestType($request$formationtype'all''post');
  135.         if ($form->isSubmitted() && $form->isValid()) {
  136.             $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  137.             $libelle $data['libelle'];
  138.             $code $data['code'];
  139.             if (empty($data['libelle'])) {
  140.                 $result = ['success' => false'info' => 'Le champ libellé est obligatoire.'];
  141.                 $status JsonResponse::HTTP_OK;
  142.             } elseif (empty($data['code'])) {
  143.                 $result = ['success' => false'info' => 'Le champ code est obligatoire.'];
  144.                 $status JsonResponse::HTTP_OK;
  145.             } else {
  146.                 $formationtype->setLibelleFormation($libelle);
  147.                 $formationtype->setCode($code);
  148.                 $entityManager $this->doctrine->getManager();
  149.                 $entityManager->persist($formationtype);
  150.                 $entityManager->flush();
  151.                 $result = ['success' => true];
  152.                 $status JsonResponse::HTTP_OK;
  153.             }
  154.         } else {
  155.             $result = [
  156.                 'success' => false,
  157.                 'data' => self::ERROR_VALIDATION_FORM,
  158.                 'error' => (string) $form->getErrors(truefalse)
  159.             ];
  160.             $status JsonResponse::HTTP_BAD_REQUEST;
  161.         }
  162.         return new JsonResponse($result$status);
  163.     }
  164.     #[Route(path'/api/supprimer_type_formation/{id}'name'ctsweb_formations_supprimer_type_formation')]
  165.     public function supprimerTypeFormation(Request $requestFormationType $formationType)
  166.     {
  167.         try {
  168.             // $form = $this->handleRequestType($request, $formationType, 'all', 'post');
  169.             $em $this->doctrine->getManager();
  170.             $repository $em->getRepository(FormationType::class);
  171.             $cg $repository->countFormationTypeId($formationType->getIdFormationType());
  172.             if (count($cg) > 0) {
  173.                 $data = ['success' => false'data' => 'Ce type de formation est déjà utilisé. Il ne peut être supprimé'];
  174.                 return new JsonResponse($data);
  175.             } else {
  176.                 $repository->deleteFormationType($formationType->getIdFormationType());
  177.                 $data = ['success' => true'data' => 'Le Type a été supprimé'];
  178.                 return new JsonResponse($data);
  179.             }
  180.         } catch (\Exception $e) {
  181.             $data = ['success' => false'data' => $e->getMessage()];
  182.             return new JsonResponse($data);
  183.         }
  184.     }
  185.     /* Assertions for the function that get the formations:
  186.        - Let n = the number of formation types 
  187.        For each formation session, there are n formation types
  188.        - Results not involving motivations are sorted by id_formation_session DESC
  189.        - Results involving motivations are sorted by id_formation_motivation ASC
  190.        These assertions are fairly easy to preserve, but breaking any of these assertion will break
  191.        the algorithm. It was written this way to prevent doing a query to the database when
  192.        getting motivations for each formation session since they are in another table.
  193.        */
  194.     #[Route(path'/api/create-FormationType/'name'ctsweb_formations_creer_types_formation')]
  195.     public function createFormationType(Request $request)
  196.     {
  197.         $formationtype = new FormationType();
  198.         $form $this->handleRequestType($request$formationtype'all''post');
  199.         try {
  200.             if ($form->isSubmitted() && $form->isValid()) {
  201.                 $entityManager $this->doctrine->getManager();
  202.                 $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  203.                 $libelle $data['libelle'] ?? null;
  204.                 $code $data['code'] ?? null;
  205.                 if (!$libelle) {
  206.                     return new JsonResponse(
  207.                         ['success' => false'info' => 'Le champ libellé est obligatoire.'],
  208.                         JsonResponse::HTTP_OK
  209.                     );
  210.                 }
  211.                 if (!$code) {
  212.                     return new JsonResponse(
  213.                         ['success' => false'info' => 'Le champ code est obligatoire.'],
  214.                         JsonResponse::HTTP_OK
  215.                     );
  216.                 }
  217.                 $formationtype->setLibelleFormation($libelle);
  218.                 $formationtype->setCode($code);
  219.                 $entityManager->persist($formationtype);
  220.                 $entityManager->flush();
  221.                 return new JsonResponse(
  222.                     [
  223.                         'success' => true,
  224.                         'Formation' => $formationtype->getIdFormationType()
  225.                     ],
  226.                     JsonResponse::HTTP_CREATED
  227.                 );
  228.             } else {
  229.                 $result = [
  230.                     'success' => false,
  231.                     'data' => self::ERROR_VALIDATION_FORM,
  232.                     'error' => (string) $form->getErrors(truefalse)
  233.                 ];
  234.             }
  235.         } catch (\Exception $e) {
  236.             // echo $e->getMessage();
  237.             $result = [
  238.                 'success' => false,
  239.                 'data' => self::ERROR_OCCURED
  240.             ];
  241.         }
  242.         return new JsonResponse($resultJsonResponse::HTTP_BAD_REQUEST);
  243.     }
  244.     #[Route(path'/api/get_liste_types_formation'name'ctsweb_formations_liste_types_formation')]
  245.     public function getListeTypesFormation()
  246.     {
  247.         $em $this->doctrine->getManager();
  248.         $getListeTypesFormation $em->getRepository(FormationType::class)
  249.             ->getSessionFormationType();
  250.         return new JsonResponse(['success' => true'data' => $getListeTypesFormation]);
  251.     }
  252.     #[Route(path'/api/liste_formation_en_ecriture'name'ctsweb_mes_formations_en_attente')]
  253.     public function mesFormationsEnAttente()
  254.     {
  255.         $em $this->doctrine->getManager();
  256.         $user $this->getUser();
  257.         $number_of_motivation_types 0;
  258.         $types $em->getRepository(FormationMotivationType::class)->getNumberOfTypes();
  259.         if (!empty($types) && isset($types[0]['count'])) {
  260.             $number_of_motivation_types $types[0]['count'];
  261.         }
  262.         $id_user $user->getIdUtilisateur();
  263.         $pending_filter $em->getRepository(FormationSession::class)
  264.             ->getPendingFilter();
  265.         $pending_sessions $em->getRepository(FormationSession::class)
  266.             ->getSessionsOfUserWithWorkflow($id_user$pending_filter);
  267.         $pending_sessions_motivations $em->getRepository(FormationSession::class)
  268.             ->getMotivationsOfUserSessionsWithWorkflow($id_user$pending_filter);
  269.         $pending $this->fillSessions(
  270.             $pending_sessions,
  271.             $pending_sessions_motivations,
  272.             $number_of_motivation_types
  273.         );
  274.         return new JsonResponse(['success' => true'data' => $pending]);
  275.     }
  276.     #[Route(path'/api/mes_formations_en_cours'name'ctsweb_mes_formations_en_cours')]
  277.     public function mesFormationsEnCours()
  278.     {
  279.         $em $this->doctrine->getManager();
  280.         $user $this->getUser();
  281.         $number_of_motivation_types $em->getRepository(FormationMotivationType::class)
  282.             ->getNumberOfTypes()[0]['count'];
  283.         $id_user $user->getIdUtilisateur();
  284.         $ongoing_filter $em->getRepository(FormationSession::class)
  285.             ->getOngoingFilter();
  286.         $ongoing_sessions $em->getRepository(FormationSession::class)
  287.             ->getSessionsOfUserWithWorkflow($id_user$ongoing_filter);
  288.         $ongoing_sessions_motivations $em->getRepository(FormationSession::class)
  289.             ->getMotivationsOfUserSessionsWithWorkflow($id_user$ongoing_filter);
  290.         $ongoing $this->fillSessions(
  291.             $ongoing_sessions,
  292.             $ongoing_sessions_motivations,
  293.             $number_of_motivation_types
  294.         );
  295.         return new JsonResponse(['success' => true'data' => $ongoing]);
  296.     }
  297.     #[Route(path'/api/liste_formation_enAttente'name'ctsweb_formations_en_attente')]
  298.     public function formationsEnAttente()
  299.     {
  300.         $pending_sessions null;
  301.         $pending_sessions_motivations null;
  302.         $em $this->doctrine->getManager();
  303.         $user $this->getUser();
  304.         $number_of_motivation_types $em->getRepository(FormationMotivationType::class)
  305.             ->getNumberOfTypes()[0]['count'];
  306.         $id_role $user->getUtilisateur()->getIdRole();
  307.         $id_affectation $user->getIdAffectation() == null $user->getIdAffectation()->getIdAffectation();
  308.         $id_federation $user->getIdFederation() == null null $user->getIdFederation()->getIdFederation();
  309.         $pending_filter $em->getRepository(FormationSession::class)
  310.             ->getPendingFilter();
  311.         switch ($id_role) {
  312.             case RefRole::ROLE_FEDE:
  313.             case RefRole::ROLE_FEDE_INVITE:
  314.                 $pending_sessions =
  315.                     $em->getRepository(FormationSession::class)
  316.                     ->getSessionsOfFederationWithWorkflow($id_federation$pending_filter);
  317.                 $pending_sessions_motivations =
  318.                     $em->getRepository(FormationSession::class)
  319.                     ->getMotivationsOfFederationSessionsWithWorkflow($id_federation$pending_filter);
  320.                 break;
  321.             case RefRole::ROLE_DR:
  322.             case RefRole::ROLE_DR_SIGNATAIRE:
  323.                 $pending_sessions =
  324.                     $em->getRepository(FormationSession::class)
  325.                     ->getSessionsOfAffectationWithWorkflow($id_affectation$pending_filter);
  326.                 $pending_sessions_motivations =
  327.                     $em->getRepository(FormationSession::class)
  328.                     ->getMotivationsOfAffectationSessionsWithWorkflow($id_affectation$pending_filter);
  329.                 break;
  330.             case RefRole::ROLE_DS_ADMIN:
  331.             case RefRole::ROLE_DS_INVITE:
  332.             case RefRole::ROLE_DS_SIGNATAIRE:
  333.             case RefRole::ROLE_LECTEUR:
  334.                 $pending_sessions =
  335.                     $em->getRepository(FormationSession::class)
  336.                     ->getSessionsWithWorkflow($pending_filter);
  337.                 $pending_sessions_motivations =
  338.                     $em->getRepository(FormationSession::class)
  339.                     ->getMotivationsOfSessionsWithWorkflow($pending_filter);
  340.                 break;
  341.         }
  342.         $pending $this->fillSessions(
  343.             $pending_sessions,
  344.             $pending_sessions_motivations,
  345.             $number_of_motivation_types
  346.         );
  347.         return new JsonResponse(['success' => true'data' => $pending]);
  348.     }
  349.     #[Route(path'/api/liste_formation_enCours'name'ctsweb_formations_en_cours')]
  350.     public function formationsEnCours()
  351.     {
  352.         $ongoing_sessions null;
  353.         $ongoing_sessions_motivations null;
  354.         $em $this->doctrine->getManager();
  355.         $user $this->getUser();
  356.         $number_of_motivation_types $em->getRepository(FormationMotivationType::class)
  357.             ->getNumberOfTypes()[0]['count'];
  358.         $id_role $user->getUtilisateur()->getIdRole();
  359.         $id_affectation $user->getIdAffectation() == null $user->getIdAffectation()->getIdAffectation();
  360.         $id_federation $user->getIdFederation() == null null $user->getIdFederation()->getIdFederation();
  361.         $ongoing_filter $em->getRepository(FormationSession::class)
  362.             ->getOngoingFilter();
  363.         switch ($id_role) {
  364.             case RefRole::ROLE_FEDE:
  365.             case RefRole::ROLE_FEDE_INVITE:
  366.                 $ongoing_sessions =
  367.                     $em->getRepository(FormationSession::class)
  368.                     ->getSessionsOfFederationWithWorkflow($id_federation$ongoing_filter);
  369.                 $ongoing_sessions_motivations =
  370.                     $em->getRepository(FormationSession::class)
  371.                     ->getMotivationsOfFederationSessionsWithWorkflow($id_federation$ongoing_filter);
  372.                 break;
  373.             case RefRole::ROLE_DR:
  374.             case RefRole::ROLE_DR_SIGNATAIRE:
  375.                 $ongoing_sessions =
  376.                     $em->getRepository(FormationSession::class)
  377.                     ->getSessionsOfAffectationWithWorkflow($id_affectation$ongoing_filter);
  378.                 $ongoing_sessions_motivations =
  379.                     $em->getRepository(FormationSession::class)
  380.                     ->getMotivationsOfAffectationSessionsWithWorkflow($id_affectation$ongoing_filter);
  381.                 break;
  382.             case RefRole::ROLE_DS_ADMIN:
  383.             case RefRole::ROLE_DS_INVITE:
  384.             case RefRole::ROLE_DS_SIGNATAIRE:
  385.             case RefRole::ROLE_LECTEUR:
  386.                 $ongoing_sessions =
  387.                     $em->getRepository(FormationSession::class)
  388.                     ->getSessionsWithWorkflow($ongoing_filter);
  389.                 $ongoing_sessions_motivations =
  390.                     $em->getRepository(FormationSession::class)
  391.                     ->getMotivationsOfSessionsWithWorkflow($ongoing_filter);
  392.                 break;
  393.         }
  394.         $ongoing $this->fillSessions(
  395.             $ongoing_sessions,
  396.             $ongoing_sessions_motivations,
  397.             $number_of_motivation_types
  398.         );
  399.         return new JsonResponse(['success' => true'data' => $ongoing]);
  400.     }
  401.     #[Route(path'/api/formation/consulter/{id}'name'ctsweb_consulter_formation')]
  402.     public function consulter(FormationSession $sessionFormation)
  403.     {
  404.         $data = [];
  405.         $dataMotivation = [];
  406.         $idFormationSession $sessionFormation->getIdFormationSession();
  407.         $em $this->doctrine->getManager();
  408.         $listeDocuments $em->getRepository(FormationSessionDocument::class)->getDocumentBySessionFormation($idFormationSession);
  409.         $motivations $em->getRepository(FormationSessionMotivation::class)->getMotivationsBySessionFormation($idFormationSession);
  410.         $formations $em->getRepository(FormationSession::class)->getSessionFormation($idFormationSession);
  411.         $workflow_filter " fs.id_workflow =" $formations[0]['id_workflow'];
  412.         $data['user'] = $em->getRepository(FormationSession::class)->getSessionsOfUserWithWorkflow($sessionFormation->getIdUtilisateur()->getIdUtilisateur(), $workflow_filter);
  413.         $data['user']['0']['telephonePortable'] = isset($data['user']['0']['telephoneportable']) ? $data['user']['0']['telephoneportable'] : "";
  414.         foreach ($motivations as $motivation) {
  415.             $dataMotivation[$motivation['id_formation_motivation']] = $motivation['valeur'];
  416.         }
  417.         try {
  418.             if ($sessionFormation instanceof FormationSession) {
  419.                 $data[] = [
  420.                     "id" => $sessionFormation->getIdFormationSession(),
  421.                     "id_utilisateur" => $sessionFormation->getIdUtilisateur()->getIdUtilisateur(),
  422.                     "organisme_formation" => $sessionFormation->getLibelleOrganisme(),
  423.                     "titre" => $sessionFormation->getTitre(),
  424.                     "titre_session" => $sessionFormation->getTitreSession(),
  425.                     "certification" => $sessionFormation->getCertification(),
  426.                     "libelle_formation" => $sessionFormation->getLibelleFormation(),
  427.                     "id_formation_type" => $formations[0]['id_formation_type'],
  428.                     "nb_jours" => $sessionFormation->getNbJours(),
  429.                     "avis_dtn" => $sessionFormation->getAvisDtn(),
  430.                     "avis_sh" => $sessionFormation->getAvisSh(),
  431.                     "presentation_formation" => $sessionFormation->getPresentation(),
  432.                     "id_workflow" => $formations[0]['id_workflow'],
  433.                     "date_debut" => $sessionFormation->getDateDebut(),
  434.                     "date_fin" => $sessionFormation->getDateFin(),
  435.                     "lien_formation" => $sessionFormation->getLienFormation(),
  436.                     "liste_documents" => (isset($listeDocuments[0]['liste_documents']) && !empty($listeDocuments[0]['liste_documents'])) ? json_decode((string) $listeDocuments[0]['liste_documents'], true512JSON_THROW_ON_ERROR) : [],
  437.                     "lieuFormation" => $sessionFormation->getLieuFormation(),
  438.                     "responsable" => ["nom_prenom" => $sessionFormation->getPrenomResponsable() . " " $sessionFormation->getNomResponsable(), "mail" => $sessionFormation->getMailResponsable(), "tel" => $sessionFormation->getTelephoneResponsable()],
  439.                     "motivation" => $this->tab_motivation($dataMotivation),
  440.                     'commentaire_dtn' => $sessionFormation->getCommentaireDtn(),
  441.                     'commentaire_sh' =>  $sessionFormation->getCommentaireSh(),
  442.                     'date_avis_dtn' =>  $sessionFormation->getDateAvisDtn(),
  443.                     'date_sgn_sh' =>  $sessionFormation->getDateSgnSh(),
  444.                 ];
  445.                 // -idFormationSession: 1
  446.                 // -idFormationType: FormationType {#2099 ▶}
  447.                 // -idUtilisateur: Utilisateur {#2098 ▶}
  448.                 // -idWorkflow: Workflow {#2127 ▶}
  449.                 // -titre: null
  450.                 // -dateDebut: DateTime @1661990400 {#2079 ▶}
  451.                 // -dateFin: DateTime @1662163200 {#2080 ▶}
  452.                 // -libelleOrganisme: "IPOS"
  453.                 // -lien: null
  454.                 // -nbJours: 3
  455.                 // -avisDtn: true
  456.                 // -avisSh: null
  457.                 // -lieuFormation: "Roubaix"
  458.                 // -nomResponsable: "Gilbert"
  459.                 // -prenomResponsable: "Coco"
  460.                 // -mailResponsable: "coco@gilbert.com"
  461.                 // -telephoneResponsable: "0612345678"
  462.                 // $data[] = array(
  463.                 //     "idEvenement" => $idEvenement,
  464.                 //     "idWorkflow" => $odm->getWorkflow()->getIdWorkflow(),
  465.                 //     "dateDebut" => $dateDebut,
  466.                 //     "dateFin" => $dateFin,
  467.                 //     "ville" => $ville,
  468.                 //     "pays" => $pays->getIdPays(),
  469.                 //     "paysLibelle" => $pays->getLibellePays(),
  470.                 //     "euro" => $pays->getUnionEuropeenne(),
  471.                 //     "motif" => $motif,
  472.                 //     "statut" => $statut,
  473.                 //     "espace_libre_DTN" => $odm->getespace_libre_DTN(),
  474.                 //     "espace_libre_HS" => $odm->getespace_libre_SH(),
  475.                 //     "avisdtn" => $avisdtn,
  476.                 //     "organisme" => $organisme,
  477.                 //     "avisDefaut" => $avisDefaut,
  478.                 //     "modifyOrDeleteEvent" => ($modifyOrDeleteEvent) ? $modifyOrDeleteEvent : false,
  479.                 //     "idUtilisateur" => $user->getIdUtilisateur(),
  480.                 //     "courrielUtilisateur" => $user->getCourriel(),
  481.                 //     "adresseUtilisateur" => $userInformation->getAdresse(),
  482.                 //     "prenomNomUtilisateur" => $prenomNomagent,
  483.                 //     "libellePoste"=> $userInformation->getIdPoste()->getLibellePoste()
  484.                 // );
  485.             }
  486.             $result = ['success' => true'data' => $data];
  487.         } catch (\Exception $e) {
  488.             $result = ['success' => false'data' => $e->getMessage()];
  489.         }
  490.         return new JsonResponse($result);
  491.     }
  492.     #[Route(path'/api/formation/modifier/{id}'name'ctsweb_modifier_formation')]
  493.     public function modifierFormation(Request $requestFormationSession $formation)
  494.     {
  495.     // Utilisez la méthode 'json' pour renvoyer une réponse JSON avec les données que vous voulez déboguer
  496.     
  497.         $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  498.         $id_role $this->getUser()->getUtilisateur()->getIdRole();
  499.         $em $this->doctrine->getManager();
  500.         if (($id_role == RefRole::ROLE_DR || $id_role == RefRole::ROLE_DR_SIGNATAIRE)) {
  501.             if (!is_null($data['increment_workflow']) && $data['increment_workflow'] == true && $data['avis_sh'] == true) {
  502.                 $workflow $em->getRepository(Workflow::class)->find(Workflow::FO_SIGNE);
  503.                 $formation->setAvisSh(true);
  504.                 $formation->setIdWorkflow($workflow);
  505.             } elseif ($data['avis_sh'] == false) {
  506.                 $workflow $em->getRepository(Workflow::class)->find(Workflow::FO_REFUSE);
  507.                 $formation->setAvisSh(false);
  508.                 $formation->setIdWorkflow($workflow);
  509.             }
  510.             if (isset($data['commentaire_sh'])) {
  511.                 $formation->setCommentaireSh($data['commentaire_sh']);
  512.             }
  513.             if (isset($data['date_debut'])) {
  514.                 $newDateDebut date_create_from_format("Y-m-d"$data['date_debut']);
  515.                 $formation->setDateDebut($newDateDebut);
  516.             }
  517.             if (isset($data['date_fin'])) {
  518.                 $newDateFin date_create_from_format("Y-m-d"$data['date_fin']);
  519.                 $formation->setDateFin($newDateFin);
  520.             }
  521.             $formation->setDateSgnSh(new \DateTime());
  522.             // Appel function update document
  523.             $this->updateDocument($formation$request);
  524.             $em->persist($formation);
  525.             $em->flush();
  526.             // Appel signature
  527.             $this->initSignatureFormations($formation->getIdFormationSession(), $workflow->getIdWorkflow());
  528.             $result = ['success' => true];
  529.             $status JsonResponse::HTTP_OK;
  530.             return new JsonResponse($result$status);
  531.         }
  532.         // AVISDTN
  533.         elseif (($id_role == RefRole::ROLE_FEDE || $id_role == RefRole::ROLE_FEDE_INVITE)) {
  534.             if (!is_null($data['avis_dtn']) && $data['avis_dtn'] == true) {
  535.                 $formation->setAvisDtn(true);
  536.             } else {
  537.                 $formation->setAvisDtn(false);
  538.             }
  539.             if (isset($data['commentaire_dtn'])) {
  540.                 $formation->setCommentaireDtn($data['commentaire_dtn']);
  541.             }
  542.             if (isset($data['date_debut'])) {
  543.                 $newDateDebut date_create_from_format("Y-m-d"$data['date_debut']);
  544.                 $formation->setDateDebut($newDateDebut);
  545.             }
  546.             if (isset($data['date_fin'])) {
  547.                 $newDateFin date_create_from_format("Y-m-d"$data['date_fin']);
  548.                 $formation->setDateFin($newDateFin);
  549.             }
  550.             $formation->setDateAvisDtn(new \DateTime());
  551.             $formation->setSignataireValidationfonctionelle($this->getUser()->getUtilisateur()->getIdUtilisateur());
  552.             // Appel function update document
  553.             $this->updateDocument($formation$request);
  554.             if (($formation->getIdUtilisateur()->getRole()->getIdRole() == RefRole::ROLE_FEDE || $formation->getIdUtilisateur()->getRole()->getIdRole() == RefRole::ROLE_FEDE_INVITE) && (is_null($data['is_gerer_formation']) || $data['is_gerer_formation'] == false)) {
  555.                 $form $this->handleRequest($request$formation'all''post');
  556.                 $repository $em->getRepository(FormationType::class);
  557.                 $formationType $repository->findOneBy(['idFormationType' => (int) $formation->getIdFormationType()]);
  558.                 $formation->setIdFormationType($formationType);
  559.                 $idFormationSession $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
  560.                 $this->updateMotivation($data$idFormationSession);
  561.             }
  562.             $em->persist($formation);
  563.             $em->flush();
  564.             $result = ['success' => true];
  565.             $status JsonResponse::HTTP_OK;
  566.             return new JsonResponse($result$status);
  567.         } elseif (($id_role == RefRole::ROLE_DS_ADMIN || $id_role == RefRole::ROLE_DS_SIGNATAIRE || $id_role == RefRole::ROLE_DS_INVITE)) {
  568.             if (!is_null($data['avis_dtn']) && $data['avis_dtn'] == true) {
  569.                 $formation->setAvisDtn(true);
  570.             } elseif ($data['avis_dtn'] == false && !is_null($data['avis_dtn'])) {
  571.                 $formation->setAvisDtn(false);
  572.             }
  573.             if (!is_null($data['increment_workflow']) && $data['increment_workflow'] == true) {
  574.                 if (!is_null($data['avis_sh']) && $data['avis_sh'] == true) {
  575.                     $workflow $em->getRepository(Workflow::class)->find(Workflow::FO_SIGNE);
  576.                     $formation->setAvisSh(true);
  577.                     $formation->setIdWorkflow($workflow);
  578.                     // Appel signature
  579.                 } elseif ($data['avis_sh'] == false && !is_null($data['avis_sh'])) {
  580.                     $workflow $em->getRepository(Workflow::class)->find(Workflow::FO_REFUSE);
  581.                     $formation->setAvisSh(false);
  582.                     $formation->setIdWorkflow($workflow);
  583.                 }
  584.                 $formation->setDateSgnSh(new \DateTime());
  585.                 // Appel function update document
  586.                 $this->updateDocument($formation$request);
  587.                 $em->persist($formation);
  588.                 $em->flush();
  589.                 // Appel signature
  590.                 $this->initSignatureFormations($formation->getIdFormationSession(), $workflow->getIdWorkflow());
  591.                 $result = ['success' => true];
  592.                 $status JsonResponse::HTTP_OK;
  593.                 return new JsonResponse($result$status);
  594.             }
  595.             $em->persist($formation);
  596.             $em->flush();
  597.             $result = ['success' => true];
  598.             $status JsonResponse::HTTP_OK;
  599.             return new JsonResponse($result$status);
  600.         }
  601.         $form $this->handleRequest($request$formation'all''post');
  602.         $em $this->doctrine->getManager();
  603.         $repository $em->getRepository(FormationSession::class);
  604.         if ($form->isSubmitted() && $form->isValid()) {
  605.             $em $this->doctrine->getManager();
  606.             if (($id_role == RefRole::ROLE_CTS)) {
  607.                 if (Workflow::FO_SIGNE == $formation->getIdWorkflow()->getIdWorkflow() || Workflow::FO_REFUSE == $formation->getIdWorkflow()->getIdWorkflow()) {
  608.                     $workflow $em->getRepository(Workflow::class)->find($formation->getIdWorkflow()->getIdWorkflow());
  609.                     $formation->setIdWorkflow($workflow);
  610.                 } else {
  611.                     $workflow $em->getRepository(Workflow::class)->find(Workflow::FO_EN_ATTENTE_DE_VALIDATION);
  612.                     $formation->setIdWorkflow($workflow);
  613.                 }
  614.             }
  615.             $entityManager $this->doctrine->getManager();
  616.             if (!$repository->check_datedebutfin($formation)) {
  617.                 $result = [
  618.                     'success' => false,
  619.                     'error' => 'Date de fin de la formation doit être supérieure ou égale à la date début de formation '
  620.                 ];
  621.                 return new JsonResponse($resultJsonResponse::HTTP_OK);
  622.             }
  623.             $repository $em->getRepository(FormationType::class);
  624.             $formationType $repository->findOneBy(['idFormationType' => (int) $formation->getIdFormationType()]);
  625.             $formation->setIdFormationType($formationType);
  626.             $entityManager->persist($formation);
  627.             $entityManager->flush();
  628.             // Document
  629.             $document = new FormationSessionDocument();
  630.             $form $this->handleRequestdocument($request$document'all''post');
  631.             $idFormationSession $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
  632.             $document->setIdFormationSessionDocument($idFormationSession);
  633.             $listeDocuments $em->getRepository(FormationSessionDocument::class)->getDocumentBySessionFormation($formation->getIdFormationSession());
  634.             if ($listeDocuments && (is_countable($listeDocuments) ? count($listeDocuments) : 0) > 0) {
  635.                 $document->setIdDocumentFormation($listeDocuments[0]['id_document_formation']);
  636.             }
  637.             $entityDocument $this->doctrine->getManager();
  638.             $document->setLien($document->getLien());
  639.             $entityDocument->merge($document);
  640.             $entityDocument->flush();
  641.             $this->updateMotivation($data$idFormationSession);
  642.             $result = ['success' => true];
  643.             $status JsonResponse::HTTP_OK;
  644.         } else {
  645.             $result = [
  646.                 'success' => false,
  647.                 'data' => self::ERROR_VALIDATION_FORM,
  648.                 'error' => (string) $form->getErrors(truefalse)
  649.             ];
  650.             $status JsonResponse::HTTP_BAD_REQUEST;
  651.         }
  652.         return new JsonResponse($result$status);
  653.     }
  654.     public function updateDocument($formation$request)
  655.     {
  656.         $em $this->doctrine->getManager();
  657.         $document = new FormationSessionDocument();
  658.         $form $this->handleRequestdocument($request$document'all''post');
  659.         $idFormationSession $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
  660.         $document->setIdFormationSessionDocument($idFormationSession);
  661.         $listeDocuments $em->getRepository(FormationSessionDocument::class)->getDocumentBySessionFormation($formation->getIdFormationSession());
  662.         if ($listeDocuments && (is_countable($listeDocuments) ? count($listeDocuments) : 0) > 0) {
  663.             $document->setIdDocumentFormation($listeDocuments[0]['id_document_formation']);
  664.         }
  665.         $entityDocument $this->doctrine->getManager();
  666.         $document->setLien($document->getLien());
  667.         $entityDocument->merge($document);
  668.         $entityDocument->flush();
  669.     }
  670.     public function updateMotivation($data$idFormationSession)
  671.     {
  672.         $em $this->doctrine->getManager();
  673.         // $data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
  674.         $datamotivation $this->motivations($data);
  675.         foreach ($datamotivation as $motiv) {
  676.             $motivation = new FormationSessionMotivation();
  677.             $idformationmotivationType $em->getRepository(FormationMotivationType::class)->findOneBy(['idFormationMotivation' => $motiv]);
  678.             $motivation->setIdFormationMotivation($idformationmotivationType);
  679.             $motivation->setIdFormationSession($idFormationSession);
  680.             $valeur TRUE;
  681.             $motivation->setValeur($valeur);
  682.             $entitymotivation $this->doctrine->getManager();
  683.             $entitymotivation->persist($motivation);
  684.             $entitymotivation->flush();
  685.         }
  686.     }
  687.     public function tab_motivation($motivations)
  688.     {
  689.         $motivation_array = ['1' => "formation_professionelle"'2' => "adaptation_immediate"'3' => "adaptation_previsible"'4' => "developement_qualification"];
  690.         foreach ($motivation_array as $v => $value) {
  691.             if (isset($motivations[$v])) {
  692.                 $data[$value] = true;
  693.             } else
  694.                 $data[$value] = false;
  695.         }
  696.         return $data;
  697.     }
  698.     #[Route(path'/api/fs/{id}'name'api_fs_delete')]
  699.     public function delete(Request $requestFormationSession $formationSession)
  700.     {
  701.         $em null;
  702.         $formation null;
  703.         $entitymotivation null;
  704.         try {
  705.             $form $this->createDeleteForm($formationSession);
  706.             $form->handleRequest($request);
  707.             if ($form->isSubmitted() && $form->isValid()) {
  708.                 $accessRuleService $this->accessRule;
  709.                 $accessRuleService->readerFirewall();
  710.                 $em $this->doctrine->getManager();
  711.                 $em->remove($formationSession);
  712.                 $em->flush();
  713.             }
  714.             // Document
  715.             $document = new FormationSessionDocument();
  716.             $form $this->handleRequestdocument($request$document'all''post');
  717.             $idFormationSession $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
  718.             $entityDocument $this->doctrine->getManager();
  719.             $entityDocument->remove($document);
  720.             $entityDocument->flush();
  721.             // MOTIVATION 
  722.             $motivation = new FormationSessionMotivation();
  723.             $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  724.             $datamotivation $this->motivations($data);
  725.             foreach ($datamotivation as $motiv) {
  726.                 $idformationmotivationType $em->getRepository(FormationMotivationType::class)->findOneBy(['idFormationMotivation' => $motiv]);
  727.                 $motivation->setIdFormationMotivation($idformationmotivationType);
  728.                 $motivation->setIdFormationSession($idFormationSession);
  729.                 $valeur TRUE;
  730.                 $motivation->setValeur($valeur);
  731.                 $entitymotivation $this->doctrine->getManager();
  732.                 $entitymotivation->remove($motivation);
  733.             }
  734.             $entitymotivation->flush();
  735.             $data = ['success' => true'data' => 'Delete Ok'];
  736.         } catch (\Exception $e) {
  737.             $data = ['success' => false'data' => $e->getMessage()];
  738.         }
  739.         return new JsonResponse($data);
  740.     }
  741.     /**
  742.      *
  743.      * @param FormationSession $fs The fs entity
  744.      *
  745.      * @return \Symfony\Component\Form\Form
  746.      */
  747.     private function createDeleteForm(FormationSession $formationSession)
  748.     {
  749.         return $this->createFormBuilder()
  750.             ->setAction($this->generateUrl('api_fs_delete', ['id' => $formationSession->getIdFormationSession()]))
  751.             ->setMethod(\Symfony\Component\HttpFoundation\Request::METHOD_DELETE)
  752.             ->getForm();
  753.     }
  754.     /**
  755.      * @return objectFormation
  756.      */
  757.     private function getServiceAccessRule()
  758.     {
  759.         return $this->accessRule;
  760.     }
  761.     #[Route(path'/api/creation_formation'name'ctsweb_create_formations'methods: ['POST'])]
  762.     public function create(Request $request)
  763.     {
  764.         $utilisateurInformation $this->getUser();
  765.         $utilisateur $utilisateurInformation->getUtilisateur();
  766.         $idRole $utilisateur->getIdRole();
  767.         $uid $this->getUser()->getUtilisateur()->getIdUtilisateur();
  768.         $accessRuleService $this->getServiceAccessRule();
  769.         if (!$accessRuleService->hasRightForTakingDayOff()) {
  770.             return new JsonResponse(''JsonResponse::HTTP_FORBIDDEN);
  771.         }
  772.         $formation = new FormationSession();
  773.         $form $this->handleRequest($request$formation'all''post');
  774.         $em $this->doctrine->getManager();
  775.         $repository $em->getRepository(FormationSession::class);
  776.         try {
  777.             if ($form->isSubmitted() && $form->isValid()) {
  778.                 $entityManager $this->doctrine->getManager();
  779.                 if (!$repository->check_datedebutfin($formation)) {
  780.                     $result = [
  781.                         'success' => false,
  782.                         'error' => 'Date de fin de la formation doit être supérieure ou égale à la date début de formation '
  783.                     ];
  784.                     return new JsonResponse($resultJsonResponse::HTTP_OK);
  785.                 }
  786.                 if (FormationSession::DTN === $request->request->get('from')) {
  787.                     $formation->setAvisDtn(true);
  788.                     $formation->setDateAvisDtn(new \DateTime());
  789.                 }
  790.                 $repository $em->getRepository(FormationType::class);
  791.                 $formationType $repository->findOneBy(['idFormationType' => (int) $formation->getIdFormationType()]);
  792.                 $formation->setIdFormationType($formationType);
  793.                 $repository $em->getRepository(Workflow::class);
  794.                 if ($idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
  795.                     $formation->setAvisDtn(true);
  796.                     $formation->setDateAvisDtn(new \DateTime());
  797.                 }
  798.                 $workflow $repository->findOneBy(['idWorkflow' => Workflow::FO_EN_ATTENTE_DE_VALIDATION]);
  799.                 $formation->setIdWorkflow($workflow); // ajout workflow
  800.                 $IdUtilisateur $em->getRepository(Utilisateur::class)->findOneBy(['idUtilisateur' => $uid]);
  801.                 $formation->setIdUtilisateur($IdUtilisateur); //
  802.                 $formation->setLibelleFormation($formation->getTitre());
  803.                 $entityManager->persist($formation);
  804.                 $entityManager->flush();
  805.                 // Document
  806.                 $document = new FormationSessionDocument();
  807.                 $form $this->handleRequestdocument($request$document'all''post');
  808.                 $idFormationSession $em->getRepository(FormationSession::class)->findOneBy(['idFormationSession' => $formation->getIdFormationSession()]);
  809.                 $document->setIdFormationSessionDocument($idFormationSession);
  810.                 $entityDocument $this->doctrine->getManager();
  811.                 $entityDocument->persist($document);
  812.                 $entityDocument->flush();
  813.                 // MOTIVATION 
  814.                 $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  815.                 $datamotivation $this->motivations($data);
  816.                 foreach ($datamotivation as $motiv) {
  817.                     $motivation = new FormationSessionMotivation();
  818.                     $idformationmotivationType $em->getRepository(FormationMotivationType::class)->findOneBy(['idFormationMotivation' => $motiv]);
  819.                     $motivation->setIdFormationMotivation($idformationmotivationType);
  820.                     $motivation->setIdFormationSession($idFormationSession);
  821.                     $valeur TRUE;
  822.                     $motivation->setValeur($valeur);
  823.                     $entitymotivation $this->doctrine->getManager();
  824.                     $entitymotivation->persist($motivation);
  825.                     $entitymotivation->flush();
  826.                 }
  827.                 if ($idRole == RefRole::ROLE_CTS || $idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
  828.                     $this->sendMailNotification($formation);
  829.                 }
  830.                 return new JsonResponse(
  831.                     [
  832.                         'success' => true,
  833.                         'Formation' => $formation->getIdFormationSession()
  834.                     ],
  835.                     JsonResponse::HTTP_CREATED
  836.                 );
  837.             } else {
  838.                 $result = [
  839.                     'success' => false,
  840.                     'data' => self::ERROR_VALIDATION_FORM,
  841.                     'error' => (string) $form->getErrors(truefalse)
  842.                 ];
  843.             }
  844.         } catch (\Exception $e) {
  845.             echo $e->getMessage();
  846.             $result = [
  847.                 'success' => false,
  848.                 'data' => self::ERROR_OCCURED
  849.             ];
  850.         }
  851.         return new JsonResponse($resultJsonResponse::HTTP_BAD_REQUEST);
  852.     }
  853.     private function motivations($data)
  854.     {
  855.         $datamotivation = [];
  856.         $datamotivation['formation_professionelle'] = (isset($data['motivation']['formation_professionelle']) && (!$data['motivation']['formation_professionelle'])) ? false 1;
  857.         $datamotivation['adaptation_immediate'] = (isset($data['motivation']['adaptation_immediate']) && (!$data['motivation']['adaptation_immediate'])) ? false 2;
  858.         $datamotivation['adaptation_previsible'] = (isset($data['motivation']['adaptation_previsible']) && (!$data['motivation']['adaptation_previsible'])) ? false 3;
  859.         $datamotivation['developement_qualification'] = (isset($data['motivation']['developement_qualification']) && (!$data['motivation']['developement_qualification'])) ? false 4;
  860.         return array_filter($datamotivation);
  861.     }
  862.     private function sendMailNotification($formationObj)
  863.     {
  864.         $em $this->doctrine->getManager();
  865.         $gabRep $em->getRepository(RefGabarit::class);
  866.         $ui $this->getUser();
  867.         $uid $this->getUser()->getUtilisateur()->getIdUtilisateur();
  868.         $uimail $em->getRepository(Utilisateur::class)->findBy(['idUtilisateur' => $uid])[0]->getCourriel();
  869.         $role $this->getUser()->getUtilisateur()->getIdRole();
  870.         $subject sprintf('CTS-WEB : Formation à valider - %s %s'$ui->getNom(), $ui->getPrenom());
  871.         $emailMailer $this->getParameter('mailer_user');
  872.         $expediteurMail =  (filter_var($emailMailerFILTER_VALIDATE_EMAIL)) ? $emailMailer 'donotreply@sports.gouv.fr';
  873.         //$host = $this->getParameter('host');
  874.         $mail_contact null;
  875.         $mail_ass_info $this->doctrine->getManager()->getRepository(ParametrageTexte::class)->getByCode('COURRIEL_ASSISTANCE_INFO');
  876.         if ((is_countable($mail_ass_info) ? count($mail_ass_info) : 0) > 0)
  877.             $mail_contact $mail_ass_info[0]->getTexte();
  878.         if (RefRole::ROLE_FEDE === $role || RefRole::ROLE_FEDE_INVITE === $role || RefRole::ROLE_CTS === $role) {
  879.             $federation $ui->getIdFederation()->getIdFederation();
  880.             $affectation $ui->getIdAffectation()->getIdAffectation();
  881.         } else {
  882.             $federation null;
  883.             $affectation $ui->getIdAffectation()->getIdAffectation();
  884.         }
  885.         $recipients $gabRep->emailNotification($federation$affectation'emailFo');
  886.         // if (!filter_var($recipients, FILTER_VALIDATE_EMAIL)) {
  887.         //     $recipients = [];
  888.         // }
  889.         if (!empty($recipients)) {
  890.             $message = (new Email())
  891.                 ->subject($subject)
  892.                 ->from($expediteurMail)
  893.                 ->to(...$recipients)
  894.                 ->html(
  895.                     $this->twig->render(
  896.                         'Notification/notification_formation_dtn.html.twig',
  897.                         ['host' => $mail_contact'civility' => $ui->getCivilite(), 'lastname' => $ui->getNom(), 'firstname' => $ui->getPrenom(), 'mailDemandeur' => $expediteurMail]
  898.                     ),
  899.                     'text/html'
  900.                 );
  901.             $pdfData $this->generatePdf->generatePdfFormation($formationObjfalse$affectationfalse);
  902.             $filename sha1($formationObj->getIdFormationSession()) . '.pdf';
  903.             $pdfFilePath $this->getParameter('dir_file_formations') . $filename;
  904.             file_put_contents($pdfFilePath$pdfData);
  905.             if (file_exists($pdfFilePath)) {
  906.                 $pieceJointe $pdfFilePath;
  907.             } else {
  908.                 $pieceJointe false;
  909.             }
  910.             if ($pieceJointe) {
  911.                 // Path to the PDF file to attach
  912.                 if (file_exists($pdfFilePath)) {
  913.                     // Create a attach for the attachment
  914.                     chmod($pdfFilePath0644);
  915.                     $message->attach(fopen($pdfFilePath'r'),  $filename);
  916.                 }
  917.             }
  918.             $this->mailer->send($message);
  919.             // Supprimer le fichier PDF temporaire après l'envoi de l'email (facultatif)
  920.             unlink($pdfFilePath);
  921.         }
  922.     }
  923.     /**
  924.      * @param FormationSession $formation
  925.      * @return \Symfony\Component\Form\FormInterface
  926.      */
  927.     private function handleRequestType(
  928.         Request $request,
  929.         FormationType $formationType,
  930.         string $label,
  931.         string $validationGroup
  932.     ) {
  933.         $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  934.         $request->request->replace(is_array($data) ? $data : []);
  935.         $form $this->createForm(
  936.             FormationTypeType::class,
  937.             $formationType,
  938.             ['label' => $label'validation_groups' => $validationGroup]
  939.         );
  940.         $form->handleRequest($request);
  941.         return $form;
  942.     }
  943.     /**
  944.      * @return \Symfony\Component\Form\FormInterface
  945.      */
  946.     private function handleRequest(
  947.         Request $request,
  948.         FormationSession $formation,
  949.         string $label,
  950.         string $validationGroup
  951.     ) {
  952.         $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  953.         if ('status' != $label) {
  954.             $data['nom_responsable'] = $data['responsable']['nom_responsable'];
  955.             $data['mail_responsable'] = $data['responsable']['mail_responsable'];
  956.             $data['telephone_responsable'] = $data['responsable']['telephone_responsable'];
  957.         }
  958.         $request->request->replace(is_array($data) ? $data : []);
  959.         $form $this->createForm(
  960.             FormationSessionType::class,
  961.             $formation,
  962.             ['label' => $label'validation_groups' => $validationGroup]
  963.         );
  964.         $form->handleRequest($request);
  965.         return $form;
  966.     }
  967.     /**
  968.      * @return \Symfony\Component\Form\FormInterface
  969.      */
  970.     private function handleRequestdocument(
  971.         Request $request,
  972.         FormationSessionDocument $document,
  973.         string $label,
  974.         string $validationGroup
  975.     ) {
  976.         $datadocument = [];
  977.         $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  978.         $datadocument['lien'] = json_encode($data['liste_documents'], JSON_THROW_ON_ERROR);
  979.         $request->request->replace(is_array($datadocument) ? $datadocument : []);
  980.         $form $this->createForm(
  981.             FormationSessionDocumentType::class,
  982.             $document,
  983.             ['label' => $label'validation_groups' => $validationGroup]
  984.         );
  985.         $form->handleRequest($request);
  986.         return $form;
  987.     }
  988.     /**
  989.      * @return \Symfony\Component\Form\FormInterface
  990.      */
  991.     private function handleRequestmotivation(
  992.         Request $request,
  993.         FormationSessionMotivation $motivation,
  994.         string $label,
  995.         string $validationGroup
  996.     ) {
  997.         $datamotivation = [];
  998.         $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  999.         $datamotivation['formation_professionelle'] = isset($data['motivation']['formation_professionelle']) ? false;
  1000.         $datamotivation['adaptation_immediate'] = isset($data['motivation']['adaptation_immediate']) ? false;
  1001.         $datamotivation['adaptation_previsible'] = isset($data['motivation']['adaptation_previsible']) ? false;
  1002.         $datamotivation['developement_qualification'] = isset($data['motivation']['developement_qualification']) ? false;
  1003.         $request->request->replace(is_array($datamotivation) ? $datamotivation : []);
  1004.         $form $this->createForm(
  1005.             FormationSessionMotivationType::class,
  1006.             $motivation,
  1007.             ['label' => $label'validation_groups' => $validationGroup]
  1008.         );
  1009.         $form->handleRequest($request);
  1010.         return $form;
  1011.     }
  1012.     /**
  1013.      * Get a user from the Security Token Storage.
  1014.      *
  1015.      * @return UserInterface|object|null
  1016.      *
  1017.      * @throws \LogicException If SecurityBundle is not available
  1018.      *
  1019.      * @see TokenInterface::getUser()
  1020.      *
  1021.      * @final since version 3.4
  1022.      */
  1023.     protected function getUser()
  1024.     {
  1025.         if (!$this->has('security.token_storage')) {
  1026.             throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
  1027.         }
  1028.         if (null === $token $this->get('security.token_storage')->getToken()) {
  1029.             return null;
  1030.         }
  1031.         if (!\is_object($user $token->getUser())) {
  1032.             // e.g. anonymous authentication
  1033.             return null;
  1034.         }
  1035.         return $user;
  1036.     }
  1037.     #[Route(path'/api/delete_formation/{id}'name'ctsweb_delete_formations')]
  1038.     public function deleteFormations(Request $requestFormationSession $formationSession)
  1039.     {
  1040.         //$idFormationSession = $sessionFormation->getIdFormationSession();
  1041.         try {
  1042.             // $form = $this->handleRequest($request, $formationSession, 'all', 'post');
  1043.             $em $this->doctrine->getManager();
  1044.             $repository $em->getRepository(FormationSession::class);
  1045.             $cg $repository->findOneBy(['idFormationSession' => $formationSession->getIdFormationSession()]);
  1046.             $role $this->getUser()->getUtilisateur()->getIdRole();
  1047.             if ($cg) {
  1048.                 if ($cg->getIdWorkflow()->getIdWorkflow() == Workflow::FO_SIGNE) {
  1049.                     $workflow $em->getRepository(Workflow::class)->find(Workflow::FO_ANNULATION);
  1050.                     $formationSession->setIdWorkflow($workflow);
  1051.                     $em->persist($formationSession);
  1052.                     $em->flush();
  1053.                     $data = ['success' => true'data' => 'La formation a été annulé'];
  1054.                     return new JsonResponse($data);
  1055.                 } else {
  1056.                     $filename sha1($formationSession->getIdFormationSession());
  1057.                     $repository->deleteformation($formationSession->getIdFormationSession());
  1058.                     $repertoire $this->getParameter('dir_file_formations');
  1059.                     $nomFichier $filename '.pdf';
  1060.                     $this->supprimerFichier($repertoire$nomFichier);
  1061.                     $data = ['success' => true'data' => 'La formation a été supprimée'];
  1062.                     return new JsonResponse($data);
  1063.                 }
  1064.             }
  1065.         } catch (\Exception $e) {
  1066.             $data = ['success' => false'data' => $e->getMessage()];
  1067.             return new JsonResponse($data);
  1068.         }
  1069.     }
  1070.     public  function supprimerFichier($repertoire$nomFichier)
  1071.     {
  1072.         $cheminFichier $repertoire $nomFichier;
  1073.         // Vérifiez si le fichier existe avant de le supprimer
  1074.         if (file_exists($cheminFichier)) {
  1075.             if (unlink($cheminFichier)) {
  1076.                 // return "Le fichier $nomFichier a été supprimé avec succès.";
  1077.             } else {
  1078.                 // return "Une erreur s'est produite lors de la suppression du fichier.";
  1079.             }
  1080.         } else {
  1081.             // return "Le fichier $nomFichier n'existe pas dans le répertoire.";
  1082.         }
  1083.     }
  1084.     /**
  1085.      * @return Response
  1086.      */
  1087.     #[Route(path'/api/export_pdf_mes_Formations/{id}'name'ctsweb_export_pdf_mes_Formations')]
  1088.     public function exportpdfFormations(FormationSession $formation)
  1089.     {
  1090.         if (
  1091.             Workflow::FO_SIGNE === $formation->getIdWorkflow()->getIdWorkflow()
  1092.         ) {
  1093.             $filename sha1($formation->getIdFormationSession()) . '.pdf';
  1094.             $path $this->getParameter('dir_file_formations') . $filename;
  1095.             if (file_exists($path)) {
  1096.                 $content file_get_contents($pathFILE_USE_INCLUDE_PATH);
  1097.                 $response $this->getResponse($content$filename);
  1098.             } else {
  1099.                 $response = new JsonResponse(['error' => self::ERROR_FILE], JsonResponse::HTTP_BAD_REQUEST);
  1100.             }
  1101.         } else {
  1102.             $serviceGeneratePdf $this->generatePdf;
  1103.             $content $serviceGeneratePdf->generatePdfFormation($formationfalse);
  1104.             $filename sha1($formation->getIdFormationSession()) . '.pdf';
  1105.             $response $this->getResponse($content$filename);
  1106.         }
  1107.         return $response;
  1108.     }
  1109.     public function getResponse(string $contentstring $filename): Response
  1110.     {
  1111.         return new Response(
  1112.             $content,
  1113.             Response::HTTP_OK,
  1114.             [
  1115.                 'Content-Type' => 'application/pdf',
  1116.                 'Content-Length' => strlen($content),
  1117.                 'Content-Disposition' => "attachment;filename=\"{$filename}",
  1118.                 'Accept-Ranges' => 'bytes'
  1119.             ]
  1120.         );
  1121.     }
  1122.     /**
  1123.      * @param Utilisateur $utilisateur
  1124.      * @return JsonResponse
  1125.      */
  1126.     #[Route(path'/api/formations/archive/{idUser}'name'ctsweb_formations_archive'requirements: ['idUser' => '\d+'])]
  1127.     public function findMyArchive($idUser)
  1128.     {
  1129.         $idUtilisateur = ($idUser == 0) ? $this->getUser()->getIdUtilisateur() : $idUser;
  1130.         $repository $this->doctrine->getManager()->getRepository(FormationSession::class);
  1131.         $accepted Workflow::FO_SIGNE;
  1132.         $refused Workflow::FO_REFUSE;
  1133.         $filter " fs.id_workflow IN (" $accepted ", " $refused ")";
  1134.         //  les formations validées/refusées de plus d’un an sont visibles uniquement dans les synthèses et archives cf. 7.2.4 et 7.3.5) 
  1135.         //@todo:A verifier
  1136.         $formationListe $repository->getSessiondocument($idUtilisateur$filter);
  1137.         if (isset($formationListe[0]) && isset($formationListe[0]['liste_documents'])) {
  1138.             $formationListe[0]['liste_documents'] = json_decode((string) $formationListe[0]['liste_documents'], true512JSON_THROW_ON_ERROR);
  1139.         }
  1140.         if (isset($formationListe[0]) && isset($formationListe[0]['id'])) {
  1141.             $formationListe[0]['id'] = $formationListe[0]['id'];
  1142.         }
  1143.         try {
  1144.             $data = ['success' => true'data' => $formationListe];
  1145.         } catch (\Exception $e) {
  1146.             $data = ['success' => false'error' => $e->getMessage()];
  1147.         }
  1148.         return new JsonResponse($data);
  1149.     }
  1150.     #[Route(path'/api/export_formations_enCours'name'ctsweb_export_csv_formation_en_cours')]
  1151.     public function exportFormationsEnCour()
  1152.     {
  1153.         $em $this->doctrine->getManager();
  1154.         $user $this->getUser();
  1155.         $federation $user->getIdFederation();
  1156.         $affectation $user->getIdAffectation();
  1157.                 $listformationEnCours $this->formationsEnCours();
  1158.         $data_retour = [];
  1159.         $data = (array) $listformationEnCours;
  1160.         $dataValues array_values($data)[1];
  1161.         $dataArray json_decode((string) $dataValuestrue512JSON_THROW_ON_ERROR);
  1162.         foreach ($dataArray["data"] as $key => $value) {
  1163.             $value['motivation'] = $em->getRepository(FormationSessionMotivation::class)->getMotivationsBySessionFormationtype($value['id']);
  1164.             $data_retour['data'][] = $value;
  1165.         }
  1166.         $response $this->exportFormation->exportListEncoursAttente((array) $data_retour$affectation$federation'en cours');
  1167.         $handle fopen('php://memory''r+');
  1168.         $fileName 'Formations_En_Cours_' date('d_m_Y');
  1169.         rewind($handle);
  1170.         $dispositionHeader $response->headers->makeDisposition(
  1171.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  1172.             $fileName '.xls'
  1173.         );
  1174.         $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  1175.         $response->headers->set('Pragma''public');
  1176.         $response->headers->set('Cache-Control''maxage=1');
  1177.         $response->headers->set('Content-Disposition'$dispositionHeader);
  1178.         return $response;
  1179.     }
  1180.     #[Route(path'/api/export_formations_enAttente'name'ctsweb_export_csv_formation_en_attente')]
  1181.     public function exportFormationsEnAttente()
  1182.     {
  1183.         $em $this->doctrine->getManager();
  1184.         $user $this->getUser();
  1185.         $federation $user->getIdFederation();
  1186.         $affectation $user->getIdAffectation();
  1187.         $listformationEnAttente $this->formationsEnAttente();
  1188.         $data_retour = [];
  1189.         $data = (array) $listformationEnAttente;
  1190.         $dataValues array_values($data)[1];
  1191.         $dataArray json_decode((string) $dataValuestrue512JSON_THROW_ON_ERROR);
  1192.         foreach ($dataArray["data"] as $key => $value) {
  1193.             $value['motivation'] = $em->getRepository(FormationSessionMotivation::class)->getMotivationsBySessionFormationtype($value['id']);
  1194.             $data_retour['data'][] = $value;
  1195.         }
  1196.         $response $this->exportFormation->exportListEncoursAttente((array) $data_retour$affectation$federation'en attente');
  1197.         $handle fopen('php://memory''r+');
  1198.         $fileName 'Formations_En_Attente_'date('d_m_Y');
  1199.         rewind($handle);
  1200.         $dispositionHeader $response->headers->makeDisposition(
  1201.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  1202.             $fileName '.xls'
  1203.         );
  1204.         $response->headers->set('Content-Type''text/vnd.ms-excel; charset=utf-8');
  1205.         $response->headers->set('Pragma''public');
  1206.         $response->headers->set('Cache-Control''maxage=1');
  1207.         $response->headers->set('Content-Disposition'$dispositionHeader);
  1208.         return $response;
  1209.     }
  1210.     function AffichageFormationArchivesAction($idUser)
  1211.     {
  1212.         $idUtilisateur = ($idUser == 0) ? $this->getUser()->getIdUtilisateur() : $idUser;
  1213.         $em $this->doctrine->getManager();
  1214.         $repository $em->getRepository(FormationSession::class);
  1215.         $workflow_filter $em->getRepository(FormationSession::class)->getOngoingFilter();
  1216.         try {
  1217.             $Liste $repository->getSessionsOfUserWithWorkflow($idUtilisateur$workflow_filter);
  1218.             $data = ['success' => true'data' => $Liste];
  1219.         } catch (\Exception $e) {
  1220.             $data = ['success' => false'error' => $e->getMessage()];
  1221.         }
  1222.         return new JsonResponse($data);
  1223.     }
  1224.     public function initSignatureFormations($idformation$idWorkflow)
  1225.     {
  1226.         try {
  1227.             $em $this->doctrine->getManager();
  1228.             $FormationRepo $em->getRepository(FormationSession::class);
  1229.             $utilisateurRepository $em->getRepository(Utilisateur::class);
  1230.             $formationObj $FormationRepo->find($idformation);
  1231.             $info_signature $this->getInfosSignatureSh($formationObj);
  1232.             $signatureDtn $this->getInfosSignatureDtn($formationObj);
  1233.             $signature_Dtn = (isset($signatureDtn) && !empty($signatureDtn)) ? $signatureDtn false;
  1234.             $info_signature['signatureDtn'] = $signature_Dtn;
  1235.             $idUtilisateur $formationObj->getIdUtilisateur()->getIdUtilisateur();
  1236.             $affectation $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idUtilisateur)->getIdAffectation()->getIdAffectation();
  1237.             $formationObj $FormationRepo->find($idformation);
  1238.             $formationObj->setDateSgnSh(new \DateTime());
  1239.             $idUtilisateur $formationObj->getIdUtilisateur()->getIdUtilisateur();
  1240.             $emails $utilisateurRepository->findCourrielById($idUtilisateur);
  1241.             $email = isset($emails[0]['courriel']) ? $emails[0]['courriel'] : null;
  1242.             $em->persist($formationObj);
  1243.             $em->flush();
  1244.             $this->generatePdf->generatePdfFormation($formationObjfalse$affectation$info_signature);
  1245.             $filename sha1($formationObj->getIdFormationSession()) . '.pdf';
  1246.             $pdfFilePath $this->getParameter('dir_file_formations') . $filename;
  1247.             if (file_exists($pdfFilePath)) {
  1248.                 $pieceJointe $pdfFilePath;
  1249.             } else {
  1250.                 $pieceJointe false;
  1251.             }
  1252.             if ($idWorkflow == Workflow::FO_SIGNE) {
  1253.                 $decision EmailSHDecision::SIGNED;
  1254.             } else {
  1255.                 $decision EmailSHDecision::REFUSED;
  1256.             }
  1257.             $beginDate $formationObj->getDateDebut();
  1258.             $mail $this->emailSHDecision->getMailFormation(
  1259.                 $decision,
  1260.                 EmailSHDecision::FO,
  1261.                 $email,
  1262.                 $beginDate,
  1263.                 $pieceJointe,
  1264.                 $filename
  1265.             );
  1266.             if ($mail) {
  1267.                 $this->mailer->send($mail);
  1268.             }
  1269.             $message 'Tous les conges ont été signés avec succès.';
  1270.             $return = array(
  1271.                 'success' => true,
  1272.                 'data' => $message
  1273.             );
  1274.         } catch (\Exception $e) {
  1275.             $message 'Un ou plusieurs congés n\'ont pu être signés.';
  1276.             $return = array(
  1277.                 'success' => false,
  1278.                 'data' => $e->getMessage()
  1279.             );
  1280.         }
  1281.         return new JsonResponse(
  1282.             $return,
  1283.             JsonResponse::HTTP_CREATED
  1284.         );
  1285.     }
  1286.     public function getInfosSignatureSh($formationObj)
  1287.     {
  1288.         $em $this->doctrine->getManager();
  1289.         $idSignataire $this->getUser()->getUtilisateur()->getIdUtilisateur();
  1290.         $affectationSignataire $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idSignataire)->getIdAffectation()->getIdAffectation();
  1291.         $idUtilisateur $formationObj->getIdUtilisateur()->getIdUtilisateur();
  1292.         $affectation $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idUtilisateur)->getIdAffectation()->getIdAffectation();
  1293.         # TODO : Valider la logique de sélection du signataire en fonction de l'affectation.
  1294.        /* if ($affectationSignataire == $affectation) {
  1295.             $signataire = $em->getRepository(UtilisateurInformation::class)->findOneBy(['utilisateur' => $idSignataire]);
  1296.         } else {
  1297.             if ($affectation != 1) {
  1298.                 $drsignataire = $em->getRepository(UtilisateurInformation::class)->findDrSuperieur($affectation);
  1299.             } else {
  1300.                 $drsignataire = $em->getRepository(UtilisateurInformation::class)->findDsSuperieur($affectation);
  1301.             }
  1302.             $signataire = $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($drsignataire);
  1303.         }
  1304.         $path = $signataire->getScan() ? $this->getParameter('dir_file_signature') . $signataire->getScan()->getAbsolutePath() : '';*/
  1305.         if ($affectation != 1) {
  1306.             $drsignataire $em->getRepository(UtilisateurInformation::class)->findDrSuperieur($affectation);
  1307.         } else {
  1308.             $drsignataire $em->getRepository(UtilisateurInformation::class)->findDsSuperieur($affectation);
  1309.         }
  1310.         $signataire $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($drsignataire);
  1311.         
  1312.         $path $signataire->getScan() ? $this->getParameter('dir_file_signature') . $signataire->getScan()->getAbsolutePath() : '';
  1313.         if ($path && file_exists($path)) {
  1314.             chmod($path0644);
  1315.             $content file_get_contents($path);
  1316.             if ($content !== false) {
  1317.                 $pathvrai $path;
  1318.             } else {
  1319.                 // Gérer l'erreur si le contenu n'a pas pu être lu
  1320.                 $pathvrai "";
  1321.             }
  1322.         } else {
  1323.             // Gérer l'erreur si le fichier n'existe pas
  1324.             $pathvrai "";
  1325.         }
  1326.         $info_signature = [
  1327.             'nom' => $signataire->getNom(),
  1328.             'prenom' => $signataire->getPrenom(),
  1329.             'dateSignature' => date("d/m/Y"),
  1330.             'sup' => true,
  1331.             'fonction' => $signataire->getFonction(),
  1332.             'path' => $pathvrai,
  1333.             'civilite' => $signataire->getCivilite(),
  1334.             'signatureDtn' => false
  1335.         ];
  1336.         return $info_signature;
  1337.     }
  1338.     public function getInfosSignatureDtn($formationObj)
  1339.     {
  1340.         $em $this->doctrine->getManager();
  1341.         $idUtilisateur $formationObj->getIdUtilisateur()->getIdUtilisateur();
  1342.         $signatureDtn = [];
  1343.         if (!is_null($formationObj->getSignataireValidationfonctionelle())) {
  1344.             $informationSignataireDTN $em->getRepository(UtilisateurInformation::class)->findOneBy(['utilisateur' => $formationObj->getSignataireValidationfonctionelle()]);
  1345.             if ($informationSignataireDTN && !is_null($informationSignataireDTN->getIdPoste())) {
  1346.                 if ($informationSignataireDTN->getIdFederation()) {
  1347.                     $oFede $em->getRepository(RFederation::class)->getRFederationByRefFederation($informationSignataireDTN->getIdFederation()->getIdFederation());
  1348.                     $libelleFedertation $oFede->getRSerLibl();
  1349.                 }
  1350.                 $signatureDtn = [
  1351.                     'nom' => $informationSignataireDTN->getNom(),
  1352.                     'prenom' => $informationSignataireDTN->getPrenom(),
  1353.                     'fonction' => $informationSignataireDTN->getFonction(),
  1354.                     'path' => $informationSignataireDTN->getScan() ? $this->getParameter('dir_file_signature') . $informationSignataireDTN->getScan()->getAbsolutePath() : false,
  1355.                     'federation' => $libelleFedertation ?: '',
  1356.                     'civilite' => $informationSignataireDTN->getCivilite()
  1357.                 ];
  1358.             }
  1359.         } else {
  1360.             $idFederation $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idUtilisateur)->getIdFederation()->getIdFederation();
  1361.             $UserInfoDTN $em->getRepository(UtilisateurInformation::class)->getUserInfoDTN($idFederation3);
  1362.             if (isset($UserInfoDTN[0]) && is_array($UserInfoDTN[0])) {
  1363.                 $libelleFedertation $UserInfoDTN[0]['r_ser_libl'];
  1364.                 $idsignDtn $UserInfoDTN[0]['id_utilisateur'];
  1365.                 $infSignataireDTN $em->getRepository(UtilisateurInformation::class)->findOneBy(array('utilisateur' =>  $idsignDtn));
  1366.                 $path $infSignataireDTN->getScan() ? $this->getParameter('dir_file_signature') . $infSignataireDTN->getScan()->getAbsolutePath() : '';
  1367.                 if ($path && file_exists($path)) {
  1368.                     chmod($path0644);
  1369.                     $content file_get_contents($path);
  1370.                     if ($content !== false) {
  1371.                         $pathvrai $path;
  1372.                     } else {
  1373.                         // Gérer l'erreur si le contenu n'a pas pu être lu
  1374.                         $pathvrai "";
  1375.                     }
  1376.                 } else {
  1377.                     // Gérer l'erreur si le fichier n'existe pas
  1378.                     $pathvrai "";
  1379.                 }
  1380.                 $signatureDtn = array(
  1381.                     'nom' => $infSignataireDTN->getNom(),
  1382.                     'prenom' => $infSignataireDTN->getPrenom(),
  1383.                     'fonction' => $infSignataireDTN->getFonction(),
  1384.                     'path' => $pathvrai,
  1385.                     'federation' => $libelleFedertation $libelleFedertation '',
  1386.                     'civilite' => $infSignataireDTN->getCivilite()
  1387.                 );
  1388.             }
  1389.         }
  1390.         return (isset($signatureDtn) && !empty($signatureDtn)) ? $signatureDtn false;
  1391.     }
  1392.     #[Route('/api/formation/update_state/{id}'name'cts_update_formation_state'methods: ['POST'])]
  1393.     /**
  1394.      * Cette méthode met à jour le statut d'une formation existante.
  1395.      * 
  1396.      * @param Request $request La requête contenant les données de la formation à mettre à jour.
  1397.      * @param int $id L'ID de la formation à mettre à jour.
  1398.      * @return JsonResponse Retourne un JSON contenant l'ID de la formation mis à jour ou un message d'erreur si la mise à jour échoue.
  1399.      */
  1400.     public function updateStateForm(Request $requestFormationSession $formation): JsonResponse
  1401.     {
  1402.         // Initialisation du gestionnaire d'entités
  1403.         $em $this->doctrine->getManager();
  1404.         // Décodage des données reçues en JSON
  1405.         $formData json_decode($request->getContent(), true);
  1406.         // Création et traitement du formulaire
  1407.         //TODO : à vérifier la soumission du formulaire
  1408.         #$form = $this->handleRequest($request, $formation, 'status', 'post');
  1409.         // Récupération du workflow associé à la formation
  1410.         $workflow $em->getRepository(Workflow::class)->find($formData['idWorkflow']);
  1411.         try {
  1412.             $formation->setIdWorkflow($workflow);
  1413.             // Si le workflow est 'signé' ou 'refusé'
  1414.             if ((Workflow::FO_SIGNE  == $workflow->getIdWorkflow()) || (Workflow::FO_REFUSE == $workflow->getIdWorkflow())) {
  1415.                 // Appel de la méthode de signature
  1416.                 //TODO : à bien vérifier
  1417.                 $this->initSignatureFormations($formation->getIdFormationSession(), $workflow->getIdWorkflow());
  1418.                 // Mise à jour de la date de signature
  1419.                 $formation->setDateSgnSh(new \DateTime());
  1420.             }
  1421.             //mettre à jour l'avis du SH
  1422.             if (Workflow::FO_SIGNE == $workflow->getIdWorkflow()) {
  1423.                 $formation->setAvisSh(true);
  1424.             } elseif (Workflow::FO_REFUSE == $workflow->getIdWorkflow()) {
  1425.                 $formation->setAvisSh(false);
  1426.             }
  1427.             // Enregistrement des modifications dans la base de données
  1428.             $em->persist($formation);
  1429.             $em->flush();
  1430.             $data = [
  1431.                 'success' => true,
  1432.                 'message' => 'La formation a été mise à jour avec succès'
  1433.             ];
  1434.         } catch (\Exception $e) {
  1435.             // Gestion des erreurs inattendues
  1436.             $data = [
  1437.                 'status' => Response::HTTP_INTERNAL_SERVER_ERROR,
  1438.                 'message' => 'Une erreur est survenue lors de la mise à jour de la formation. Veuillez réessayer ultérieurement. ' $e->getMessage()
  1439.             ];
  1440.         }
  1441.         return new JsonResponse($data);
  1442.     }
  1443.     function retirerAccents($str)
  1444.     {
  1445.         $str str_replace(
  1446.             ['à''á''â''ã''ä''å''ç''è''é''ê''ë''ì''í''î''ï''ñ''ò''ó''ô''õ''ö''ù''ú''û''ü''ý''ÿ'],
  1447.             ['a''a''a''a''a''a''c''e''e''e''e''i''i''i''i''n''o''o''o''o''o''u''u''u''u''y''y'],
  1448.             $str
  1449.         );
  1450.         return strtolower(str_replace(" """$str));
  1451.     }
  1452. }