src/Controller/DemandeReportController.php line 612

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use JMS\Serializer\SerializationContext;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use App\Entity\DemandeReport;
  10. use App\Entity\Conge;
  11. use App\Entity\CongeType;
  12. use App\Entity\CongeDroitAnnuel;
  13. use App\Entity\ParametrageTexte;
  14. use App\Entity\RefRole;
  15. use App\Entity\Utilisateur;
  16. use App\Entity\UtilisateurInformation;
  17. use App\Entity\Workflow;
  18. use App\Form\DemandeReportType;
  19. use App\Entity\RefGabarit;
  20. use App\Entity\RefAffectation;
  21. use Doctrine\Persistence\ManagerRegistry;
  22. use Symfony\Component\Mailer\MailerInterface;
  23. use App\Services\GeneratePdf;
  24. use App\Services\AccessRule;
  25. use JMS\Serializer\SerializerInterface;
  26. use Symfony\Component\Mime\Email;
  27. use App\Services\Lib\EmailSHDecision;
  28. use Twig\Environment;
  29. use App\Entity\RefAffectationCalendrier;
  30. /**
  31.  * Class DemandeReportController
  32.  * @package App\Controller
  33.  */
  34. class DemandeReportController 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 $doctrine;
  40.     private  $mailer;
  41.     private  $generatePdf;
  42.     private  $accessRule;
  43.     private $serializer;
  44.     private $twig;
  45.     private  $emailSHDecision;
  46.     public function __construct(ManagerRegistry $doctrineMailerInterface $mailerGeneratePdf $generatePdfEnvironment $twigAccessRule $accessRuleSerializerInterface $serializerEmailSHDecision $emailSHDecision,)
  47.     {
  48.         $this->doctrine $doctrine;
  49.         $this->mailer $mailer;
  50.         $this->generatePdf $generatePdf;
  51.         $this->accessRule $accessRule;
  52.         $this->serializer $serializer;
  53.         $this->emailSHDecision $emailSHDecision;
  54.         $this->twig $twig;
  55.     }
  56.     #[Route(path'/api/demandes_report/{id}'name'ctsweb_get_demandes_report'methods: ['GET'], requirements: ['id' => '\d+'])]
  57.     public function detail(DemandeReport $report): JsonResponse
  58.     {
  59.         $jsonv = [];
  60.         $repositoryUI $this->doctrine->getManager()->getRepository(UtilisateurInformation::class);
  61.         $uid $report->getUtilisateur()->getIdUtilisateur();
  62.         $utilisateurData $repositoryUI->findDataForPageProfil($uid);
  63.         $accessRuleService $this->getServiceAccessRule();
  64.         if (!$accessRuleService->hasRightTodetailAccessReport($report)) {
  65.             return new JsonResponse(''JsonResponse::HTTP_FORBIDDEN);
  66.         }
  67.         // Obtenir les données sérialisées de "$report" et les décoder en tableau associatif
  68.         $reportSerialized $this->serialize($report);
  69.         $reportSerializedArray json_decode($reportSerializedtrue);
  70.         $dateRefuseValide $report->getDateDerniereModification();
  71.         $infosValidation['annee'] = $this->getAnneeSaisie($uid1);
  72.         $infosValidation['dateRefuseValide'] = (isset($dateRefuseValide) && !empty($dateRefuseValide)) ? $dateRefuseValide->format('Y-m-d') : "";
  73.         $uData $this->serialize($utilisateurData);
  74.         $jsonv['items']['infos'] =  $infosValidation;
  75.         $jsonv['items']['conge'] = $reportSerializedArray;
  76.         $jsonv['items']['user'] = json_decode((string) $uDatatrue512JSON_THROW_ON_ERROR);
  77.         $json_merge json_encode($jsonv);
  78.         return new JsonResponse($json_mergeJsonResponse::HTTP_OK, [], true);
  79.     }
  80.     /**
  81.      * @return JsonResponse
  82.      */
  83.     #[Route(path'/api/demandes_report'name'ctsweb_create_demandes_report'methods: ['POST'])]
  84.     public function create(Request $request)
  85.     {
  86.         $utilisateurInformation $this->getUser();
  87.         $utilisateur $utilisateurInformation->getUtilisateur();
  88.         $idRole $utilisateur->getIdRole();
  89.         $accessRuleService $this->getServiceAccessRule();
  90.         if (!$accessRuleService->hasRightForTakingDayOff()) {
  91.             return new JsonResponse(''JsonResponse::HTTP_FORBIDDEN);
  92.         }
  93.         $solderestant false;
  94.         $report = new DemandeReport();
  95.         $form $this->handleRequest($request$report'all''post');
  96.         $em $this->doctrine->getManager();
  97.         $repository $em->getRepository(DemandeReport::class);
  98.         try {
  99.             if ($form->isSubmitted() && $form->isValid()) {
  100.                 $entityManager $this->doctrine->getManager();
  101.                 $year $this->getYear($utilisateurInformation);
  102.                 if (!$repository->checkDemandeReport($year$this->getUser())) {
  103.                     $result = [
  104.                         'success' => false,
  105.                         'error' => 'Il y a déjà une demande de report sur cette période ou les dates credit et debit ne sont pas renseignés par le SH'
  106.                     ];
  107.                     return new JsonResponse($resultJsonResponse::HTTP_BAD_REQUEST);
  108.                 }
  109.                 $solderestant $this->solderestant($utilisateur$report->getNbJour());
  110.                 if (!$solderestant) {
  111.                     $result = [
  112.                         'success' => false,
  113.                         'error' => 'Le nombre de jour demandé est superieure au solde de congé restante'
  114.                     ];
  115.                     return new JsonResponse($resultJsonResponse::HTTP_BAD_REQUEST);
  116.                 }
  117.                 $report->setType(DemandeReport::TYPE_ONE); // Pour définir le type à 1
  118.                 $entityManager->persist($report);
  119.                 $this->createReport($report);
  120.                 $entityManager->flush();
  121.                 if ($idRole == RefRole::ROLE_CTS || $idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
  122.                     $this->sendMailNotification();
  123.                 }
  124.                 return new JsonResponse(
  125.                     [
  126.                         'success' => true,
  127.                         'Conge' => $report->getId(),
  128.                     ],
  129.                     JsonResponse::HTTP_CREATED
  130.                 );
  131.             } else {
  132.                 $result = [
  133.                     'success' => false,
  134.                     'data' => self::ERROR_VALIDATION_FORM,
  135.                     'error' => (string) $form->getErrors(truefalse)
  136.                 ];
  137.             }
  138.         } catch (\Exception $e) {
  139.             echo $e->getMessage();
  140.             $result = [
  141.                 'success' => false,
  142.                 'data' => self::ERROR_OCCURED
  143.             ];
  144.         }
  145.         return new JsonResponse($resultJsonResponse::HTTP_BAD_REQUEST);
  146.     }
  147.     /**
  148.      * @return JsonResponse
  149.      */
  150.     #[Route(path'/api/report_solde_ca/{id}'name'ctsweb_report_solde_ca'requirements: ['id' => '\d+'])]
  151.     public function soldeCa(Utilisateur $report)
  152.     {
  153.         $entityManager $this->doctrine->getManager();
  154.         $idutilisateur $report->getidUtilisateur();
  155.         $utilisateurInformation $entityManager
  156.             ->getRepository(UtilisateurInformation::class)
  157.             ->findOneBy(["idUtilisateur" =>  $idutilisateur]);
  158.         $year $this->getYear($utilisateurInformation);
  159.         $userInfos $entityManager
  160.             ->getRepository(UtilisateurInformation::class)
  161.             ->getInfos(
  162.                 $report,
  163.                 $year
  164.             );
  165.         $totalCan  = isset($userInfos['totalCan']) ? $userInfos['totalCan'] : 0;
  166.         $givenCan  = isset($userInfos['givenCan']) ? $userInfos['givenCan'] : 0;
  167.         $totalfrac = isset($userInfos['totalFrac']) ? $userInfos['totalFrac'] : 0;
  168.         $total $totalCan $totalfrac;
  169.         $result['soldeCan']  = $total $givenCan;
  170.         return new JsonResponse(
  171.             $this->serialize($result),
  172.             JsonResponse::HTTP_OK,
  173.             [],
  174.             true
  175.         );
  176.     }
  177.     public function solderestant($report$nb)
  178.     {
  179.         $entityManager $this->doctrine->getManager();
  180.         $idutilisateur $report->getidUtilisateur();
  181.         $utilisateurInformation $entityManager
  182.             ->getRepository(UtilisateurInformation::class)
  183.             ->findOneBy(["idUtilisateur" =>  $idutilisateur]);
  184.         $year $this->getYear($utilisateurInformation);
  185.         $userInfos $entityManager
  186.             ->getRepository(UtilisateurInformation::class)
  187.             ->getInfos(
  188.                 $report,
  189.                 $year
  190.             );
  191.         $totalCan  = isset($userInfos['totalCan']) ? $userInfos['totalCan'] : 0;
  192.         $givenCan  = isset($userInfos['givenCan']) ? $userInfos['givenCan'] : 0;
  193.         $totalfrac = isset($userInfos['totalFrac']) ? $userInfos['totalFrac'] : 0;
  194.         $total $totalCan $totalfrac;
  195.         $result['soldeCan']  = $total $givenCan;
  196.         if ($result['soldeCan'] < $nb) {
  197.             return false;
  198.         }
  199.         return true;
  200.     }
  201.     /**
  202.      * Fonction pour gérer la création d'un rapport
  203.      * @param DemandeReport $report
  204.      * @return bool
  205.      */
  206.     public function createReport(DemandeReport $report): bool
  207.     {
  208.         $entityManager $this->doctrine->getManager();
  209.         // Récupérer les informations de l'utilisateur
  210.         $utilisateur $report->getUtilisateur();
  211.         $utilisateurInformation $entityManager
  212.             ->getRepository(UtilisateurInformation::class)
  213.             ->findOneBy(["idUtilisateur" => $utilisateur]);
  214.         $Idaffectation $utilisateurInformation->getIdAffectation()->getIdAffectation();
  215.         $affectation $entityManager
  216.             ->getRepository(RefAffectation::class)
  217.             ->findOneBy(["idAffectation" => $Idaffectation]);
  218.         $report->setAffectation($affectation);
  219.         // $congeScolaire = $affectation->getCalendrierScolaire();
  220.         $getRefCalendrier =  $entityManager
  221.             ->getRepository(RefAffectationCalendrier::class)
  222.             ->getRefCalendrier($Idaffectation);
  223.         $congeScolaire $getRefCalendrier['calendrierScolaire'];
  224.         $dateBasculeCongeSolaire $getRefCalendrier['dateBascule'];
  225.         $today = (new \DateTime());
  226.         $year $today->format("Y");
  227.         // $dateBasculeCongeSolaire = $affectation->getDateBascule();
  228.         $typeCalendrier = ($congeScolaire) ? 's' 'c';
  229.         $report->setTypeCalendrier($typeCalendrier);
  230.         if ((true === $congeScolaire) && ($dateBasculeCongeSolaire $today) && ($today < new \DateTime("$year-09-01"))) {
  231.             $report->setAnnee($year 1);
  232.             // $report->setAnnee($year);
  233.         } else {
  234.             $report->setAnnee($year);
  235.             // $report->setAnnee($year +1);
  236.         }
  237.         $accessRuleService $this->getServiceAccessRule();
  238.         if (!$accessRuleService->hasRightWithoutCheckAffectation($report->getUtilisateur(), $this->getUser())) {
  239.             return false;
  240.         }
  241.         $entityManager->persist($report);
  242.         // $entityManager->flush();
  243.         // Retourner une valeur booléenne pour indiquer si la création du rapport a réussi
  244.         return true;
  245.     }
  246.     private function sendMailNotification()
  247.     {
  248.         $em $this->doctrine->getManager();
  249.         $gabRep $em->getRepository(RefGabarit::class);
  250.         $ui $this->getUser();
  251.         $uid $this->getUser()->getUtilisateur()->getIdUtilisateur();
  252.         $uimail $em->getRepository(Utilisateur::class)->findBy(['idUtilisateur' => $uid])[0]->getCourriel();
  253.         $role $this->getUser()->getUtilisateur()->getIdRole();
  254.         $subject sprintf('CTS-WEB : Demande de report  à valider - %s %s'$ui->getNom(), $ui->getPrenom());
  255.         $emailMailer $this->getParameter('mailer_user');
  256.         $expediteurMail =  (filter_var($emailMailerFILTER_VALIDATE_EMAIL)) ? $emailMailer 'donotreply@sports.gouv.fr';
  257.         //$host = $this->getParameter('host');
  258.         $mail_contact null;
  259.         $mail_ass_info $this->doctrine->getManager()->getRepository(ParametrageTexte::class)->getByCode('COURRIEL_ASSISTANCE_INFO');
  260.         if ((is_countable($mail_ass_info) ? count($mail_ass_info) : 0) > 0)
  261.             $mail_contact $mail_ass_info[0]->getTexte();
  262.         if (RefRole::ROLE_FEDE === $role || RefRole::ROLE_FEDE_INVITE === $role || RefRole::ROLE_CTS === $role) {
  263.             $federation $ui->getIdFederation()->getIdFederation();
  264.             $affectation $ui->getIdAffectation()->getIdAffectation();
  265.         } else {
  266.             $federation null;
  267.             $affectation $ui->getIdAffectation()->getIdAffectation();
  268.         }
  269.         $recipients $gabRep->emailNotification($federation$affectation'emailConges');
  270.         // if (!filter_var($recipients, FILTER_VALIDATE_EMAIL)) {
  271.         //     $recipients = [];
  272.         // }
  273.         if (!empty($recipients)) {
  274.             $message = (new Email())
  275.                 ->subject($subject)
  276.                 ->from($expediteurMail)
  277.                 ->to(...$recipients)
  278.                 ->html(
  279.                     $this->twig->render(
  280.                         'Notification/notification_report_dtn.html.twig',
  281.                         ['host' => $mail_contact'civility' => $ui->getCivilite(), 'lastname' => $ui->getNom(), 'firstname' => $ui->getPrenom(), 'mailDemandeur' => $expediteurMail]
  282.                     ),
  283.                     'text/html'
  284.                 );
  285.             $this->mailer->send($message);
  286.         }
  287.     }
  288.     /**
  289.      * @return JsonResponse
  290.      */
  291.     #[Route(path'/api/update_reports/{id}'name'ctsweb_update_report'methods: ['POST'], requirements: ['id' => '\d+'])]
  292.     public function update(Request $requestDemandeReport $report)
  293.     {
  294.         $utilisateurInformation $this->getUser();
  295.         $utilisateur $utilisateurInformation->getUtilisateur();
  296.         $idRole $utilisateur->getIdRole();
  297.         $accessRuleService $this->getServiceAccessRule();
  298.         if (!$accessRuleService->hashRightToModifyReport($report)) {
  299.             return new JsonResponse(''JsonResponse::HTTP_FORBIDDEN);
  300.         }
  301.         // $report = new Conge();
  302.         $form $this->handleRequest($request$report'all''post');
  303.         $em $this->doctrine->getManager();
  304.         $repository $em->getRepository(DemandeReport::class);
  305.         $popup false;
  306.         if ($form->isSubmitted() && $form->isValid()) {
  307.             $em $this->doctrine->getManager();
  308.             $workflow $em->getRepository(Workflow::class)->find(Workflow::RE_WAITING);
  309.             if (Workflow::RE_SIGN !== $report->getWorkflow()->getIdWorkflow())
  310.                 $report->setWorkflow($workflow);
  311.             $entityManager $this->doctrine->getManager();
  312.             if ($idRole == RefRole::ROLE_CTS || $idRole == RefRole::ROLE_FEDE || $idRole == RefRole::ROLE_FEDE_INVITE) {
  313.                 $solderestant $this->solderestant($utilisateur$report->getNbJour());
  314.                 if (!$solderestant) {
  315.                     $result = [
  316.                         'success' => false,
  317.                         'error' => 'Le nombre de jour demandé est superieure au solde de congé restante'
  318.                     ];
  319.                     return new JsonResponse($resultJsonResponse::HTTP_BAD_REQUEST);
  320.                 }
  321.             }
  322.             $entityManager->persist($report);
  323.             $entityManager->flush();
  324.             $result = ['success' => true];
  325.             $status JsonResponse::HTTP_OK;
  326.         } else {
  327.             $result = [
  328.                 'success' => false,
  329.                 'data' => self::ERROR_VALIDATION_FORM,
  330.                 'error' => (string) $form->getErrors(truefalse)
  331.             ];
  332.             $status JsonResponse::HTTP_BAD_REQUEST;
  333.         }
  334.         return new JsonResponse($result$status);
  335.     }
  336.     #[Route(path'/api/delete_reports/{id}'name'ctsweb_delete_report'requirements: ['id' => '\d+'])]
  337.     public function delete(DemandeReport $report)
  338.     {
  339.         try {
  340.             $em $this->doctrine->getManager();
  341.             $repository $em->getRepository(DemandeReport::class);
  342.             $cg $repository->findOneBy(['id' => $report->getId()]);
  343.             if ($cg) {
  344.                 if ($cg->getWorkflow()->getIdWorkflow() == Workflow::RE_SIGN) {
  345.                     $workflow $em->getRepository(Workflow::class)->find(Workflow::RE_ANNULE);
  346.                     $report->setWorkflow($workflow);
  347.                     $em->persist($report);
  348.                     $em->flush();
  349.                     $repository->annulerreport($report);
  350.                     $data = ['success' => true'data' => 'Le  report  a été annulé'];
  351.                     return new JsonResponse($data);
  352.                 } else {
  353.                     $repository->deleteReport($report);
  354.                     $data = ['success' => true'data' => 'Le  report  a été supprimé'];
  355.                     return new JsonResponse($data);
  356.                 }
  357.             }
  358.         } catch (\Exception $e) {
  359.             $data = ['success' => false'data' => $e->getMessage()];
  360.             return new JsonResponse($data);
  361.         }
  362.     }
  363.     /**
  364.      * @return JsonResponse
  365.      */
  366.     #[Route(path'/api/report/{id}/change-status'name'ctsweb_change_status_report'methods: ['POST'], requirements: ['id' => '\d+'])]
  367.     public function changeStatus(Request $requestDemandeReport $report)
  368.     {
  369.         $accessRuleService $this->getServiceAccessRule();
  370.         if (!$accessRuleService->isAdmin()) {
  371.             return new JsonResponse(''JsonResponse::HTTP_FORBIDDEN);
  372.         }
  373.         $form $this->handleRequest($request$report'status''status');
  374.         if ($form->isSubmitted() && $form->isValid()) {
  375.             $report->setFrom(DemandeReport::ADMIN);
  376.             $entityManager $this->doctrine->getManager();
  377.             $entityManager->flush();
  378.             $result = ['success' => true];
  379.             $status JsonResponse::HTTP_OK;
  380.         } else {
  381.             $result = [
  382.                 'success' => false,
  383.                 'data' => self::ERROR_VALIDATION_FORM,
  384.                 'error' => (string) $form->getErrors(truefalse)
  385.             ];
  386.             $status JsonResponse::HTTP_BAD_REQUEST;
  387.         }
  388.         return new JsonResponse($result$status);
  389.     }
  390.     /**
  391.      * @return JsonResponse
  392.      */
  393.     #[Route(path'/api/report/response/{id}'name'ctsweb_response_report'methods: ['POST'], requirements: ['id' => '\d+'])]
  394.     public function response(Request $requestDemandeReport $report)
  395.     {
  396.         $form $this->handleRequest(
  397.             $request,
  398.             $report,
  399.             'response',
  400.             'response'
  401.         );
  402.         if ($form->isValid()) {
  403.             $accessRuleService $this->getServiceAccessRule();
  404.             $this->update($request$report);
  405.             if (DemandeReport::DTN === $report->getFrom()) {
  406.                 if (!$accessRuleService->hashRightToResponseReport($report) && !$accessRuleService->isAdmin()) {
  407.                     return new JsonResponse(''JsonResponse::HTTP_FORBIDDEN);
  408.                 }
  409.             } elseif (DemandeReport::MANAGER === $report->getFrom() || DemandeReport::ADMIN === $report->getFrom()) {
  410.                 $this->setWorkflow($report);
  411.             }
  412.             $entityManager $this->doctrine->getManager();
  413.             $entityManager->flush();
  414.             if ($report->getResponse() && !is_null($report->getId())) {
  415.                 $role $this->getUser()->getUtilisateur()->getIdRole();
  416.                 if (in_array($roleUtilisateur::MANAGER)) {
  417.                     $this->initSignatureConges($report->getId());
  418.                 }
  419.             }
  420.             $result = ["success" => true];
  421.             $response JsonResponse::HTTP_OK;
  422.         } else {
  423.             $result = [
  424.                 'success' => false,
  425.                 'data' => self::ERROR_VALIDATION_FORM,
  426.                 'error' => (string) $form->getErrors(truefalse)
  427.             ];
  428.             $response JsonResponse::HTTP_BAD_REQUEST;
  429.         }
  430.         return new JsonResponse($result$response);
  431.     }
  432.     /**
  433.      * @return JsonResponse
  434.      */
  435.     #[Route(path'/api/report/generate-to-print'name'ctsweb_print_report'methods: ['POST'])]
  436.     public function generateToPrint(Request $request)
  437.     {
  438.         $accessRuleService $this->getServiceAccessRule();
  439.         if (!$accessRuleService->hasRightForTakingDayOff()) {
  440.             return new JsonResponse(''JsonResponse::HTTP_FORBIDDEN);
  441.         }
  442.         $report = new DemandeReport();
  443.         $form $this->handleRequest($request$report'all''post');
  444.         $em $this->doctrine->getManager();
  445.         $repository $em->getRepository(DemandeReport::class);
  446.         try {
  447.             if ($form->isSubmitted() && $form->isValid()) {
  448.                 $entityManager $this->doctrine->getManager();
  449.                 $report->setUtilisateur($this->getUser()->getUtilisateur());
  450.                 $serviceGeneratePdf $this->generatePdf;
  451.                 $entityManager->persist($report);
  452.                 $content $serviceGeneratePdf->generateReportPdf($reporttrue);
  453.                 $filename sha1($report->getId()) . '.pdf';
  454.                 $response $this->getResponse($content$filename);
  455.             } else {
  456.                 $response = new JsonResponse(['error' => self::ERROR_FILE], JsonResponse::HTTP_BAD_REQUEST);
  457.             }
  458.         } catch (\Exception) {
  459.             $response = new JsonResponse(['error' => self::ERROR_FILE], JsonResponse::HTTP_BAD_REQUEST);
  460.         }
  461.         return $response;
  462.     }
  463.     /**
  464.      * @return Response
  465.      */
  466.     #[Route(path'/api/report/pdf/{id}'name'ctsweb_reports_generate-pdf'methods: ['GET'], requirements: ['id' => '\d+'])]
  467.     public function pdf(DemandeReport $report)
  468.     {
  469.         if (
  470.             Workflow::RE_REJECT === $report->getWorkflow()->getIdWorkflow()
  471.             || Workflow::RE_SIGN === $report->getWorkflow()->getIdWorkflow()
  472.         ) {
  473.             $filename sha1($report->getId()) . '.pdf';
  474.             $path $this->getParameter('dir_file_report') . $filename;
  475.             if (file_exists($path)) {
  476.                 $content file_get_contents($pathFILE_USE_INCLUDE_PATH);
  477.                 $response $this->getResponse($content$filename);
  478.             } else {
  479.                 $response = new JsonResponse(['error' => self::ERROR_FILE], JsonResponse::HTTP_BAD_REQUEST);
  480.             }
  481.         } else {
  482.             $serviceGeneratePdf $this->generatePdf;
  483.             $content $serviceGeneratePdf->generateReportPdf($reportfalse);
  484.             $filename sha1($report->getId()) . '.pdf';
  485.             $response $this->getResponse($content$filename);
  486.         }
  487.         return $response;
  488.     }
  489.     #[Route(path'/api/report/status/list'name'ctsweb_reports_status-list-pdf'methods: ['GET'], requirements: ['id' => '\d+'])]
  490.     public function statusList(): JsonResponse
  491.     {
  492.         $entityManager $this->doctrine->getManager();
  493.         $statuses $entityManager
  494.             ->getRepository(Workflow::class)
  495.             ->findBy(['idWorkflow' => Workflow::FILTER]);
  496.         return new JsonResponse(
  497.             $this->serialize($statuses),
  498.             JsonResponse::HTTP_OK,
  499.             [],
  500.             true
  501.         );
  502.     }
  503.     #[Route(path'/api/report/access/{conge}'name'ctsweb_reports_access'methods: ['GET'], requirements: ['conge' => '\d+'])]
  504.     public function accesreport(utilisateur $conge)
  505.     {
  506.         $entityManager $this->doctrine->getManager();
  507.         $user $this->getUser();
  508.         $utilisateur $conge->getidUtilisateur();
  509.         $utilisateurInformation $entityManager
  510.             ->getRepository(UtilisateurInformation::class)
  511.             ->findOneBy(["idUtilisateur" => $utilisateur]);
  512.         $Idaffectation $utilisateurInformation->getIdAffectation()->getIdAffectation();
  513.         $affectation $entityManager
  514.             ->getRepository(RefAffectation::class)
  515.             ->findOneBy(["idAffectation" => $Idaffectation]);
  516.         $getRefCalendrier =  $entityManager
  517.             ->getRepository(RefAffectationCalendrier::class)
  518.             ->getRefCalendrier($Idaffectation);
  519.         $congeScolaire $getRefCalendrier['calendrierScolaire'];
  520.         $year $this->getYear($user);
  521.         $statuses $entityManager
  522.             ->getRepository(DemandeReport::class)
  523.             ->accessReport($year$user$congeScolaire);
  524.         return new JsonResponse(
  525.             $this->serialize($statuses),
  526.             JsonResponse::HTTP_OK,
  527.             [],
  528.             true
  529.         );
  530.     }
  531.     /**
  532.      * @return \Symfony\Component\Form\FormInterface
  533.      */
  534.     private function handleRequest(
  535.         Request $request,
  536.         DemandeReport $report,
  537.         string $label,
  538.         string $validationGroup
  539.     ) {
  540.         $data json_decode($request->getContent(), true512JSON_THROW_ON_ERROR);
  541.         $request->request->replace(is_array($data) ? $data : []);
  542.         $form $this->createForm(
  543.             DemandeReportType::class,
  544.             $report,
  545.             ['label' => $label'validation_groups' => $validationGroup]
  546.         );
  547.         $form->handleRequest($request);
  548.         return $form;
  549.     }
  550.     /**
  551.      * @param array $states
  552.      * @return mixed
  553.      */
  554.     private function serializeto($item)
  555.     {
  556.         $data = [$item];
  557.         $context = new SerializationContext();
  558.         $context->setSerializeNull(true);
  559.         return $this->serializer->serialize($data'json'$context);
  560.     }
  561.     /**
  562.      * @param array $states
  563.      * @return mixed
  564.      */
  565.     private function serialize($item)
  566.     {
  567.         $data = ["items" => $item];
  568.         $context = new SerializationContext();
  569.         $context->setSerializeNull(true);
  570.         return $this->serializer->serialize($data'json'$context);
  571.     }
  572.     /**
  573.      * @return object
  574.      */
  575.     private function getServiceAccessRule()
  576.     {
  577.         return $this->accessRule;
  578.     }
  579.     private function setWorkflow(DemandeReport $report)
  580.     {
  581.         $workflow Workflow::RE_REJECT;
  582.         if ($report->getResponse()) {
  583.             $workflow Workflow::RE_SIGN;
  584.         }
  585.         $entityManager $this->doctrine->getManager();
  586.         $workflowEntity $entityManager
  587.             ->getRepository(Workflow::class)
  588.             ->find($workflow);
  589.         $report->setWorkflow($workflowEntity);
  590.     }
  591.     public function getResponse(string $contentstring $filename): Response
  592.     {
  593.         return new Response(
  594.             $content,
  595.             Response::HTTP_OK,
  596.             [
  597.                 'Content-Type' => 'application/pdf',
  598.                 'Content-Length' => strlen($content),
  599.                 'Content-Disposition' => "attachment;filename=\"{$filename}",
  600.                 'Accept-Ranges' => 'bytes'
  601.             ]
  602.         );
  603.     }
  604.     public function initSignatureConges($idconges)
  605.     {
  606.         try {
  607.             // $listeConges =   explode(',', $request->request->get('listeConges'));
  608.             // $listeConges = json_decode($request->getContent(), true);
  609.             $em $this->doctrine->getManager();
  610.             $reportsRepo $em->getRepository(DemandeReport::class);
  611.             $workflow $em->getRepository(Workflow::class)->find(Workflow::RE_SIGN);
  612.             $jourdhui = (new \DateTime())->format('Y-m-d');
  613.             $utilisateurRepository $em->getRepository(Utilisateur::class);
  614.             $congObj $reportsRepo->find($idconges);
  615.             $idUtilisateur $congObj->getUtilisateur()->getIdUtilisateur();
  616.             $affectation $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($idUtilisateur)->getIdAffectation()->getIdAffectation();
  617.             if ($affectation != 1) {
  618.                 $drsignataire $em->getRepository(UtilisateurInformation::class)->findDrSuperieur($affectation);
  619.             } else {
  620.                 $drsignataire $em->getRepository(UtilisateurInformation::class)->findDsSuperieur($affectation);
  621.             }
  622.             $signataire $em->getRepository(UtilisateurInformation::class)->findOneByIdUtilisateur($drsignataire);
  623.             $info_signature = array(
  624.                 'nom' => $signataire->getNom(),
  625.                 'prenom' => $signataire->getPrenom(),
  626.                 'dateSignature' => date("d/m/Y"),
  627.                 'sup' => true,
  628.                 'fonction' => $signataire->getFonction(),
  629.                 'path' => $signataire->getScan() ? $this->getParameter('dir_file_signature') . $signataire->getScan()->getAbsolutePath() : '',
  630.                 'civilite' => $signataire->getCivilite()
  631.             );
  632.             //  foreach ($listeConges as $report) {
  633.             $congObj $reportsRepo->find($idconges);
  634.             $congObj->setWorkflow($workflow);
  635.             $idUtilisateur $congObj->getUtilisateur()->getIdUtilisateur();
  636.             $email $utilisateurRepository->findCourrielById($idUtilisateur)[0]['courriel'];
  637.             $mail $this->emailSHDecision->getMail(
  638.                 EmailSHDecision::SIGNED,
  639.                 EmailSHDecision::RE,
  640.                 $email,
  641.             );
  642.             if ($mail) {
  643.                 $this->mailer->send($mail);
  644.             }
  645.             // $info_signature['dateSignature']=$congObj->getDateDerniereModification();
  646.             //  $em->setDateDeSignature($jourdhui);
  647.             //  $em->setSignataire($signataire);
  648.             $em->persist($congObj);
  649.             $em->flush();
  650.             // UPDATE ET CREE RAA dans la table conge_droit_annuel
  651.             $this->createUpdateRAA($congObj);
  652.             $this->generatePdf->generateReportPdf($congObjfalse$affectation$info_signature);
  653.             // }
  654.             $message 'Tous les demandes de report ont été signés avec succès.';
  655.             $return = array(
  656.                 'success' => true,
  657.                 'data' => $message
  658.             );
  659.         } catch (\Exception $e) {
  660.             $message 'Un ou plusieurs reports n\'ont pu être signés.';
  661.             $return = array(
  662.                 'success' => false,
  663.                 'data' => $e->getMessage()
  664.             );
  665.         }
  666.         return new JsonResponse(
  667.             $return,
  668.             JsonResponse::HTTP_CREATED
  669.         );
  670.     }
  671.     public function createUpdateRAA(DemandeReport $report)
  672.     {
  673.         $entityManager $this->doctrine->getManager();
  674.         $congeDroitAnnuelRepository $entityManager->getRepository(CongeDroitAnnuel::class);
  675.         $raaId 4;
  676.         $raa $entityManager->find(CongeType::class, $raaId);
  677.         if (!$raa) {
  678.             throw new \Exception("Impossible de trouver l'entité CongeType avec l'ID $raaId.");
  679.         }
  680.         $utilisateurInformation $entityManager
  681.             ->getRepository(UtilisateurInformation::class)
  682.             ->findOneBy(["idUtilisateur" => $report->getUtilisateur()]);
  683.         $Idaffectation $utilisateurInformation->getIdAffectation()->getIdAffectation();
  684.         $getRefCalendrier =  $entityManager
  685.             ->getRepository(RefAffectationCalendrier::class)
  686.             ->getRefCalendrier($Idaffectation);
  687.         $dateBasculeCongeSolaire $getRefCalendrier['dateBascule'];
  688.         $congeScolaire $getRefCalendrier['calendrierScolaire'];
  689.         $dateBasculeCongeSolaire $getRefCalendrier['dateBascule'];
  690.         $today = (new \DateTime());
  691.         $year $today->format("Y");
  692.         if ((true === $congeScolaire) && ($dateBasculeCongeSolaire $today) && ($today < new \DateTime("$year-09-01"))) {
  693.             $Annee =  $year;
  694.         }
  695.         else{
  696.             $Annee $year+;
  697.         }
  698.         $Type_cal = ($getRefCalendrier['calendrierAffectation']) ? 's' 'c';
  699.         $existingCongeDroitAnnuel $congeDroitAnnuelRepository->findOneBy([
  700.             'congeType' => $raa,
  701.             'utilisateur' => $report->getUtilisateur(),
  702.             'annee' => $Annee,
  703.             'typeCalendrier' =>$Type_cal,
  704.         ]);
  705.         if (!$existingCongeDroitAnnuel) {
  706.             // create
  707.             $newCongeDroitAnnuel = new CongeDroitAnnuel();
  708.             $newCongeDroitAnnuel->setCongeType($raa);
  709.             $newCongeDroitAnnuel->setUtilisateur($report->getUtilisateur());
  710.             $newCongeDroitAnnuel->setAnnee($Annee);
  711.             $newCongeDroitAnnuel->setTypeCalendrier($Type_cal);
  712.             $newCongeDroitAnnuel->setNbJourTotal($report->getNbJour());
  713.             $newCongeDroitAnnuel->setArchive(false);
  714.             $entityManager->persist($newCongeDroitAnnuel);
  715.             $entityManager->flush();
  716.             return true;
  717.         } else {
  718.             // Update
  719.             $existingCongeDroitAnnuel->setNbJourTotal($report->getNbJour());
  720.             $entityManager->flush();
  721.             return true;
  722.         }
  723.     }
  724.     public function getYear($user)
  725.     {
  726.         $entityManager $this->doctrine->getManager();
  727.         // Récupérer les informations de l'utilisateur
  728.         $Idaffectation $user->getIdAffectation()->getIdAffectation();
  729.         $today = (new \DateTime());
  730.         $year $today->format("Y");
  731.         $getRefCalendrier =  $entityManager
  732.             ->getRepository(RefAffectationCalendrier::class)
  733.             ->getRefCalendrier($Idaffectation);
  734.         $congeScolaire $getRefCalendrier['calendrierScolaire'];
  735.         $dateBasculeCongeSolaire $getRefCalendrier['dateBascule'];
  736.         if ((true === $congeScolaire) && ($dateBasculeCongeSolaire $today) && ($today < new \DateTime("$year-09-01"))) {
  737.             return $year 1;
  738.         } else {
  739.             return $year;
  740.         }
  741.         return $year;
  742.     }
  743.     public function getAnneeSaisie(
  744.         int $id,
  745.         int $n
  746.     ) {
  747.         $congesDroitsAnnees = [];
  748.         $entityManager $this->doctrine->getManager();
  749.         $utilisateurInformation $entityManager
  750.             ->getRepository(UtilisateurInformation::class)
  751.             ->findOneBy(["idUtilisateur" => $id]);
  752.         // $affectation = $utilisateurInformation->getIdAffectation();
  753.         // $congeScolaire = $affectation->getCalendrierScolaire();
  754.         // $dateBascule = $affectation->getDateBascule();
  755.         $idaffectation $utilisateurInformation->getIdAffectation()->getIdAffectation();
  756.         $getRefCalendrier =  $entityManager
  757.             ->getRepository(RefAffectationCalendrier::class)
  758.             ->getRefCalendrier($idaffectation);
  759.         $congeScolaire $getRefCalendrier['calendrierScolaire'];
  760.         $dateBascule $getRefCalendrier['dateBascule'];
  761.         $today = new \DateTime();
  762.         $currentYear $today->format('Y');
  763.         if ($n == 0) {
  764.             $year $currentYear 1;
  765.             $currentDay $today;
  766.         } else {
  767.             $year $currentYear;
  768.             $currentDay $today;
  769.         }
  770.         $currentDay $currentDay->format('Y-m-d');
  771.         $nextYear $year 1;
  772.         $lastYear $year 1;
  773.         if ((true == $congeScolaire) && (null != $dateBascule) && ($currentDay >= $dateBascule)) {
  774.             if ($n == 1) {
  775.                 $congesDroitsAnnees['libelle'] =   $lastYear "/" $year;
  776.             } else {
  777.                 $congesDroitsAnnees['libelle'] = strval($year);
  778.             }
  779.         } elseif ((true == $congeScolaire) && (null != $dateBascule) && ($currentDay $dateBascule)) {
  780.             $congesDroitsAnnees['libelle'] = strval($year);
  781.         } elseif ((false == $congeScolaire) && (null != $dateBascule) && ($currentDay <= $dateBascule)) {
  782.             $congesDroitsAnnees['libelle'] =   $lastYear "/" $year;
  783.         } else {
  784.             $congesDroitsAnnees['libelle'] = strval($year);
  785.         }
  786.         return $congesDroitsAnnees;
  787.     }
  788. }