<?php
namespace App\Controller\higotrigo;
use App\Entity\HtFile;
use App\Entity\User;
use App\Entity\WidgetNotes;
use App\Form\WidgetNotesType;
use App\MDS\GreenPatioBundle\Entity\Reservation;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\JsonResponse;
use Google_Client;
use Google_Service_Calendar;
use Psr\Log\LoggerInterface;
use Google_Service_Calendar_Event;
use Google_Service_Calendar_EventDateTime;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use DateTime;
use App\MDS\GreenPatioBundle\Entity\CvrReservationInvoice;
use App\MDS\GreenPatioBundle\Entity\ReservationInvoice;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple;
use App\MDS\GreenPatioBundle\Entity\ReservationPaymentsClient;
use DatePeriod;
use DateInterval;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class CateringCalendarController extends AbstractController
{
/**
* @Route("/higotrigo/calendar", name="ht_calendar")
*/
public function calendarCateringAction(Request $request) {
$session = new Session();
$token=$session->get('tokenGoogleCalendar');
if (!is_null($token)) {
$this->googleCalendar->setAccessToken($token);
$connectGoogle = "1";
}else{
$connectGoogle = "0";
}
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$wnotes = new WidgetNotes();
$wnotes->setDateAt(new \DateTime("now"));
$form = $this->createWidgetNotesCreateForm($wnotes);
return $this->render('higotrigo/calendar-ht-caterings.html.twig',
array(
'form' => $form->createView(),
'user'=> $user_id,
'connectGoogle' => $connectGoogle,
)
);
}
/**
* @Route("/widget/notes/calendarht/create/", name="widget_notes_calendar_ht_create")
*/
public function addNotesAction(Request $request, LoggerInterface $logger)
{
$em = $this->getDoctrine()->getManager();
$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->get('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->get('translator')->trans($event);
$this->addFlash('mensajeerror', $errorMessage);
}
}else{
$errorMessage = $this->get('translator')->trans('Error, some fields are empty');
$this->addFlash('mensajeerror', $errorMessage);
}
// return $this->redirectToRoute('homepage');
return $this->redirectToRoute('ht_calendar');
}
/**
* @Route("/higotrigo/eventsht_OLD", name="get_caterings_ht_OLD")
*/
public function htEventsOLDAction(EntityManagerInterface $em)
{
$todayOneYearAgo = new \DateTime('first day of January last year');
$parameters = array('dateStart' => $todayOneYearAgo, );
$dql = 'SELECT p
FROM App:HtFile p
WHERE p.dateStart >= :dateStart AND p.dateEnd >= p.dateStart
AND p.reservation IS NULL
ORDER BY p.dateStart ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservation = $query->getResult();
$datos = array();
if (!empty($reservation)) {
foreach ($reservation as $reserva) {
if ($reserva->getDateStart()->format('d') == $reserva->getDateEnd()->format('d')) {
$tooltip = $reserva->getTitle() . ' - Del'. $reserva->getDateStart()->format('d/m') . ' desde ' . $reserva->getDateStart()->format('H:i') . " a " . $reserva->getDateEnd()->format('H:i');
} else {
$tooltip = $reserva->getTitle() . ' - Del'. $reserva->getDateStart()->format('d/m') . ' desde ' . $reserva->getDateStart()->format('H:i') . " a " . $reserva->getDateEnd()->format('d/m') . " a " . $reserva->getDateEnd()->format('H:i');
}
$color = "#c4771a";
// Si el que crea la reserva es un agente de GP, se asigna el color #dd610b (naranja)
$agent = $reserva->getCreatedId();
if ($agent->getTeam() == 17) {
// $color = "#d9023d";
$color = "#ba0d0d";
}
// Iniciado o Cotizando
if (($reserva->getStatus() == 'Iniciado') or ($reserva->getStatus() == 'Quoting')){ $color = '#ed3939'; }
// Cancelado
if ($reserva->getStatus() == 'Cancel'){ $color = '#000000'; }
$datos[] = array(
"title" => $reserva->getDateStart()->format('d/m/Y H:i') . ' ' . '<br>' . '<br>' . $reserva->getTitle(),
"titleOne" => $reserva->getDateStart()->format('H:i') . '<br>',
"titleTwo" => $reserva->getDateEnd()->format('H:i') . '<br>',
"titleThree" => '' . '<br>' . '<br>' . $reserva->getTitle(),
"type" => '',
"id" => $reserva->getId(),
"tooltip" => $tooltip,
"start" => $reserva->getDateStart(),
"end" => $reserva->getDateEnd(),
"color" => $color,
"loungeId" => 1,
"url" => "/higotrigo/ht/file/".$reserva->getId()."/edit",
"status" => $reserva->getStatus(),
);
}
}
$return = array(
'reservation' => $datos,
);
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/higotrigo/eventsht", name="get_caterings_ht")
*/
public function htEventsAction(UrlGeneratorInterface $urlGenerator)
{
$em = $this->getDoctrine()->getManager();
// Buscamos las reservas desde 1 aƱo atras en adelante para no traer exceso de datos
$todayOneYearAgo = new DateTime('now -180 days');
$parameters = array('dateStart' => $todayOneYearAgo,);
$dql = 'SELECT p
FROM GreenPatioBundle:ReservationLoungeSimple p
WHERE p.dateStart >= :dateStart
ORDER BY p.dateStart ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservation = $query->getResult();
// Buscamos las visitas desde 1 semana atras en adelante para no traer exceso de datos (Tiempo confirmado por Gabriela Bracho)
$todayOneWeekAgo = new DateTime('now -1 week');
$parameters = array('dateStart' => $todayOneWeekAgo,);
$dql = 'SELECT p
FROM GreenPatioBundle:ReservationVisit p
WHERE p.dateStart >= :dateStart
ORDER BY p.dateStart ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$visitas = $query->getResult();
$arrayFechaVisitas = array();
foreach ($visitas as $item) {
//Se agrupan las visitas por fechas
$arrayFechaVisitas[$item->getDateStart()->format('Y-m-d')][] = $item;
}
$newArrayVisitas = array();
//Se agrupan las visitas por agente
foreach ($arrayFechaVisitas as $fecha) {
foreach ($fecha as $item) {
//Se van concatenando los titulos de las visitas en una sola
$loungeNameTemp = '';
$idAgentLounge = ($item->getIdLounge() == 0) ? $item->getAgentId() : '0';
if (!empty($newArrayVisitas[$item->getDateStart()->format('Y-m-d') . '-' . $idAgentLounge])) {
$loungeNameTemp = $newArrayVisitas[$item->getDateStart()->format('Y-m-d') . '-' . $idAgentLounge]->getLoungeName();
}
$item->setLoungeName($loungeNameTemp . $item->getDateStart()->format('H:i') . ' ' . $item->getLoungeName() . '<br>');
$newArrayVisitas[$item->getDateStart()->format('Y-m-d') . '-' . $idAgentLounge] = $item;
}
}
$visitas = $newArrayVisitas;
foreach ($visitas as $item) { array_push($reservation, $item); }
$datos = array();
if (!empty($reservation)) {
foreach ($reservation as $reservaSala) {
if (!empty($reservaSala->getIdReservation())) {
$reserva = $em->getRepository(Reservation::class)->findOneById($reservaSala->getIdReservation());
if ($reservaSala->getType() == 'Visit') {
$reserva->setStatus('Visit');
}
} else {
// Estamos con una visita
$reserva = new Reservation();
$reserva->setStatus('Visit');
$reserva->setTitle($reservaSala->getLoungeName());
}
if ($reservaSala->getDateStart()->format('d') == $reservaSala->getDateEnd()->format('d')) {
$tooltip = $reserva->getTitle() . ' - <b><h3>' . $reservaSala->getLoungeName() . "</h3></b> Del " . $reservaSala->getDateStart()->format('d/m') . ' desde ' . $reservaSala->getHourStart() . ":" . $reservaSala->getMinStart() . " a " . $reservaSala->getHourEnd() . ":" . $reservaSala->getMinEnd();
} else {
$tooltip = $reserva->getTitle() . ' - <b><h3>' . $reservaSala->getLoungeName() . "</h3></b> Del " . $reservaSala->getDateStart()->format('d/m') . ' desde ' . $reservaSala->getHourStart() . ":" . $reservaSala->getMinStart() . " al " . $reservaSala->getDateEnd()->format('d/m') . ' hasta ' . $reservaSala->getHourEnd() . ":" . $reservaSala->getMinEnd();
}
$logicoVisita = false;
if (!is_null($reserva->getStatus())) {
$statusColorMap = [
'Bloqueo' => function($reservaSala) { return ($reservaSala->getIdLounge() > 21) ? "#b873bf" : "#ffaa00"; },
'Confirmed' => "#13ad27",
'Invoiced' => "#13ad27",
'Deleted' => "#ff0000",
'Cotizado' => "#faafc3",
'Reservado' => "#13ad27",
'Visit' => function($reservaSala) {
if ($reservaSala->getIdLounge() == 0) {
$agentColorMap = [
77 => "#22cbf5",
82 => "#f5229a",
106 => "#157cc2",
];
return $agentColorMap[$reservaSala->getAgentId()] ?? "";
} else {
return '#f0d800';
}
},
'default' => "",
];
$color = "";
$logicoVisita = false;
if (array_key_exists($reserva->getStatus(), $statusColorMap)) {
$value = $statusColorMap[$reserva->getStatus()];
// Si el valor es una función, la ejecutamos para obtener el color.
$color = is_callable($value) ? $value($reservaSala) : $value;
if ($reserva->getStatus() === 'Visit') {
$logicoVisita = true;
}
} else {
$color = $statusColorMap['default'];
}
if (!empty($reservaSala->getType()) and !($reservaSala->getType() == 'Visit')) {
//Es un montaje o desmontaje
$color = "#a5b8a2";
// Si es un montaje o desmontaje pero esta cancelado debe prevalecer el color de cancelado
if ($reserva->getStatus() == 'Deleted') { $color = "#ff0000"; }
}
if (($reservaSala->getIdLounge() == 22) or ($reservaSala->getIdLounge() == 23) or
($reservaSala->getIdLounge() == 24) or ($reservaSala->getIdLounge() == 25)){
//Ajustamos el color a una sala de covarrubia
switch ($color) {
case '#ffaa00': $color = "#b873bf"; break; //naranja (bloqueo) => morado
case '#13ad27': $color = "#017362"; break; //verde (Confirmed) => verde olivo
case '#ff0000': $color = "#ff0000"; break; //rojo
case '#faafc3': $color = "#faafc3"; break; //Rojo claro
default: break; //no modificar el color
}
}
}
$ht = "";
if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
$ht = "<a style='color: #000 !important;'><strong>H&T</strong></a>"; // Es una reserva con servicio de Catering Higo & Trigo
}
// Pagos parciales y totales
$pago1 = ""; $pago2 = ""; // En HT no son relevantes los pagos de GP
if (!empty($reserva)) {
if (!$logicoVisita) {
$urlReserva = "#";
if($reserva->getHtFile() != Null){
$urlReserva = $urlGenerator->generate('app_ht_file_edit', ['id' => $reserva->getHtFile()->getId()]);
}
$datos[] = array(
"title" => $reservaSala->getDateStart()->format('H:i') . ' ' . $pago2 . $pago1 . $ht . ' ' . $reservaSala->getType() . '<br>' . $reservaSala->getLoungeName() . '<br>' . '<br>' . $reserva->getTitle(),
"titleOne" => $reservaSala->getDateStart()->format('H:i') . ' ' . $pago2 . $pago1 . $ht . ' ' . $reservaSala->getType() . '<br>',
"titleTwo" => $reservaSala->getLoungeName(),
"titleThree" => '' . '<br>' . '<br>' . $reserva->getTitle(),
"type" => $reservaSala->getType(),
"id" => $reserva->getId(),
"tooltip" => $tooltip,
"start" => $reservaSala->getDateStart(),
"end" => $reservaSala->getDateEnd(),
"color" => $color,
"loungeId" => $reservaSala->getIdLounge(),
"url" => $urlReserva,
"status" => $reserva->getStatus(),
);
} else {
// Es una visita
$datos[] = array(
"title" => $reservaSala->getLoungeName(),
"titleOne" => $reservaSala->getDateStart()->format('H:i') . ' ' . ' ' . $reservaSala->getType() . '<br>',
"titleTwo" => $reservaSala->getLoungeName(),
"titleThree" => '' . '<br>' . '<br>' . $reserva->getTitle(),
"type" => $reservaSala->getType(),
"id" => $reservaSala->getId() . 'V',
"tooltip" => $tooltip,
"start" => $reservaSala->getDateStart(),
"end" => $reservaSala->getDateEnd(),
"color" => $color,
"loungeId" => $reservaSala->getIdLounge(),
"url" => '/reservations-greenpatio/addvisit',
"status" => $reserva->getStatus(),
"agentId" => $reservaSala->getAgentId(),
);
}
} else {
$datos = [];
}
}
}
$newDatos = array();
// INICIO: Se unen las salas en una sola reserva por ID de reserva
foreach ($datos as $dato) {
// Inicializamos el arreglo para crear los indices
switch ($dato['color']){
case '#a5b8a2': //Montaje o Desmontaje
if ($dato['type'] == 'Montaje'){
$newDatos[$dato['id'].'M'] = null;
} else {
$newDatos[$dato['id'].'D'] = null;
}
break;
default: //Dia de reserva o Visita (la visita ya viene con su indice #V )
$newDatos[$dato['id']] = null;
break;
}
}
foreach ($datos as $dato) {
switch ($dato['color']){
//Montaje o Desmontaje
case '#a5b8a2':
if ($dato['type'] == "Montaje") {
if (!empty($newDatos[$dato['id'] . 'M'])) {
// El Montaje esta ocupando mas de 1 dia, se deben unir los dias de montaje
if ($newDatos[$dato['id'] . 'M']['start'] > $dato['start']) { $newDatos[$dato['id'] . 'M']['start'] = $dato['start']; }
if ($newDatos[$dato['id'] . 'M']['end'] < $dato['end']) { $newDatos[$dato['id'] . 'M']['end'] = $dato['end']; }
} else {
$newDatos[$dato['id'] . 'M'] = $dato;
}
} else {
if ($dato['type'] == "Desmontaje") {
if (!empty($newDatos[$dato['id'] . 'D'])) {
// El Desmontaje esta ocupando mas de 1 dia, se deben unir los dias de desmontaje
if ($newDatos[$dato['id'] . 'D']['start'] > $dato['start']) { $newDatos[$dato['id'] . 'D']['start'] = $dato['start']; }
if ($newDatos[$dato['id'] . 'D']['end'] < $dato['end']) { $newDatos[$dato['id'] . 'D']['end'] = $dato['end']; }
} else {
$newDatos[$dato['id'] . 'D'] = $dato;
}
}
}
break;
//Visita Angie (id user 77)
case '#22cbf5':
if ($dato['type'] == "Visit") {
if (!empty($newDatos[$dato['start']->format('Ymd').'V77'])) {
// Hay varias visitas ese mismo dia para el agente
$newDatos[$dato['start']->format('Ymd').'V77']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V77']['tooltip'] . $dato['tooltip'];
} else {
$newDatos[$dato['start']->format('Ymd').'V77'] = $dato;
}
}
break;
//Visita Gabriela (id user 82)
case '#f5229a':
if ($dato['type'] == "Visit") {
if (!empty($newDatos[$dato['start']->format('Ymd').'V82'])) {
// Hay varias visitas ese mismo dia para el agente
$newDatos[$dato['start']->format('Ymd').'V82']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V82']['tooltip'] . $dato['tooltip'];
} else {
$newDatos[$dato['start']->format('Ymd').'V82'] = $dato;
}
}
break;
//Visita MarĆa (id user 106)
case '#157cc2':
if ($dato['type'] == "Visit") {
if (!empty($newDatos[$dato['start']->format('Ymd').'V106'])) {
// Hay varias visitas ese mismo dia para el agente
$newDatos[$dato['start']->format('Ymd').'V106']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V106']['tooltip'] . $dato['tooltip'];
} else {
$newDatos[$dato['start']->format('Ymd').'V106'] = $dato;
}
}
break;
//Visita Generica para agentes a Covarrubias
case '#f0d800':
if ($dato['type'] == "Visit") {
if (!empty($newDatos[$dato['start']->format('Ymd').'V0'])) {
// Hay varias visitas ese mismo dia para el agente
$newDatos[$dato['start']->format('Ymd').'V0']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V0']['tooltip'] . $dato['tooltip'];
} else {
$newDatos[$dato['start']->format('Ymd').'V0'] = $dato;
}
}
break;
//Reserva color naranja Bloqueo
case '#ffaa00':
if (empty($newDatos[$dato['id']])){
$newDatos[$dato['id']] = $dato;
} else {
// Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
if ($newDatos[$dato['id']]['start'] > $dato['start']) {
$newDatos[$dato['id']]['start'] = $dato['start'];
}
if ($newDatos[$dato['id']]['end'] < $dato['end']) {
$newDatos[$dato['id']]['end'] = $dato['end'];
}
$newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' . $dato['tooltip'];
// Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
// No se encontro la cadena, debemos agregar
$newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' . $dato['titleTwo'];
$newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
}
}
break;
//Reserva color morado Bloqueo (Covarrubias)
case '#b873bf':
if (empty($newDatos[$dato['id']])){
$newDatos[$dato['id']] = $dato;
} else {
// Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
if ($newDatos[$dato['id']]['start'] > $dato['start']) {
$newDatos[$dato['id']]['start'] = $dato['start'];
}
if ($newDatos[$dato['id']]['end'] < $dato['end']) {
$newDatos[$dato['id']]['end'] = $dato['end'];
}
$newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' . $dato['tooltip'];
// Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
// No se encontro la cadena, debemos agregar
$newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' . $dato['titleTwo'];
$newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
}
}
break;
//Reserva color Rojo claro Cotizado
case '#faafc3':
if (empty($newDatos[$dato['id']])){
$newDatos[$dato['id']] = $dato;
} else {
// Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
if ($newDatos[$dato['id']]['start'] > $dato['start']) {
$newDatos[$dato['id']]['start'] = $dato['start'];
}
if ($newDatos[$dato['id']]['end'] < $dato['end']) {
$newDatos[$dato['id']]['end'] = $dato['end'];
}
$newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' . $dato['tooltip'];
// Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
// No se encontro la cadena, debemos agregar
$newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' . $dato['titleTwo'];
$newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
}
}
break;
//Reserva color Rojo Reserva Cancelada
// Revisar el caso de una reserva externa para el calendario y el caso de una reserva cancelada de GP pero sigue firme para HT
case '#ff0000':
//Las canceladas no se muestran en el calendario
break;
//Reserva color Verde Reserva Confirmada, Facturada, (se ha adelantado un pago parcial)
case '#13ad27':
if (empty($newDatos[$dato['id']])){
$newDatos[$dato['id']] = $dato;
} else {
// Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
if ($newDatos[$dato['id']]['start'] > $dato['start']) {
$newDatos[$dato['id']]['start'] = $dato['start'];
}
if ($newDatos[$dato['id']]['end'] < $dato['end']) {
$newDatos[$dato['id']]['end'] = $dato['end'];
}
$newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' . $dato['tooltip'];
// Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
// No se encontro la cadena, debemos agregar
$newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' . $dato['titleTwo'];
$newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
}
}
break;
//Reserva color Verde Reserva Confirmada, Facturada, (Covarrubias)
case '#017362':
if (empty($newDatos[$dato['id']])){
$newDatos[$dato['id']] = $dato;
} else {
// Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
if ($newDatos[$dato['id']]['start'] > $dato['start']) {
$newDatos[$dato['id']]['start'] = $dato['start'];
}
if ($newDatos[$dato['id']]['end'] < $dato['end']) {
$newDatos[$dato['id']]['end'] = $dato['end'];
}
$newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' . $dato['tooltip'];
// Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
// No se encontro la cadena, debemos agregar
$newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' . $dato['titleTwo'];
$newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
}
}
break;
//Se pondra color a negro para resaltar este cualquier caso que no haya sido considerado (status Pendiente)
default:
if (empty($newDatos[$dato['id']])){
$newDatos[$dato['id']] = $dato;
} else {
// Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
if ($newDatos[$dato['id']]['start'] > $dato['start']) {
$newDatos[$dato['id']]['start'] = $dato['start'];
}
if ($newDatos[$dato['id']]['end'] < $dato['end']) {
$newDatos[$dato['id']]['end'] = $dato['end'];
}
$newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' . $dato['tooltip'];
// Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
// No se encontro la cadena, debemos agregar
$newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' . $dato['titleTwo'];
$newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
}
}
// Se pone en color amarillo para resaltar este caso que no esta entrando en ninguno de los casos anteriores
$newDatos[$dato['id']]['color'] = '#f0d800';
break;
}
}
$datos0 = array();
foreach ($newDatos as $key => $item) {
if (!empty($item['id'])) {
$datos0[$key] = array('title' => $item['title'],
'titleOne' => $item['titleOne'],
'titleTwo' => $item['titleTwo'],
'titleThree' => $item['titleThree'],
'type' => $item['type'],
'id' => $item['id'],
'tooltip' => $item['tooltip'],
'start' => $item['start'],
'end' => $item['end'],
'color' => $item['color'],
'loungeId' => $item['loungeId'],
'url' => $item['url'],
'status' => $item['status'],
);
}
}
$newDatos = $datos0;
$datos = array();
foreach ($newDatos as $item) {
if ($item['color'] != '#ff0000') {
// No se agregan al calendario los elementos eliminados o elementos vacios
if (!empty($item)) {
//INICIO: Verificamos por huecos dentro de la reserva
if (empty($item['type'])) {
// solo las reservas se van a verificar en este if
if ((date_diff($item['start'], $item['end'])->d) > 1) { //el evento tiene mas de 2 dias, puede haber huecos
$resSimples = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($item['id']);
$period = new DatePeriod( $item['start'], new DateInterval('P1D'), $item['end'] );
$arrayPeriod = array();
foreach ($period as $key => $value) { $arrayPeriod[] = $value; }
$logAllDiasEnReserva = false;
$logDiaEnReserva = false;
//Verificamos que cada dia tenga su reserva de sala para que no haya hueco
foreach ($arrayPeriod as $day) {
foreach ($resSimples as $resSimple) {
if ($resSimple->getDateStart()->format('Y-m-d') == $day->format('Y-m-d')) {
$logDiaEnReserva = true;
break;
}
}
if (!$logDiaEnReserva) {
//Un dia no se encontraba, hay un hueco
foreach ($resSimples as $resDayToAdd) {
if (empty($resDayToAdd->getType())) { // Solo se deben agregar salsa los montajes y desmontajes aqui no van
$item['start'] = $resDayToAdd->getDateStart();
$item['end'] = $resDayToAdd->getDateEnd();
$br = '<br>';
$br = strpos($item['title'], $br);
$tempText = substr($item['title'], $br + 4);
$item['title'] = $resDayToAdd->getDateStart()->format('H:i') . ' ' . '<br>' . $tempText;
$datos[] = $item;
}
}
break;
} else {
//Se debe evaluar el siguiente dia
$logDiaEnReserva = false;
if ($day->format('Y-m-d') == (end($arrayPeriod))->format('Y-m-d')) { //Si es el ultimo elemento evaluado, todos los dias se encontraban en Reservas Simple
$logAllDiasEnReserva = true;
}
}
}
if ($logAllDiasEnReserva) { $datos[] = $item; }
} else {
// El evento es de 1 o 2 dias, no hay posibilidad de hueco
$datos[] = $item;
}
} else {
//Es Visita Las visitas son las unicas entradas que no tienen hueco
if ($item['type'] == 'Visit'){
$datos[] = $item;
} else {
// es montaje o desmontaje, se va verificar por huecos
if ((date_diff($item['start'], $item['end'])->d) > 1) { //el item tiene mas de 2 dias, puede haber huecos
$parameters = array(
'id' => $item['id'],
'type' => $item['type'],
);
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLoungeSimple i
WHERE i.idReservation = :id
and i.type = :type';
$query = $em->createQuery($dql)->setParameters($parameters);
$resSimples = $query->getResult();
$period = new DatePeriod( $item['start'], new DateInterval('P1D'), $item['end'] );
$arrayPeriod = array();
foreach ($period as $key => $value) { $arrayPeriod[] = $value; }
$logAllDiasEnReserva = false;
$logDiaEnReserva = false;
//Verificamos que cada dia tenga su reserva de sala para que no haya hueco
foreach ($arrayPeriod as $day) {
foreach ($resSimples as $resSimple) {
if ($resSimple->getDateStart()->format('Y-m-d') == $day->format('Y-m-d')) {
$logDiaEnReserva = true;
break;
}
}
if (!$logDiaEnReserva) {
//Un dia no se encontraba, hay un hueco
foreach ($resSimples as $resDayToAdd) {
if (!empty($resDayToAdd->getType())) { // Solo se deben agregar montajes y desmontajes aqui
$item['start'] = $resDayToAdd->getDateStart();
$item['end'] = $resDayToAdd->getDateEnd();
$br = '<br>';
$br = strpos($item['title'], $br);
$tempText = substr($item['title'], $br + 4);
$item['title'] = $resDayToAdd->getDateStart()->format('H:i') . ' ' . '<br>' . $tempText;
$datos[] = $item;
}
}
break;
} else {
//Se debe evaluar el siguiente dia
$logDiaEnReserva = false;
if ($day->format('Y-m-d') == (end($arrayPeriod))->format('Y-m-d')) { //Si es el ultimo elemento evaluado, todos los dias se encontraban en Reservas Simple
$logAllDiasEnReserva = true;
}
}
}
if ($logAllDiasEnReserva) { $datos[] = $item; }
} else {
// El montaje o desmontaje es de 1 o 2 dias, no hay posibilidad de hueco
$datos[] = $item;
}
}
}
//FIN: Verificamos por huecos dentro de la reserva
}
}
}
// Buscamos las pruebas de menu desde 6 meses atras
$todayHalfYearAgo = new DateTime('now -180 days');
$parameters = array('dateStart' => $todayHalfYearAgo,);
$dql = 'SELECT p
FROM App:HtVisit p
WHERE p.dateStart >= :dateStart
ORDER BY p.dateStart ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$pmenu = $query->getResult();
$arrayPmenu = array(); $color = '#ccad11';
foreach ($pmenu as $item){
$agent = (!empty($item->getAgentId())) ? ($item->getAgentId())->getName() : 'Sin agente';
$pax = (!empty($item->getPax())) ? (' - '.$item->getPax() . ' PAX') : null;
$title =''; $titleOne =''; $titleTwo =''; $titleThree =''; $type =''; $id =''; $tooltip =''; $start =''; $end =''; $loungeId =''; $url ='';
if(!empty($item->getReservation())){
$title = ($item->getDateStart())->format('H:i'). ' PRUEBA DE MENU ( '.$agent. ' )<br>' . $item->getName(). $pax . ' - ' . ($item->getReservation())->getTitle();
$titleOne = '$titleOne';
$titleTwo = '$titleTwo';
$titleThree = '$titleThree';
$type = 'Prueba Menu';
$id = $item->getId();
$loungeId = (!empty(($item->getLounge()))) ? '<b> - '. ($item->getLounge())->getName() : null;
$tooltip = '<b>'. ($item->getReservation())->getTitle() .$loungeId;
$start = $item->getDateStart();
$end = $item->getDateEnd();
$end->modify('+1 hour');
$loungeId = ($item->getLounge())->getId();
$url = '/higotrigo/ht/file/'.($item->getReservation())->getId().'/edit';
} else {
$title = ($item->getDateStart())->format('H:i'). ' PRUEBA DE MENU ( '.$agent. ' )<br>' . $item->getName() . $pax;
$titleOne = '$titleOne';
$titleTwo = '$titleTwo';
$titleThree = '$titleThree';
$type = 'Prueba Menu';
$id = $item->getId();
$loungeId = (!empty(($item->getLounge()))) ? '<b> '. ($item->getLounge())->getName() : null;
$tooltip = '<b>' . $loungeId;
$start = $item->getDateStart();
$end = $item->getDateEnd();
$end->modify('+1 hour');
$loungeId = ($item->getLounge())->getId();
$url = '/#';
}
$arrayPmenu[] = array(
'title' => $title,
'titleOne' => $titleOne,
'titleTwo' => $titleTwo,
'titleThree' => $titleThree,
'type' => $type,
'id' => $id,
'tooltip' => $tooltip,
'start' => $start,
'end' => $end,
'color' => $color,
'loungeId' => $loungeId,
'url' => $url,
);
}
foreach ($arrayPmenu as $item){ array_push($datos, $item); }
$return = array( 'reservation' => $datos, );
$response = new JsonResponse($return);
return $response;
}
private function createWidgetNotesCreateForm(WidgetNotes $entity)
{
$form = $this->createForm(WidgetNotesType::class, $entity, array(
'action' => $this->generateUrl('widget_notes_calendar_ht_create'),
'method' => 'POST'
));
return $form;
}
};