src/Controller/AlertController.php line 352

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. ini_set("memory_limit""2G");
  4. set_time_limit(800);
  5. use DateTime;
  6. use Mandrill;
  7. use Exception;
  8. use App\Entity\Etat;
  9. use App\Entity\User;
  10. use App\Entity\Actor;
  11. use App\Entity\Alert;
  12. use App\Entity\Pcode;
  13. use Twig\Environment;
  14. use App\Entity\Cluster;
  15. use App\Entity\Process;
  16. use App\Form\AlertType;
  17. use App\Entity\Decision;
  18. use App\Entity\Document;
  19. use App\Entity\RrmGtacq;
  20. use App\Entity\WorkFlow;
  21. use App\Entity\Procedure;
  22. use App\Entity\AlertDetail;
  23. use App\Entity\EventReason;
  24. use App\Entity\RrmCaseload;
  25. use Psr\Log\LoggerInterface;
  26. use App\Entity\AlertDocument;
  27. use App\Entity\EventSousType;
  28. use App\Form\AlertAvorteType;
  29. use App\Form\DetailAlertType;
  30. use App\Form\SearchAlertType;
  31. use Ramsey\Uuid\Type\Integer;
  32. use App\Entity\RrmPonderation;
  33. use App\Form\SearchDocumentType;
  34. use App\Service\MandrillService;
  35. use Symfony\Component\Mime\Email;
  36. use App\Entity\AlertAccommodation;
  37. use App\Entity\AlertAgglomeration;
  38. use App\Form\NextProcessAlertType;
  39. use App\Entity\EhtoolsNotification;
  40. use Symfony\Component\Mime\Address;
  41. use Doctrine\ORM\EntityManagerInterface;
  42. use Symfony\Component\Form\AbstractType;
  43. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  44. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  45. use Sentry\EventType;
  46. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  47. use Symfony\Component\HttpFoundation\Request;
  48. use Symfony\Component\Mailer\MailerInterface;
  49. use Symfony\Component\HttpFoundation\Response;
  50. use Symfony\Component\Routing\Annotation\Route;
  51. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  52. use Symfony\Component\HttpFoundation\JsonResponse;
  53. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  54. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  55. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  56. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  57. class AlertController extends AbstractController
  58. {
  59.     private $em;
  60.     private $logger;
  61.     private $mailer;
  62.     private $twig;
  63.     private $mandrillService;
  64.     public function __construct(EntityManagerInterface $emLoggerInterface $loggerMailerInterface $mailerEnvironment $twigMandrillService $mandrillService)
  65.     {
  66.         $this->em $em;
  67.         $this->logger $logger;
  68.         $this->mailler $mailer;
  69.         $this->twig $twig;
  70.         //$this->mandrillService = $mandrillService;
  71.         // $this->mandrillService = new Mandrill('md-z_sIqHhENLSpPIsUDryYLA');
  72.         $this->mandrillService = new Mandrill('md-xgYZd4-I5EVZUfxAiThadg');
  73.       
  74.     }
  75.     public function add(Request $requestEntityManagerInterface $em)
  76.     {
  77.         if (!$this->isGranted('ROLE_ENCODEUR')) {
  78.             return $this->redirectToRoute('ehtools_exception');
  79.         }
  80.         // $em = $em->getManager();
  81.         $alert = new Alert();
  82.         // $currentDate = \DateTime::createFromFormat();
  83.         // dump($currentDate);
  84.         $alertform $this->createForm(AlertType::class, $alert);
  85.         $countryId $this->getUser()->getCountry()->getId();
  86.         $country $em->getRepository(Pcode::class)->findOneBy([
  87.             'id' => $countryId,
  88.         ]);
  89.         $alertform->handleRequest($request);
  90.         if ($alertform->isSubmitted() && $alertform->isValid()) {
  91.             $strDate $alertform->get('startDate')->getData();
  92.             $startDate = new \DateTime($strDate);
  93.             $alert->setUserCreate($this->getUser());
  94.             $alert->setStartDate($startDate);
  95.             $alert->setCountry($country);
  96.             $eventSousType$this->em->getRepository(EventSousType::class)->findBy(['id'=>$request->get('eventSousType')])[0];
  97.             $accommodation$this->em->getRepository(AlertAccommodation::class)->findBy(['id'=>$request->get('accommodation')])[0];
  98.             
  99.             $alert->setEventSousType($eventSousType);
  100.             $alert->setAccommodation($accommodation);
  101.             $em->persist($alert);
  102.             $em->flush();
  103.             $this->addFlash('success_message'"l'alerte a été créee avec succès prière de lui ajouter au moins un détails avant de le valider!");
  104.             return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  105.         }
  106.         return $this->render('alert/add.html.twig', ['alertForm' => $alertform->createView()]);
  107.     }
  108.     public function view(Request $requestEntityManagerInterface $em)
  109.     {
  110.         $alert $em->getRepository(Alert::class)->findOneBy([
  111.             'id' => $request->get('id'),
  112.         ]);
  113.         if (is_null($alert)) {
  114.             $this->addFlash('warning_message'"Alerte non trouvée dans la base de données, prière de selectionner une alerte!");
  115.             return $this->redirectToRoute('ehtools_alert_register');
  116.         }
  117.         $alertDetails $em->getRepository(AlertDetail::class)->findBy([
  118.             'alert' => $alert,
  119.             'isDeleted' => false,
  120.         ]);
  121.         $listProcess $em->getRepository(Process::class)->findBy([
  122.             'alert' => $alert,
  123.         ]);
  124.         $documents $em->getRepository(AlertDocument::class)->findBy([
  125.             'alert' => $alert,
  126.         ]);
  127.         $process null;
  128.         if (!is_null($listProcess) && count($listProcess) > 0) {
  129.             $listProcess array_reverse($listProcess);
  130.             $process $listProcess[0];
  131.         }
  132.         //dump($process);
  133.         $workFlows = [];
  134.         $procedure $em->getRepository(Procedure::class)->findOneBy([], ['id' => 'DESC']);
  135.         if (!is_null($procedure)) {
  136.             $workFlows $em->getRepository(WorkFlow::class)->findBy([
  137.                 'procedureID' => $procedure,
  138.             ]);
  139.         }
  140.         $endProcess false;
  141.         $isLastProcess false;
  142.         if (!is_null($listProcess) && !is_null($workFlows)) {
  143.             //dump(count($listProcess)."|".count($workFlows));
  144.             if (count($workFlows) == count($listProcess)) {
  145.                 $endProcess true;
  146.             } else {
  147.                 if (count($workFlows) - count($listProcess) == 1) {
  148.                     $isLastProcess true;
  149.                 }
  150.             }
  151.         }
  152.         return $this->render('alert/view.html.twig', [
  153.             'alert' => $alert,
  154.             'alertDetails' => $alertDetails,
  155.             'endProcess' => $endProcess,
  156.             'process' => $process,
  157.             'workFlows' => $workFlows,
  158.             'documents' => $documents,
  159.             'isLastProcess' => $isLastProcess,
  160.             '$listProcess' => $listProcess,
  161.         ]);
  162.     }
  163.     public function validate(Alert $alertRequest $requestEntityManagerInterface $emMailerInterface $mailer): Response
  164.     {
  165.         if (!$this->isGranted('ROLE_ENCODEUR')) {
  166.             return $this->redirectToRoute('ehtools_exception');
  167.         }
  168.         if ($alert->getId() instanceof Alert) {
  169.             $this->addFlash('warning_message'"Alerte non trouvée dans la base de données");
  170.             return $this->redirectToRoute('ehtools_alert_register');
  171.         } else {
  172.             $details $em->getRepository(AlertDetail::class)->findBy([
  173.                 'alert' => $alert,
  174.             ]);
  175.             if (is_null($details) || count($details) < 1) {
  176.                 $this->addFlash('danger_message'"Impossible de valider l'alerte, prière d'ajouter au moins un détail");
  177.                 return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  178.             }
  179.             $procedure $em->getRepository(Procedure::class)->findOneBy([], ['id' => 'DESC']);
  180.             if (!is_null($procedure)) {
  181.                 $workFlow $em->getRepository(WorkFlow::class)->findOneBy([
  182.                     'procedureID' => $procedure,
  183.                 ], ['id' => 'ASC']);
  184.                 $etat $em->getRepository(Etat::class)->findOneBy([
  185.                     'id' => 1,
  186.                 ]);
  187.                 $process = new Process();
  188.                 $process->setAlert($alert);
  189.                 $process->setProcedureA($procedure);
  190.                 $process->setWorkflow($workFlow);
  191.                 $process->setUsercreate($this->getUser());
  192.                 $process->setEtat($etat);
  193.                 $process->setDatecreate(new \DateTime());
  194.                 //Alert Score de Severité RRM
  195.                 $rrmScore=$this->rrmScore($alert);
  196.                 $alert->setSeverityAlertRrm($rrmScore);
  197.                 $alert->setIsValid(true);
  198.                 $alert->setStatut($process);
  199.                 // $em = $em->getManager();
  200.                 $em->persist($alert);
  201.                 $em->persist($process);
  202.                 $em->flush();
  203.                 // send email
  204.                 try {
  205.                     $userConnect $this->getUser();
  206.                     $userEmail $userConnect->getEmail();
  207.                     $alertID $alert->getId();
  208.                     $alertSeverity round($alert->getSeverityAlertRrm(), 2);
  209.                     $eventReason $alert->getEventReason()->getLabel();
  210.                 
  211.                     $details $em->getRepository(AlertDetail::class)->findOneBy([
  212.                         'alert' => $alertID
  213.                     ]);
  214.                 
  215.                     $admin1Id $details->getAdmin1()->getId();
  216.                     $admin2Id $details->getAdmin2()->getId();
  217.                     $admin1 $this->em->getRepository(Pcode::class)->find($admin1Id);
  218.                     $admin2 $this->em->getRepository(Pcode::class)->find($admin2Id);
  219.                     $province $admin1->getLabel();
  220.                     $territoire $admin2->getLabel();
  221.                 
  222.                     $url "https://ehtools.org/alert-view/$alertID";
  223.                 
  224.                     // Récupérer les emails en CC depuis ehtoolsNotification
  225.                     $ccUsers $this->getDoctrine()->getRepository(EhtoolsNotification::class)->findBy(['isActive'=>true]);
  226.                     $ccEmails = [];
  227.                     foreach ($ccUsers as $ccUser) {
  228.                         $ccEmails[] = $ccUser->getEmail();
  229.                     }
  230.                 
  231.                     // Fusionner tous les destinataires (utilisateur principal + CC)
  232.                     $allRecipients array_unique(array_merge([$userEmail], $ccEmails));
  233.                 
  234.                     // Template Mandrill
  235.                     $templateName 'ehtoolsTemplateNotification';
  236.                     $templateContent = [
  237.                         ['name' => 'header''content' => 'Welcome to our service!'],
  238.                     ];
  239.                 
  240.                     // Envoi individuel avec personnalisation
  241.                     foreach ($allRecipients as $email) {
  242.                         $message = [
  243.                             'to' => [[
  244.                                 'email' => $email,
  245.                                 'type' => 'to'
  246.                             ]],
  247.                             'from_email' => 'ocha-drc-imunit@un.org',
  248.                             'from_name' => 'COHP-RDC',
  249.                             'subject' => 'Notification ehtools System',
  250.                             'merge' => true,
  251.                             'merge_language' => 'mailchimp',
  252.                             'merge_vars' => [[
  253.                                 'rcpt' => $email,
  254.                                 'vars' => [
  255.                                     ['name' => 'USERNAME''content' => $email],
  256.                                     ['name' => 'CODE_ALERT''content' => $alertID],
  257.                                     ['name' => 'ALERT_ID''content' => $alertID],
  258.                                     ['name' => 'EVENTREASON''content' => $eventReason],
  259.                                     ['name' => 'PROVINCE''content' => $province],
  260.                                     ['name' => 'TERRITOIRE''content' => $territoire],
  261.                                     ['name' => 'SEVERITYRRM''content' => $alertSeverity],
  262.                                     ['name' => 'ALERT_URL''content' => $url],
  263.                                 ]
  264.                             ]]
  265.                         ];
  266.                 
  267.                         // Envoi via Mandrill
  268.                         $this->mandrillService->messages->sendTemplate($templateName$templateContent$message);
  269.                     }
  270.                 
  271.                     // Optionnel : log ou message de confirmation
  272.                 } catch (\Exception $e) {
  273.                     return new JsonResponse(['success' => false'message' => $e->getMessage()]);
  274.                 }
  275.                 
  276.                 $this->addFlash('success_message'"L'alert a été validée avec succès !");
  277.                 return $this->redirectToRoute('ehtools_alert_view', [
  278.                     'id' => $alert->getId(),
  279.                 ]);
  280.             }
  281.             $this->logger->info('After else', []);
  282.         }
  283.         $this->addFlash('warning_message'"La validation a échoué !");
  284.         return $this->render('alert/show_alert.html.twig', [
  285.             'id' => $alert,
  286.         ]);
  287.     }
  288.     public function nextProcess(Alert $alertEntityManagerInterface $emRequest $request)
  289.     {
  290.         if (!$this->isGranted('ROLE_ENCODEUR')) {
  291.             return $this->redirectToRoute('ehtools_exception');
  292.         }
  293.         if ($alert->getId() instanceof Alert) {
  294.             $this->addFlash('warning_message'"Alerte non trouvée dans la base de données");
  295.             return $this->redirectToRoute('ehtools_alert_register');
  296.         }
  297.         $process = new Process();
  298.         $listProcess $em->getRepository(Process::class)->findBy([
  299.             'alert' => $alert,
  300.         ]);
  301.         $currentProcess null;
  302.         if (!is_null($listProcess) && count($listProcess) > 0) {
  303.             $listProcess array_reverse($listProcess);
  304.             $currentProcess $listProcess[0];
  305.         }
  306.         $processform $this->createForm(NextProcessAlertType::class, $currentProcess);
  307.         $processform->handleRequest($request);
  308.         if ($processform->isSubmitted() && $processform->isValid()) {
  309.             $procedure $em->getRepository(Procedure::class)->findOneBy([], ['id' => 'DESC']);
  310.             $strDate $processform->get('dateTraitement')->getData();
  311.             $traitmentDate = new \DateTime($strDate);
  312.             if (!is_null($procedure)) {
  313.                 $listProcess $em->getRepository(Process::class)->findBy([
  314.                     'alert' => $alert,
  315.                 ]);
  316.                 $workFlows $em->getRepository(WorkFlow::class)->findBy([
  317.                     'procedureID' => $procedure,
  318.                 ]);
  319.                 $workFlows $em->getRepository(WorkFlow::class)->createQueryBuilder('w')
  320.                     ->join('w.procedureID''p')
  321.                     ->where('p.id = :p1')
  322.                     ->setParameter('p1'$procedure->getId())
  323.                     ->andWhere('w.id > :p2')
  324.                     ->setParameter('p2'$currentProcess->getWorkflow()->getId())
  325.                     ->getQuery()->getResult();
  326.                 if (!is_null($workFlows) && count($workFlows) > 0) {
  327.                     $nextWorkFlow $workFlows[0];
  328.                     $etat $em->getRepository(Etat::class)->findOneBy(['id' => 1,]);
  329.                     $process->setAlert($alert);
  330.                     $process->setProcedureA($procedure);
  331.                     $process->setWorkflow($nextWorkFlow);
  332.                     $process->setUsercreate($this->getUser());
  333.                     $process->setEtat($etat);
  334.                     //$process->setDateTraitement($startDate);
  335.                     $process->setDatecreate(new \DateTime());
  336.                     $currentProcess->setDateTraitement($traitmentDate);
  337.                     $alert->setStatut($process);
  338.                     if ($request->get('affected') || $request->get('displaced') || $request->get('returned')) {
  339.                         $alert->setAffectedEval($request->get('affected'));
  340.                         $alert->setHouseholdEval($request->get('household'));
  341.                         $alert->setDisplacedEval($request->get('displaced'));
  342.                         $alert->setDisplacedEvalHousehold($request->get('displacedHousehold'));
  343.                         $alert->setReturnedEval($request->get('returned'));
  344.                         $alert->setReturnedEvalHousehold($request->get('returnedHouseHold'));
  345.                     }
  346.                     //$em = $em->getManager();
  347.                     $em->persist($currentProcess);
  348.                     $em->persist($process);
  349.                     $em->persist($alert);
  350.                     $em->flush();
  351.                     $this->addFlash('success_message'"Etape suivante validée avec succès !");
  352.                     return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  353.                 }
  354.             } else {
  355.                 $this->addFlash('warning_message'"L'opération a échoué !");
  356.                 return $this->redirectToRoute('ehtools_alert_register', ['id' => $alert->getId()]);
  357.             }
  358.         }
  359.         return $this->render('alert/next_process.html.twig', [
  360.             'alert' => $alert,
  361.             'processform' => $processform->createView(),
  362.             'currentProcess' => $currentProcess,
  363.         ]);
  364.     }
  365.     public function avorteProcess(Alert $alertEntityManagerInterface $emRequest $request)
  366.     {
  367.         if (!$this->isGranted('ROLE_ENCODEUR')) {
  368.             return $this->redirectToRoute('ehtools_exception');
  369.         }
  370.         if ($alert->getId() instanceof Alert) {
  371.             $this->addFlash('warning_message'"Alerte non trouvée dans la base de données");
  372.             return $this->redirectToRoute('ehtools_alert_register');
  373.         }
  374.         $listProcess $em->getRepository(Process::class)->findBy([
  375.             'alert' => $alert,
  376.         ]);
  377.         $currentProcess null;
  378.         if (!is_null($listProcess) && count($listProcess) > 0) {
  379.             $listProcess array_reverse($listProcess);
  380.             $currentProcess $listProcess[0];
  381.         }
  382.         $alertform $this->createForm(AlertAvorteType::class, $alert);
  383.         $alertform->handleRequest($request);
  384.         if ($alertform->isSubmitted() && $alertform->isValid()) {
  385.             $alert->setUserAvorte($this->getUser());
  386.             $alert->setIsAvorte(true);
  387.             $alert->setDateAvorte(new \DateTime());
  388.             //$em = $em->getManager();
  389.             $em->persist($alert);
  390.             $em->flush();
  391.             $this->addFlash('success_message'"Opération effectuée avec succès!");
  392.             return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  393.         }
  394.         return $this->render('alert/avorte.html.twig', [
  395.             'alert' => $alert,
  396.             'currentProcess' => $currentProcess,
  397.             'alertform' => $alertform->createView(),
  398.         ]);
  399.     }
  400.     public function register(Request $request)
  401.     {
  402.         $searchAlertForm $this->createForm(SearchAlertType::class);
  403.         $workflows $this->em->getRepository(WorkFlow::class)->findBy([]);
  404.         //$detailAlerts = $this->em->getRepository(AlertDetail::class)->findAll([]);
  405.         // $searchAlertForm->add(
  406.         //     'statut',
  407.         //     EntityType::class,
  408.         //     [
  409.         //         'label' => 'Statut',
  410.         //         'required' => false,
  411.         //         'multiple' => true,
  412.         //         'expanded' => true,
  413.         //         'choices' => $workflows,
  414.         //         'choice_label' => 'description',
  415.         //         'choice_value' => 'id',
  416.         //     ]
  417.         // );
  418.         $searchAlertForm->add('statut'EntityType::class, [
  419.             'label' => "- Statut -",
  420.             'required' => false,
  421.             'placeholder' => '- Sélectionner -',
  422.             'help' => "Sélectionnez Statut ",
  423.             'class' => WorkFlow::class,
  424.             //'choice_label' => 'username',
  425.             'choice_label' => 'description',
  426.             'attr' => [
  427.                     'class' => 'chosen-select',
  428.                 ],
  429.             'multiple' => true,
  430.         ]);
  431.         $searchAlertForm->handleRequest($request);
  432.         //$alerts = [];
  433.         //$alerts = $this->em->getRepository(Alert::class)->findByAlertCriteria();
  434.         if ($searchAlertForm->isSubmitted() && $searchAlertForm->isValid()) {
  435.             $criters $searchAlertForm->getData();
  436.             $criters['admin1'] = $searchAlertForm->get('admin1')->getData();
  437.             $criters['admin2'] = $searchAlertForm->get('admin2')->getData();
  438.             //dump($criters);
  439.             //$admin2 =  $searchAlertForm->get('admin2')->getData();
  440.             //$admin2 =  $searchAlertForm->get('valHealthZone')->getData();
  441.             //dump($admin2);
  442.             $alerts $this->em->getRepository(Alert::class)->findByAlertCriteria($criters);
  443.             if (!is_null($alerts) && count($alerts) > 0) {
  444.                 $operation $criters['operation'];
  445.                 if (!is_null($operation) && $operation == 'EXPORTATION') {
  446.                     $list = [];
  447.                     $alertDetail = [];
  448.                     foreach ($alerts as $alert) {
  449.                         $labelCrise = \is_null($alert->getCrisis()) ? "NULL" $alert->getCrisis()->getLabel();
  450.                         $CriseId = \is_null($alert->getCrisis()) ? "NULL" $alert->getCrisis()->getId();
  451.                         $description = \is_null($alert->getSeverity()) ? "NULL" $alert->getSeverity()->getDescription();
  452.                         $statut = \is_null($alert->getStatut()) ? "NULL" $alert->getStatut()->getWorkFlow()->getDescription();
  453.                         $accessRisk = \is_null($alert->getAccessRisk()) ? "NULL" $alert->getAccessRisk()->getLabel();
  454.                         $secondarySource = \is_null($alert->getSecondarySource()) ? "NULL" $alert->getSecondarySource();
  455.                         $axe = \is_null($alert->getAxe()) ? "NULL" $alert->getAxe();
  456.                         $primarySource = \is_null($alert->getPrimarySource()) ? "NULL" $alert->getPrimarySource()->getLabelFr();
  457.                         $primarySource_id = \is_null($alert->getPrimarySource()) ? "NULL" $alert->getPrimarySource()->getId();
  458.                         $creationDate = \is_null($alert->getCreationDate()) ? "NULL" $alert->getCreationDate();
  459.                         $eventReason = \is_null($alert->getEventReason()) ? "NULL" $alert->getEventReason()->getLabel();
  460.                         $description = \is_null($alert->getDescription()) ? "NULL" $alert->getDescription();
  461.                         $dateStatut = \is_null($alert->getStatut()) ? "NULL" $alert->getStatut()->getDatecreate();
  462.                         $statutAlert = \is_null($alert->getStatut()) ? "NULL" $alert->getStatut()->getWorkFlow()->getDescription();
  463.                         $pays = \is_null($alert->getCountry()) ? "NULL" $alert->getCountry()->getLabel();
  464.                         $severityAlertRrm = \is_null($alert->getSeverityAlertRrm()) ? "NULL" $alert->getSeverityAlertRrm();
  465.                         $typeMovement = \is_null($alert->getMovementCategory) ? "NULL" $alert->getMovementCategory();
  466.                         if (!is_null($alert->getAlertDetails()) && count($alert->getAlertDetails()) > 0) {
  467.                             foreach ($alert->getAlertDetails() as $ad) {
  468.                                 if ($ad->getIsDeleted() == 0) {
  469.                                     $province = \is_null($ad->getAdmin1()) ? "NULL" $ad->getAdmin1()->getLabel();
  470.                                     $province_id = \is_null($ad->getAdmin1()) ? "NULL" $ad->getAdmin1()->getId();
  471.                                     $territoire = \is_null($ad->getAdmin2()) ? "NULL" $ad->getAdmin2()->getLabel();
  472.                                     $territoire_id = \is_null($ad->getAdmin2()) ? "NULL" $ad->getAdmin2()->getId();
  473.                                     $chefferie = \is_null($ad->getAdmin3()) ? "NULL" $ad->getAdmin3()->getLabel();
  474.                                     $chefferie_id = \is_null($ad->getAdmin3()) ? "NULL" $ad->getAdmin3()->getId();
  475.                                     $groupement = \is_null($ad->getAdmin4()) ? "NULL" $ad->getAdmin4()->getLabel();
  476.                                     $groupement_id = \is_null($ad->getAdmin4()) ? "NULL" $ad->getAdmin4()->getId();
  477.                                     $localite = \is_null($ad->getAdmin5()) ? "NULL" $ad->getAdmin5()->getLabel();
  478.                                     $localite_id = \is_null($ad->getAdmin5()) ? "NULL" $ad->getAdmin5()->getId();
  479.                                     $healthZone = \is_null($ad->getHealthZone()) ? "NULL" $ad->getHealthZone()->getLabel();
  480.                                     $healthZone_id = \is_null($ad->getHealthZone()) ? "NULL" $ad->getHealthZone()->getId();
  481.                                     $displaced = \is_null($ad->getDisplaced()) ? "NULL" $ad->getDisplaced();
  482.                                     $returned = \is_null($ad->getReturned()) ? "NULL" $ad->getReturned();
  483.                                     $affected = \is_null($ad->getAffected()) ? "NULL" $ad->getAffected();
  484.                                     // $dead = \is_null($ad->getDead()) ? "NULL" : $ad->getDead();
  485.                                     $detailId = \is_null($ad->getId()) ? "NULL" $ad->getId();
  486.                                     $list[] = [
  487.                                         $alert->getId(),
  488.                                         $alert->getCluster()->getId(),
  489.                                         $alert->getCluster()->getLabel(),
  490.                                         $alert->getStartDate(),
  491.                                         $eventReason,
  492.                                         $creationDate,
  493.                                         $primarySource,
  494.                                         $axe,
  495.                                         $secondarySource,
  496.                                         $accessRisk,
  497.                                         $statut,
  498.                                         $description,
  499.                                         $labelCrise,
  500.                                         $pays,
  501.                                         $province,
  502.                                         $province_id,
  503.                                         $territoire,
  504.                                         $territoire_id,
  505.                                         $chefferie,
  506.                                         $chefferie_id,
  507.                                         $groupement,
  508.                                         $groupement_id,
  509.                                         $localite,
  510.                                         $localite_id,
  511.                                         $healthZone,
  512.                                         $healthZone_id,
  513.                                         $displaced,
  514.                                         $returned,
  515.                                         $affected,
  516.                                         //    $dead,
  517.                                         $primarySource_id,
  518.                                         $description,
  519.                                         $detailId,
  520.                                         $CriseId,
  521.                                         $dateStatut,
  522.                                         $statutAlert,
  523.                                         $severityAlertRrm,
  524.                                         $typeMovement
  525.                                     ];
  526.                                 }
  527.                             }
  528.                         }
  529.                     }
  530.                     $list;
  531.                     //code d'exportation
  532.                     $spreadsheet = new Spreadsheet();
  533.                     $sheet $spreadsheet->getActiveSheet();
  534.                     $sheet->setTitle('Alerts-List');
  535.                     $sheet->getCell('A1')->setValue('IdAlert');
  536.                     $sheet->getCell('B1')->setValue('IdCluster');
  537.                     $sheet->getCell('C1')->setValue('clusterLabel');
  538.                     $sheet->getCell('D1')->setValue('startDate');
  539.                     $sheet->getCell('E1')->setValue('eventReanson');
  540.                     $sheet->getCell('F1')->setValue('datecreation');
  541.                     $sheet->getCell('G1')->setValue('primarySource');
  542.                     $sheet->getCell('H1')->setValue('axe');
  543.                     $sheet->getCell('I1')->setValue('secondarySource');
  544.                     $sheet->getCell('J1')->setValue('AccessRisk');
  545.                     $sheet->getCell('K1')->setValue('descritpion');
  546.                     $sheet->getCell('L1')->setValue('severity');
  547.                     $sheet->getCell('M1')->setValue('crisis');
  548.                     $sheet->getCell('N1')->setValue('pays');
  549.                     $sheet->getCell('O1')->setValue('admin1Label');
  550.                     $sheet->getCell('P1')->setValue('admin1_Id');
  551.                     $sheet->getCell('Q1')->setValue('admin2Label');
  552.                     $sheet->getCell('R1')->setValue('admin2_Id');
  553.                     $sheet->getCell('S1')->setValue('admin3Label');
  554.                     $sheet->getCell('T1')->setValue('admin3_Id');
  555.                     $sheet->getCell('U1')->setValue('admin4Label');
  556.                     $sheet->getCell('V1')->setValue('admin3_Id');
  557.                     $sheet->getCell('W1')->setValue('admin4Label');
  558.                     $sheet->getCell('X1')->setValue('admin3_Id');
  559.                     $sheet->getCell('Y1')->setValue('hzLabel');
  560.                     $sheet->getCell('Z1')->setValue('hz_Id');
  561.                     $sheet->getCell('AA1')->setValue('Deplacées');
  562.                     $sheet->getCell('AB1')->setValue('Retournées');
  563.                     $sheet->getCell('AC1')->setValue('Affectées');
  564.                     // $sheet->getCell('AC1')->setValue('Morte');
  565.                     $sheet->getCell('AD1')->setValue('primarySource_id');
  566.                     $sheet->getCell('AE1')->setValue('descritpion');
  567.                     $sheet->getCell('AF1')->setValue('Alert_detail_id');
  568.                     $sheet->getCell('AG1')->setValue('Crisis_Id');
  569.                     $sheet->getCell('AH1')->setValue('Date_status');
  570.                     $sheet->getCell('AI1')->setValue('Statut_Alert');
  571.                     $sheet->getCell('AJ1')->setValue('severity_alert_rrm');
  572.                     $sheet->fromArray($listnull'A2'true);
  573.                     $writer = new Xlsx($spreadsheet);
  574.                     // Create a Temporary file in the system
  575.                     //$fileName = 'my_alerts_excel_ehtools.xlsx';
  576.                     $fileName 'Alert_from_ehtools_' date('Ymd') . time() . '.xlsx';
  577.                     $temp_file tempnam(sys_get_temp_dir(), $fileName);
  578.                     $writer->save($temp_file);
  579.                     return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE);
  580.                     // $writer->save('crisis.xlsx');
  581.                     return $this->redirectToRoute('ehtools_alert_register');
  582.                     //--------------
  583.                 }
  584.             }
  585.         } else {
  586.             $alerts $this->em->getRepository(Alert::class)->findByAlertCriteria();
  587.             //     // $repo = $em->getRepository(Alert::class);
  588.             //     // $alerts = $repo->findBy([
  589.             //     //     // 'userCreate'=>($this->getUser())
  590.             //     //     'isDeleted' => false,
  591.             //     // ]);
  592.         }
  593.         return $this->render('alert/registre.html.twig', [
  594.             'alerts' => $alerts,
  595.             'searchAlertForm' => $searchAlertForm->createView()
  596.         ]);
  597.     }
  598.     public function joinDocument(Request $request)
  599.     {
  600.         if (!$this->getUser()) {
  601.             return $this->redirectToRoute('app_core_homepage');
  602.         }
  603.         if (!$this->isGranted('ROLE_ENCODEUR')) {
  604.             return $this->redirectToRoute('ehtools_exception');
  605.         }
  606.         $alertId $request->get('alert');
  607.         $documentId $request->get('document');
  608.         $alert $this->em->getRepository(Alert::class)->findOneBy([
  609.             'id' => $alertId,
  610.         ]);
  611.         if (is_null($alert)) {
  612.             $this->addFlash('warning_message'"Alerte non trouvée dans la base de données");
  613.             return $this->redirectToRoute('ehtools_alert_register');
  614.         }
  615.         $document $this->em->getRepository(Document::class)->findOneBy([
  616.             'id' => $documentId,
  617.         ]);
  618.         //dump($documentId);
  619.         $this->logger->info('ICI', [$documentId]);
  620.         if (is_null($document)) {
  621.             $this->addFlash('warning_message'"Document non trouvé dans la base de données, veuillez choisir un document valide!");
  622.             return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  623.         }
  624.         $alertsdocument $this->em->getRepository(AlertDocument::class)->findBy([
  625.             'document' => $document,
  626.             'alert' => $alert
  627.         ]);
  628.         if (!is_null($alertsdocument) && count($alertsdocument) > 0) {
  629.             $this->addFlash('warning_message'"Ce document est deja lié à cette alerte");
  630.             return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  631.         }
  632.         if (!is_null($alert) && !is_null($document)) {
  633.             $alertDoc = new AlertDocument();
  634.             $alertDoc->setAlert($alert);
  635.             $alertDoc->setDocument($document);
  636.             $alertDoc->setDatecreate(new \DateTime());
  637.             $alertDoc->setUsercreate($this->getUser());
  638.             $this->em->persist($alertDoc);
  639.             $this->em->flush();
  640.             $this->addFlash('success_message'"Opération effectuée avec succès!");
  641.             return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  642.         }
  643.         // return $this->redirectToRoute('ehtools_alert_register');
  644.         return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  645.     }
  646.     public function sendMail($adress$subject$content)
  647.     {
  648.         $mailFrom $this->getParameter('mailFrom');
  649.         $email = (new Email())
  650.             ->from($mailFrom)
  651.             ->to($adress)
  652.             ->subject($subject)
  653.             ->text('Notification ehtools')
  654.             ->html($content);
  655.         $this->mailler->send($email);
  656.         $this->addFlash('success_message''le mail de confirmation a été envoyé');
  657.         $this->logger->info('After send mail code', []);
  658.     }
  659.     public function update(Request $request)
  660.     {
  661.         if (!$this->isGranted('ROLE_ENCODEUR')) {
  662.             return $this->redirectToRoute('ehtools_exception');
  663.         }
  664.         $userConnect $this->getUser();
  665.         // dump($userConnect);
  666.         $id $request->get('id');
  667.         //$em = $em->getManager();
  668.         $user = new User();
  669.         $alert $this->em->getRepository(Alert::class)->findOneBy([
  670.             'id' => $id
  671.         ]);
  672.         $date $alert->getStartDate();
  673.         $userEdit $alert->getUserCreate();
  674.         if ($userConnect != $userEdit && !$this->isGranted('ROLE_IM')) {
  675.             $this->addFlash('warning_message'"Cette alerte n'a pas été édité par vous! seul son éditeur peut le modifier");
  676.             return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  677.         }
  678.         $startDateD null;
  679.         $startDateD $alert->getStartDate();
  680.         $startDateD = isset($startDateD) ? $startDateD->format("Y-m-d") : null;
  681.         // $startDateD = \DateTime::createFromFormat('d/m/y', $startDateD)->format('Y-m-d');
  682.         $alertForm $this->createForm(AlertType::class, $alert);
  683.         $alertForm->handleRequest($request);
  684.         if ($alertForm->isSubmitted() && $alertForm->isValid()) {
  685.             $dtrDate $alertForm->get('startDate')->getData();
  686.             $alert->setStartDate(new \DateTime($dtrDate));
  687.             // $data = $request->request->get('detail_alert');
  688.             // $alert->setUserCreate($this->getUser());
  689.             $eventSousType$this->em->getRepository(EventSousType::class)->findBy(['id'=>$request->get('eventSousType')])[0];
  690.             $accommodation$this->em->getRepository(AlertAccommodation::class)->findBy(['id'=>$request->get('accommodation')])[0];
  691.             
  692.             $alert->setEventSousType($eventSousType);
  693.             $alert->setAccommodation($accommodation);
  694.             //Alert Score de Severité RRM
  695.             $rrmScore=$this->rrmScore($alert);
  696.             $alert->setSeverityAlertRrm($rrmScore);
  697.             $this->em->persist($alert);
  698.             $this->em->flush();
  699.             $this->addFlash('success_message'"l'alerte a été mise à jour avec succès");
  700.             return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
  701.         }
  702.         return $this->render('alert/update.html.twig', [
  703.             'alertForm' => $alertForm->createView(),
  704.             //'detailAlert'=> $detailAlert,
  705.             'alert' => $alert,
  706.             'startDateD' => $startDateD,
  707.             'userEdit' => $userEdit
  708.         ]);
  709.     }
  710.     // /**
  711.     //  * @Route("/email")
  712.     //  */
  713.     //  public function sendEmail(MailerInterface $mailer)
  714.     // {
  715.     //     try {
  716.     //         $email = (new Email())
  717.     //         ->from('steven.tshiamala@un.org')
  718.     //         ->to('steventshas@gmail.com')
  719.     //         //->cc('cc@example.com')
  720.     //         //->bcc('bcc@example.com')
  721.     //         //->replyTo('fabien@example.com')
  722.     //         //->priority(Email::PRIORITY_HIGH)
  723.     //         ->subject('Time for Symfony Mailer loup!')
  724.     //         ->text('Sending emails is fun again!')
  725.     //         ->html('<p>See Twig integration for better HTML integration!</p>');
  726.     //         $this->logger->info('before else', []);
  727.     //     $mailer->send($email);
  728.     //     $this->logger->info('After else', []);
  729.     //     } catch (Exception $e) {
  730.     //         $this->logger->info('catch >>>>>', [$e->getMessage()]);
  731.     //     }
  732.     //     $this->logger->info('out try', []);
  733.     //     return $this->json('Ok');
  734.     //     // ...
  735.     // }
  736.     /**
  737.      * @Route("/email")
  738.      */
  739.     public function sendEmail(Request $request): JsonResponse
  740.     {
  741.         // Envois simple mail
  742.         // $fromEmail = 'steven.tshiamala@un.org';
  743.         // $fromName = '';
  744.         // $toEmail = 'steven.tshiamala@un.org';
  745.         // $subject = 'Notification ehtools system';
  746.         // $htmlContent = '<h1>Ceci est un e-mail envoyé via Mandrill</h1>';
  747.         // $textContent = 'Ceci est la version texte de l\'e-mail.';
  748.         // try {
  749.         //     $response = $this->mandrillService->sendEmail($fromEmail, $fromName, $toEmail, $subject, $htmlContent, $textContent);
  750.         //     return new JsonResponse(['success' => true, 'response' => $response]);
  751.         // } catch (\Exception $e) {
  752.         //     return new JsonResponse(['success' => false, 'error' => $e->getMessage()]);
  753.         // }
  754.         $id 5425// Exemple d'ID dynamique
  755.         $url "https://ehtools.org/alert-view/$id";
  756.         $message = [
  757.             'to' => [
  758.                 ['email' => 'ocha-drc-imunit@un.org''type' => 'to']
  759.             ],
  760.             'from_email' => 'steven.tshiamala@un.org',
  761.             'from_name' => 'COHP-RDC',
  762.             'subject' => 'Notification ehtools System test',
  763.             'merge' => true,
  764.             'merge_vars' => [
  765.                 [
  766.                     'rcpt' => 'ocha-drc-imunit@un.org ',
  767.                     'vars' => [
  768.                         ['name' => 'USERNAME''content' => 'steventshas'],
  769.                         ['name' => 'CODE_ALERT''content' => '5425'],
  770.                         ['name' => 'ALERT_URL''content' => $url],
  771.                     ]
  772.                 ]
  773.             ],
  774.         ];
  775.         $templateName 'ehtoolsTemplateNotification'// Nom du template Mandrill
  776.         $templateContent = [
  777.             ['name' => 'header''content' => 'Welcome to our service!'],
  778.         ];
  779.         try {
  780.             $response $this->mandrillService->messages->sendTemplate($templateName$templateContent$message);
  781.             return new JsonResponse(['success' => true'response' => $response]);
  782.         } catch (\Exception $e) {
  783.             return new JsonResponse(['success' => false'error' => $e->getMessage()]);
  784.         }
  785.     }
  786.     /**
  787.      * @Route("/rrm-action")
  788.      */
  789.     public function rrmAction(Request $request)
  790.     {
  791.         $action $request->get('action');
  792.         $data $request->get('data');
  793.         if($action=="categorieMouvement"){
  794.            //$rqEvent = $this->em->getRepository(EventType::class)->findBy(['eventReason'=>$data]);
  795.             $listEvent = [];
  796.             if($data==1){
  797.                 $listEvent[] = ['id'=>"1"'label'=>"Attaques, affrontements armées"];
  798.                 $listEvent[] = ['id'=>"2"'label'=>"Conflits fonciers, intercommunautaires"];
  799.                 $listEvent[] = ['id'=>"3"'label'=>"Catastrophe naturelle"];
  800.                 //$listEvent[] = ['id'=>"7", 'label'=>"Autre"];
  801.             }
  802.             else if($data==2){
  803.                 $listEvent[] = ['id'=>"6"'label'=>"Amélioration des conditions"];
  804.                 //$listEvent[] = ['id'=>"7", 'label'=>"Autre"];
  805.             }
  806.             else if($data==3){
  807.                 $listEvent[] = ['id'=>"8"'label'=>"Mixte (Violence, Retour, Forcées, ...)"];
  808.                 /*$listEvent[] = ['id'=>"1", 'label'=>"Attaques, affrontements armées"];
  809.                 $listEvent[] = ['id'=>"2", 'label'=>"Conflits fonciers, intercommunautaires"];
  810.                 $listEvent[] = ['id'=>"6", 'label'=>"Amélioration des conditions"];*/
  811.             }
  812.             else if($data==4){
  813.                 $listEvent[] = ['id'=>"3"'label'=>"Catastrophe naturelle"];
  814.                 $listEvent[] = ['id'=>"4"'label'=>"Malnutrition"];
  815.                 $listEvent[] = ['id'=>"5"'label'=>"Epidemie"];
  816.                 $listEvent[] = ['id'=>"7"'label'=>"Autre"];
  817.             }
  818.             /*if($rqEvent){
  819.                 foreach ($rqEvent as $c) {
  820.                     $listEvent[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
  821.                 }
  822.             }*/
  823.             $rep=new JsonResponse();
  824.             return $rep->setData(['listRaison' => $listEvent]);
  825.         }
  826.         else if($action=="eventReason"){
  827.             
  828.             $rqEvent $this->em->getRepository(EventSousType::class)->findBy(['eventReason'=>$data]);
  829.             $listEvent = [];
  830.             if($rqEvent){
  831.                 foreach ($rqEvent as $c) {
  832.                     $listEvent[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
  833.                 }
  834.             }
  835.             $rep=new JsonResponse();
  836.             return $rep->setData(['listSousRaison' => $listEvent]);
  837.         }
  838.         else if($action=="agglomeration"){
  839.            $rqAgglomeration $this->em->getRepository(AlertAgglomeration::class)->findAll();
  840.             $listAgglo = [];
  841.             if($rqAgglomeration){
  842.                 foreach ($rqAgglomeration as $c) {
  843.                     $listAgglo[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
  844.                 }
  845.             }
  846.             $rep=new JsonResponse();
  847.             return $rep->setData(['listAgglomeration' => $listAgglo]);
  848.         }
  849.         else if($action=="accommodation"){
  850.            $rqAccomodation $this->em->getRepository(AlertAccommodation::class)->findBy(['agglomeration'=>$data]);
  851.             $listAccom = [];
  852.             if($rqAccomodation){
  853.                 foreach ($rqAccomodation as $c) {
  854.                     $listAccom[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
  855.                 }
  856.             }
  857.             $rep=new JsonResponse();
  858.             return $rep->setData(['listAccommodation' => $listAccom]);
  859.         }
  860.         else return null;
  861.     }
  862.     private function rrmScore(Alert $alert /*$alert_id*/){
  863.         $score=0;
  864.         //Force du Choc
  865.         $event=$alert->getEventReason()->getId();
  866.         $choc=$alert->getEventSousType()->getScore();
  867.         //Lieu d'accueil / refuge
  868.         $refuge=$alert->getAccommodation()->getScore();
  869.         //Gtacq
  870.         $zs=$alert->getAlertDetail()->getHealthZone();
  871.         $rqGtacq=$this->em->getRepository(RrmGtacq::class)->findBy(['healthZone'=>$zs"isDeleted"=>0]);
  872.         $gtacq=$rqGtacq $rqGtacq[0]->getScore() : ;
  873.         //CaseLoad
  874.         $caseload=1;
  875.         $nbrMenage=0;
  876.         $rqNbrMen $this->em->getRepository(AlertDetail::class)->findBy(['alert'=>$alert"isDeleted"=>0]); //$alert->getAlertDetail();
  877.         if($rqNbrMen){
  878.             foreach ($rqNbrMen as $c) {
  879.                 if($event==1//attaques
  880.                     $nbrMenage += $c->getDisplacedHousehold();
  881.                 else if($event==6//Retour
  882.                     $nbrMenage += $c->getReturnedHousehold();
  883.                 else if($event==//conflits 
  884.                     $nbrMenage $nbrMenage $c->getDisplacedHousehold();
  885.                 else if($event==8//Mixte
  886.                     $nbrMenage $c->getDisplacedHousehold() + $c->getReturnedHousehold();
  887.                 else //Catastrophe, Epidemie, Malnutrition et Autre
  888.                     $nbrMenage += $c->getHousehold();    
  889.             }
  890.         }
  891.                 
  892.         $rqCaseload=$this->em->getRepository(RrmCaseload::class)->findBy([], ['id'=>'DESC']);    
  893.         if($rqCaseload)
  894.             foreach ($rqCaseload as $n
  895.                 if($nbrMenage <= $n->getcaseload()) $caseload=$n->getScore();
  896.             
  897.         
  898.         //Calcul Score final
  899.         $rqPonderation=$this->em->getRepository(RrmPonderation::class)->findAll();    
  900.         if($rqPonderation){
  901.             foreach ($rqPonderation as $p
  902.             {
  903.                 if($p->getFacteur()=="choc"$score+=($p->getPonderation()/100 $choc);
  904.                 else if($p->getFacteur()=="refuge"$score+=($p->getPonderation()/100 $refuge);
  905.                 else if($p->getFacteur()=="caseload"$score+=($p->getPonderation()/100 $caseload);
  906.                 else if($p->getFacteur()=="gtacq"$score+=($p->getPonderation()/100 $gtacq);
  907.             }
  908.         }
  909.         return $score;
  910.     }
  911. }