<?php
namespace App\MDS\AvexpressBundle\Controller;
use App\Entity\User;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Psr\Log\LoggerInterface;
use App\Form\WidgetNotesType;
use App\Entity\WidgetNotes;
use App\MDS\AvexpressBundle\Entity\AveFiles;
use App\MDS\AvexpressBundle\Entity\AveProductFile;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple;
use Symfony\Contracts\Translation\TranslatorInterface;
use DateTime;
class CalendarController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/**
* @Route("/calendarav/", name="ave_calendarav")
* Ver Calendario de Av. Se cargan expedientes Av, Proposal asociados con Av y eventos de Green Patio
*/
public function calendarAvAction( Request $request)
{
$wnotes = new WidgetNotes();
$wnotes->setDateAt(new \DateTime("now"));
$form = $this->createWidgetNotesCreateForm($wnotes);
return $this->render('MDS/AvexpressBundle/Avexpress/calendar.html.twig',
array(
'form' => $form->createView(),
)
);
}
/**
* @Route("/widget/notes/calendar/create/", name="widget_notes_calendar_av_create")
*/
public function addNotesAction(Request $request, LoggerInterface $logger)
{
$em = $this->getDoctrine()->getManager();
$notes = $em->getRepository(WidgetNotes::class)->findAll();
$wnotes = new WidgetNotes();
$form = $this->createWidgetNotesCreateForm($wnotes);
$form->handleRequest($request);
$forAgent = $form->get('forAgent')->getData();
if(!is_null($forAgent)){
$wnotes->setForAgent($forAgent->getId());
}
if($form->isValid())
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$wnotes->setCreatedId($user_id);
$wnotes->setUpdatedId($user_id);
/* Gestión de eventos en Log */
$user_lastname = $user_logueado->getLastname();
$user_name = $user_logueado->getName();
$user_email = $user_logueado->getEmail();
$user_rol = $user_logueado->getRoles();
$event_url = $request->getPathInfo();
$event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
try{
$em->persist($wnotes);
$em->flush();
$event = 'The Note has been created succesfully.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensaje', $successMessage);
$logger->info($event_complete.' | '.$event);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el log */
$logger->error($event_complete.' | '.$event);
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeerror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeerror', $errorMessage);
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/eventsav", name="get_eventsav")
* Eventos para el Calendario consultados desde el dashboard
*/
public function eventsavAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$datos = array();
$datosAV = $this->buscarEventosAvFiles();
$datosGP = $this->buscarEventosGreenPatio();
$datosIO = $this->buscarEventosInOut();
$datos = array_merge($datosAV, $datosGP, $datosIO);
$return = array(
'reservation' => $datos,
);
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/calendarav/avexpress/fileedit/{id}", name="get_calendar_redirection")
* Redireccion desde el calendario a los expedientes de AV
*/
public function calendarRedirectionAction($id, Request $request)
{
return $this->redirectToRoute('ave_edit_file', array( 'id' => $id ));
}
private function buscarEventosAvFiles()
{
$em = $this->getDoctrine()->getManager();
$todayOneYearAgo = new \Datetime('-365 days'); //Al dia actual se le resta un año
$datos = [];
//
$parameters = array(
'desde' => $todayOneYearAgo,
'cancelado' => 'deleted',
);
//
// $dql = 'SELECT p
// FROM App\MDS\AvexpressBundle\Entity\AveFiles p
// WHERE p.dateStart >= :desde AND p.status <> :cancelado
// ORDER BY p.dateStart ASC';
//
// $query = $em->createQuery($dql)->setParameters($parameters);
// $filesAv = $query->getResult();
//
// $colorAv = '#e86100';
//
// foreach($filesAv as $fileAv){
// $id = $fileAv->getReservation()? 'AV'. ($fileAv->getReservation())->getId() : $fileAv->getId();
// $tooltip = 'Evento Av Express ID: '.$id.'<br>Fecha inicio: '.$fileAv->getDateStart()->format('d/m/Y').'<br>Fecha fin: '.$fileAv->getDateEnd()->format('d/m/Y');
//
// $datos[] = array(
// "id" => $fileAv->getId(),
// "title" => $fileAv->getTitle(),
// "tooltip" => $tooltip,
// "date" => $fileAv->getDateStart(),
// "start" => $fileAv->getDateStart(),
// "end" => $fileAv->getDateEnd(),
// "color" => $colorAv,
// "url" => "avexpress/fileedit/".$fileAv->getId()
// );
// }
$dql = 'SELECT
p.id,
p.title,
p.dateStart,
p.dateEnd,
r.id AS reservationId
FROM App\MDS\AvexpressBundle\Entity\AveFiles p
LEFT JOIN p.reservation r
WHERE p.dateStart >= :desde AND p.status <> :cancelado
ORDER BY p.dateStart ASC';
$query = $em->createQuery($dql)
->setParameters($parameters);
$filesAv = $query->getArrayResult();
$colorAv = '#e86100';
$datos = [];
foreach($filesAv as $fileAv){
$id = $fileAv['reservationId'] ? 'AV' . $fileAv['reservationId'] : $fileAv['id'];
$tooltip = 'Evento Av Express ID: ' . $id . '<br>Fecha inicio: ' . ($fileAv['dateStart'])->format('d/m/Y') . '<br>Fecha fin: ' . ($fileAv['dateEnd'])->format('d/m/Y');
$datos[] = [
"id" => $fileAv['id'],
"title" => $fileAv['title'],
"tooltip" => $tooltip,
"date" => $fileAv['dateStart'],
"start" => $fileAv['dateStart'],
"end" => $fileAv['dateEnd'],
"color" => $colorAv,
"url" => "avexpress/fileedit/" . $fileAv['id']
];
}
return $datos;
}
private function buscarEventosInOut()
{
$em = $this->getDoctrine()->getManager();
$todayOneYearAgo = new \Datetime('-60 days'); //Al dia actual se le resta dos meses
$datos = array();
$parameters = array(
'desde' => $todayOneYearAgo,
'supAv' => 80,
'cancelado' => 'cancel',
);
$dql = 'SELECT cl
FROM App\MDS\EventsBundle\Entity\Proposal cl
INNER JOIN EventsBundle:ProposalSupplierControl c WITH cl.id = c.proposalId
WHERE cl.dateEventStarAt >= :desde AND c.supplierId =:supAv AND cl.status <> :cancelado';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
// $colorInOut = '#12b8c4';
$colorInOut = '#3ea83e';
foreach($proposals as $proposal){
// Solo agregamos los proposals que no estén asociados a un expediente de AV, asi evitamos repeticiones
$fileAv = $em->getRepository(AveFiles::class)->findOneByIdProposal($proposal->getId());
if (empty($fileAv)){
if (!empty($proposal->getAgentId())){
$textoAgente = '';
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if (!empty($agent)){
$textoAgente = ''.'<br>Agente: '.$agent->getName().' '.$agent->getLastName();
}
}
$tooltip = $proposal->getTitle().', Proposal: '.$proposal->getId().'<br>Fecha inicio: '.$proposal->getDateEventStarAt()->format('d/m/Y').'<br>Fecha fin: '.$proposal->getDateEventEndAt()->format('d/m/Y').$textoAgente;
$datos[] = array(
"id" => $proposal->getId(),
"title" => 'IN OUT - '.$proposal->getTitle(),
"tooltip" => $tooltip,
"date" => $proposal->getDateEventStarAt(),
"start" => $proposal->getDateEventStarAt(),
"end" => $proposal->getDateEventEndAt(),
"color" => $colorInOut,
"url" => ""
);
}
}
return $datos;
}
private function buscarEventosGreenPatio()
{
$em = $this->getDoctrine()->getManager();
$todayOneYearAgo = new \Datetime('-60 days'); //Al dia actual se le resta dos meses
$datos = array();
$parameters = array(
'desde' => $todayOneYearAgo,
'Confirmed' => 'Confirmed',
'Bloqueo' => 'Bloqueo',
'Invoiced' => 'Invoiced',
);
$dql = 'SELECT p
FROM App\MDS\GreenPatioBundle\Entity\Reservation p
WHERE p.dateStart >= :desde
AND ((p.status = :Confirmed) OR (p.status = :Bloqueo) OR (p.status = :Invoiced))
AND p.dateStart <= p.dateEnd
ORDER BY p.dateStart ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservation = $query->getResult();
foreach($reservation as $reserva){
$reservationLounges = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($reserva->getId());
$arrayNameLounges = array();
foreach ($reservationLounges as $sala) {
if (($sala->getType() == 'Montaje') or ($sala->getType() == 'Desmontaje')) {
$colorGreenPatio = '#a5b8a2';
$nameLounges = $sala->getType() . ': ' . $sala->getLoungeName();
$datos[] = array(
"id" => $reserva->getId(),
"title" => '( '.$nameLounges.' ) -'.$reserva->getTitle(),
"tooltip" => '<br>Inicio: '.$sala->getDateStart()->format('d/m/Y H:i').'<br>Fin: '.$sala->getDateEnd()->format('d/m/Y H:i').'<br>',
"date" => $reserva->getDateStart(),
"start" => $reserva->getDateStart(),
"end" => $reserva->getDateEnd(),
"color" => $colorGreenPatio,
"url" => ""
);
} else {
$arrayNameLounges[$sala->getIdLounge()] = $sala->getLoungeName();
}
}
$nameLounges = implode(",", $arrayNameLounges);
$tooltip = $reserva->getTitle().', ID: '.$reserva->getId().'<br>Salas: '.$nameLounges.'<br>Fecha inicio: '.$reserva->getDateStart()->format('d/m/Y').'<br>Fecha fin: '.$reserva->getDateEnd()->format('d/m/Y').'<br>';
switch ($reserva->getStatus()){
case 'Bloqueo': /* BLOQUEADO */ $colorGreenPatio = '#facc61'; $reserva->setTitle('BLOQUEO - '.$reserva->getTitle()); break;
case 'Confirmed': /* CONFIRMADO */ $colorGreenPatio = '#3ea83e'; break;
case 'Invoiced': /* FACTURADO */ $colorGreenPatio = '#3ea83e'; break;
default: $colorGreenPatio = '#056905'; break;
}
if (!empty($reservationLounges)){
$datos[] = array(
"id" => $reserva->getId(),
"title" => '( '.$nameLounges.' ) -'.$reserva->getTitle(),
"tooltip" => $tooltip,
"date" => $reserva->getDateStart(),
"start" => $reserva->getDateStart(),
"end" => $reserva->getDateEnd(),
"color" => $colorGreenPatio,
"url" => ""
);
}
}
return $datos;
}
private function createWidgetNotesCreateForm(WidgetNotes $entity)
{
$form = $this->createForm(WidgetNotesType::class, $entity, array(
'action' => $this->generateUrl('widget_notes_calendar_av_create'),
'method' => 'POST'
));
return $form;
}
};