<?php
namespace App\Controller;
ini_set("memory_limit", "2G");
set_time_limit(800);
use DateTime;
use Mandrill;
use Exception;
use App\Entity\Etat;
use App\Entity\User;
use App\Entity\Actor;
use App\Entity\Alert;
use App\Entity\Pcode;
use Twig\Environment;
use App\Entity\Cluster;
use App\Entity\Process;
use App\Form\AlertType;
use App\Entity\Decision;
use App\Entity\Document;
use App\Entity\RrmGtacq;
use App\Entity\WorkFlow;
use App\Entity\Procedure;
use App\Entity\AlertDetail;
use App\Entity\EventReason;
use App\Entity\RrmCaseload;
use Psr\Log\LoggerInterface;
use App\Entity\AlertDocument;
use App\Entity\EventSousType;
use App\Form\AlertAvorteType;
use App\Form\DetailAlertType;
use App\Form\SearchAlertType;
use Ramsey\Uuid\Type\Integer;
use App\Entity\RrmPonderation;
use App\Form\SearchDocumentType;
use App\Service\MandrillService;
use Symfony\Component\Mime\Email;
use App\Entity\AlertAccommodation;
use App\Entity\AlertAgglomeration;
use App\Form\NextProcessAlertType;
use App\Entity\EhtoolsNotification;
use Symfony\Component\Mime\Address;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Sentry\EventType;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
class AlertController extends AbstractController
{
private $em;
private $logger;
private $mailer;
private $twig;
private $mandrillService;
public function __construct(EntityManagerInterface $em, LoggerInterface $logger, MailerInterface $mailer, Environment $twig, MandrillService $mandrillService)
{
$this->em = $em;
$this->logger = $logger;
$this->mailler = $mailer;
$this->twig = $twig;
//$this->mandrillService = $mandrillService;
// $this->mandrillService = new Mandrill('md-z_sIqHhENLSpPIsUDryYLA');
$this->mandrillService = new Mandrill('md-xgYZd4-I5EVZUfxAiThadg');
}
public function add(Request $request, EntityManagerInterface $em)
{
if (!$this->isGranted('ROLE_ENCODEUR')) {
return $this->redirectToRoute('ehtools_exception');
}
// $em = $em->getManager();
$alert = new Alert();
// $currentDate = \DateTime::createFromFormat();
// dump($currentDate);
$alertform = $this->createForm(AlertType::class, $alert);
$countryId = $this->getUser()->getCountry()->getId();
$country = $em->getRepository(Pcode::class)->findOneBy([
'id' => $countryId,
]);
$alertform->handleRequest($request);
if ($alertform->isSubmitted() && $alertform->isValid()) {
$strDate = $alertform->get('startDate')->getData();
$startDate = new \DateTime($strDate);
$alert->setUserCreate($this->getUser());
$alert->setStartDate($startDate);
$alert->setCountry($country);
$eventSousType= $this->em->getRepository(EventSousType::class)->findBy(['id'=>$request->get('eventSousType')])[0];
$accommodation= $this->em->getRepository(AlertAccommodation::class)->findBy(['id'=>$request->get('accommodation')])[0];
$alert->setEventSousType($eventSousType);
$alert->setAccommodation($accommodation);
$em->persist($alert);
$em->flush();
$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!");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
return $this->render('alert/add.html.twig', ['alertForm' => $alertform->createView()]);
}
public function view(Request $request, EntityManagerInterface $em)
{
$alert = $em->getRepository(Alert::class)->findOneBy([
'id' => $request->get('id'),
]);
if (is_null($alert)) {
$this->addFlash('warning_message', "Alerte non trouvée dans la base de données, prière de selectionner une alerte!");
return $this->redirectToRoute('ehtools_alert_register');
}
$alertDetails = $em->getRepository(AlertDetail::class)->findBy([
'alert' => $alert,
'isDeleted' => false,
]);
$listProcess = $em->getRepository(Process::class)->findBy([
'alert' => $alert,
]);
$documents = $em->getRepository(AlertDocument::class)->findBy([
'alert' => $alert,
]);
$process = null;
if (!is_null($listProcess) && count($listProcess) > 0) {
$listProcess = array_reverse($listProcess);
$process = $listProcess[0];
}
//dump($process);
$workFlows = [];
$procedure = $em->getRepository(Procedure::class)->findOneBy([], ['id' => 'DESC']);
if (!is_null($procedure)) {
$workFlows = $em->getRepository(WorkFlow::class)->findBy([
'procedureID' => $procedure,
]);
}
$endProcess = false;
$isLastProcess = false;
if (!is_null($listProcess) && !is_null($workFlows)) {
//dump(count($listProcess)."|".count($workFlows));
if (count($workFlows) == count($listProcess)) {
$endProcess = true;
} else {
if (count($workFlows) - count($listProcess) == 1) {
$isLastProcess = true;
}
}
}
return $this->render('alert/view.html.twig', [
'alert' => $alert,
'alertDetails' => $alertDetails,
'endProcess' => $endProcess,
'process' => $process,
'workFlows' => $workFlows,
'documents' => $documents,
'isLastProcess' => $isLastProcess,
'$listProcess' => $listProcess,
]);
}
public function validate(Alert $alert, Request $request, EntityManagerInterface $em, MailerInterface $mailer): Response
{
if (!$this->isGranted('ROLE_ENCODEUR')) {
return $this->redirectToRoute('ehtools_exception');
}
if ($alert->getId() instanceof Alert) {
$this->addFlash('warning_message', "Alerte non trouvée dans la base de données");
return $this->redirectToRoute('ehtools_alert_register');
} else {
$details = $em->getRepository(AlertDetail::class)->findBy([
'alert' => $alert,
]);
if (is_null($details) || count($details) < 1) {
$this->addFlash('danger_message', "Impossible de valider l'alerte, prière d'ajouter au moins un détail");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
$procedure = $em->getRepository(Procedure::class)->findOneBy([], ['id' => 'DESC']);
if (!is_null($procedure)) {
$workFlow = $em->getRepository(WorkFlow::class)->findOneBy([
'procedureID' => $procedure,
], ['id' => 'ASC']);
$etat = $em->getRepository(Etat::class)->findOneBy([
'id' => 1,
]);
$process = new Process();
$process->setAlert($alert);
$process->setProcedureA($procedure);
$process->setWorkflow($workFlow);
$process->setUsercreate($this->getUser());
$process->setEtat($etat);
$process->setDatecreate(new \DateTime());
//Alert Score de Severité RRM
$rrmScore=$this->rrmScore($alert);
$alert->setSeverityAlertRrm($rrmScore);
$alert->setIsValid(true);
$alert->setStatut($process);
// $em = $em->getManager();
$em->persist($alert);
$em->persist($process);
$em->flush();
// send email
try {
$userConnect = $this->getUser();
$userEmail = $userConnect->getEmail();
$alertID = $alert->getId();
$alertSeverity = round($alert->getSeverityAlertRrm(), 2);
$eventReason = $alert->getEventReason()->getLabel();
$details = $em->getRepository(AlertDetail::class)->findOneBy([
'alert' => $alertID
]);
$admin1Id = $details->getAdmin1()->getId();
$admin2Id = $details->getAdmin2()->getId();
$admin1 = $this->em->getRepository(Pcode::class)->find($admin1Id);
$admin2 = $this->em->getRepository(Pcode::class)->find($admin2Id);
$province = $admin1->getLabel();
$territoire = $admin2->getLabel();
$url = "https://ehtools.org/alert-view/$alertID";
// Récupérer les emails en CC depuis ehtoolsNotification
$ccUsers = $this->getDoctrine()->getRepository(EhtoolsNotification::class)->findBy(['isActive'=>true]);
$ccEmails = [];
foreach ($ccUsers as $ccUser) {
$ccEmails[] = $ccUser->getEmail();
}
// Fusionner tous les destinataires (utilisateur principal + CC)
$allRecipients = array_unique(array_merge([$userEmail], $ccEmails));
// Template Mandrill
$templateName = 'ehtoolsTemplateNotification';
$templateContent = [
['name' => 'header', 'content' => 'Welcome to our service!'],
];
// Envoi individuel avec personnalisation
foreach ($allRecipients as $email) {
$message = [
'to' => [[
'email' => $email,
'type' => 'to'
]],
'from_email' => 'ocha-drc-imunit@un.org',
'from_name' => 'COHP-RDC',
'subject' => 'Notification ehtools System',
'merge' => true,
'merge_language' => 'mailchimp',
'merge_vars' => [[
'rcpt' => $email,
'vars' => [
['name' => 'USERNAME', 'content' => $email],
['name' => 'CODE_ALERT', 'content' => $alertID],
['name' => 'ALERT_ID', 'content' => $alertID],
['name' => 'EVENTREASON', 'content' => $eventReason],
['name' => 'PROVINCE', 'content' => $province],
['name' => 'TERRITOIRE', 'content' => $territoire],
['name' => 'SEVERITYRRM', 'content' => $alertSeverity],
['name' => 'ALERT_URL', 'content' => $url],
]
]]
];
// Envoi via Mandrill
$this->mandrillService->messages->sendTemplate($templateName, $templateContent, $message);
}
// Optionnel : log ou message de confirmation
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'message' => $e->getMessage()]);
}
$this->addFlash('success_message', "L'alert a été validée avec succès !");
return $this->redirectToRoute('ehtools_alert_view', [
'id' => $alert->getId(),
]);
}
$this->logger->info('After else', []);
}
$this->addFlash('warning_message', "La validation a échoué !");
return $this->render('alert/show_alert.html.twig', [
'id' => $alert,
]);
}
public function nextProcess(Alert $alert, EntityManagerInterface $em, Request $request)
{
if (!$this->isGranted('ROLE_ENCODEUR')) {
return $this->redirectToRoute('ehtools_exception');
}
if ($alert->getId() instanceof Alert) {
$this->addFlash('warning_message', "Alerte non trouvée dans la base de données");
return $this->redirectToRoute('ehtools_alert_register');
}
$process = new Process();
$listProcess = $em->getRepository(Process::class)->findBy([
'alert' => $alert,
]);
$currentProcess = null;
if (!is_null($listProcess) && count($listProcess) > 0) {
$listProcess = array_reverse($listProcess);
$currentProcess = $listProcess[0];
}
$processform = $this->createForm(NextProcessAlertType::class, $currentProcess);
$processform->handleRequest($request);
if ($processform->isSubmitted() && $processform->isValid()) {
$procedure = $em->getRepository(Procedure::class)->findOneBy([], ['id' => 'DESC']);
$strDate = $processform->get('dateTraitement')->getData();
$traitmentDate = new \DateTime($strDate);
if (!is_null($procedure)) {
$listProcess = $em->getRepository(Process::class)->findBy([
'alert' => $alert,
]);
$workFlows = $em->getRepository(WorkFlow::class)->findBy([
'procedureID' => $procedure,
]);
$workFlows = $em->getRepository(WorkFlow::class)->createQueryBuilder('w')
->join('w.procedureID', 'p')
->where('p.id = :p1')
->setParameter('p1', $procedure->getId())
->andWhere('w.id > :p2')
->setParameter('p2', $currentProcess->getWorkflow()->getId())
->getQuery()->getResult();
if (!is_null($workFlows) && count($workFlows) > 0) {
$nextWorkFlow = $workFlows[0];
$etat = $em->getRepository(Etat::class)->findOneBy(['id' => 1,]);
$process->setAlert($alert);
$process->setProcedureA($procedure);
$process->setWorkflow($nextWorkFlow);
$process->setUsercreate($this->getUser());
$process->setEtat($etat);
//$process->setDateTraitement($startDate);
$process->setDatecreate(new \DateTime());
$currentProcess->setDateTraitement($traitmentDate);
$alert->setStatut($process);
if ($request->get('affected') || $request->get('displaced') || $request->get('returned')) {
$alert->setAffectedEval($request->get('affected'));
$alert->setHouseholdEval($request->get('household'));
$alert->setDisplacedEval($request->get('displaced'));
$alert->setDisplacedEvalHousehold($request->get('displacedHousehold'));
$alert->setReturnedEval($request->get('returned'));
$alert->setReturnedEvalHousehold($request->get('returnedHouseHold'));
}
//$em = $em->getManager();
$em->persist($currentProcess);
$em->persist($process);
$em->persist($alert);
$em->flush();
$this->addFlash('success_message', "Etape suivante validée avec succès !");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
} else {
$this->addFlash('warning_message', "L'opération a échoué !");
return $this->redirectToRoute('ehtools_alert_register', ['id' => $alert->getId()]);
}
}
return $this->render('alert/next_process.html.twig', [
'alert' => $alert,
'processform' => $processform->createView(),
'currentProcess' => $currentProcess,
]);
}
public function avorteProcess(Alert $alert, EntityManagerInterface $em, Request $request)
{
if (!$this->isGranted('ROLE_ENCODEUR')) {
return $this->redirectToRoute('ehtools_exception');
}
if ($alert->getId() instanceof Alert) {
$this->addFlash('warning_message', "Alerte non trouvée dans la base de données");
return $this->redirectToRoute('ehtools_alert_register');
}
$listProcess = $em->getRepository(Process::class)->findBy([
'alert' => $alert,
]);
$currentProcess = null;
if (!is_null($listProcess) && count($listProcess) > 0) {
$listProcess = array_reverse($listProcess);
$currentProcess = $listProcess[0];
}
$alertform = $this->createForm(AlertAvorteType::class, $alert);
$alertform->handleRequest($request);
if ($alertform->isSubmitted() && $alertform->isValid()) {
$alert->setUserAvorte($this->getUser());
$alert->setIsAvorte(true);
$alert->setDateAvorte(new \DateTime());
//$em = $em->getManager();
$em->persist($alert);
$em->flush();
$this->addFlash('success_message', "Opération effectuée avec succès!");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
return $this->render('alert/avorte.html.twig', [
'alert' => $alert,
'currentProcess' => $currentProcess,
'alertform' => $alertform->createView(),
]);
}
public function register(Request $request)
{
$searchAlertForm = $this->createForm(SearchAlertType::class);
$workflows = $this->em->getRepository(WorkFlow::class)->findBy([]);
//$detailAlerts = $this->em->getRepository(AlertDetail::class)->findAll([]);
// $searchAlertForm->add(
// 'statut',
// EntityType::class,
// [
// 'label' => 'Statut',
// 'required' => false,
// 'multiple' => true,
// 'expanded' => true,
// 'choices' => $workflows,
// 'choice_label' => 'description',
// 'choice_value' => 'id',
// ]
// );
$searchAlertForm->add('statut', EntityType::class, [
'label' => "- Statut -",
'required' => false,
'placeholder' => '- Sélectionner -',
'help' => "Sélectionnez Statut ",
'class' => WorkFlow::class,
//'choice_label' => 'username',
'choice_label' => 'description',
'attr' => [
'class' => 'chosen-select',
],
'multiple' => true,
]);
$searchAlertForm->handleRequest($request);
//$alerts = [];
//$alerts = $this->em->getRepository(Alert::class)->findByAlertCriteria();
if ($searchAlertForm->isSubmitted() && $searchAlertForm->isValid()) {
$criters = $searchAlertForm->getData();
$criters['admin1'] = $searchAlertForm->get('admin1')->getData();
$criters['admin2'] = $searchAlertForm->get('admin2')->getData();
//dump($criters);
//$admin2 = $searchAlertForm->get('admin2')->getData();
//$admin2 = $searchAlertForm->get('valHealthZone')->getData();
//dump($admin2);
$alerts = $this->em->getRepository(Alert::class)->findByAlertCriteria($criters);
if (!is_null($alerts) && count($alerts) > 0) {
$operation = $criters['operation'];
if (!is_null($operation) && $operation == 'EXPORTATION') {
$list = [];
$alertDetail = [];
foreach ($alerts as $alert) {
$labelCrise = \is_null($alert->getCrisis()) ? "NULL" : $alert->getCrisis()->getLabel();
$CriseId = \is_null($alert->getCrisis()) ? "NULL" : $alert->getCrisis()->getId();
$description = \is_null($alert->getSeverity()) ? "NULL" : $alert->getSeverity()->getDescription();
$statut = \is_null($alert->getStatut()) ? "NULL" : $alert->getStatut()->getWorkFlow()->getDescription();
$accessRisk = \is_null($alert->getAccessRisk()) ? "NULL" : $alert->getAccessRisk()->getLabel();
$secondarySource = \is_null($alert->getSecondarySource()) ? "NULL" : $alert->getSecondarySource();
$axe = \is_null($alert->getAxe()) ? "NULL" : $alert->getAxe();
$primarySource = \is_null($alert->getPrimarySource()) ? "NULL" : $alert->getPrimarySource()->getLabelFr();
$primarySource_id = \is_null($alert->getPrimarySource()) ? "NULL" : $alert->getPrimarySource()->getId();
$creationDate = \is_null($alert->getCreationDate()) ? "NULL" : $alert->getCreationDate();
$eventReason = \is_null($alert->getEventReason()) ? "NULL" : $alert->getEventReason()->getLabel();
$description = \is_null($alert->getDescription()) ? "NULL" : $alert->getDescription();
$dateStatut = \is_null($alert->getStatut()) ? "NULL" : $alert->getStatut()->getDatecreate();
$statutAlert = \is_null($alert->getStatut()) ? "NULL" : $alert->getStatut()->getWorkFlow()->getDescription();
$pays = \is_null($alert->getCountry()) ? "NULL" : $alert->getCountry()->getLabel();
$severityAlertRrm = \is_null($alert->getSeverityAlertRrm()) ? "NULL" : $alert->getSeverityAlertRrm();
$typeMovement = \is_null($alert->getMovementCategory) ? "NULL" : $alert->getMovementCategory();
if (!is_null($alert->getAlertDetails()) && count($alert->getAlertDetails()) > 0) {
foreach ($alert->getAlertDetails() as $ad) {
if ($ad->getIsDeleted() == 0) {
$province = \is_null($ad->getAdmin1()) ? "NULL" : $ad->getAdmin1()->getLabel();
$province_id = \is_null($ad->getAdmin1()) ? "NULL" : $ad->getAdmin1()->getId();
$territoire = \is_null($ad->getAdmin2()) ? "NULL" : $ad->getAdmin2()->getLabel();
$territoire_id = \is_null($ad->getAdmin2()) ? "NULL" : $ad->getAdmin2()->getId();
$chefferie = \is_null($ad->getAdmin3()) ? "NULL" : $ad->getAdmin3()->getLabel();
$chefferie_id = \is_null($ad->getAdmin3()) ? "NULL" : $ad->getAdmin3()->getId();
$groupement = \is_null($ad->getAdmin4()) ? "NULL" : $ad->getAdmin4()->getLabel();
$groupement_id = \is_null($ad->getAdmin4()) ? "NULL" : $ad->getAdmin4()->getId();
$localite = \is_null($ad->getAdmin5()) ? "NULL" : $ad->getAdmin5()->getLabel();
$localite_id = \is_null($ad->getAdmin5()) ? "NULL" : $ad->getAdmin5()->getId();
$healthZone = \is_null($ad->getHealthZone()) ? "NULL" : $ad->getHealthZone()->getLabel();
$healthZone_id = \is_null($ad->getHealthZone()) ? "NULL" : $ad->getHealthZone()->getId();
$displaced = \is_null($ad->getDisplaced()) ? "NULL" : $ad->getDisplaced();
$returned = \is_null($ad->getReturned()) ? "NULL" : $ad->getReturned();
$affected = \is_null($ad->getAffected()) ? "NULL" : $ad->getAffected();
// $dead = \is_null($ad->getDead()) ? "NULL" : $ad->getDead();
$detailId = \is_null($ad->getId()) ? "NULL" : $ad->getId();
$list[] = [
$alert->getId(),
$alert->getCluster()->getId(),
$alert->getCluster()->getLabel(),
$alert->getStartDate(),
$eventReason,
$creationDate,
$primarySource,
$axe,
$secondarySource,
$accessRisk,
$statut,
$description,
$labelCrise,
$pays,
$province,
$province_id,
$territoire,
$territoire_id,
$chefferie,
$chefferie_id,
$groupement,
$groupement_id,
$localite,
$localite_id,
$healthZone,
$healthZone_id,
$displaced,
$returned,
$affected,
// $dead,
$primarySource_id,
$description,
$detailId,
$CriseId,
$dateStatut,
$statutAlert,
$severityAlertRrm,
$typeMovement
];
}
}
}
}
$list;
//code d'exportation
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Alerts-List');
$sheet->getCell('A1')->setValue('IdAlert');
$sheet->getCell('B1')->setValue('IdCluster');
$sheet->getCell('C1')->setValue('clusterLabel');
$sheet->getCell('D1')->setValue('startDate');
$sheet->getCell('E1')->setValue('eventReanson');
$sheet->getCell('F1')->setValue('datecreation');
$sheet->getCell('G1')->setValue('primarySource');
$sheet->getCell('H1')->setValue('axe');
$sheet->getCell('I1')->setValue('secondarySource');
$sheet->getCell('J1')->setValue('AccessRisk');
$sheet->getCell('K1')->setValue('descritpion');
$sheet->getCell('L1')->setValue('severity');
$sheet->getCell('M1')->setValue('crisis');
$sheet->getCell('N1')->setValue('pays');
$sheet->getCell('O1')->setValue('admin1Label');
$sheet->getCell('P1')->setValue('admin1_Id');
$sheet->getCell('Q1')->setValue('admin2Label');
$sheet->getCell('R1')->setValue('admin2_Id');
$sheet->getCell('S1')->setValue('admin3Label');
$sheet->getCell('T1')->setValue('admin3_Id');
$sheet->getCell('U1')->setValue('admin4Label');
$sheet->getCell('V1')->setValue('admin3_Id');
$sheet->getCell('W1')->setValue('admin4Label');
$sheet->getCell('X1')->setValue('admin3_Id');
$sheet->getCell('Y1')->setValue('hzLabel');
$sheet->getCell('Z1')->setValue('hz_Id');
$sheet->getCell('AA1')->setValue('Deplacées');
$sheet->getCell('AB1')->setValue('Retournées');
$sheet->getCell('AC1')->setValue('Affectées');
// $sheet->getCell('AC1')->setValue('Morte');
$sheet->getCell('AD1')->setValue('primarySource_id');
$sheet->getCell('AE1')->setValue('descritpion');
$sheet->getCell('AF1')->setValue('Alert_detail_id');
$sheet->getCell('AG1')->setValue('Crisis_Id');
$sheet->getCell('AH1')->setValue('Date_status');
$sheet->getCell('AI1')->setValue('Statut_Alert');
$sheet->getCell('AJ1')->setValue('severity_alert_rrm');
$sheet->fromArray($list, null, 'A2', true);
$writer = new Xlsx($spreadsheet);
// Create a Temporary file in the system
//$fileName = 'my_alerts_excel_ehtools.xlsx';
$fileName = 'Alert_from_ehtools_' . date('Ymd') . time() . '.xlsx';
$temp_file = tempnam(sys_get_temp_dir(), $fileName);
$writer->save($temp_file);
return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
// $writer->save('crisis.xlsx');
return $this->redirectToRoute('ehtools_alert_register');
//--------------
}
}
} else {
$alerts = $this->em->getRepository(Alert::class)->findByAlertCriteria();
// // $repo = $em->getRepository(Alert::class);
// // $alerts = $repo->findBy([
// // // 'userCreate'=>($this->getUser())
// // 'isDeleted' => false,
// // ]);
}
return $this->render('alert/registre.html.twig', [
'alerts' => $alerts,
'searchAlertForm' => $searchAlertForm->createView()
]);
}
public function joinDocument(Request $request)
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_core_homepage');
}
if (!$this->isGranted('ROLE_ENCODEUR')) {
return $this->redirectToRoute('ehtools_exception');
}
$alertId = $request->get('alert');
$documentId = $request->get('document');
$alert = $this->em->getRepository(Alert::class)->findOneBy([
'id' => $alertId,
]);
if (is_null($alert)) {
$this->addFlash('warning_message', "Alerte non trouvée dans la base de données");
return $this->redirectToRoute('ehtools_alert_register');
}
$document = $this->em->getRepository(Document::class)->findOneBy([
'id' => $documentId,
]);
//dump($documentId);
$this->logger->info('ICI', [$documentId]);
if (is_null($document)) {
$this->addFlash('warning_message', "Document non trouvé dans la base de données, veuillez choisir un document valide!");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
$alertsdocument = $this->em->getRepository(AlertDocument::class)->findBy([
'document' => $document,
'alert' => $alert
]);
if (!is_null($alertsdocument) && count($alertsdocument) > 0) {
$this->addFlash('warning_message', "Ce document est deja lié à cette alerte");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
if (!is_null($alert) && !is_null($document)) {
$alertDoc = new AlertDocument();
$alertDoc->setAlert($alert);
$alertDoc->setDocument($document);
$alertDoc->setDatecreate(new \DateTime());
$alertDoc->setUsercreate($this->getUser());
$this->em->persist($alertDoc);
$this->em->flush();
$this->addFlash('success_message', "Opération effectuée avec succès!");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
// return $this->redirectToRoute('ehtools_alert_register');
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
public function sendMail($adress, $subject, $content)
{
$mailFrom = $this->getParameter('mailFrom');
$email = (new Email())
->from($mailFrom)
->to($adress)
->subject($subject)
->text('Notification ehtools')
->html($content);
$this->mailler->send($email);
$this->addFlash('success_message', 'le mail de confirmation a été envoyé');
$this->logger->info('After send mail code', []);
}
public function update(Request $request)
{
if (!$this->isGranted('ROLE_ENCODEUR')) {
return $this->redirectToRoute('ehtools_exception');
}
$userConnect = $this->getUser();
// dump($userConnect);
$id = $request->get('id');
//$em = $em->getManager();
$user = new User();
$alert = $this->em->getRepository(Alert::class)->findOneBy([
'id' => $id
]);
$date = $alert->getStartDate();
$userEdit = $alert->getUserCreate();
if ($userConnect != $userEdit && !$this->isGranted('ROLE_IM')) {
$this->addFlash('warning_message', "Cette alerte n'a pas été édité par vous! seul son éditeur peut le modifier");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
$startDateD = null;
$startDateD = $alert->getStartDate();
$startDateD = isset($startDateD) ? $startDateD->format("Y-m-d") : null;
// $startDateD = \DateTime::createFromFormat('d/m/y', $startDateD)->format('Y-m-d');
$alertForm = $this->createForm(AlertType::class, $alert);
$alertForm->handleRequest($request);
if ($alertForm->isSubmitted() && $alertForm->isValid()) {
$dtrDate = $alertForm->get('startDate')->getData();
$alert->setStartDate(new \DateTime($dtrDate));
// $data = $request->request->get('detail_alert');
// $alert->setUserCreate($this->getUser());
$eventSousType= $this->em->getRepository(EventSousType::class)->findBy(['id'=>$request->get('eventSousType')])[0];
$accommodation= $this->em->getRepository(AlertAccommodation::class)->findBy(['id'=>$request->get('accommodation')])[0];
$alert->setEventSousType($eventSousType);
$alert->setAccommodation($accommodation);
//Alert Score de Severité RRM
$rrmScore=$this->rrmScore($alert);
$alert->setSeverityAlertRrm($rrmScore);
$this->em->persist($alert);
$this->em->flush();
$this->addFlash('success_message', "l'alerte a été mise à jour avec succès");
return $this->redirectToRoute('ehtools_alert_view', ['id' => $alert->getId()]);
}
return $this->render('alert/update.html.twig', [
'alertForm' => $alertForm->createView(),
//'detailAlert'=> $detailAlert,
'alert' => $alert,
'startDateD' => $startDateD,
'userEdit' => $userEdit
]);
}
// /**
// * @Route("/email")
// */
// public function sendEmail(MailerInterface $mailer)
// {
// try {
// $email = (new Email())
// ->from('steven.tshiamala@un.org')
// ->to('steventshas@gmail.com')
// //->cc('cc@example.com')
// //->bcc('bcc@example.com')
// //->replyTo('fabien@example.com')
// //->priority(Email::PRIORITY_HIGH)
// ->subject('Time for Symfony Mailer loup!')
// ->text('Sending emails is fun again!')
// ->html('<p>See Twig integration for better HTML integration!</p>');
// $this->logger->info('before else', []);
// $mailer->send($email);
// $this->logger->info('After else', []);
// } catch (Exception $e) {
// $this->logger->info('catch >>>>>', [$e->getMessage()]);
// }
// $this->logger->info('out try', []);
// return $this->json('Ok');
// // ...
// }
/**
* @Route("/email")
*/
public function sendEmail(Request $request): JsonResponse
{
// Envois simple mail
// $fromEmail = 'steven.tshiamala@un.org';
// $fromName = '';
// $toEmail = 'steven.tshiamala@un.org';
// $subject = 'Notification ehtools system';
// $htmlContent = '<h1>Ceci est un e-mail envoyé via Mandrill</h1>';
// $textContent = 'Ceci est la version texte de l\'e-mail.';
// try {
// $response = $this->mandrillService->sendEmail($fromEmail, $fromName, $toEmail, $subject, $htmlContent, $textContent);
// return new JsonResponse(['success' => true, 'response' => $response]);
// } catch (\Exception $e) {
// return new JsonResponse(['success' => false, 'error' => $e->getMessage()]);
// }
$id = 5425; // Exemple d'ID dynamique
$url = "https://ehtools.org/alert-view/$id";
$message = [
'to' => [
['email' => 'ocha-drc-imunit@un.org', 'type' => 'to']
],
'from_email' => 'steven.tshiamala@un.org',
'from_name' => 'COHP-RDC',
'subject' => 'Notification ehtools System test',
'merge' => true,
'merge_vars' => [
[
'rcpt' => 'ocha-drc-imunit@un.org ',
'vars' => [
['name' => 'USERNAME', 'content' => 'steventshas'],
['name' => 'CODE_ALERT', 'content' => '5425'],
['name' => 'ALERT_URL', 'content' => $url],
]
]
],
];
$templateName = 'ehtoolsTemplateNotification'; // Nom du template Mandrill
$templateContent = [
['name' => 'header', 'content' => 'Welcome to our service!'],
];
try {
$response = $this->mandrillService->messages->sendTemplate($templateName, $templateContent, $message);
return new JsonResponse(['success' => true, 'response' => $response]);
} catch (\Exception $e) {
return new JsonResponse(['success' => false, 'error' => $e->getMessage()]);
}
}
/**
* @Route("/rrm-action")
*/
public function rrmAction(Request $request)
{
$action = $request->get('action');
$data = $request->get('data');
if($action=="categorieMouvement"){
//$rqEvent = $this->em->getRepository(EventType::class)->findBy(['eventReason'=>$data]);
$listEvent = [];
if($data==1){
$listEvent[] = ['id'=>"1", 'label'=>"Attaques, affrontements armées"];
$listEvent[] = ['id'=>"2", 'label'=>"Conflits fonciers, intercommunautaires"];
$listEvent[] = ['id'=>"3", 'label'=>"Catastrophe naturelle"];
//$listEvent[] = ['id'=>"7", 'label'=>"Autre"];
}
else if($data==2){
$listEvent[] = ['id'=>"6", 'label'=>"Amélioration des conditions"];
//$listEvent[] = ['id'=>"7", 'label'=>"Autre"];
}
else if($data==3){
$listEvent[] = ['id'=>"8", 'label'=>"Mixte (Violence, Retour, Forcées, ...)"];
/*$listEvent[] = ['id'=>"1", 'label'=>"Attaques, affrontements armées"];
$listEvent[] = ['id'=>"2", 'label'=>"Conflits fonciers, intercommunautaires"];
$listEvent[] = ['id'=>"6", 'label'=>"Amélioration des conditions"];*/
}
else if($data==4){
$listEvent[] = ['id'=>"3", 'label'=>"Catastrophe naturelle"];
$listEvent[] = ['id'=>"4", 'label'=>"Malnutrition"];
$listEvent[] = ['id'=>"5", 'label'=>"Epidemie"];
$listEvent[] = ['id'=>"7", 'label'=>"Autre"];
}
/*if($rqEvent){
foreach ($rqEvent as $c) {
$listEvent[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
}
}*/
$rep=new JsonResponse();
return $rep->setData(['listRaison' => $listEvent]);
}
else if($action=="eventReason"){
$rqEvent = $this->em->getRepository(EventSousType::class)->findBy(['eventReason'=>$data]);
$listEvent = [];
if($rqEvent){
foreach ($rqEvent as $c) {
$listEvent[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
}
}
$rep=new JsonResponse();
return $rep->setData(['listSousRaison' => $listEvent]);
}
else if($action=="agglomeration"){
$rqAgglomeration = $this->em->getRepository(AlertAgglomeration::class)->findAll();
$listAgglo = [];
if($rqAgglomeration){
foreach ($rqAgglomeration as $c) {
$listAgglo[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
}
}
$rep=new JsonResponse();
return $rep->setData(['listAgglomeration' => $listAgglo]);
}
else if($action=="accommodation"){
$rqAccomodation = $this->em->getRepository(AlertAccommodation::class)->findBy(['agglomeration'=>$data]);
$listAccom = [];
if($rqAccomodation){
foreach ($rqAccomodation as $c) {
$listAccom[] = ['id'=>$c->getId(), 'label'=>$c->getLabel()];
}
}
$rep=new JsonResponse();
return $rep->setData(['listAccommodation' => $listAccom]);
}
else return null;
}
private function rrmScore(Alert $alert /*$alert_id*/){
$score=0;
//Force du Choc
$event=$alert->getEventReason()->getId();
$choc=$alert->getEventSousType()->getScore();
//Lieu d'accueil / refuge
$refuge=$alert->getAccommodation()->getScore();
//Gtacq
$zs=$alert->getAlertDetail()->getHealthZone();
$rqGtacq=$this->em->getRepository(RrmGtacq::class)->findBy(['healthZone'=>$zs, "isDeleted"=>0]);
$gtacq=$rqGtacq ? $rqGtacq[0]->getScore() : 1 ;
//CaseLoad
$caseload=1;
$nbrMenage=0;
$rqNbrMen = $this->em->getRepository(AlertDetail::class)->findBy(['alert'=>$alert, "isDeleted"=>0]); //$alert->getAlertDetail();
if($rqNbrMen){
foreach ($rqNbrMen as $c) {
if($event==1) //attaques
$nbrMenage += $c->getDisplacedHousehold();
else if($event==6) //Retour
$nbrMenage += $c->getReturnedHousehold();
else if($event==2 ) //conflits
$nbrMenage = $nbrMenage + $c->getDisplacedHousehold();
else if($event==8) //Mixte
$nbrMenage = $c->getDisplacedHousehold() + $c->getReturnedHousehold();
else //Catastrophe, Epidemie, Malnutrition et Autre
$nbrMenage += $c->getHousehold();
}
}
$rqCaseload=$this->em->getRepository(RrmCaseload::class)->findBy([], ['id'=>'DESC']);
if($rqCaseload)
foreach ($rqCaseload as $n)
if($nbrMenage <= $n->getcaseload()) $caseload=$n->getScore();
//Calcul Score final
$rqPonderation=$this->em->getRepository(RrmPonderation::class)->findAll();
if($rqPonderation){
foreach ($rqPonderation as $p)
{
if($p->getFacteur()=="choc") $score+=($p->getPonderation()/100 * $choc);
else if($p->getFacteur()=="refuge") $score+=($p->getPonderation()/100 * $refuge);
else if($p->getFacteur()=="caseload") $score+=($p->getPonderation()/100 * $caseload);
else if($p->getFacteur()=="gtacq") $score+=($p->getPonderation()/100 * $gtacq);
}
}
return $score;
}
}