<?php
namespace App\MDS\GreenPatioBundle\Controller;
use App\Entity\DocContract;
use App\Entity\DocContractModel;
use App\Entity\Client;
use App\Entity\ClientContact;
use App\Entity\Supplier;
use App\Entity\User;
use App\Entity\HtFile;
use App\MDS\AvexpressBundle\Entity\AveFiles;
use App\Entity\WidgetNotes;
use App\Form\WidgetNotesType;
use App\MDS\DevelupBundle\Entity\MdvTelegramUser;
use App\MDS\EventsBundle\Entity\Proposal;
use App\MDS\GreenPatioBundle\Entity\CvrReservationInvoice;
use App\MDS\GreenPatioBundle\Entity\CvrReservationInvoiceRec;
use App\MDS\GreenPatioBundle\Entity\ExternalUser;
use App\MDS\GreenPatioBundle\Entity\Reservation;
use App\MDS\GreenPatioBundle\Entity\ReservationDeposit;
use App\MDS\GreenPatioBundle\Entity\ReservationLounge;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungeDescription;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungeDetails;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungePicture;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungeProfile;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungeSimple;
use App\MDS\GreenPatioBundle\Entity\ReservationLoungeVideo;
use App\MDS\GreenPatioBundle\Entity\ReservationMailAlertClient;
use App\MDS\GreenPatioBundle\Entity\ReservationPeriod;
use App\MDS\GreenPatioBundle\Entity\ReservationService;
use App\MDS\GreenPatioBundle\Entity\ReservationVisit;
use App\MDS\GreenPatioBundle\Entity\ReservationAlertStarted;
use App\MDS\GreenPatioBundle\Entity\ReservationAlertSecondDeposit;
use App\MDS\GreenPatioBundle\Entity\ReservationInvoice;
use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceDepositItems;
use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceItems;
use App\MDS\GreenPatioBundle\Entity\ReservationInvoiceRec;
use App\MDS\GreenPatioBundle\Entity\ReservationPaymentsClient;
use App\MDS\GreenPatioBundle\Form\ReservationLoungeDetailsType;
use App\MDS\GreenPatioBundle\Form\ReservationLoungeProfileType;
use App\MDS\GreenPatioBundle\Form\ReservationLoungeType;
use App\MDS\GreenPatioBundle\Form\ReservationPeriodType;
use App\MDS\GreenPatioBundle\Form\ReservationType;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Service\DocContractService;
use Google_Client;
use Google_Service_Calendar;
use Psr\Log\LoggerInterface;
use DateTime;
use DatePeriod;
use DateInterval;
use Symfony\Contracts\Translation\TranslatorInterface;
use Doctrine\ORM\EntityManagerInterface;
class ReservationsController extends AbstractController
{
// private $translator;
// protected $googleCalendar;
//
// public function __construct(TranslatorInterface $translator)
// {
//// $redirect_uri='urn:ietf:wg:oauth:2.0:oob';
// $redirect_uri = 'https://' . $_SERVER['HTTP_HOST']. '/calendar/token';
// $googleCalendar = new Google_Client();
// $googleCalendar->setApplicationName('Google Calendar API PHP Quickstart');
// //campos a extraer de la base de datos User
// $googleCalendar->setClientId('2790497987-57qc3vu4pr7vb0s8phpub2me58pe34lb.apps.googleusercontent.com');
// $googleCalendar->setClientSecret('nj2C7unaTO68DRhyORsyipSj');
// //fin campos user
//// $api_key = "AIzaSyBR84cS1IU2BPvk5V3VnbqdkJESlv440Ac";
//// $client->setDeveloperKey($api_key);
// $googleCalendar->setRedirectUri($redirect_uri);
// $googleCalendar->addScope(Google_Service_Calendar::CALENDAR);
// $guzzleClient = new \GuzzleHttp\Client(array('curl' => array(CURLOPT_SSL_VERIFYPEER => false)));
// $googleCalendar->setHttpClient($guzzleClient);
// $this->googleCalendar = $googleCalendar;
// $this->translator = $translator;
// }
private $translator;
protected $googleCalendar;
private $docContractService;
public function __construct(TranslatorInterface $translator, DocContractService $docContractService)
{
$redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/calendar/token';
$googleCalendar = new Google_Client();
$googleCalendar->setApplicationName('Google Calendar API PHP Quickstart');
$googleCalendar->setClientId('2790497987-57qc3vu4pr7vb0s8phpub2me58pe34lb.apps.googleusercontent.com');
$googleCalendar->setClientSecret('nj2C7unaTO68DRhyORsyipSj');
$googleCalendar->setRedirectUri($redirect_uri);
$googleCalendar->addScope(Google_Service_Calendar::CALENDAR);
$guzzleClient = new \GuzzleHttp\Client(['curl' => [CURLOPT_SSL_VERIFYPEER => false]]);
$googleCalendar->setHttpClient($guzzleClient);
$this->googleCalendar = $googleCalendar;
$this->translator = $translator;
$this->docContractService = $docContractService;
}
/**
* @Route("/connectGoogle", name="homepage_Connect_Google")
*/
public function indexConnectGoogleAction(Request $request) {
$session = new Session();
$token=$session->get('tokenGoogleCalendar');
if (!is_null($token)) {
$this->googleCalendar->setAccessToken($token);
}
// If there is no previous token or it's expired.
$data=array();
if ($this->googleCalendar->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($this->googleCalendar->getRefreshToken()) {
$this->googleCalendar->fetchAccessTokenWithRefreshToken($this->googleCalendar->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $this->googleCalendar->createAuthUrl();
return $this->redirect($authUrl);
}
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/add", name="reservations_greenpatio_add")
*/
public function addReservationAction( Request $request)
{
return $this->redirectToRoute('reservations_greenpatio_add_simple');
}
/**
* @Route("/create", name="reservations_greenpatio_create")
*/
public function createAction(EntityManagerInterface $em, Request $request)
{
$reserva = new Reservation();
$form = $this->createReservationCreateForm($reserva);
$form->handleRequest($request);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
if($form->isValid())
{
$reserva->setUpdatedBy($user_id);
$reserva->setUpdatedAt($hoy);
if (is_null($reserva->getCateringName())){
$reserva->setSupplier(null);
$reserva->setCateringName(null);
} else {
$reserva->setSupplier($reserva->getCateringName()->getId());
$reserva->setCateringName($reserva->getCateringName()->getName());
}
if (!empty($reserva->getClient())){ $reserva->setClient($reserva->getClient()->getId()); }
$reserva->setCreatedAt($hoy);
$reserva->setCreatedBy($user_id);
$reserva->setDateStart(new \DateTime('2078-01-01'));
$reserva->setDateEnd(new \DateTime('2000-01-01'));
if(is_null($reserva->getStatus())){$reserva->setStatus('Cotizado');}
if(is_null($reserva->getPriority()) or empty($reserva->getPriority()) or ($reserva->getPriority() == 'Auto')){ $reserva->setPriority(1); }
// Buscamos la menor fecha de sala para el inicio y la mayor para determinar el fin del evento
$salas = $request->request->get('salas');
// crea una reserva sin sala. que fechas le pongo al evento
if (!is_null($salas)) {
foreach ($salas as $sala) {
if (sizeof($sala['mountingHourStart']) != 5){
// Necesitamos la hora en formato HH:mm
switch (strlen($sala['mountingHourStart'])) {
case 0: $sala['mountingHourStart'] = '00:00'; break; // Vacio
case 1: // H -> 0H:00
if (is_numeric($sala['mountingHourStart'])){
$sala['mountingHourStart'] = '0'.$sala['mountingHourStart'].':00';
} else {
$sala['mountingHourStart'] = '00:00';
}
break;
case 2: $sala['mountingHourStart'] = $sala['mountingHourStart'].':00'; break; // HH -> HH:00
case 3:$sala['mountingHourStart'] = '0'.$sala['mountingHourStart']; break; // Hmm -> 0H:mm
case 4: $sala['mountingHourStart'] = substr($sala['mountingHourStart'], 0, 2) . ':' . substr($sala['mountingHourStart'], 2, 2); break; // HHmm -> HH:mm
default: $sala['mountingHourStart'] = '00:00'; break; // XXXXyyy
}
}
if (sizeof($sala['removalHourEnd']) != 5){
// Necesitamos la hora en formato HH:mm
switch (strlen($sala['removalHourEnd'])) {
case 0: $sala['removalHourEnd'] = '00:00'; break; // Vacio
case 1:
if (is_numeric($sala['removalHourEnd'])){
$sala['removalHourEnd'] = '0'.$sala['removalHourEnd'].':00';
} else {
$sala['removalHourEnd'] = '00:00';
}
break; // H -> 0H:00
case 2: $sala['removalHourEnd'] = $sala['removalHourEnd'].':00'; break; // HH -> HH:00
case 3: $sala['removalHourEnd'] = '0'.$sala['removalHourEnd']; break; // Hmm -> 0H:mm
case 4: $sala['removalHourEnd'] = substr($sala['removalHourEnd'], 0, 2) . ':' . substr($sala['removalHourEnd'], 2, 2); break; // HHmm -> HH:mm
default: $sala['removalHourEnd'] = '00:00'; break; // XXXXyyy
}
}
// Verificamos el montaje
if ($reserva->getDateStart() > (new \DateTime($sala['mountingDate']))) { $reserva->setDateStart((new \DateTime($sala['mountingDate']." ".$sala['mountingHourStart']))); }
if ($reserva->getDateStart() > (new \DateTime($sala['dateStart']))) { $reserva->setDateStart((new \DateTime($sala['dateStart']." ".$sala['hourStart']))); }
if ($reserva->getDateEnd() < (new \DateTime($sala['dateEnd']))) { $reserva->setDateEnd((new \DateTime($sala['dateEnd']." ".$sala['hourEnd']))); }
//Verificamos el desmontaje
if ($reserva->getDateEnd() < (new \DateTime($sala['removalDate']))) { $reserva->setDateEnd((new \DateTime($sala['removalDate']." ".$sala['removalHourEnd']))); }
}
} else {
// No hay salas, se asigna a la reserva la fecha del dia actual
$reserva->setDateStart((new \DateTime()));
$reserva->setDateEnd((new \DateTime()));
}
// INICIO: se determina el numero de opcion o prioridad que tiene el evento
$salasTemp =$request->request->get('salas');
// Pendiente reunion con Rafa (se determina el numero de opcion o prioridad que tiene el evento)
// FIN: se determina el numero de opcion o prioridad que tiene el evento
try{
$em->persist($reserva);
$em->flush();
$event = 'The Reservation has been created.';
// $successMessage = $this->translator->trans($event);
$successMessage = 'La reserva ha sido creada.';
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
} else {
$errorMessagebase = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajetracingerror', $errorMessagebase);
$periods = $em->getRepository(ReservationPeriod::class)->findAll();
return $this->render('MDS/GreenPatioBundle/reservations/add-reservations.html.twig',
array(
'form' => $form->createView(),
'periods' => $periods,
)
);
}
/* Fin Gestión de eventos en Log */
$salas =$request->request->get('salas');
// Inicio: Verificamos que hayan metido bien las salas, toda sala para poder facturar debe tener IdLounge, Fecha de inicio y fecha de fin
for ($i=0; $i<sizeof($salas); $i++){
if (empty($salas[$i]['idLounge']) or empty($salas[$i]['dateStart']) or empty($salas[$i]['dateEnd'])){ unset($salas[$i]); }
}
// Fin: Verificamos que hayan metido bien las salas, toda sala para poder facturar debe tener IdLounge, Fecha de inicio y fecha de fin
if (!is_null($reserva->getId())){
if (!is_null($salas)) {
foreach ($salas as $sala) {
// Se guarda una sala si hay una sala seleccionada
// IdLounge es el ID en la tabla reservation profile
if (!empty(($sala['idLounge']))) {
// consulto la tabla de precios para obtener el id de salon desde el id de precios
$queryProfile = $em->getRepository(ReservationLoungeProfile::class)->findOneById($sala['idLounge']);
$reservaLounge = new ReservationLounge();
$reservaLounge->setIdLounge($queryProfile->getLoungeId());
$reservaLounge->setLoungeName(($em->getRepository(ReservationLoungeDetails::class)->findOneById($queryProfile->getLoungeId()))->getName());
$reservaLounge->setCreatedAt($hoy);
$reservaLounge->setCreatedBy($user_id);
$reservaLounge->setUpdatedAt($hoy);
$reservaLounge->setUpdatedBy($user_id);
$reservaLounge->setIdReservation($reserva->getId());
$reservaLounge->setDateStart(new \DateTime($sala['dateStart']." ".$sala['hourStart']));
$reservaLounge->setDateEnd(new \DateTime($sala['dateEnd']." ".$sala['hourEnd']));
$reservaLounge->setHourStart(substr($sala['hourStart'], 0, 2));
$reservaLounge->setMinStart(substr($sala['hourStart'], 3, 2));
$reservaLounge->setHourEnd(substr($sala['hourEnd'], 0, 2));
$reservaLounge->setMinEnd(substr($sala['hourEnd'], 3, 2));
$reservaLounge->setServicePrice($sala['servicePrice']);
// el service name es la descripcion
$reservaLounge->setServiceName($sala['serviceName']);
$reservaLounge->setIdPeriod($sala['idLoungePrice']);
if (empty($sala['servicePax'])){$reservaLounge->setPax(null);} else {$reservaLounge->setPax($sala['servicePax']);}
$reservaLounge->setMounting($sala['serviceMounting']);
if (empty($sala['mountingPrice'])){$reservaLounge->setMountingPrice(0);} else {$reservaLounge->setMountingPrice($sala['mountingPrice']);}
$reservaLounge->setMountingLapse($sala['mountingLapse']);
switch (strlen($sala['mountingHourStart'])) {
case 0: // Vacio
$reservaLounge->setMountingHourStart('00');
$reservaLounge->setMountingMinStart('00');
break;
case 1: // H -> 0H:00
if (is_numeric($sala['mountingHourStart'])){
$reservaLounge->setMountingHourStart('0'.$sala['mountingHourStart']);
} else {
$reservaLounge->setMountingHourStart('00');
}
$reservaLounge->setMountingMinStart('00');
break;
case 2: // HH -> HH:00
$reservaLounge->setMountingHourStart($sala['mountingHourStart']);
$reservaLounge->setMountingMinStart('00');
break;
case 3: // Hmm -> 0H:mm
$reservaLounge->setMountingHourStart('0'.substr($sala['mountingHourStart'], 0, 1));
$reservaLounge->setMountingMinStart(substr($sala['mountingHourStart'], 1, 2));
break;
case 4: // HHmm -> HH:mm
$reservaLounge->setMountingHourStart(substr($sala['mountingHourStart'], 0, 2));
$reservaLounge->setMountingMinStart(substr($sala['mountingHourStart'], 2, 2));
break;
case 5: // HH:mm -> HH:mm
$reservaLounge->setMountingHourStart(substr($sala['mountingHourStart'], 0, 2));
$reservaLounge->setMountingMinStart(substr($sala['mountingHourStart'], 3, 2));
break;
default: // XXXXyyy
$reservaLounge->setMountingHourStart('00');
$reservaLounge->setMountingMinStart('00');
break;
}
switch (strlen($sala['mountingHourEnd'])) {
case 0: // Vacio
$reservaLounge->setMountingHourEnd('00');
$reservaLounge->setMountingMinEnd('00');
break;
case 1: // H -> 0H:00
if (is_numeric($sala['mountingHourEnd'])){
$reservaLounge->setMountingHourEnd('0'.$sala['mountingHourEnd']);
} else {
$reservaLounge->setMountingHourEnd('00');
}
$reservaLounge->setMountingMinEnd('00');
break;
case 2: // HH -> HH:00
$reservaLounge->setMountingHourEnd($sala['mountingHourEnd']);
$reservaLounge->setMountingMinEnd('00');
break;
case 3: // Hmm -> 0H:mm
$reservaLounge->setMountingHourEnd('0'.substr($sala['mountingHourEnd'], 0, 1));
$reservaLounge->setMountingMinEnd(substr($sala['mountingHourEnd'], 1, 2));
break;
case 4: // HHmm -> HH:mm
$reservaLounge->setMountingHourEnd(substr($sala['mountingHourEnd'], 0, 2));
$reservaLounge->setMountingMinEnd(substr($sala['mountingHourEnd'], 2, 2));
break;
case 5: // HH:mm -> HH:mm
$reservaLounge->setMountingHourEnd(substr($sala['mountingHourEnd'], 0, 2));
$reservaLounge->setMountingMinEnd(substr($sala['mountingHourEnd'], 3, 2));
break;
default: // XXXXyyy
$reservaLounge->setMountingHourEnd('00');
$reservaLounge->setMountingMinEnd('00');
break;
}
$reservaLounge->setMountingDate(new \DateTime($sala['mountingDate'].' '.$reservaLounge->getMountingHourStart().':'.$reservaLounge->getMountingMinStart()));
$reservaLounge->setRemovalLapse($sala['removalLapse']);
$reservaLounge->setRemovalDate(new \DateTime($sala['removalDate']));
switch (strlen($sala['removalHourStart'])) {
case 0: // Vacio
$reservaLounge->setRemovalHourStart('00');
$reservaLounge->setRemovalMinStart('00');
break;
case 1: // H -> 0H:00
if (is_numeric($sala['removalHourStart'])){
$reservaLounge->setRemovalHourStart('0'.$sala['removalHourStart']);
} else {
$reservaLounge->setRemovalHourStart('00');
}
$reservaLounge->setRemovalMinStart('00');
break;
case 2: // HH -> HH:00
$reservaLounge->setRemovalHourStart($sala['removalHourStart']);
$reservaLounge->setRemovalMinStart('00');
break;
case 3: // Hmm -> 0H:mm
$reservaLounge->setRemovalHourStart('0'.substr($sala['removalHourStart'], 0, 1));
$reservaLounge->setRemovalMinStart(substr($sala['removalHourStart'], 1, 2));
break;
case 4: // HHmm -> HH:mm
$reservaLounge->setRemovalHourStart(substr($sala['removalHourStart'], 0, 2));
$reservaLounge->setRemovalMinStart(substr($sala['removalHourStart'], 2, 2));
break;
case 5: // HH:mm -> HH:mm
$reservaLounge->setRemovalHourStart(substr($sala['removalHourStart'], 0, 2));
$reservaLounge->setRemovalMinStart(substr($sala['removalHourStart'], 3, 2));
break;
default: // XXXXyyy
$reservaLounge->setRemovalHourStart('00');
$reservaLounge->setRemovalMinStart('00');
break;
}
switch (strlen($sala['removalHourEnd'])) {
case 0: // Vacio
$reservaLounge->setRemovalHourEnd('00');
$reservaLounge->setRemovalMinEnd('00');
break;
case 1: // H -> 0H:00
if (is_numeric($sala['removalHourEnd'])){
$reservaLounge->setRemovalHourEnd('0'.$sala['removalHourEnd']);
} else {
$reservaLounge->setRemovalHourEnd('00');
}
$reservaLounge->setRemovalMinEnd('00');
break;
case 2: // HH -> HH:00
$reservaLounge->setRemovalHourEnd($sala['removalHourEnd']);
$reservaLounge->setRemovalMinEnd('00');
break;
case 3: // Hmm -> 0H:mm
$reservaLounge->setRemovalHourEnd('0'.substr($sala['removalHourEnd'], 0, 1));
$reservaLounge->setRemovalMinEnd(substr($sala['removalHourEnd'], 1, 2));
break;
case 4: // HHmm -> HH:mm
$reservaLounge->setRemovalHourEnd(substr($sala['removalHourEnd'], 0, 2));
$reservaLounge->setRemovalMinEnd(substr($sala['removalHourEnd'], 2, 2));
break;
case 5: // HH:mm -> HH:mm
$reservaLounge->setRemovalHourEnd(substr($sala['removalHourEnd'], 0, 2));
$reservaLounge->setRemovalMinEnd(substr($sala['removalHourEnd'], 3, 2));
break;
default: // XXXXyyy
$reservaLounge->setRemovalHourEnd('00');
$reservaLounge->setRemovalMinEnd('00');
break;
}
if (empty($sala['removalPrice'])){$reservaLounge->setRemovalPrice(0);} else {$reservaLounge->setRemovalPrice($sala['removalPrice']);}
// INICIO: Verificamos si choca con otra reserva
// Si sucede se usara el booleano OtherPriceSave para indicarlo
$resFun = $this->VerificarCoflictosEnSalas($reservaLounge);
$tempBool = $resFun['bool'];
if($tempBool){
$reservaLounge->setOtherPriceSave(true);
$reserva->setPriority($resFun['priority']);
// Se debe modificar la prioridad de la nueva reserva, que ya se habia guardado previamente
try {
$em->persist($reserva);
$em->flush();
} catch (\Exception $e) {
$event = 'Error al actualizar la prioridad del evento ' . $e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
} else {
$reservaLounge->setOtherPriceSave(false);
}
// FIN: Verificamos si choca con otra reserva
// INICIO: Si es necesario se actualizan fechas de inicio y fin usando dia de montaje y desmontaje
if (($reservaLounge->getMountingDate() < $reserva->getDateStart()) or ($reserva->getDateEnd() < $reservaLounge->getRemovalDate())){
if ($reservaLounge->getMountingDate() < $reserva->getDateStart()){
$reserva->setDateStart($reservaLounge->getMountingDate());
}
if ($reserva->getDateEnd() < $reservaLounge->getRemovalDate()){
$reserva->setDateEnd($reservaLounge->getRemovalDate());
}
try {
$em->persist($reserva);
$em->flush();
} catch (\Exception $e) {
$event = 'Error al actualizar fechas de inicio y fin, por montaje y desmontaje de sala: ' . $e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
}
// FIN: Si es necesario se actualizan fechas de inicio y fin usando dia de montaje y desmontaje
try {
$em->persist($reservaLounge);
$em->flush();
} catch (\Exception $e) {
$event = 'Al agregar la sala ha ocurrido un error: ' . $e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
}
}
// INICIO: Verificamos la prioridad
$numeroPriority = 1;
//INICIO: Buscamos las salas que coincidan en tiempo de reserva
foreach ($salas as $sala){
$newdateStar = $sala['dateStart'].' '.$sala['hourStart'];
$newdateEnd = $sala['dateEnd'].' '.$sala['hourEnd'];
$reservaProfile = $em->getRepository(ReservationLoungeProfile::class)->findOneById($sala['idLounge']);
$parameters = array(
'dateStar' => $newdateStar,
'dateEnd' => $newdateEnd,
'idLounge' => $reservaProfile->getLoungeId(),
'idRes' => $reserva->getId(),
);
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLounge i
WHERE (i.dateStart >= :dateStar
and i.dateStart <= :dateEnd
and i.idLounge = :idLounge
and i.idReservation != :idRes)
or
(i.dateStart <= :dateStar
and i.dateStart >= :dateEnd
and i.idLounge = :idLounge
and i.idReservation != :idRes)
';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservationLounge = $query->getResult();
}
//FIN: Buscamos las salas que coincidan en tiempo de reserva
// INICIO: Buscamos el numero de opcion a asignar
$modificarPrior = false;
if (!empty($reservaLounge)){
foreach($reservationLounge as $resLoung){
$reservaClash = $em->getRepository(Reservation::class)->findOneById($resLoung->getIdReservation());
$tempPrior = $reservaClash->getPriority();
if ($numeroPriority <= $tempPrior){
// Ya tenemos una reserva con opcion de mayor relevancia (un numero de opción inferior)
$numeroPriority = $tempPrior +1;
$modificarPrior = true;
}
}
if ($modificarPrior){
// Se debe modificar la prioridad
$reserva->setPriority($numeroPriority);
try{
$em->persist($reserva);
$em->flush();
$event = 'The Reservation has been created.';
// $successMessage = $this->translator->trans($event);
$successMessage = 'La reserva ha sido creada.';
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
}
} else {
// El numero de opción asignada fue el correcto
}
// FIN: Buscamos el numero de opcion a asignar
// FIN: Verificamos la prioridad
}
} else {
$lounges = null; // Si fallo la reserva no habrá salas
}
return $this->redirectToRoute('reservations_greenpatio_index');
}
public function VerificarCoflictosEnSalas(EntityManagerInterface $em, $nuevaSala)
{
$allSalas = $em->getRepository(ReservationLounge::class)->findAll();
$tempBool = false; //Aun no se ha detectado un conflicto
$prioridad = 1;
foreach ($allSalas as $sala){
if ($sala->getIdReservation()== $nuevaSala->getIdReservation()){
// No hay conflicto son de la misma reserva
$tempBool = ($tempBool or false);
} else {
if (!($sala->getIdLounge() == $nuevaSala->getIdLounge())) {
// No hay conflicto no son la misma sala
$tempBool = ($tempBool or false);
} else {
// Caso 1: F. inicio de $nuevaSala entre las feachas de $sala
if (($nuevaSala->getDateStart()>$sala->getDateStart()) and ($nuevaSala->getDateStart()<$sala->getDateEnd())){
$tempBool = true;
// Buscamos la prioridad que tiene el evento de la sala que colisiona para determinar la nueva prioridad del evento que se está creando
$resTemp = $em->getRepository(Reservation::class)->findOneById($sala->getIdReservation());
if (($prioridad < $resTemp->getPriority()) or ($prioridad == $resTemp->getPriority())){
$prioridad = $resTemp->getPriority() +1;
}
}
// Caso 2: F. fin de $nuevaSala entre las feachas de $sala
if (($nuevaSala->getDateEnd()>$sala->getDateStart()) and ($nuevaSala->getDateEnd()<$sala->getDateEnd())){
$tempBool = true;
// Buscamos la prioridad que tiene el evento de la sala que colisiona para determinar la nueva prioridad del evento que se está creando
$resTemp = $em->getRepository(Reservation::class)->findOneById($sala->getIdReservation());
if (($prioridad <= $resTemp->getPriority()) or ($prioridad == $resTemp->getPriority())){
$prioridad = $resTemp->getPriority() +1;
}
}
// Caso 3: F. inicio de $sala entre las feachas de $nuevaSala
if (($sala->getDateStart()>$nuevaSala->getDateStart()) and ($sala->getDateStart()<$nuevaSala->getDateEnd())){
$tempBool = true;
// Buscamos la prioridad que tiene el evento de la sala que colisiona para determinar la nueva prioridad del evento que se está creando
$resTemp = $em->getRepository(Reservation::class)->findOneById($sala->getIdReservation());
if (($prioridad <= $resTemp->getPriority()) or ($prioridad == $resTemp->getPriority())){
$prioridad = $resTemp->getPriority() +1;
}
}
// Caso 4: F. fin de $sala entre las feachas de $nuevaSala
if (($sala->getDateEnd()>$nuevaSala->getDateStart()) and ($sala->getDateEnd()<$nuevaSala->getDateEnd())){
$tempBool = true;
// Buscamos la prioridad que tiene el evento de la sala que colisiona para determinar la nueva prioridad del evento que se está creando
$resTemp = $em->getRepository(Reservation::class)->findOneById($sala->getIdReservation());
if (($prioridad <= $resTemp->getPriority()) or ($prioridad == $resTemp->getPriority())){
$prioridad = $resTemp->getPriority() +1;
}
}
// Caso 5: fechas iguales
if (($nuevaSala->getDateStart()==$sala->getDateStart()) or
($nuevaSala->getDateStart()==$sala->getDateEnd()) or
($nuevaSala->getDateEnd()==$sala->getDateStart()) or
($nuevaSala->getDateEnd()==$sala->getDateEnd())) {
$tempBool = true;
}
}
}
}
$res = array('bool' => $tempBool,'priority' => $prioridad);
return ($res);
}
public function CalculoPrioridad(EntityManagerInterface $em, $reserva)
{
$listAllReservas = $em->getRepository(Reservation::class)->findAll();
// logico para controlar el conflicto entre salas
$logSalasError = false;
// valor original de la prioridad
$oldPriority = $reserva->getPriority();
foreach ($listAllReservas as $resv)
{
$reservaSala = explode(",", $reserva->getSalas()); // Arreglo de salas para agregar
$resSala = explode(",", $resv->getSalas()); // Arreglo de salas que ya estan en
foreach ($reservaSala as $item){
if (in_array($item, $resSala)){
$logSalasError = ($logSalasError or true); // Este logico indica si hay conflicto entre las salas
}
}
if ((($reserva->getDateStart()==$resv->getDateStart()) or ($reserva->getDateStart() < $resv->getDateStart())) and
($resv->getDateStart() < $reserva->getDateEnd()) and ($resv->getStatus()=='Confirmed')) {
if ($resv->getPriority() == $reserva->getPriority()){
$reserva->setPriority($reserva->getPriority()-1);
} else {
if ($resv->getPriority() < $reserva->getPriority()){
$reserva->setPriority($resv->getPriority()-1);
} else {
// ($resv->getPriority() > $reserva->getPriority())
// No se debe cambiar la prioridad ya que esta por debajo de la reserva ya creada
}
}
}
if ((($resv->getDateStart()==$reserva->getDateStart()) or ($resv->getDateStart() < $reserva->getDateStart())) and
($reserva->getDateEnd() < $resv->getDateEnd()) and ($resv->getStatus()=='Confirmed')) {
if ($resv->getPriority() == $reserva->getPriority()){
$reserva->setPriority($reserva->getPriority()-1);
} else {
if ($resv->getPriority() < $reserva->getPriority()){
$reserva->setPriority($resv->getPriority()-1);
} else {
// ($resv->getPriority() > $reserva->getPriority())
// No se debe cambiar la prioridad ya que esta por debajo de la reserva ya creada
}
}
}
if ((($reserva->getDateStart()==$resv->getDateStart()) or ($reserva->getDateStart() < $resv->getDateStart())) and
(($resv->getDateEnd()==$reserva->getDateEnd()) or ($resv->getDateEnd() < $reserva->getDateEnd())) and
($resv->getStatus()=='Confirmed')) {
if ($resv->getPriority() == $reserva->getPriority()){
$reserva->setPriority($reserva->getPriority()-1);
} else {
if ($resv->getPriority() < $reserva->getPriority()){
$reserva->setPriority($resv->getPriority()-1);
} else {
// ($resv->getPriority() > $reserva->getPriority())
// No se debe cambiar la prioridad ya que esta por debajo de la reserva ya creada
}
}
}
if ((($resv->getDateStart()==$reserva->getDateStart()) or ($resv->getDateStart()<$reserva->getDateStart())) and
(($resv->getDateEnd()==$reserva->getDateEnd()) or ($resv->getDateEnd()<$reserva->getDateEnd())) and
($resv->getStatus()=='Confirmed')) {
if ($resv->getPriority() == $reserva->getPriority()){
$reserva->setPriority($reserva->getPriority()-1);
} else {
if ($resv->getPriority() < $reserva->getPriority()){
$reserva->setPriority($resv->getPriority()-1);
} else {
// ($resv->getPriority() > $reserva->getPriority())
// No se debe cambiar la prioridad ya que esta por debajo de la reserva ya creada
}
}
}
}
$priority = $reserva->getPriority();
$reserva->setPriority($oldPriority); // Se restablece el valor de origen de la prioridad
$data = array( 'prioridad' => $priority );
return $data;
}
public function NombreSalasPrecios(EntityManagerInterface $em)
{
$reservaLoungeDetails = $em->getRepository(ReservationLoungeDetails::class)->findAll();
$data = array();
foreach ($reservaLoungeDetails as $res){ if (!empty($data['salas'])) { $data['salas'] = $data['salas'] . ',' . $res->getName(); } else { $data['salas'] = $res->getName(); } }
$dataArray = array('-1');
foreach ($reservaLoungeDetails as $res){ array_push($dataArray,array($res->getId(), $res->getName())); }
unset($dataArray[0]);
$data['arraySalas'] = $dataArray;
$parameters = array();
$dql = 'SELECT p
FROM GreenPatioBundle:ReservationGpPrice p
ORDER BY p.idService ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservaGpPrice = $query->getResult();
foreach ($reservaGpPrice as $res){ if (!empty($data['precios'])) { $data['precios'] = $data['precios'] . ',' . $res->getNameAndPrice(); } else { $data['precios'] = $res->getNameAndPrice(); } }
$dataArray = array('-1');
foreach ($reservaGpPrice as $res){ array_push($dataArray,array($res->getIdService(), $res->getNameAndPrice())); }
unset($dataArray[0]);
$data['arrayPrecios'] = $dataArray;
return $data;
}
// private function CalculosTotalesEdit($id)
// {
// $em = $this->getDoctrine()->getManager();
// $reservaLounges = $em->getRepository(ReservationLounge::class)->findByIdReservation($id);
// $reservaServices = $em->getRepository(ReservationService::class)->findByReservationId($id);
//
// $data_iva = array(
// 'iva' => 21,
// 'ivaMontoVeintiUno' => 0,
// 'ivaMontoDiez' => 0,
// 'ivaMontoCero' => 0,
// );
//
// $lounge = array(
// 'neto' => 0,
// 'sumSubT' => 0,
// ); // Acumula sumatoria de netos y sumantoria de subtotales
//
// $service = array(
// 'neto' => 0,
// 'sumSubT' => 0,
// ); // Acumula sumatoria de netos y sumantoria de subtotales
//
// $totales_neto_all = 0;
//
// foreach ($reservaLounges as $item){
//
// if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
// $subtotal = 0;
// $neto = 0;
// $subnetoMounting = 0;
// $subtotalLounge = 0;
// $subnetoRemoval = 0;
//
// } else {
// if (!empty($item->getMountingPrice()) and ($item->getMountingPrice() != 0 )){
// $subtotalMounting = $item->getMountingPrice() * 1.21;
// $subnetoMounting = $item->getMountingPrice();
// } else {
// $subtotalMounting = 0;
// $subnetoMounting = 0;
// }
//
// $subtotalLounge = $item->getServicePrice() * 1.21;
// $subneto = $item->getServicePrice();
//
// if (!empty($item->getRemovalPrice()) and ($item->getRemovalPrice() != 0 )){
// $subtotalRemoval = $item->getRemovalPrice() * 1.21;
// $subnetoRemoval = $item->getRemovalPrice();
// } else {
// $subtotalRemoval = 0;
// $subnetoRemoval = 0;
// }
//
// $subtotal = $subtotalMounting + $subtotalLounge + $subtotalRemoval;
// $neto = $subnetoMounting + $subneto + $subnetoRemoval;
//
// // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
// $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
// $neto = round($neto,2,PHP_ROUND_HALF_UP);
// }
//
// // Acumula netos totales e IVA
// $totales_neto_all = $totales_neto_all + $neto;
// $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * 0.21);
// // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
// $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
// $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
// // Acumula netos totales e IVA
//
// $lounge['neto'] = $lounge['neto'] + $neto;
// $lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
//// // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
// $lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
// $lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
// }
//
// foreach ($reservaServices as $item){
// if (is_null($item->getPrice()) or empty($item->getPrice())){
// $subtotal = 0;
// $neto = 0;
// $subtotalService = 0;
//
// } else {
// $subtotalService = $item->getPrice();
// $subneto = $item->getPrice();
//
// // Commission
// if ($item->getOpCommission()=='1'){
// $subtotalService = $subtotalService * (1 + ($item->getCommission()/100));
// $subneto = $subneto * (1 + ($item->getCommission()/100));
// } else {
// $subtotalService = $subtotalService * (1 - ($item->getCommission()/100));
// $subneto = $subneto * (1 - ($item->getCommission()/100));
// }
//
// // Over
// if ($item->getOpOver()=='1'){
// $subtotalService = $subtotalService + $item->getOver();
// $subneto = $subneto + $item->getOver();
// } else {
// $subtotalService = $subtotalService - $item->getOver();
// $subneto = $subneto - $item->getOver();
// }
//
// // IVA
// if ($item->getOpIva()=='1'){
// $subtotalService = $subtotalService * (1 + ($item->getIva()/100));
// } else {
// $subtotalService = $item->getPrice();
// $subneto = ($subneto * 100) / (100 + $item->getIva());
// }
//
// switch ($item->getServiceCatId()){
// case 1: // Alojamiento
// // el numero de noches $numNoches; precio unitario $subneto
// $numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
// // La personas no afectan este calculo
// $subtotal = $subtotalService * $numNoches * $item->getUnits();
// $subnetoUnit = $subneto;
// $subneto = $subneto * $numNoches * $item->getUnits();
// break;
//
// case 2: //Actividades
// // El número de personas es considerado en el calculo
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
//
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $subtotal = $subtotalService * $days * $item->getUnits();
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $item->getUnits();
// break;
//
// case 3: // AV
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 4: //Creative
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 5: //Cruise
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 6: //Entertaiment
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 7: // Gifts
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
//// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// $days = 1;
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 8: //Guide
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 9: //Itineraries
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 10: //Lounge -- No Aplica
// break;
//
// case 11: //Menu
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 12: //Others
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 13: //Transport
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 14: //Technology
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
//// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// $days = 1;
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 15: //Assisstant
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// case 16: //DDR
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") {
// $pax = 1;
// }
//
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// if ($days > 1){
// $dateServ = ($item->getDateInAt())->format('d/m/Y'). ' - '.($item->getDateOutAt())->format('d/m/Y');
// } else {
// $dateServ = ($item->getDateInAt())->format('d/m/Y');
// }
//
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") {
// $unitsServ = 1;
// }
//
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
//
// default:
// $pax = $item->getPax();
// if (empty($pax) or $pax == "0") { $pax = 1; }
// $days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
// $unitsServ = $item->getUnits();
// if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
// $subtotal = $subtotalService * $days * $unitsServ * $pax;
// $subnetoUnit = $subneto;
// $subneto = $subneto * $days * $unitsServ * $pax;
// break;
// }
//
// // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
// $subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
// $neto = round($subneto,2,PHP_ROUND_HALF_UP);
// }
//
// switch ($item->getIva()){
// // Acumula IVA
// case 21:
// $data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva()/100));
// break;
//
// case 10:
// $data_iva['ivaMontoDiez'] = $data_iva['ivaMontoDiez'] + ($neto * ($item->getIva()/100));
// break;
//
// case 0:
// break;
//
// default:
// break;
//
// }
//
// $totales_neto_all = $totales_neto_all + $neto;
//
// // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
// $totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
// $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
// $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
// // Acumula netos totales e IVA
//
// $service['neto'] = $service['neto'] + $neto;
// $service['sumSubT'] = $service['sumSubT'] + $subtotal;
// // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
// $service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
// $service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
//
//
//// $i++;
//
// }
//
// $data = array(
// 'totales_global_con_iva' => $lounge['sumSubT'],
// 'totales_global_iva' => $lounge['sumSubT'] - $lounge['neto'],
// 'totales_global_neto' => $lounge['neto'],
// 'totales_global_servicios_neto' => $service['neto'],
// 'totales_global_servicios_con_iva' => $service['sumSubT'],
// 'totales_global_servicios_iva' => $service['sumSubT'] - $service['neto'],
// 'sumatoria_totales_global_con_iva' => $lounge['sumSubT'] + $service['sumSubT'],
// 'sumatoria_totales_global_neto' => $lounge['neto'] + $service['neto'],
// 'sumatoria_totales_global_iva' => $lounge['sumSubT'] + $service['sumSubT'] - $lounge['neto'] - $service['neto'],
// );
//
// return $data;
// }
private function CalculosTotalesEditSimple($id)
{
$em = $this->getDoctrine()->getManager();
$reservaLounges = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
$reservaServices = $em->getRepository(ReservationService::class)->findByReservationId($id);
$data_iva = array(
'iva' => 21,
'ivaMontoVeintiUno' => 0,
'ivaMontoDiez' => 0,
'ivaMontoCero' => 0,
);
$lounge = array(
'neto' => 0,
'sumSubT' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
$service = array(
'neto' => 0,
'sumSubT' => 0,
'sumIvas' => 0,
); // Acumula sumatoria de netos y sumantoria de subtotales
$totales_neto_all = 0;
foreach ($reservaLounges as $item){
// Si el iva es vacio se asume 21
if(empty($item->getIva()) && !is_numeric($item->getIva())){
$item->setIva(21);
$this->addFlash('mensajereservationerror', 'Revisa el IVA de la sala: '.$item->getLoungeName());
}
if (is_null($item->getServicePrice()) or empty($item->getServicePrice())){
$subtotal = 0;
$neto = 0;
$subtotalLounge = 0;
} else {
$subtotalLounge = $item->getServicePrice() * (1+ ($item->getIva()/100));
$subneto = $item->getServicePrice();
$subtotal = $subtotalLounge;
$neto = $subneto;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
$neto = round($neto,2,PHP_ROUND_HALF_UP);
}
// Acumula netos totales e IVA
$totales_neto_all = $totales_neto_all + $neto;
$data_iva['ivaMontoVeintiUno'] = $data_iva['ivaMontoVeintiUno'] + ($neto * ($item->getIva()/100));
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
// Acumula netos totales e IVA
$lounge['neto'] = $lounge['neto'] + $neto;
$lounge['sumSubT'] = $lounge['sumSubT'] + $subtotal;
// // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$lounge['neto'] = round($lounge['neto'],2,PHP_ROUND_HALF_UP);
$lounge['sumSubT'] = round($lounge['sumSubT'],2,PHP_ROUND_HALF_UP);
}
foreach ($reservaServices as $item){
$subtotal = 0; $neto = 0; $subtotalService = 0;
if (!is_null($item->getPrice()) and !empty($item->getPrice())){
$subtotalService = $item->getPrice();
$subneto = $item->getPrice();
// Commission
if ($item->getOpCommission()=='1'){
$subtotalService = (float)$subtotalService * (1 + ((float)$item->getCommission()/100));
$subneto = (float)$subneto * (1 + ($item->getCommission()/100));
} else {
$subtotalService = (float)$subtotalService * (1 - ((float)$item->getCommission()/100));
$subneto = (float)$subneto * (1 - ($item->getCommission()/100));
}
switch ($item->getServiceCatId()){
case 1: // Alojamiento
// el numero de noches $numNoches; precio unitario $subneto
$numNoches = (($item->getDateOutAt())->diff($item->getDateInAt()))->days;
// La personas no afectan este calculo
$subtotal = $subtotalService * $numNoches * $item->getUnits();
$subneto = $subneto * $numNoches * $item->getUnits();
break;
case 2: //Actividades
// El número de personas es considerado en el calculo
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$subtotal = $subtotalService * $days * $item->getUnits();
$subneto = $subneto * $days * $item->getUnits();
break;
case 3: // AV
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 4: //Creative
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 5: //Cruise
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 6: //Entertaiment
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 7: // Gifts
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = 1;
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 8: //Guide
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 9: //Itineraries
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 10: break; //Lounge -- No Aplica
case 11: //Menu
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 12: //Others
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 13: //Transport
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 14: //Technology
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = 1;
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 15: //Assisstant
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotalService = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
case 16: //DDR
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotal = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
default:
$pax = $item->getPax();
if (empty($pax) or $pax == "0") { $pax = 1; }
$days = ((($item->getDateOutAt())->diff($item->getDateInAt()))->days + 1);
$unitsServ = $item->getUnits();
if (empty($unitsServ) or $unitsServ == "0") { $unitsServ = 1; }
$subtotalService = $subtotalService * $days * $unitsServ * $pax;
$subneto = $subneto * $days * $unitsServ * $pax;
break;
}
// Over
if ($item->getOpOver()=='1'){
$subtotalService = $subtotalService + $item->getOver();
$subneto = $subneto + $item->getOver();
} else {
$subtotalService = $subtotalService - $item->getOver();
$subneto = $subneto - $item->getOver();
}
// IVA
if ($item->getOpIva()=='1'){
$subtotalService = ($subtotalService * (1 + ($item->getIva()/100)));
} else {
$subtotalService = $item->getPrice();
$subneto = ($subneto * 100) / (100 + $item->getIva());
}
$subtotal += $subtotalService;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP),
$subtotal = round($subtotal,2,PHP_ROUND_HALF_UP);
$neto = round($subneto,2,PHP_ROUND_HALF_UP);
}
// Iva vacio se calcula al 21%
$ivaServ = (empty($item->getIva()) && !is_numeric($item->getIva())) ? ($neto * (21/100)) : ($neto * ($item->getIva()/100));
switch ($item->getIva()){
// Acumula IVA
case 21: $data_iva['ivaMontoVeintiUno'] += $ivaServ; break;
case 10: $data_iva['ivaMontoDiez'] += $ivaServ; break;
case 0: break;
default: $data_iva['ivaMontoVeintiUno'] += $ivaServ; break;
}
$totales_neto_all += $neto;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$totales_neto_all = round($totales_neto_all,2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
$data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
// Acumula netos totales e IVA
$service['neto'] += $neto;
$service['sumSubT'] += $subtotalService;
$service['sumIvas'] += $ivaServ;
// Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
$service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
$service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
}
$data = array(
'totales_global_con_iva' => $lounge['sumSubT'],
'totales_global_iva' => $lounge['sumSubT'] - $lounge['neto'],
'totales_global_neto' => $lounge['neto'],
'totales_global_servicios_neto' => $service['neto'],
'totales_global_servicios_con_iva' => $service['sumSubT'],
'totales_global_servicios_iva' => $service['sumSubT'] - $service['neto'],
'sumatoria_totales_global_con_iva' => $lounge['sumSubT'] + $service['sumSubT'],
'sumatoria_totales_global_neto' => $lounge['neto'] + $service['neto'],
'sumatoria_totales_global_iva' => $lounge['sumSubT'] + $service['sumSubT'] - $lounge['neto'] - $service['neto'],
);
return $data;
}
/**
* @Route("/", name="reservations_greenpatio")
*/
public function calendarReservationAction(Request $request) {
// Enviar correos a los agentes de las reservas que se deban Cotizar
$this->notificacionReservasPorCotizar();
// Enviar correos a los agentes de las reservas que tienen depositos pendientes por recibir
$this->notificacionReservasPendientesDelSegundoDeposito();
$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('MDS/GreenPatioBundle/reservations/calendar-reservations.html.twig',
array(
'form' => $form->createView(),
'user'=> $user_id,
'connectGoogle' => $connectGoogle,
)
);
}
private function createWidgetNotesCreateForm(WidgetNotes $entity)
{
$form = $this->createForm(WidgetNotesType::class, $entity, array(
'action' => $this->generateUrl('widget_notes_calendar_create'),
'method' => 'POST'
));
return $form;
}
// private function createWidgetNotesEditForm(WidgetNotes $entity, $id)
// {
// $form = $this->createForm(WidgetNotesType::class, $entity, array(
// 'action' => $this->generateUrl('widget_notes_edit',
// array(
// 'id' => $id
// )),
// 'method' => 'PUT'
// ));
//
// return $form;
// }
/**
* @Route("/widget/notes/calendar/create/", name="widget_notes_calendar_create")
*/
public function addNotesAction(EntityManagerInterface $em, Request $request, LoggerInterface $logger)
{
$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("/list/{idgroup}", defaults={"idgroup" = 0}, name="reservations_greenpatio_index")
*/
public function indexAction($idgroup, EntityManagerInterface $em, Request $request) {
$parameters = array( 'statusdel' => 'Deleted' );
$dql = 'SELECT i
FROM GreenPatioBundle:Reservation i
WHERE i.status <> :statusdel
ORDER BY i.dateStart ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$ref = array();
$reservas = $query->getResult();
$reservasZero = array();
foreach ($reservas as $res){
$client = $em->getRepository(Client::class)->findOneById($res->getClient());
if (!empty($client)){ $res->setClient($client->getName()); } else { $res->setClient(null); }
$res->setCreatedBy(
($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getName() . ' '.
($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getLastName());
$ref[$res->getId()] = '#'.($res->getDateStart())->format('ymd').($res->getDateEnd())->format('ymd');
switch ($res->getStatus()){
case 'Bloqueo': $res->setStatus('BLOQUEO'); break;
case 'Confirmed': $res->setStatus('CONFIRMADO'); break;
case 'Invoiced': $res->setStatus('FACTURADO'); break;
case 'Cotizado': $res->setStatus('COTIZADO'); break;
case 'Deleted': $res->setStatus('CANCELADO'); break;
default: $res->setStatus('INICIADO'); break;
}
$reservasZero[] = array(
'dateStart' => $res->getDateStart(),
'dateEnd' => $res->getDateEnd(),
'id' => $res->getId(),
'title' => $res->getTitle(),
'client' => $res->getClient(),
'createdBy' => $res->getCreatedBy(),
'createdAt' => $res->getCreatedAt(),
'ref' => $ref[$res->getId()],
'status' => $res->getStatus(),
);
}
$reservas = $reservasZero;
return $this->render('MDS/GreenPatioBundle/reservations/list-reservations.html.twig',
array(
'groups' => null,
'titleView' => '',
'reservations' => $reservas
)
);
}
/**
* @Route("/listcanceled/{idgroup}", defaults={"idgroup" = 0}, name="reservations_canceled")
*/
public function indexCanceledAction(EntityManagerInterface $em, $idgroup, Request $request) {
$parameters = array( 'status' => 'Deleted' );
$dql = 'SELECT i
FROM GreenPatioBundle:Reservation i
WHERE i.status = :status
ORDER BY i.dateStart ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$ref = array();
$reservas = $query->getResult();
foreach ($reservas as $res){
$client = $em->getRepository(Client::class)->findOneById($res->getClient());
if (!empty($client)){ $res->setClient($client->getName()); } else { $res->setClient(null); }
$res->setCreatedBy(
($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getName() . ' '.
($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getLastName());
$ref[$res->getId()] = '#'.($res->getDateStart())->format('ymd').($res->getDateEnd())->format('ymd');
}
$reservasZero = array();
foreach ($reservas as $res){
$reservasZero[] = array(
'dateStart' => $res->getDateStart(),
'dateEnd' => $res->getDateEnd(),
'id' => $res->getId(),
'title' => $res->getTitle(),
'client' => $res->getClient(),
'createdBy' => $res->getCreatedBy(),
'createdAt' => $res->getCreatedAt(),
'ref' => $ref[$res->getId()],
'status' => $res->getStatus(),
);
}
$reservas = $reservasZero;
return $this->render('MDS/GreenPatioBundle/reservations/list-reservations.html.twig',
array(
'groups' => null,
'titleView' => ' Canceladas',
'reservations' => $reservas
)
);
}
/**
* @Route("/listquoted/{idgroup}", defaults={"idgroup" = 0}, name="reservations_quoted")
*/
public function indexQuotedAction(EntityManagerInterface $em, $idgroup, Request $request) {
$parameters = array( 'status' => 'Cotizado' );
$dql = 'SELECT i
FROM GreenPatioBundle:Reservation i
WHERE i.status = :status
ORDER BY i.createdAt ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$ref = array();
$reservas = $query->getResult();
foreach ($reservas as $res){
$client = $em->getRepository(Client::class)->findOneById($res->getClient());
if (!empty($client)){ $res->setClient($client->getName()); } else { $res->setClient(null); }
$res->setCreatedBy(
($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getName() . ' '.
($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getLastName());
$ref[$res->getId()] = '#'.($res->getCreatedAt())->format('ymdHi');
}
$reservasZero = array();
foreach ($reservas as $res){
$data = $this->CalculosTotalesEditSimple($res->getId());
$reservasZero[] = array(
'dateStart' => $res->getDateStart(),
'dateEnd' => $res->getDateEnd(),
'id' => $res->getId(),
'title' => $res->getTitle(),
'client' => $res->getClient(),
'sales' => $data['sumatoria_totales_global_con_iva'],
'ref' => $ref[$res->getId()],
'createdAt' => $res->getCreatedAt(),
);
}
$reservas = $reservasZero;
return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-quotation.html.twig',
array(
'groups' => null,
'titleView' => ' Cotizadas',
'reservations' => $reservas
)
);
}
/**
* @Route("/edit/{id}", name="reservations_greenpatio_edit")
*/
public function editAction($id)
{
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id, 'token' => null ));
}
private function createEditReservationsForm(Reservation $entity, $id)
{
$form = $this->createForm(ReservationType::class, $entity, array( 'action' => $this->generateUrl('reservations_update', array( 'id' => $id ) ), 'method' => 'PUT'));
return $form;
}
/**
* @Route("/update/{id}", name="reservations_update")
*/
public function updateAction($id, EntityManagerInterface $em, Request $request)
{
// INICIO: Si la reserva esta facturada no puede ser modificada
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$oldPriority = $reserva->getPriority(); // Si no es un administrador la prioridad no se debe modificar
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
$reserva->setUpdatedBy($user_id);
$reserva->setUpdatedAt($hoy);
$arrayRequest = $request->request->get('reservation');
$boolConfirmacion = false;
$clientContact = $request->request->get('clientContact');
$contactUnregistered = $request->request->get('contactUnregistered');
$nameContactUnregistered = $request->request->get('nameContactUnregistered');
$phoneContactUnregistered = $request->request->get('phoneContactUnregistered');
$reserva->setTitle($arrayRequest['title']);
$reserva->setIdWebLanguage($arrayRequest['idWebLanguage']);
$reserva->setClientContact($clientContact);
$reserva->setContactUnregistered($contactUnregistered);
if (!empty($nameContactUnregistered)){ $reserva->setNameContactUnregistered($nameContactUnregistered); }
if (!empty($phoneContactUnregistered)){ $reserva->setPhoneContactUnregistered($phoneContactUnregistered); }
if(!empty($arrayRequest['client'])){
// Solo se puede cambiar un cliente si no se ha creado una factura
if ($this->verificarCambioCliente($id)){ $reserva->setClient($arrayRequest['client']); }
} else {
$reserva->setClient(null);
}
$daysBlock = $arrayRequest['daysBlock'] ?? null;
if(!is_null($daysBlock) && $reserva->getDaysBlock() != $daysBlock){
if (empty($daysBlock) && $daysBlock !== 0) {
$reserva->setDaysBlock(7);
} else {
$reserva->setDaysBlock($daysBlock);
}
}
// Si se ha cambiado al estado "Bloqueo" se envia un correo al cliente y al agente
if (!empty($arrayRequest['status'])){
if ($arrayRequest['status'] == 'Bloqueo'){
//Calculamos la fecha limite de bloqueo en función de los dias de bloqueo
if(empty($reserva->getDays())){
$now = new \DateTime("now");
$dateLimit = date( "Y-m-d H:i", strtotime( $now->format('Y-m-d H:i') . "+".$reserva->getDaysBlock()." days" ));
$dateLimit = new \DateTime($dateLimit);
$reserva->setDays($dateLimit);
}
if ((!empty($reserva->getClient())) or (!empty($reserva->getClientContact())) or (!empty($reserva->getContactUnregistered()))) {
//Solo se envia correo de notificacion del correo si hay cliente o contacto o contacto no registrado
$client = $em->getRepository(Client::class)->findOneById($reserva->getClient());
$mailAddressTo = null;
// if (!empty($client) and (!empty($client->getEmail()))){ $mailAddressTo = $client->getEmail(); } // Si hay cliente con correo se le envia a este
// if (!empty($reserva->getClientContact())){
// $contacto = $em->getRepository(ClientContact::class)->findOneById($reserva->getClientContact());
// if (!empty($contacto) and (!empty($contacto->getEmail()))){ $mailAddressTo = $contacto->getEmail(); } // Si hay un contacto seleccionado tiene prioridad sobre el contacto de cliente
// }
// if (!empty($reserva->getContactUnregistered())){ $mailAddressTo = $reserva->getContactUnregistered(); } // Si hay correo de contacto no registrado este tiene prioridad sobre todos
if (!empty($mailAddressTo)) {
$agente = $em->getRepository(User::class)->findOneById($user_id);
$mailAddressFrom = $agente->getEmail();
$mailSubject = 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
$mailBody = 'Estimado cliente,' .
'<br><br> Nos ponemos en contacto con usted para confirmarle que su reserva ha quedado registrada en Green Patio para la realización de su próximo evento.' .
'<br>Le recordamos que esta reserva tiene una validez de ' . $reserva->getDaysBlock() . ' días. Si pasado este tiempo no hemos recibido confirmación de vuestra parte, procederemos a la cancelación de la misma.' .
'<br><br>Reserva: ' . $reserva->getId() .' - '. $reserva->getTitle();
$mailBody = $mailBody . '<br><br><br>Muchas gracias por su colaboración.<br><br><br>';
//Se envia el correo al cliente y al agente
$alertaPrevia = $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($reserva->getId());
if (empty($alertaPrevia)){
//El correo solo se enviara si no se ha enviado ya una alerta previamente
$this->sendMail($mailAddressFrom, $mailAddressTo, $mailSubject, $mailBody);
}
//Se genera el control de la alerta
$this->makeAlert($reserva->getId(), $reserva->getClient(), $mailAddressTo, $agente->getId(), $agente->getEmail());
}
}
// Modificar la fecha de notificación
if (!empty($arrayRequest['dateNextMailAlert'])) {
$nextReservaMailAlert = $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($id);
if (!empty($nextReservaMailAlert)){
// La nueva fecha tiene que ser de mañana en adelante
if (new \Datetime($arrayRequest['dateNextMailAlert']) > new \Datetime('now')){
if ($nextReservaMailAlert->getAlertSended() == 0){
// Si no se ha enviado el mensaje de alerta se modifican la alerta y la cancelacion (+2 dias)
$newAlertDatetime = new \DateTime($arrayRequest['dateNextMailAlert'].' 15:00');
$newCancelDatetime = date( "Y-m-d H:i", strtotime( $newAlertDatetime->format('Y-m-d H:i') . "+2 days" ));
$newCancelDatetime = new \DateTime($newCancelDatetime);
$nextReservaMailAlert->setAlertDateTime($newAlertDatetime);
$nextReservaMailAlert->setCancelDateTime($newCancelDatetime);
$em->persist($nextReservaMailAlert);
$em->flush();
} else {
// Si no se ha enviado el mensaje de cancelacion (paso a cotizacion)
$newCancelDatetime = new \DateTime($arrayRequest['dateNextMailAlert'].' 15:00');
$nextReservaMailAlert->setCancelDateTime($newCancelDatetime);
$em->persist($nextReservaMailAlert);
$em->flush();
}
}
}
}
} else{
if(!empty($reserva->getDays())){
$reserva->setDays(null);
}
}
$newStatus = $this->verificarStatusInicialyFinal($id,$user_id,$reserva->getStatus(),$arrayRequest['status']);
// Despues de estudiar el estatus se actualiza con el valor que puede tomar
$arrayRequest['status'] = $newStatus;
$reserva->setStatus($newStatus);
if (!($arrayRequest['status'] == 'Bloqueo')){
// Si no es un bloqueo, tal vez se deba eliminar una alerta
$alertaPrevia = $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($id);
if (!empty($alertaPrevia)){
if ($arrayRequest['status'] == 'Deleted'){
// Si se cancela y hay una alerta previa se debe enviar automaticamente correo al cliente y agente acerca de la cancelacion o desbloqueo
$agent = $em->getRepository(User::class)->findOneById($alertaPrevia->getAgentId());
$mailAddressTo = $alertaPrevia->getClientMail();
$mailAddressFrom = $alertaPrevia->getAgentMail();
$replyTo = array(
$alertaPrevia->getClientMail() => $alertaPrevia->getClientMail(),
$alertaPrevia->getAgentMail() => $agent->getName().' '. $agent->getLastName(),
);
$mailSubject = 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
$mailBody = 'Estimado cliente,'.
'<br><br>Nos ponemos en contacto con usted para informarle de que su reserva ha sido cancelada.'.
'<br><br>Reserva: ' . $reserva->getId() .' - '. $reserva->getTitle();
if (!empty($reserva->getDays())){ $mailBody = $mailBody . '<br>Días bloqueados: '.$reserva->getDays(); }
$mailBody = $mailBody . '<br><br><br>Muchas gracias por su colaboración.<br><br><br>';
//Se envia el correo al cliente y al agente
$this->sendMail($mailAddressFrom, $mailAddressTo, $mailSubject, $mailBody);
$alertaPrevia->setOldReservationId($alertaPrevia->getReservationId());
$alertaPrevia->setReservationId(0);
$alertaPrevia->setCancelSended(1);
} else {
$alertaPrevia->setOldReservationId($alertaPrevia->getReservationId());
$alertaPrevia->setReservationId(0);
}
$em->persist($alertaPrevia);
$em->flush();
}
}
}
$boolConfirmacion = ($boolConfirmacion and ($reserva->getStatus() == 'Pendiente')); // Si se pidio cambiar el estado y se quedo en Pendiente y es un usario de GreenPatio (rol 48)
$reserva->setContract($arrayRequest['contract']);
$reserva->setDescription($arrayRequest['description']);
if(!empty($arrayRequest['advancePayment'])){ $reserva->setAdvancePayment($arrayRequest['advancePayment']); } else { $reserva->setAdvancePayment(0); }
if(!empty($arrayRequest['deposit'])){ $reserva->setDeposit($arrayRequest['deposit']); } else { $reserva->setDeposit(0); }
if(!empty($arrayRequest['pax'])){ $reserva->setPax($arrayRequest['pax']); } else { $reserva->setPax(null); }
if(!empty($arrayRequest['idProposal'])){ $reserva->setIdProposal($arrayRequest['idProposal']); } else { $reserva->setIdProposal(null); }
if (!empty($arrayRequest['cateringName'])){ $reserva->setCateringName($arrayRequest['cateringName']); }
if(is_null($arrayRequest['priority']) or empty($arrayRequest['priority']) or ($arrayRequest['priority'] == 0)){ $reserva->setPriority(1); } else { $reserva->setPriority($arrayRequest['priority']); }
if ($user_logueado->getRole() == 'ROLE_USER'){
// La opcion o prioridad solo la pueden modificar los administradores para evitar competencias entre lo agentes
$reserva->setPriority($oldPriority);
}
if(empty($reserva->getStatus())){$reserva->setStatus('Cotizado');} //El estado de reserva en vacio es que esta en el proceso de cotizacion
// Actualizamos las fechas de la reserva
$resLoungeSimples = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
$newStart = null; $newEnd = null;
foreach ($resLoungeSimples as $item) {
$dateStart = $item->getDateStart();
$dateEnd = $item->getDateEnd();
if ($newStart === null || $dateStart < $newStart) { $newStart = $dateStart; }
if ($newEnd === null || $dateEnd > $newEnd) { $newEnd = $dateEnd; }
}
if (!empty($newStart) and !empty($newEnd)){
$reserva->setDateStart($newStart);
$reserva->setDateEnd($newEnd);
}
try{
$em->persist($reserva);
$em->flush();
// $event = 'The Reservation has been Updated. Now';
$successMessage = 'La reserva ha sido actualizada.';
// $successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
// Se debe solicitar la confirmación ed la reserva
if ($boolConfirmacion){ return $this->redirectToRoute('reservations_greenpatio_send_confirmation_request_mail', array( 'id' => $id )); }
// Si han confirmado se debe notificar a Salvador y a Rafa, no para que confirmen sino para que esten informados
if ($reserva->getStatus() == 'Confirmed'){ return $this->redirectToRoute('reservations_greenpatio_send_confirmation_request_mail', array( 'id' => $id )); }
// Sincronización con HT
if (!empty($reserva)) {
// Rafa indico que siempre se sincronice al abrir un expediente de GP
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
// Si no se ha creado aun el expediente de HT debemos crearlo
$htFile = $em->getRepository(HtFile::class)->findByReservation($reserva);
if (empty($htFile)) {
return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,));
}
}
}
}
// Sincronización con Av Express
$cotizable = $this->laReservaEsCotizable($reserva->getId());
if ($cotizable) {
// Rafa indico que siempre se sincronice al abrir un expediente de GP
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
$AveFile = $em->getRepository(AveFiles::class)->findByReservation($reserva);
if (empty($AveFile)) {
// Si no se ha creado aun el expediente de Av Express debemos crearlo
return $this->redirectToRoute('sinc_gp_ave', array('id' => $id,));
}
}
}
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id, 'token' => null ));
}
/**
* @Route("/events", name="get_reservations")
*/
public function reservationSelectAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$fechaInicio = new \DateTime('first day of January last year');
$qb = $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
$reservation = $qb->where('r.dateStart >= :fechaInicio')
->andWhere('r.idLounge < :idLounge')
->setParameter('fechaInicio', $fechaInicio)
->setParameter('idLounge', 22)
->getQuery()
->getResult();
$qb = $em->getRepository(ReservationVisit::class)->createQueryBuilder('v');
$visitas = $qb->where('v.dateStart >= :fechaInicio')
->andWhere('v.idLounge = 0')
->setParameter('fechaInicio', $fechaInicio)
->getQuery()
->getResult();
$arrayFechaVisitas = [];
//Se agrupan las visitas por fechas
foreach ($visitas as $item) { $arrayFechaVisitas[$item->getDateStart()->format('Y-m-d')][] = $item; }
$newArrayVisitas = [];
//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 = '';
$item->setLoungeName($loungeNameTemp . $item->getDateStart()->format('H:i') . ' ' . $item->getLoungeName() . '<br>');
$newArrayVisitas[$item->getDateStart()->format('Y-m-d') . '-' . $item->getAgentId()] = $item;
}
}
$visitas = $newArrayVisitas;
$xArray = [];
foreach ($arrayFechaVisitas as $elem) { foreach ($elem as $item) { $xArray[] = $item; } }
foreach ($xArray as $item) { array_push($reservation, $item); }
$datos = [];
$datosMontaje = [];
$datosDesMontaje = [];
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())) {
switch ($reserva->getStatus()) {
case 'Bloqueo': //naranja
$color = "#ffaa00";
break;
case 'Confirmed': //verde
$color = "#13ad27";
break;
case 'Invoiced': //verde
$color = "#13ad27";
break;
case 'Deleted': //rojo
$color = "#ff0000";
break;
case 'Cotizado': //Rojo claro
$color = "#faafc3";
break;
case 'Reservado': //verde, se ha adelantado un pago parcial
$color = "#13ad27";
break;
case 'Visit': //Azul Almudena (id user 77), Rosa Gaby
$logicoVisita = true;
if ($reservaSala->getAgentId() == 77) {
$color = "#22cbf5";
} else {
$color = "#f5229a";
}
break;
default: //naranja
$color = "";
break;
}
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
}
}
}
}
$pago1 = "";
$pago2 = "";
$ht = "";
if (!($reserva->getStatus() == 'Visit')) {
$paymentsAll = $em->getRepository(ReservationPaymentsClient::class)->findOneByReservationId($reserva->getId());
} else {
$paymentsAll = null;
}
if (!empty($paymentsAll)) {
$pago2 = "<i class='icon-coin-euro' style='color: #000 !important;'></i>"; //Hay pagos parciales
}
if (!($reserva->getStatus() == 'Visit')) {
$facturas = $em->getRepository(ReservationInvoice::class)->findByReservationId($reserva->getId());
}
if (!empty($facturas)) {
foreach ($facturas as $factura) {
if ($factura->getMaster() == "master") {
$pago1 = "<i class='icon-thumbs-up3' style='color: #000 !important;'></i>";// Se ha pagado la totalidad
}
if ($factura->getMaster() != "master") {
$pago2 = "<i class='icon-coin-euro' style='color: #000 !important;'></i>"; //Hay pagos parciales
}
}
}
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
if (!empty($reserva)) {
if (!$logicoVisita) {
$datos[] = array(
// "title" => $reservaSala->getDateStart()->format('H:i') . ' ' . $pago2 . $pago1 . $ht . ' ' . $reservaSala->getType() . '<br>' . $reservaSala->getLoungeName() . '<br>' . '<br>' . $reserva->getTitle(),
"title" => $reservaSala->getDateStart()->format('H:i') . ' ' . $pago2 . $pago1 . $ht . ' ' . $reservaSala->getType() .' '. $reservaSala->getLoungeName() . '<br>' . $reserva->getTitle(),
"titleOne" => $reservaSala->getDateStart()->format('H:i') . ' ' . $pago2 . $pago1 . $ht . ' ' . $reservaSala->getType(),
"titleTwo" => $reservaSala->getLoungeName(),
"titleThree" => '' . '<br>' . $reserva->getTitle(),
"type" => $reservaSala->getType(),
"id" => $reserva->getId(),
"tooltip" => $tooltip,
"start" => $reservaSala->getDateStart(),
"end" => $reservaSala->getDateEnd(),
"color" => $color,
"loungeId" => $reservaSala->getIdLounge(),
"url" => "/reservations-greenpatio/edit/" . $reserva->getId(),
"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': if ($dato['type'] == 'Montaje'){ $newDatos[$dato['id'].'M'] = null; } else { $newDatos[$dato['id'].'D'] = null; } break; //Montaje o Desmontaje
default: $newDatos[$dato['id']] = null; break; //Dia de reserva o Visita (la visita ya viene con su indice #V )
}
}
foreach ($datos as $dato) {
switch ($dato['color']){
//Montaje o Desmontaje
case '#a5b8a2':
if ($dato['type'] == "Montaje") {
if (!empty($newDatos[$dato['id'] . 'M'])) {
// 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']; }
// El Montaje esta ocupando mas de 1 dia, se deben unir los dias de montaje si estamos tratando la misma sala (no se deben unir montajes de salas diferentes)
if ($newDatos[$dato['id'] . 'M']['loungeId'] == $dato['loungeId']) {
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 {
if (array_key_exists($dato['id'] . 'M'.$dato['loungeId'],$newDatos)){
if ($newDatos[$dato['id'] . 'M'.$dato['loungeId']]['start'] > $dato['start']) { $newDatos[$dato['id'] . 'M'.$dato['loungeId']]['start'] = $dato['start']; }
if ($newDatos[$dato['id'] . 'M'.$dato['loungeId']]['end'] < $dato['end']) { $newDatos[$dato['id'] . 'M'.$dato['loungeId']]['end'] = $dato['end']; }
} else {
$newDatos[$dato['id'] . 'M'.$dato['loungeId']] = $dato;
}
}
} 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 Almudena (id user 77)
case '#22cbf5':
if ($dato['type'] == "Visit") {
$newDatos[$dato['start']->format('Ymd').'V77'.$dato['id']] = $dato;
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") {
$newDatos[$dato['start']->format('Ymd').'V82'.$dato['id']] = $dato;
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 120)
case '#157cc2':
if ($dato['type'] == "Visit") {
$newDatos[$dato['start']->format('Ymd').'V120'.$dato['id']] = $dato;
if (!empty($newDatos[$dato['start']->format('Ymd').'V120'])) {
// Hay varias visitas ese mismo dia para el agente
// $newDatos[$dato['start']->format('Ymd').'V120']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V120']['tooltip'] . $dato['tooltip'];
} else {
// $newDatos[$dato['start']->format('Ymd').'V120'] = $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 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
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 ($newDatos[$dato['id']]['end'] < $dato['end']) {
if (empty($newDatos[$dato['id']])){
$newDatos[$dato['id']]['end'] = $dato['end'];
$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 negro para resaltar este caso que no esta entrando en ninguno de los casos anteriores
$newDatos[$dato['id']]['color'] = '#000000';
if ($dato['type'] == "Visit") {
// Si no es una de los agentes regulares (Gaby, Angie, Cristina) se busca el color del usuario configurado en el perfil
$elAgente = $em->getRepository(User::class)->findOneById($dato['agentId']);
$elAgenteColor = !empty($elAgente) ? $elAgente->getColor() : null;
if (!empty($elAgenteColor)){ $newDatos[$dato['id']]['color'] = $elAgenteColor; }
}
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']);
}
}
$newDatos = $datos0;
$datos = [];
foreach ($newDatos as $item) {
if ($item['color'] != '#ff0000') {
// No se agregan al calendario los elementos eliminados oelementos 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 = [];
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 = [];
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
}
}
}
$return = array( 'reservation' => $datos, );
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/delete/{id}", name="reservations_delete")
*/
public function deleteAction($id, EntityManagerInterface $em, Request $request)
{
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$hoy = new \DateTime("now", NULL);
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$reserva->setUpdatedBy($user_id);
$reserva->setUpdatedAt($hoy);
$reserva->setStatus('Deleted');
try{
$em->persist($reserva);
$em->flush();
$successMessage = 'La reserva ha sido actualizada.';
// $successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_greenpatio_index');
}
/**
* @Route("/listgpprices", name="reservations_greenpatio_prices")
*/
public function indexPricesAction(EntityManagerInterface $em, Request $request) {
$prices = $em->getRepository(ReservationLoungeProfile::class)->findBy(
array(),
array('id' => 'ASC')
);
$data = [];
foreach ($prices as $price){
$periodSql = $em->getRepository(ReservationPeriod::class)->findOneById($price->getPeriodId());
$price->setPeriodId($periodSql->getName());
$loungeTemp = $em->getRepository(ReservationLoungeDetails::class)->findOneById($price->getLoungeId());
if(!is_null($loungeTemp)){ $price->setLoungeId($loungeTemp->getName()); }
$data[] = $price;
}
$reserv = new ReservationLoungeProfile();
$form = $this->createReservationLoungeProfileCreateForm($reserv);
return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-gp-prices.html.twig',
array(
'groups' => null,
'prices' => $data,
'form' => $form->createView()
)
);
}
/**
* @Route("/deletegpprice/{id}", name="reservations_price_delete")
*/
public function deletePriceAction($id, EntityManagerInterface $em, Request $request)
{
$price = $em->getRepository(ReservationLoungeProfile::class)->findOneById($id);
try{
$em->remove($price);
$em->flush();
$event = 'The Item has been Deleted.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_greenpatio_prices');
}
/**
* @Route("/addgpprice/", name="reservations_greenpatio_addgpprice")
*/
public function addReservationGpPriceAction(EntityManagerInterface $em, Request $request)
{
$reserv = new ReservationLoungeProfile();
$form = $this->createReservationLoungeProfileCreateForm($reserv);
$gpPrices = $em->getRepository(ReservationLoungeProfile::class)->findAll();
return $this->render('MDS/GreenPatioBundle/reservations/add-reservations-gp-price.html.twig', array('form' => $form->createView(), 'gpPrices' => $gpPrices ));
}
private function createReservationLoungeProfileCreateForm(ReservationLoungeProfile $entity)
{
$form = $this->createForm(ReservationLoungeProfileType::class, $entity, array(
'action' => $this->generateUrl('reservations_greenpatio_price_create'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/creategpprice", name="reservations_greenpatio_price_create")
*/
public function createGpPriceAction(EntityManagerInterface $em, Request $request){
$reservaGpPrice = new ReservationLoungeProfile();
$form = $this->createReservationLoungeProfileCreateForm($reservaGpPrice);
$form->handleRequest($request);
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
$reservaGpPrice->setCreatedAt($hoy);
$reservaGpPrice->setCreatedId($user_id);
$reservaGpPrice->setUpdatedAt($hoy);
$reservaGpPrice->setUpdatedId($user_id);
$periodSql = $em->getRepository(ReservationPeriod::class)->findOneById($form->get('periodId')->getData());
if (!empty($periodSql)){ $descTemp = $periodSql->getName(); } else { $descTemp = null; }
$reservaGpPrice->setPeriodId($reservaGpPrice->getPeriodId()->getId());
$reservaGpPrice->setLoungeId($reservaGpPrice->getLoungeId()->getId());
if ((!is_null($reservaGpPrice->getLoungeId())) and (!is_null($descTemp))){
$descriptionSql = $em->getRepository(ReservationLoungeDetails::class)->findOneById($form->get('loungeId')->getData());
$description = $descriptionSql->getName().' - '.$descTemp;
$reservaGpPrice->setDescription($description);
} else {
$reservaGpPrice->setDescription(null);
}
if($form->isValid())
{
try{
$em->persist($reservaGpPrice);
$em->flush();
$event = 'The Item Price has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_greenpatio_prices');
}
/**
* @Route("/getReservationLoungeProfile", name="get_reservation_lounge_profile")
*/
public function getReservationLoungeProfileAction(EntityManagerInterface $em, Request $request) {
$codProfile = $_POST['idprofile'];
$salasPorPerfil = $em->getRepository(ReservationLoungeProfile::class)->findBy( array( 'periodId' => $codProfile ) );
$datos = [];
if (!empty($salasPorPerfil)){
foreach($salasPorPerfil as $sala){
$datos[] = array(
"id" => $sala->getId(),
"idlounge" => $sala->getLoungeId(),
"nameDescription" => $sala->getDescription(),
"price" => $sala->getPrice(),
);
}
}
$return = array( 'salasPerfil' => $datos, 'id' => $codProfile, );
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/getReservationPeriod", name="get_reservation_Period")
*/
public function getReservationPeriodAction(EntityManagerInterface $em, Request $request) {
$id = $_POST['id'];
$period = $em->getRepository(ReservationPeriod::class)->findOneById($id);
$datos = array();
if (!empty($period)){
$datos = array(
"id" => $period->getId(),
"hourStart" => is_null($period->getHourStart())?"":$period->getHourStart()->format('H:i'),
"hourEnd" => is_null($period->getHourEnd())?"":$period->getHourEnd()->format('H:i'),
);
}
$return = $datos;
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/getReservationLoungePrice", name="get_reservation_lounge_price")
*/
public function getReservationLoungePriceAction(EntityManagerInterface $em, Request $request) {
$id = $_POST['id'];
$precio = $em->getRepository(ReservationLoungeProfile::class)->findOneById($id);
$datos = array();
if (!empty($precio)){ $datos = array( "id" => $precio->getId(), "price" => $precio->getPrice() ); }
$return = $datos;
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/addloungedetails/", name="reservations_greenpatio_addloungedetails")
*/
public function addReservationLoungeDetailsAction( Request $request)
{
$lounge = new ReservationLoungeDetails();
$form = $this->createReservationLoungeDetailsCreateForm($lounge);
return $this->render('MDS/GreenPatioBundle/reservations/add-reservations-lounge-details.html.twig', array('form' => $form->createView() ));
}
private function createReservationLoungeDetailsCreateForm(ReservationLoungeDetails $entity)
{
$form = $this->createForm(ReservationLoungeDetailsType::class, $entity, array(
'action' => $this->generateUrl('reservations_greenpatio_lounge_details_create'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/createloungedetails", name="reservations_greenpatio_lounge_details_create")
*/
public function createLoungeDetailsAction(EntityManagerInterface $em, Request $request)
{
$lounge = new ReservationLoungeDetails();
$form = $this->createReservationLoungeDetailsCreateForm($lounge);
$form->handleRequest($request);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
$lounge->setCreatedAt($hoy);
$lounge->setCreatedId($user_id);
$lounge->setUpdatedAt($hoy);
$lounge->setUpdatedId($user_id);
if($form->isValid()){
try{
$em->persist($lounge);
$em->flush();
$event = 'The Lounge has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
$this->reordenarSalas($lounge->getRankLounge(), $lounge->getId());
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_greenpatio_list_lounges');
}
/**
* @Route("/listloungedetails", name="reservations_greenpatio_list_lounges")
*/
public function indexLoungesAction(EntityManagerInterface $em, Request $request) {
$salas = $em->getRepository(ReservationLoungeDetails::class)->findAll();
$lounge = new ReservationLoungeDetails();
$form = $this->createReservationLoungeDetailsCreateForm($lounge);
return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-lounges-details.html.twig',
array(
'groups' => null,
'salas' => $salas,
'form' => $form->createView()
)
);
}
/**
* @Route("/editloungedetails/{id}", name="reservations_lounge_details")
*/
public function editLoungeDetailsAction($id, EntityManagerInterface $em, Request $request)
{
$lounge = $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
$loungeContract = $em->getRepository(DocContractModel::class)->findBy(array('companyId' => 7, 'modelId' => $id,));
$loungeContract = empty($loungeContract) ? array('contractualDocument' => '') : $loungeContract[0];
$loungePictures = $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id, 'title' => null,));
$loungeVideos = $em->getRepository(ReservationLoungeVideo::class)->findByLoungeId($id);
$loungeDescriptions = $em->getRepository(ReservationLoungeDescription::class)->findByLoungeId($id);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
/* 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;
$hoy = new \DateTime("now", NULL);
$form = $this->createEditReservationLoungeDetailsForm($lounge, $id);
// Para evitar le duplicidad de idiomas en las descripciones
$loungeDescriptionsPreexistentes = $em->getRepository(ReservationLoungeDescription::class)->findByLoungeId($id);
$idiomasPreexistentes = array();
foreach ($loungeDescriptionsPreexistentes as $item){ $idiomasPreexistentes[] = $item->getLanguage(); }
$datos_videos = array();
foreach ($loungeVideos as $video){
$urvideo_final = '<iframe class="embed-responsive-item" src="'.$video->getVideo().'"></iframe>';
$datos_videos[] = array(
'id' => $video->getId(),
'urlvideo' => $urvideo_final
);
}
$blueprints = $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id, 'title' => 'Blueprint', ) );
$pictTeatro = $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id, 'title' => 'Teatro', ) );
if (sizeof($pictTeatro) == 0) {$pictTeatro = null;}
$pictCoctel = $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id, 'title' => 'Coctel', ) );
if (sizeof($pictCoctel) == 0) {$pictCoctel = null;}
$pictEscuela = $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id, 'title' => 'Escuela', ) );
if (sizeof($pictEscuela) == 0) {$pictEscuela = null;}
$picsMontaje = array (
'pictTeatro' => $pictTeatro,
'pictCoctel' => $pictCoctel,
'pictEscuela' => $pictEscuela
);
if(empty($picsMontaje['pictTeatro']) and empty($picsMontaje['pictCoctel']) and empty($picsMontaje['pictEscuela'])){ $picsMontaje = null; }
$loungedimmensions = $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-lounge-details.html.twig',
array(
'id' => $id,
'hoy' => $hoy,
'lounge' => $lounge,
'loungeContract' => $loungeContract,
'descriptions' => $loungeDescriptions,
'pictures' => $loungePictures,
'blueprints' => $blueprints,
'picsMontaje' => $picsMontaje,
'loungedimmensions' => $loungedimmensions,
'videos' => $datos_videos,
'idiomasPreexistentes' => $idiomasPreexistentes,
'form' => $form->createView()
));
}
private function createEditReservationLoungeDetailsForm(ReservationLoungeDetails $entity, $id)
{
$form = $this->createForm(ReservationLoungeDetailsType::class, $entity,
array(
'action' => $this->generateUrl('reservations_lounge_details_update',
array(
'id' => $id,
'price' => $entity
)
), 'method' => 'PUT'));
return $form;
}
/**
* @Route("/updateloungedetails/{id}", name="reservations_lounge_details_update")
*/
public function updateLoungeDetailsAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$lounge = $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
$lounge->setName($request->request->get('mds_greenpatiobundle_reservationloungedetails')['name']);
$preNumber = $lounge->getRankLounge();
$postNumber = $request->request->get('mds_greenpatiobundle_reservationloungedetails')['rankLounge'];
$hoy = new \DateTime("now", NULL);
$form = $this->createEditReservationLoungeDetailsForm($lounge, $id);
$form->handleRequest($request);
if($form->isValid())
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
/* 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;
$lounge->setUpdatedId($user_id);
$lounge->setUpdatedAt($hoy);
try{
// Reordenar salas si se ha cambiado el rank number de la sala
if (!( $preNumber == $postNumber)){ $this->reordenarSalas($postNumber, $lounge->getId()); }
$em->persist($lounge);
$em->flush();
$event = 'The lounge has been Updated. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
return $this->redirectToRoute('reservations_greenpatio_list_lounges');
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-lounge-details.html.twig',
array(
'id' => $lounge->getId(),
'lounge' => $lounge,
'form' => $form->createView()
)
);
}
/**
* @Route("/deleteloungedetails/{id}", name="reservations_lounge_details_delete")
*/
public function deleteLoungeDetailsAction($id, EntityManagerInterface $em, Request $request)
{
$lounge = $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
try{
$em->remove($lounge);
$em->flush();
// INICIO: Eliminamos los precios asociados a la sala
$profiles = $em->getRepository(ReservationLoungeProfile::class)->findByLoungeId($id);
foreach ($profiles as $item){
$em->remove($item);
$em->flush();
}
// FIN: Eliminamos los precios asociados a la sala
$event = 'The Reservation has been Deleted. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
return $this->redirectToRoute('reservations_greenpatio_list_lounges');
}
/**
* @Route("/deleteloungeelement/{idlounge}/{idtype}/{idelement}", name="reservations_lounge_element_delete")
*/
public function deleteLoungeElementAction($idlounge, $idtype, $idelement, EntityManagerInterface $em, Request $request)
{
switch ($idtype){
case 1: $item = $em->getRepository(ReservationLoungeDescription::class)->findOneById($idelement); break; //Descripcion
case 2: $item = $em->getRepository(ReservationLoungePicture::class)->findOneById($idelement); break; //Imagenes
case 3: $item = $em->getRepository(ReservationLoungeVideo::class)->findOneById($idelement); break; //Videos
default: $item = null; break;
}
try{
$em->remove($item);
$em->flush();
$event = 'The Item has been Deleted. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $idlounge ));
}
/**
*@Route("/exclamation", name="get_exclamation")
*/
public function exclamationAction(EntityManagerInterface $em, Request $request) {
$dateStar = $request->request->get('dateStar');
$dateEnd = $request->request->get('dateEnd');
$hourStar = $request->request->get('hourStar');
$hourEnd = $request->request->get('hourEnd');
$profileId = $request->request->get('profileId');
$mountingDate = $request->request->get('mountingDate');
$mountingHourStart = $request->request->get('mountingHourStart');
$removalDate = $request->request->get('removalDate');
$removalHourEnd = $request->request->get('removalHourEnd');
// INICIO: Si hay montaje o desmontaje en el evento nuevo las fechas a utilizar son estas y no las del evento
if (!empty($mountingDate)){
$dateStar = $mountingDate;
if (!empty($mountingHourStart)){ $hourStar = $mountingHourStart; }
}
if (!empty($removalDate)){
$dateEnd = $removalDate;
if (!empty($removalHourEnd)){ $hourEnd = $removalHourEnd; }
}
// FIN: Si hay montaje o desmontaje en el evento nuevo las fechas a utilizar son estas y no las del evento
$loungeId = $em->getRepository(ReservationLoungeProfile::class)->findOneById($profileId);
$newdateStar = $dateStar.' '.$hourStar.':00';
$newdateEnd = $dateEnd .' '.$hourEnd.':00';
$parameters = array(
'dateStar' => $newdateStar,
'dateEnd' => $newdateEnd,
'idLounge' => $loungeId->getLoungeId(),
);
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLounge i
WHERE i.dateStart >= :dateStar
and i.dateStart <= :dateEnd
and i.idLounge = :idLounge';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservationLounge1 = $query->getResult();
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLounge i
WHERE i.dateEnd >= :dateStar
and i.dateEnd <= :dateEnd
and i.idLounge = :idLounge';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservationLounge2 = $query->getResult();
$parameters = array(
'dateStar' => $newdateStar,
'idLounge' => $loungeId->getLoungeId()
);
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLounge i
WHERE :dateStar >= i.dateStart
and :dateStar <= i.dateEnd
and i.idLounge = :idLounge';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservationLounge3 = $query->getResult();
$parameters = array(
'dateEnd' => $newdateEnd,
'idLounge' => $loungeId->getLoungeId(),
);
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLounge i
WHERE :dateEnd >= i.dateStart
and :dateEnd <= i.dateEnd
and i.idLounge = :idLounge';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservationLounge4 = $query->getResult();
// INICIO: Si hay montaje o desmontaje en los eventos de la BD, las fechas a utilizar son estas y no las del evento
$parameters = array(
'dateStar' => $newdateStar,
'dateEnd' => $newdateEnd,
'idLounge' => $loungeId->getLoungeId(),
);
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLounge i
WHERE i.mountingDate >= :dateStar
and i.mountingDate <= :dateEnd
and i.idLounge = :idLounge';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservationLounge5 = $query->getResult();
// FIN: Si hay montaje o desmontaje en los eventos de la BD, las fechas a utilizar son estas y no las del evento
$reservationLounge = array_merge($reservationLounge1,$reservationLounge2,$reservationLounge3,$reservationLounge4);
$data = array();
foreach ($reservationLounge as $res){
$reservation = $em->getRepository(Reservation::class)->findOneById($res->getIdReservation());
if (!is_null($reservation->getIdProposal() )){
$proposal = $em->getRepository(Proposal::class)->findOneById($reservation->getIdProposal());
$user = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$data[] = array(
'name' => 'Id Proposal',
'idproposal' => $proposal->getId(),
'title' => $proposal->getTitle(),
'Agent' => $user->getName().' '.$user->getLastname(),
);
} else {
$user = $em->getRepository(User::class)->findOneById($reservation->getCreatedBy());
$data[] = array(
'name' => 'Id Green Patio',
'idproposal' => $reservation->getId(),
'title' => $reservation->getTitle(),
'Agent' => $user->getName().' '.$user->getLastname(),
);
}
}
$return = array( 'reservation' => $data, );
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/addperiod/", name="reservations_greenpatio_addperiod")
*/
public function addReservationPeriodAction( Request $request)
{
$period = new ReservationPeriod();
$form = $this->createReservationperiodCreateForm($period);
return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-period.html.twig', array('form' => $form->createView() ));
}
private function createReservationperiodCreateForm(Reservationperiod $entity)
{
$form = $this->createForm(ReservationPeriodType::class, $entity, array(
'action' => $this->generateUrl('reservations_greenpatio_period_create'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/createperiod", name="reservations_greenpatio_period_create")
*/
public function createPeriodAction(EntityManagerInterface $em, Request $request)
{
$period = new ReservationPeriod();
$form = $this->createReservationPeriodCreateForm($period);
$form->handleRequest($request);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
$period->setCreatedAt($hoy);
$period->setCreatedId($user_id);
$period->setUpdatedAt($hoy);
$period->setUpdatedId($user_id);
if($form->isValid())
{
try{
$em->persist($period);
$em->flush();
$event = 'The Period has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_greenpatio_list_period');
}
/**
* @Route("/listperiod", name="reservations_greenpatio_list_period")
*/
public function indexPeriodAction(EntityManagerInterface $em, Request $request) {
$periods = $em->getRepository(ReservationPeriod::class)->findAll();
$period = new ReservationPeriod();
$form = $this->createReservationPeriodCreateForm($period);
return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-period.html.twig',
array(
'groups' => null,
'form' => $form->createView(),
'periods' => $periods
)
);
}
/**
* @Route("/deleteperiod/{id}", name="reservations_period_delete")
*/
public function deletePeriodAction(EntityManagerInterface $em, $id, Request $request)
{
$period = $em->getRepository(ReservationPeriod::class)->findOneById($id);
try{
$em->remove($period);
$em->flush();
$event = 'The Reservation has been Deleted. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
return $this->redirectToRoute('reservations_greenpatio_list_period');
}
/**
* @Route("/editperiod/{id}", name="reservations_edit_period")
*/
public function editPeriodAction($id, EntityManagerInterface $em, Request $request)
{
$period = $em->getRepository(ReservationPeriod::class)->findOneById($id);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
/* 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;
$hoy = new \DateTime("now", NULL);
$form = $this->createEditPeriodForm($period, $id);
return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-period.html.twig',
array(
'id' => $id,
'hoy' => $hoy,
'period' => $period,
'form' => $form->createView()
));
}
private function createEditPeriodForm(ReservationPeriod $entity, $id)
{
$form = $this->createForm(ReservationPeriodType::class, $entity,
array(
'action' => $this->generateUrl('reservations_period_update',
array(
'id' => $id,
'period' => $entity
)
), 'method' => 'PUT'));
return $form;
}
/**
* @Route("/updateperiod/{id}", name="reservations_period_update")
*/
public function updatePeriodAction($id, EntityManagerInterface $em, Request $request)
{
$period = $em->getRepository(ReservationPeriod::class)->findOneById($id);
$newName = $request->request->get('mds_greenpatiobundle_reservationperiod')['name'];
$period->setName($newName);
$hoy = new \DateTime("now", NULL);
$form = $this->createEditPeriodForm($period, $id);
$form->handleRequest($request);
if($form->isValid())
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
/* 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;
$period->setUpdatedId($user_id);
$period->setUpdatedAt($hoy);
try{
$em->persist($period);
$em->flush();
$event = 'The period has been Updated. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
return $this->redirectToRoute('reservations_greenpatio_list_period');
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-period.html.twig',
array(
'id' => $id,
'hoy' => $hoy,
'period' => $period,
'form' => $form->createView()
)
);
}
/**
* @Route("/getperiodos/", name="reservations_greenpatio_get_periods")
*/
public function addReservationPeriodsAction(EntityManagerInterface $em, Request $request)
{
$periods = $em->getRepository(ReservationPeriod::class)->findAll();
$data = array();
foreach ($periods as $items){ $data[] = array( 'id' => $items->getId(), 'name' => $items->getName(), ); }
$return = array( 'periods' => $data, );
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/addsimple/", name="reservations_greenpatio_add_simple")
*/
public function addReservationSimpleAction(EntityManagerInterface $em, Request $request)
{
$reserv = new Reservation();
$form = $this->createReservationCreateForm($reserv);
$parameters = array();
$dql = 'SELECT p
FROM App:ClientContact p
ORDER BY p.name ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$clientsContact = $query->getResult();
return $this->render('MDS/GreenPatioBundle/reservations/add-reservations-simple.html.twig',
array(
'form' => $form->createView(),
'clientsContact' => $clientsContact,
));
}
private function createReservationCreateForm(Reservation $entity)
{
$form = $this->createForm(ReservationType::class, $entity, array(
'action' => $this->generateUrl('reservations_greenpatio_create_simple'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/createsimple", name="reservations_greenpatio_create_simple")
*/
public function createSimpleAction(EntityManagerInterface $em, Request $request)
{
$clientContact = $request->request->get('clientContact');
$contactUnregistered = $request->request->get('contactUnregistered');
$nameContactUnregistered = $request->request->get('nameContactUnregistered');
$phoneContactUnregistered = $request->request->get('phoneContactUnregistered');
$reserva = new Reservation();
$form = $this->createReservationCreateForm($reserva);
$form->handleRequest($request);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
if($form->isValid())
{
$reserva->setUpdatedBy($user_id);
$reserva->setUpdatedAt($hoy);
// El proveedor de catering no es obligatorio
if (is_null($reserva->getCateringName())){
$reserva->setSupplier(4765);
$reserva->setCateringName('HIGO & TRIGO, S.L.'); // Por defecto se desea el Catering de Higo&Trigo
} else {
$reserva->setSupplier($reserva->getCateringName()->getId());
$reserva->setCateringName($reserva->getCateringName()->getName());
}
if (!empty($reserva->getClient())){
$reserva->setClient($reserva->getClient()->getId());
}
$reserva->setCreatedAt($hoy);
$reserva->setCreatedBy($user_id);
if(empty($reserva->getDaysBlock()) or !(is_numeric($reserva->getDaysBlock()))){
$reserva->setDaysBlock(7);
}
if(is_null($reserva->getPriority()) or empty($reserva->getPriority()) or ($reserva->getPriority() == 'Auto')){
$reserva->setPriority(1);
} else {
// Se ha establecido una prioridad y todas las prioridades que coincidan con este evento deben ser alteradas
// PENDIENTE A HABLAR CON RAFA
}
// No hay salas, se asigna a la reserva la fecha del dia actual
$reserva->setDateStart(new \DateTime('2078-01-01'));
$reserva->setDateEnd(new \DateTime('2000-01-01'));
if(!empty($clientContact)){ $reserva->setClientContact($clientContact); }
if(!empty($contactUnregistered)){
// if (filter_var($contactUnregistered, FILTER_VALIDATE_EMAIL)) { // Validamos el correo electronico
$reserva->setContactUnregistered($contactUnregistered);
// }
}
if(!empty($nameContactUnregistered)){
$reserva->setNameContactUnregistered($nameContactUnregistered);
}
if(!empty($phoneContactUnregistered)){
$reserva->setPhoneContactUnregistered($phoneContactUnregistered);
}
if(empty($reserva->getStatus())){
$reserva->setStatus('Iniciado');
} else {
//No se debe crear un evento con estado confirmado. Salva y Rafa seran quienes confirmen los eventos
if(($reserva->getStatus() == 'Confirmed')){
// $reserva->setStatus('Cotizado'); //Ya no es necesario que Rafa o Salva confirmen
}
}
// Genera un token único utilizando la función uniqid() de PHP
$token = uniqid();
$reserva->setToken($token);
try{
$em->persist($reserva);
$em->flush();
$event = 'The Reservation has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
//Envio de correo al cliente y al agente si es un bloqueo
if(is_null($reserva->getStatus())){
$reserva->setStatus('Cotizado');
$em->persist($reserva);
$em->flush();
} else {
if (($reserva->getStatus() == 'Bloqueo')) {
if(empty($reserva->getDays())){
$now = new \DateTime("now");
$dateLimit = date( "Y-m-d H:i", strtotime( $now->format('Y-m-d H:i') . "+".$reserva->getDaysBlock()." days" ));
$dateLimit = new \DateTime($dateLimit);
$reserva->setDays($dateLimit);
}
if ((!empty($reserva->getClient())) or (!empty($reserva->getClientContact())) or (!empty($reserva->getContactUnregistered()))) {
//Solo se envia correo de notificacion del correo si hay cliente o contacto o contacto no registrado
$client = $em->getRepository(Client::class)->findOneById($reserva->getClient());
$mailAddressTo = null;
// if (!empty($client) and (!empty($client->getEmail()))){ $mailAddressTo = $client->getEmail(); } // Si hay cliente con correo se le envia a este
// if (!empty($reserva->getClientContact())){
// $contacto = $em->getRepository(ClientContact::class)->findOneById($reserva->getClientContact());
// if (!empty($contacto) and (!empty($contacto->getEmail()))){ $mailAddressTo = $contacto->getEmail(); } // Si hay un contacto seleccionado tiene prioridad sobre el contacto de cliente
// }
// if (!empty($reserva->getContactUnregistered())){ $mailAddressTo = $reserva->getContactUnregistered(); } // Si hay correo de contacto no registrado este tiene prioridad sobre todos
if (!empty($mailAddressTo)) {
$agente = $em->getRepository(User::class)->findOneById($user_id);
$mailAddressFrom = $agente->getEmail();
$mailSubject = 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
$mailBody = 'Estimado cliente,' .
'<br><br> Nos ponemos en contacto con usted para confirmarle que su reserva ha quedado registrada en Green Patio para la realización de su próximo evento.' .
'<br>Le recordamos que esta reserva tiene una validez de ' . $reserva->getDaysBlock() . ' días. Si pasado este tiempo no hemos recibido confirmación de vuestra parte, procederemos a la cancelación de la misma.' .
'<br><br>Reserva: ' . $reserva->getId() .' - '. $reserva->getTitle();
$mailBody = $mailBody . '<br><br><br>Muchas gracias por su colaboración.<br><br><br>';
//Se envia el correo al cliente y al agente
$this->sendMail($mailAddressFrom, $mailAddressTo, $mailSubject, $mailBody);
//Se genera el control de la alerta
$this->makeAlert($reserva->getId(), $reserva->getClient(), $mailAddressTo, $agente->getId(), $agente->getEmail());
}
}
}
}
} else {
$errorMessagebase = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajetracingerror', $errorMessagebase);
$periods = $em->getRepository(ReservationPeriod::class)->findAll();
return $this->render('MDS/GreenPatioBundle/reservations/add-reservations.html.twig',
array(
'form' => $form->createView(),
'periods' => $periods,
));
}
$id = $reserva->getId();
// Sincronización con HT
if (!empty($reserva)) {
// Rafa indico que siempre se sincronice al abrir un expediente de GP
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
// if ($reserva->getStatus() == 'Confirmed' or $reserva->getStatus() == 'Invoiced' or $reserva->getStatus() == 'Iniciado' or $reserva->getStatus() == 'Cotizado' or $reserva->getStatus() == 'Bloqueo') {
if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
// Si no se ha creado aun el expediente de HT debemos crearlo
$htFile = $em->getRepository(HtFile::class)->findByReservation($reserva);
if (empty($htFile)) { return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,)); }
}
}
}
// Sincronización con Av Express
$cotizable = $this->laReservaEsCotizable($reserva->getId());
if ($cotizable) {
// Rafa indico que siempre se sincronice al abrir un expediente de GP
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
// if (in_array($reserva->getStatus(), ['Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
$AveFile = $em->getRepository(AveFiles::class)->findByReservation($reserva);
if (empty($AveFile)) {
// Si no se ha creado aun el expediente de Av Express debemos crearlo
return $this->redirectToRoute('sinc_gp_ave', array('id' => $id,));
}
}
}
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id, 'token' => null ));
}
/**
* @Route("/editsimple/{id}", name="reservations_greenpatio_edit_simple")
*/
public function editReservationSimpleItemsAction($id, EntityManagerInterface $em, Request $request)
{
$lounges = $em->getRepository(ReservationLounge::class)->findByIdReservation($id);
$loungesSimple = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
$services = $em->getRepository(ReservationService::class)->findByReservationId($id);
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$lounge = new ReservationLounge();
$lounge->setIdReservation($id);
$monDesmon = new ReservationLounge();
$monDesmon->setIdReservation($id);
$form1 = $this->createReservationCreateForm($reserva);
$form2 = $this->createReservationLoungeCreateForm($lounge);
$form3 = $this->createReservationLoungeMonDesCreateForm($monDesmon);
$arrayLoungesByDay = []; $arrayLoungesInFile = [];
//UPDATE GREEN
if (empty($loungesSimple)){
if (!empty($lounges)){
// INICIO: Se forma el arreglo para las salas dia a dia
foreach ($lounges as $item){
// Con un Temporal se ponen a cero las horas para que el calculo de los dias (->diff) sean exactos
$itemTemp = $item;
$tempDateStart = $item->getDateStart()->format('Y-m-d H:i'); // Se estaba perdiendo el valor de $item en horas y minutos
$tempDateEnd = $item->getDateEnd()->format('Y-m-d H:i');
$itemTemp->setDateStart(new DateTime ($itemTemp->getDateStart()->format('Y-m-d')));
$itemTemp->setDateEnd(new DateTime ($itemTemp->getDateEnd()->format('Y-m-d')));
if ($item->getDateStart() < $item->getDateEnd()) { $i = (($itemTemp->getDateEnd()->diff($itemTemp->getDateStart()))->days) + 1; } else { $i = 1; }
for ($indice = 0; $indice < $i; $indice++){
$item->setDateStart(new DateTime($tempDateStart));
$item->setDateEnd(new DateTime($tempDateEnd));
if ($item->getDateStart() < $item->getDateEnd()){
// Estas trabajando un registro antiguo de multiples dias
$dateTemp = ($item->getDateStart())->format('Ymd') + $indice;
} else {
$dateTemp = ($item->getDateStart())->format('Ymd');
}
$arrayLoungesByDay[$item->getRankQuote()][$dateTemp][] = array(
'id' => "0",
'loungeName' => $item->getLoungeName(),
'servicePrice' => $item->getServicePrice(),
'pax' => $item->getPax(),
'type' => $item->getType(),
'dateStart' => $item->getDateStart(),
'dateEnd' => $item->getDateEnd(),
'iva' => $item->getIva(),
);
}
ksort($arrayLoungesByDay[$item->getRankQuote()]);
}
} else {
$arrayLoungesByDay = array();
}
} else {
foreach ($loungesSimple as $item) {
$dateStart = $item->getDateStart()->format('Ymd');
$arrayLoungesByDay[$item->getRankQuote()][$dateStart][] = $item;
ksort($arrayLoungesByDay[$item->getRankQuote()]);
//Creamos el arreglo para las salas en la reserva. Se deben ignorar los montajes y desmontajes
if (empty($item->getType())) {
$loungeContract = $em->getRepository(DocContract::class)->findOneBy(array('modelId' => $item->getIdLounge(), 'fileId' => $id, 'companyId' => 7));
$dataContract = $this->docContractService->contractReservation($id,$item->getIdLounge());
$arrayLoungesInFile[$item->getRankQuote()][$item->getIdLounge()] = array(
'rankQuote' => $item->getRankQuote(),
'idLounge' => $item->getIdLounge(),
'loungeName' => $item->getLoungeName(),
'loungeImportantDescription' => $item->getImportantDescription(),
'loungeImportantDescGeneralText' => $item->getImportantDescGeneralText(),
'loungeImportantDescSchedules' => $item->getImportantDescSchedules(),
'loungeImportantDescParking' => $item->getImportantDescParking(),
'loungeDocContract' => empty($loungeContract) ? '': $loungeContract->getContractualDocument(),
'loungeDocBookingData' => empty($loungeContract) ? '': $loungeContract->getBookingData(),
'loungeDocDateAt' => empty($loungeContract) ? '': $loungeContract->getDateAt(),
'loungeDocClientProxy' => empty($loungeContract) ? '': $loungeContract->getClientProxy(),
'loungeDocClientJob' => empty($loungeContract) ? '': $loungeContract->getClientJob(),
'loungeDocFullContract' => empty($dataContract['fullContract']) ? '': $dataContract['fullContract'],
);
}
}
}
// FIN: Se forma el arreglo para las salas dia a dia
$numeroItems = sizeof($arrayLoungesByDay);
$data = $this->CalculosTotalesEditSimple($reserva->getId());
$client = $em->getRepository(Client::class)->findOneById($reserva->getClient());
if (!empty($client)){ $clientId = $client->getId(); } else { $clientId = 0; }
$clients = $em->getRepository(Client::class)->findAll();
/* CONSULTAMOS PARA SUMAR */
$parameters = array( 'tags' => 'CATERING', 'company' => 'HIGO & TRIGO, S.L.', );
$dql = 'SELECT p
FROM App\Entity\Supplier p
WHERE (p.tags LIKE :tags) AND (p.company <> :company)
ORDER BY p.company ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$caterings = $query->getResult();
// Agregamos el catering de Higo & Trigo de primero
$catHigoTrigo = $em->getRepository(Supplier::class)->findOneById(4765);
array_unshift($caterings, $catHigoTrigo);
$userCreatedBy = $em->getRepository(User::class)->findOneById($reserva->getCreatedBy());
$createdBy = $userCreatedBy->getName().' '.$userCreatedBy->getLastName();
$parameters = array();
$dql = 'SELECT p
FROM GreenPatioBundle:ReservationLoungeDetails p
ORDER BY p.rankLounge ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$loungesPre = $query->getResult();
$loungesNames = $em->getRepository(ReservationLoungeDetails::class)->findAll();
$listSupplier = $em->getRepository(Supplier::class)->findAll();
$em = $this->getDoctrine()->getManager();
$invoiced = $em->getRepository(ReservationInvoice::class)->findByReservationId($id);
$invoicedRec = $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($id);
foreach ($invoicedRec as $item){ array_push($invoiced, $item); }
$invoicedCvr = $em->getRepository(CvrReservationInvoice::class)->findByReservationId($id);
$invoicedLine = empty($invoicedCvr) ? 'GP' : 'CVR';
foreach ($invoicedCvr as $item){ array_push($invoiced, $item); }
$invoicedCvrRec = $em->getRepository(CvrReservationInvoiceRec::class)->findByReservationId($id);
foreach ($invoicedCvrRec as $item){ array_push($invoiced, $item); }
$sumatoriaTotalNet = 0; $sumatoriaTotalVat = 0; $sumatoriaTotal = 0;
$resultados = array( 'totalNeto' => 0, 'vat' => 0, 'total' => 0, );
foreach ($invoiced as $idArray => $item){
$reserva = $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
$invoiced[$idArray]->setNumber($reserva->getTitle());
$client = $em->getRepository(Client::class)->findOneById($reserva->getClient());
if(!empty($client)){ $invoiced[$idArray]->setPrefix($client->getName()); } else { $invoiced[$idArray]->setPrefix(''); }
if ($item->getType() == 'Invoice Deposit'){
// INICIO: Verificamos el uso de la factura de deposito dentro de una factura, en este caso se usa el valor absoluto del balance para evitar la resta doble
$paymentItem = $em->getRepository(ReservationPaymentsClient::class)->findOneByInvoiceId($item->getId());
if (!empty($paymentItem)){
$invoiceElementItem = $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($paymentItem->getId());
if (!empty($invoiceElementItem)) {
// Solo nos interesa evaluar las facturas y no las facturas de deposito
$invoiceOfItem = $em->getRepository(ReservationInvoice::class)->findOneById($invoiceElementItem->getInvoiceId());
if (!empty($invoiceOfItem)) { if ($invoiceOfItem->getType() == 'Invoice') { $invoiced[$idArray]->setBalance(0); } }
}
}
// FIN: Verificamos el uso de la factura de deposito dentro de una factura, en este caso se usa el valor absoluto del balance para evitar la resta doble
$invoicedDepositItems = $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($item->getMaster());
foreach ($invoicedDepositItems as $itemDep){
$invoiced[$idArray]->setTotalNet($invoiced[$idArray]->getTotalNet() + $itemDep->getAmount());
$invoiced[$idArray]->setVat($invoiced[$idArray]->getVat() + (($itemDep->getAmount() * $itemDep->getIva())/100));
$invoiced[$idArray]->setTotal($invoiced[$idArray]->getTotal() + ($itemDep->getAmount() + (($itemDep->getAmount() * $itemDep->getIva())/100)));
}
}
// Valores Netos
if ($item->getType()=='Invoice'){
$sumatoriaTotalNet = $sumatoriaTotalNet + $item->getTotalNet();
} else {
if ($item->getType()=='Invoice Deposit'){
//Factura de deposito
$sumatoriaTotalNet = $sumatoriaTotalNet - 0; //$item->getTotalNet(); // Las facturas de deposito no deben computar en este calculo
} else {
if ($item->getType()=='Invoice Deposit Rec'){
//Factura de Deposito rectificativa
$sumatoriaTotalNet = $sumatoriaTotalNet - 0;
} else {
//Factura rectificativa
$sumatoriaTotalNet = $sumatoriaTotalNet + $item->getTotalNet(); // Se han llenado de datos negativos las rectificativas, solo es necesario sumar
}
}
}
//Valores Iva
if ($item->getType()=='Invoice') {
$sumatoriaTotalVat = $sumatoriaTotalVat + $item->getVat();
} else {
if ($item->getType()=='Invoice Deposit'){
//Factura de deposito
$sumatoriaTotalVat = $sumatoriaTotalVat - 0; //$item->getVat(); // Las facturas de deposito no deben computar en este calculo
} else {
if ($item->getType()=='Invoice Deposit Rec'){
//Factura de Deposito rectificativa
$sumatoriaTotalNet = $sumatoriaTotalNet - 0;
} else {
//Factura rectificativa
$sumatoriaTotalVat = $sumatoriaTotalVat + $item->getVat(); // Se han llenado de datos negativos las rectificativas, solo es necesario sumar
}
}
}
if (($item->getType()=='Invoice Deposit') or ($item->getType()=='Invoice Deposit Rec')) {
$sumatoriaTotal = $sumatoriaTotal + 0; // Las facturas de deposito o de deposito rectificativas no deben computar en este calculo
} else {
$sumatoriaTotal = $sumatoriaTotal + $item->getTotal();
}
$resultados = array( 'totalNeto' => $sumatoriaTotalNet, 'vat' => $sumatoriaTotalVat, 'total' => $sumatoriaTotal, );
}
$paymentsAll = $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
// Verificamos pagos aun sin facturar
$paymentNotIvoiced = array();
foreach ($paymentsAll as $item){
$isInvoiced = $em->getRepository(ReservationInvoiceItems::class)->findBy(array('reservationId' => $id, 'payControlId' => $item->getId()));
if (empty($isInvoiced)){ array_push($paymentNotIvoiced, $item); }
}
//Buscamos los agentes y seleccionamos por defecto el usuario logeado
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$parameters = array( 'clientId' => $clientId, );
$dql = 'SELECT p
FROM App:ClientContact p
WHERE p.clientId = :clientId
ORDER BY p.name ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$clientsContact = $query->getResult();
// Fecha de notificacion en caso de ser un bloqueo
$reservationMailAlertClient = $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($id);
$nextMailAlert = null;
if (!empty($reservationMailAlertClient)){
if (!($reservationMailAlertClient->getAlertSended())){
// La proxima fecha es la de la alerta
$nextMailAlert = $reservationMailAlertClient->getAlertDateTime();
} else {
if (!($reservationMailAlertClient->getCancelSended())){
// La proxima fecha es la de la cancelacion (paso a cotización)
$nextMailAlert = $reservationMailAlertClient->getCancelDateTime();
}
}
}
$parameters = array( 'status' => 1, );
$dql = 'SELECT c
FROM App\Entity\User c
WHERE c.status = :status
ORDER BY c.name ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$allUsersActive = $query->getResult();
//Agregamos los FreeLance
$freeLances = $em->getRepository(ExternalUser::class)->findAll();
foreach ($freeLances as $item){
$item->setTeam(($item->getId() * (-1)));
$allUsersActive[] = $item;
}
// Buscamos todos los servicios y los separmos por facturados y no facturados
$datax = $this->benefitForReservation($id);
// Se quitan los clientes que no son de Green Patio
$parameters = array();
$dql = 'SELECT p
FROM App:Client p
WHERE p.isClientGreenPatio = TRUE
ORDER BY p.name ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$clients = $query->getResult();
$depositsAll = $em->getRepository(ReservationDeposit::class)->findByReservationId($id);
$confirmable = $this->laReservaEsConfirmable($id);
$cotizable = $this->laReservaEsCotizable($id);
$htFile = in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $em->getRepository(HtFile::class)->findOneByReservation($reserva) : null;
$aveFile = in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $em->getRepository(AveFiles::class)->findOneByReservation($reserva) : null;
if ($reserva) { $urlCotizacion = "https://cotizacion.greenpatio.es/index.php?token=".$reserva->getToken(); }
$viewContract = false;
//Generamos el arreglo de contratos
if (in_array($reserva->getStatus(), ['Confirmed', 'Invoiced'])) { $viewContract = true; }
return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-simple.html.twig',
array(
'form' => $form1->createView(),
'form2' => $form2->createView(),
'form3' => $form3->createView(),
'id' => $id,
'clients' => $clients,
'clientId' => $clientId,
'caterings' => $caterings,
'loungesPre' => $loungesPre,
'loungesNames' => $loungesNames,
'arrayLoungesInFile' => $arrayLoungesInFile,
'facturas' => $invoiced,
'numeroItems' => $numeroItems,
'arrayLoungesByDay' => $arrayLoungesByDay,
'totales_global_con_iva' => $data['totales_global_con_iva'],
'totales_global_iva' => $data['totales_global_iva'],
'totales_global_neto' => $data['totales_global_neto'],
'totales_global_servicios_con_iva' => $data['totales_global_servicios_con_iva'],
'totales_global_servicios_neto' => $data['totales_global_servicios_neto'],
'totales_global_servicios_iva' => $data['totales_global_servicios_iva'],
'sumatoria_totales_global_con_iva' => $data['sumatoria_totales_global_con_iva'],
'sumatoria_totales_global_neto' => $data['sumatoria_totales_global_neto'],
'sumatoria_totales_global_iva' => $data['sumatoria_totales_global_iva'],
'reserva' => $reserva,
'createdBy' => $createdBy,
'arraySalas' => null,
'lounges' => $lounges,
'salasReserva' => $lounges,
'periods' => null,
'services' => $services,
'loungesNumbers' => sizeof($lounges),
'listSupplier' => $listSupplier,
'resultados' => $resultados,
'paymentsAll' => $paymentsAll,
'paymentNotIvoiced' => $paymentNotIvoiced,
'allUsersActive' => $allUsersActive,
'userLog' => $user_id,
'clientsContact' => $clientsContact,
'nextMailAlert' => $nextMailAlert,
'benefit' => $datax['benefit'],
'percBenefit' => $datax['percBenefit'],
'payedLounges' => $datax['payedLounges'],
'payedServices' => $datax['payedServices'],
'unPayedServices' => $datax['unPayedServices'],
'depositsAll' => $depositsAll,
'confirmable' => $confirmable,
'cotizable' => $cotizable,
'invoicedLine' => $invoicedLine,
'htFile' => $htFile,
'aveFile' => $aveFile,
'urlCotizacion' => $urlCotizacion,
'viewContract' => $viewContract,
));
}
private function createReservationLoungeCreateForm(ReservationLounge $entity)
{
$form = $this->createForm(ReservationLoungeType::class, $entity, array(
'action' => $this->generateUrl('reservations_greenpatio_create_simple_lounge',
array(
'id' => $entity->getIdReservation(),
)
),
'method' => 'POST'
));
return $form;
}
private function createReservationLoungeMonDesCreateForm(ReservationLounge $entity)
{
$form = $this->createForm(ReservationLoungeType::class, $entity, array(
'action' => $this->generateUrl('reservations_greenpatio_create_simple_lounge_mondes',
array(
'id' => $entity->getIdReservation(),
)
),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/contract/{id}", name="reservations_contract")
*/
public function goContractAction($id, EntityManagerInterface $em, Request $request){
$reservationLounge = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
$arrayLounges =[];
//Buscamos el modelo de contrato mas reciente de las salas de la reserva
foreach ($reservationLounge as $item){ $arrayLounges[$item->getIdLounge()] = $item->getIdLounge(); }
if (!empty($arrayLounges)) { $parameters['stringLounges'] = $arrayLounges; } else { $parameters['stringLounges'] = []; }
$dql = 'SELECT p
FROM App:DocContractModel p
WHERE p.modelId IN (:stringLounges)
ORDER BY p.updatedAt DESC';
$query = $em->createQuery($dql)->setParameter('stringLounges', $parameters['stringLounges']);
$contractModel = $query->getResult();
if(!empty($contractModel)){ $loungeId = $contractModel[0]->getModelId(); } else { $loungeId = 0; }
$dataContract = $this->docContractService->contractReservation($id,$loungeId);
return $this->render('MDS/GreenPatioBundle/reservations/print-contract-gp.html.twig',
array(
'dataContract' => $dataContract['fullContract'],
));
}
/**
* @Route("/updateloungegrid", name="reservations_greenpatio_updateloungegrid")
*/
public function updateLoungeGridAction(EntityManagerInterface $em, Request $request)
{
$loungeGrid = $request->request->get('lounge');
$reservationGlobalLounge = $request->request->get('reservation_global_lounge');
$id = $request->request->get('reservationId'); //aqui se guardara el ID de la reserva
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
// Movemos las fechas de la reserva para que tomen los valosres de las salas
$reserva->setDateStart(new DateTime('2999-01-01'));
$reserva->setDateEnd(new DateTime('2000-01-01'));
$now = new DateTime('now');
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
foreach ($loungeGrid as $idreservationlounge => $loungeData) {
foreach ($loungeData as $dia => $items) {
foreach ($items as $name => $item) {
$reservationLounge = $em->getRepository(ReservationLoungeSimple::class)->findOneById($idreservationlounge);
if (empty($reservationLounge)) { $reservationLounge = new ReservationLoungeSimple(); }
// Autocompletacion HH:mm en Start
switch (strlen($item['dateHourMinStart'])) {
case 0:
// Vacio
$hourStart = '00';
$minStart = '00';
$hourMinStart = '00:00';
break;
case 1:
// H -> 0H:00
if (is_numeric($item['dateHourMinStart'])) {
$hourStart = '0' . $item['dateHourMinStart'];
$minStart = '00';
$hourMinStart = $hourStart . ':' . $minStart;
} else {
$hourStart = '00';
$minStart = '00';
$hourMinStart = '00:00';
}
break;
case 2:
// HH -> HH:00
if (is_numeric($item['dateHourMinStart'])) {
$hourStart = $item['dateHourMinStart'];
$minStart = '00';
$hourMinStart = $hourStart . ':' . $minStart;
} else {
$hourStart = '00';
$minStart = '00';
$hourMinStart = '00:00';
}
break;
case 3:
// Hmm -> 0H:mm
if (is_numeric($item['dateHourMinStart'])) {
$hourStart = '0' . substr($item['dateHourMinStart'], 0, 1);
$minStart = substr($item['dateHourMinStart'], 1, 2);
$hourMinStart = $hourStart . ':' . $minStart;
} else {
$hourStart = '00';
$minStart = '00';
$hourMinStart = '00:00';
}
break;
case 4:
// HHmm -> HH:mm
if (is_numeric($item['dateHourMinStart'])) {
$hourStart = substr($item['dateHourMinStart'], 0, 2);
$minStart = substr($item['dateHourMinStart'], 2, 2);
$hourMinStart = $hourStart . ':' . $minStart;
} else {
$hourStart = '00';
$minStart = '00';
$hourMinStart = '00:00';
}
break;
case 5:
// HH:mm
if (is_numeric(substr($item['dateHourMinStart'], 0, 2)) and (substr($item['dateHourMinStart'], 2, 1) == ':') and is_numeric(substr($item['dateHourMinStart'], 0, 2))) {
$hourStart = substr($item['dateHourMinStart'], 0, 2);
$minStart = substr($item['dateHourMinStart'], 3, 2);
$hourMinStart = $hourStart . ':' . $minStart;
} else {
$hourStart = '00';
$minStart = '00';
$hourMinStart = '00:00';
}
break;
default:
// XXXXyyy
$hourStart = '00';
$minStart = '00';
$hourMinStart = '00:00';
break;
}
// Autocompletacion HH:mm en End
switch (strlen($item['dateHourMinEnd'])) {
case 0:
// Vacio
$hourEnd = '00';
$minEnd = '00';
$hourMinEnd = '00:00';
break;
case 1:
// H -> 0H:00
if (is_numeric($item['dateHourMinEnd'])) {
$hourEnd = '0' . $item['dateHourMinEnd'];
$minEnd = '00';
$hourMinEnd = $hourEnd . ':' . $minEnd;
} else {
$hourEnd = '00';
$minEnd = '00';
$hourMinEnd = '00:00';
}
break;
case 2:
// HH -> HH:00
if (is_numeric($item['dateHourMinEnd'])) {
$hourEnd = $item['dateHourMinEnd'];
$minEnd = '00';
$hourMinEnd = $hourEnd . ':' . $minEnd;
} else {
$hourEnd = '00';
$minEnd = '00';
$hourMinEnd = '00:00';
}
break;
case 3:
// Hmm -> 0H:mm
if (is_numeric($item['dateHourMinEnd'])) {
$hourEnd = '0' . substr($item['dateHourMinEnd'], 0, 1);
$minEnd = substr($item['dateHourMinEnd'], 1, 2);
$hourMinEnd = $hourEnd . ':' . $minEnd;
} else {
$hourEnd = '00';
$minEnd = '00';
$hourMinEnd = '00:00';
}
break;
case 4:
// HHmm -> HH:mm
if (is_numeric($item['dateHourMinEnd'])) {
$hourEnd = substr($item['dateHourMinEnd'], 0, 2);
$minEnd = substr($item['dateHourMinEnd'], 2, 2);
$hourMinEnd = $hourEnd . ':' . $minEnd;
} else {
$hourEnd = '00';
$minEnd = '00';
$hourMinEnd = '00:00';
}
break;
case 5:
// HH:mm
if (is_numeric(substr($item['dateHourMinEnd'], 0, 2)) and (substr($item['dateHourMinEnd'], 2, 1) == ':') and is_numeric(substr($item['dateHourMinEnd'], 0, 2))) {
$hourEnd = substr($item['dateHourMinEnd'], 0, 2);
$minEnd = substr($item['dateHourMinEnd'], 3, 2);
$hourMinEnd = $hourEnd . ':' . $minEnd;
} else {
$hourEnd = '00';
$minEnd = '00';
$hourMinEnd = '00:00';
}
break;
default:
// XXXXyyy
$hourEnd = '00';
$minEnd = '00';
$hourMinEnd = '00:00';
break;
}
$dateStart = $item['newDate'] . ' ' . $hourMinStart;
$dateEnd = $item['newDate'] . ' ' . $hourMinEnd;
//dd($loungeData, $items, $item);
// $name = $item['name'];
$loungeDetails = $em->getRepository(ReservationLoungeDetails::class)->findOneByName($name);
$price = $item['price'];
$ivaNew = $item['iva'];
$pax = 0;
$type = null;
if (array_key_exists('iva', $item)) {
if (empty($item['iva']) && !is_numeric($item['iva'])) {
$ivaNew = 21;
$this->addFlash('mensajereservationerror', 'Revisa el IVA de la sala: '.$reservationLounge->getLoungeName());
} else {
$ivaNew = $item['iva'];
}
}
if (isset($item['pax'])) { $pax = $item['pax']; if (empty($pax)){$pax = 0;} } else { $type = $item['type']; }
$reservationLounge->setIdReservation($id);
if ((!empty($loungeDetails)) and (isset($reservationGlobalLounge[$loungeDetails->getId()]))){
$reservationLounge->setIdLounge($loungeDetails->getId());
//Actualizamos el Resumen Descriptivo
$reservationLounge->setImportantDescription($reservationGlobalLounge[$loungeDetails->getId()]['importantDescription']);
$reservationLounge->setImportantDescGeneralText($reservationGlobalLounge[$loungeDetails->getId()]['importantDescGeneralText']);
$reservationLounge->setImportantDescSchedules($reservationGlobalLounge[$loungeDetails->getId()]['importantDescSchedules']);
$reservationLounge->setImportantDescParking($reservationGlobalLounge[$loungeDetails->getId()]['importantDescParking']);
} else {
// No se encontro el elemento por Nombre (Se ha modificado el campo nombre de la sala, probablemente por ser una DEVOLUCION)
$reservationLounge->setIdLounge(0);
}
$reservationLounge->setDateStart(new DateTime($dateStart));
$reservationLounge->setDateEnd(new DateTime($dateEnd));
$reservationLounge->setType($type);
$reservationLounge->setPax($pax);
$reservationLounge->setServicePrice($price);
$reservationLounge->setIva($ivaNew);
$reservationLounge->setOpIva(1);
$reservationLounge->setLoungeName($name);
$reservationLounge->setHourStart($hourStart);
$reservationLounge->setMinStart($minStart);
$reservationLounge->setHourEnd($hourEnd);
$reservationLounge->setMinEnd($minEnd);
$reservationLounge->setUpdatedBy($user_id);
$reservationLounge->setCreatedBy($user_id);
try {
$em->persist($reservationLounge);
$em->flush();
// $event = 'The Item has been updated.';
$successMessage = 'The Item has been updated.';
// $successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e) {
$event = 'An error occurred: ' . $e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
// INICIO: Verificamos si es necesario actualizar las fechas de la reserva
$boolReserva = false;
if ($reservationLounge->getDateStart() < $reserva->getDateStart()){
$reserva->setDateStart($reservationLounge->getDateStart());
$boolReserva = true;
}
if ($reserva->getDateEnd() < $reservationLounge->getDateEnd()){
$reserva->setDateEnd($reservationLounge->getDateEnd());
$boolReserva = true;
}
if ($boolReserva){
$em->persist($reserva);
$em->flush();
}
// FIN: Verificamos si es necesario actualizar las fechas de la reserva
// INICIO: Verificamos si es necesario actualizar el contrato de la reserva
$loungeContract = $em->getRepository(DocContract::class)->findBy(array('companyId' => 7, 'fileId' => $id, 'modelId' => $reservationLounge->getIdLounge()));
if (empty($loungeContract)){
$loungeContract = new DocContract();
$loungeContract->setCompanyId(7);
$loungeContract->setModelId($reservationLounge->getIdLounge());
if (!empty($reserva->getClient())){ $loungeContract->setClientId($reserva->getClient()); }
$loungeContract->setFileId($reserva->getId());
$loungeContract->setCreatedId($user_id);
$loungeContract->setCreatedAt($now);
} else {
$loungeContract = $loungeContract[0];
}
if ((isset($reservationGlobalLounge[$loungeDetails->getId()]))) {
$loungeContract->setContractualDocument($reservationGlobalLounge[$loungeDetails->getId()]['contract']);
$loungeContract->setBookingData($reservationGlobalLounge[$loungeDetails->getId()]['booking']);
$loungeContract->setDateAt(new DateTime($reservationGlobalLounge[$loungeDetails->getId()]['othersDateContract']));
$loungeContract->setClientProxy($reservationGlobalLounge[$loungeDetails->getId()]['othersClientProxy']);
$loungeContract->setClientJob($reservationGlobalLounge[$loungeDetails->getId()]['othersClientJob']);
$loungeContract->setUpdatedId($user_id);
$loungeContract->setUpdatedAt($now);
}
if (in_array($reserva->getStatus(), ['Confirmed', 'Invoiced'])) { // Solo hacer el contrato si est confirmado o facturado
$em->persist($loungeContract);
$em->flush();
}
}
}
}
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id, 'token' => null, '_fragment' => 'btn_quotes' ));
}
/**
* @Route("/deleteitemservice/{idService}/{idReservation}", name="reservations_greenpatio_deleteitemservice")
*/
public function deleteItemServiceAction($idService, $idReservation, EntityManagerInterface $em, Request $request)
{
$service = $em->getRepository(ReservationService::class)->findOneById($idService);
$em->remove($service);
$em->flush();
$event = 'The Item has been deleted.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $idReservation, 'token' => null ));
}
/**
* @Route("/updateservicegrid/{id}", name="reservations_greenpatio_updateservicegrid")
*/
public function updateServiceGridAction($id, EntityManagerInterface $em, Request $request)
{
$services = $request->request->get('services');
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
foreach ($services as $idService => $service) {
$serviceOriginal = $em->getRepository(ReservationService::class)->findOneById($idService);
if (empty($serviceOriginal)){ $serviceOriginal = new ReservationService(); }
$serviceOriginal->setSupplierId($service['supplier']);
if ($serviceOriginal->getServiceCatId() == 15){
// Asistencia
if (array_key_exists('agent',$service)){
if (!empty($service['agent']) and ($service['agent'] > 0)){
$userx = $em->getRepository("App\Entity\User")->findOneById($service['agent']);
$serviceOriginal->setName($userx->getName().' '.$userx->getLastName());
$serviceOriginal->setAssistantId($service['agent']);
} else {
//Asistencia de un FreeLance
if (!empty($service['agent']) and ($service['agent'] < 0)){
// FreeLance registrado en el sistema
$idUserFree = ($service['agent'] * (-1));
$userx = $em->getRepository(ExternalUser::class)->findOneById($idUserFree);
$serviceOriginal->setName($userx->getName().' '.$userx->getLastName());
$serviceOriginal->setAssistantId($service['agent']);
} else {
$serviceOriginal->setName($service['name']);
$serviceOriginal->setAssistantId(null);
}
}
}
} else {
$serviceOriginal->setName($service['name']);
}
$price = $service['price'];
if ($price === null) {
$priceToSet = 0;
} else {
$price = str_replace('.', '', $price);
$price = str_replace(',', '.', $price);
if (is_numeric($price)) {
$priceToSet = $price;
} else {
$priceToSet = $serviceOriginal->getPrice();
}
}
$serviceOriginal->setPrice($priceToSet);
$serviceOriginal->setCurrency($service['currency']);
$serviceOriginal->setUnits($service['units']);
$serviceOriginal->setPax($service['pax']);
$serviceOriginal->setOpCommission($service['opCommission']);
$commission = $service['commission'];
if ($commission === null) {
$commissionToSet = 0;
} else {
$commission = str_replace(',', '.', $commission);
if (is_numeric($commission)) {
$commissionToSet = $commission;
} else {
$commissionToSet = $serviceOriginal->getCommission();
}
}
$serviceOriginal->setCommission($commissionToSet);
$serviceOriginal->setOpOver($service['opOver']);
$over = $service['over'];
if ($over === null) {
$overToSet = 0;
} else {
$over = str_replace('.', '', $over);
$over = str_replace(',', '.', $over);
if (is_numeric($over)) {
$overToSet = $over;
} else {
$overToSet = $serviceOriginal->getOver();
}
}
$serviceOriginal->setOver($overToSet);
$serviceOriginal->setOpIva($service['opIva']);
$serviceOriginal->setIva($service['iva']);
if (array_key_exists('toinvoice',$service)){ $serviceOriginal->setToinvoice(true); } else { $serviceOriginal->setToinvoice(false); }
if (array_key_exists('viewinfo',$service)){ $serviceOriginal->setViewInfo(true); } else { $serviceOriginal->setViewInfo(false); }
$serviceOriginal->setDateInAt(new DateTime($service['dateInAt']. ' ' . $service['start']));
$serviceOriginal->setDateOutAt(new DateTime($service['dateOutAt']. ' ' . $service['end']));
$serviceOriginal->setUpdatedId($user_id);
$serviceOriginal->setUpdatedAt(new DateTime('now'));
try{
$em->persist($serviceOriginal);
$em->flush();
$event = 'The Item has been updated.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
if(($serviceOriginal->getServiceCatId()==11) and ($serviceOriginal->getSupplierId()==4765)){
//Es un Catering de Higo&Trigo
$reserva->setCateringName('HIGO & TRIGO, S.L.');
$em->persist($reserva);
$em->flush();
}
}
// Sincronización con HT
if (!empty($reserva)) {
// Rafa indico que siempre se sincronice al abrir un expediente de GP
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
// Si no se ha creado aun el expediente de HT debemos crearlo
$htFile = $em->getRepository(HtFile::class)->findByReservation($reserva);
if (empty($htFile)) {
return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,));
}
}
}
}
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id, 'token' => null, '_fragment' => 'btn_srv' ));
}
/**
* @Route("/addloungegeneral", name="reservations_greenpatio_add_lounge_general")
*/
public function addLoungeGeneralAction(EntityManagerInterface $em, Request $request)
{
$lounge = $request->request->get('lounge_price');
$yaExisteLounge = $em->getRepository(ReservationLoungeDetails::class)->findOneByName($lounge['name']);
if (!empty($yaExisteLounge)){
//Si ya existe la sala con ese nombre se envia a la pantalla de edicion de la sala en cuestion
$id = $yaExisteLounge->getId();
return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $id ));
}
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$loungeNew = new ReservationLoungeDetails();
$loungeNew->setName($lounge['name']);
$loungeNew->setMeters($lounge['meters']);
$loungeNew->setLength($lounge['length']);
$loungeNew->setWidth($lounge['width']);
$loungeNew->setHeight($lounge['height']);
$loungeNew->setCapSchool($lounge['capschool']);
$loungeNew->setCapTheater ($lounge['captheater']);
$loungeNew->setCapCocktail($lounge['capcocktail']);
$loungeNew->setCapBanquet ($lounge['capbanquet']);
$loungeNew->setCapImperial($lounge['capimperial']);
$loungeNew->setCreatedId($user_id);
$loungeNew->setCreatedAt($now);
$loungeNew->setUpdatedId($user_id);
$loungeNew->setUpdatedAt($now);
try {
$em->persist($loungeNew);
$em->flush();
$event = 'The Item has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e) {
$event = 'An error occurred: ' . $e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
if (!empty($loungeNew->getId())){
// Esto pertenece a otra entidad
$loungeNewDescription = new ReservationLoungeDescription();
$loungeNewDescription->setLoungeId($loungeNew->getId());
$loungeNewDescription->setLanguage($lounge['language']);
$loungeNewDescription->setDescription($lounge['description']);
$loungeNewDescription->setCreatedId($user_id);
$loungeNewDescription->setCreatedAt($now);
$loungeNewDescription->setUpdatedId($user_id);
$loungeNewDescription->setUpdatedAt($now);
try {
$em->persist($loungeNewDescription);
$em->flush();
$event = 'The Item has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e) {
$event = 'An error occurred: ' . $e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $loungeNew->getId() ));
}
return $this->redirectToRoute('reservations_greenpatio_edit_general');
}
/**
* @Route("/addloungedescription/{id}", name="reservations_greenpatio_add_lounge_description")
*/
public function addLoungeDescriptionAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$loungeDescriptoin = $request->request->get('lounge_description');
// $loungeDetail = $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
// $loungeDetail->setImportantDescription($loungeDescriptoin['importantDescription']);
//
// $em->persist($loungeDetail);
// $em->flush();
if (empty($loungeDescriptoin['language']) or empty($loungeDescriptoin['description'])){ return $this->redirectToRoute('reservations_lounge_details', array('id' => $id)); }
$newLoungeDescription = new reservationLoungeDescription();
$newLoungeDescription->setLoungeId($id);
$newLoungeDescription->setLanguage($loungeDescriptoin['language']);
$newLoungeDescription->setDescription($loungeDescriptoin['description']);
$newLoungeDescription->setCreatedId($user_id);
$newLoungeDescription->setUpdatedId($user_id);
$newLoungeDescription->setCreatedAt($now);
$newLoungeDescription->setUpdatedAt($now);
try {
$em->persist($newLoungeDescription);
$em->flush();
$event = 'The Item has been created.';
// $successMessage = $this->translator->trans($event);
$successMessage = 'El elemento ha sido creado.';
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e) {
$event = 'An error occurred: ' . $e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
}
/**
* @Route("/addwebinfo/{id}", name="reservations_greenpatio_add_web_info")
* Actualiza la información de la sala a presentar en la web, que esta almacenada por defecto
* Actualiza la información del contrato
*/
public function addLoungeWebInfoAction($id, EntityManagerInterface $em, Request $request)
{
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$loungeDescriptoin = $request->request->get('lounge_description');
$loungeDetail = $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
$loungeDetail->setImportantDescription($loungeDescriptoin['importantDescription']);
$loungeDetail->setImportantDescGeneralText($loungeDescriptoin['importantDescGeneralText']);
$loungeDetail->setImportantDescSchedules($loungeDescriptoin['importantDescSchedules']);
$loungeDetail->setImportantDescParking($loungeDescriptoin['importantDescParking']);
$loungeDetail->setUpdatedAt($now);
$loungeDetail->setUpdatedId($user_id);
$em->persist($loungeDetail);
$em->flush();
$loungeContract = $em->getRepository(DocContractModel::class)->findOneBy(array('modelId' => $id, 'companyId' => 7));
if (empty($loungeContract)){
$loungeContract = new DocContractModel();
$loungeContract->setModelId($id);
$loungeContract->setCompanyId(7); // CompanyId de Green Patio: 7
$loungeContract->setCreatedAt($now);
$loungeContract->setCreatedId($user_id);
}
$loungeContract->setContractualDocument($loungeDescriptoin['contractualDocument']);
$loungeContract->setUpdatedId($user_id);
$loungeContract->setUpdatedAt($now);
$em->persist($loungeContract);
$em->flush();
return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
}
/**
* @Route("/updatedescritiongrid/{id}", name="reservations_greenpatio_updatedescriptiongrid")
*/
public function updateDescriptionGridAction($id, Request $request)
{
$descriptions = $request->request->get('description');
$em = $this->getDoctrine()->getManager();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
foreach ($descriptions as $idDesc => $description) {
$descriptionOriginal = $em->getRepository(ReservationLoungeDescription::class)->findOneById($idDesc);
$descriptionOriginal->setLanguage($description['language']);
$descriptionOriginal->setDescription($description['text']);
$descriptionOriginal->setUpdatedId($user_id);
$descriptionOriginal->setUpdatedAt(new DateTime('now'));
try{
$em->persist($descriptionOriginal);
$em->flush();
$event = 'The Item has been updated.';
// $successMessage = $this->translator->trans($event);
$successMessage = 'El elemento ha sido actualizado.';
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
}
return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $id ));
}
/**
* @Route("/addloungepicture/{id}", name="reservations_greenpatio_add_lounge_picture")
*/
public function addLoungePictureAction($id, EntityManagerInterface $em, Request $request) //, LoggerInterface $logger)
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$picturefiles = $request->files->all();
$loungeId = $id;
$imagenes = $picturefiles['loungepicturegallery'];
$data = $loungeId;
if(!empty($imagenes['image1']) || !empty($imagenes['image2']) || !empty($imagenes['image3']) || !empty($imagenes['image4']) || !empty($imagenes['image5'])){
$num = 0;
foreach($imagenes as $img){
$num = 1 + $num;
if (!is_null($img)){ $data = $this->CargarImgGalleryAction($loungeId, $img, $num, $request); } //, $logger);
}
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajegalleryerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
}
protected function CargarImgGalleryAction($loungeId, $image, $num, Request $request) //, LoggerInterface $logger)
{
$gallery = new ReservationLoungePicture();
$gallery->setLoungeId($loungeId);
$gallery->setCreatedAt(new DateTime('now'));
$gallery->setUpdatedAt(new DateTime('now'));
$gallery->setTitle(null);
if ($num == -1){$gallery->setTitle('Blueprint');}
if ($num == 'TEATRO'){$gallery->setTitle('Teatro');}
if ($num == 'COCTEL'){$gallery->setTitle('Coctel');}
if ($num == 'ESCUELA'){$gallery->setTitle('Escuela');}
$id = $loungeId;
/* Carga de imagenes */
$calidad = "90";
$calidadpng = "9";
$imageName = md5(rand() * time());
$camino = "assets/images/greenpatio/lounges/";
$extension = $image->guessExtension();
$entrada = 'si';
$image_id = $imageName.'.'.$extension;
$image_temp = $id.'-'.$imageName.'.'.$extension;
$image->move($camino, $image_temp);
// Nombres image
$s="small-";
$m="medium-";
$l="large-";
########################
# Copiar imagen 300 x Altura
########################
$datos = getimagesize($camino.$image_temp);
$anchura = "300";
$altura = "190";
$thumb = imagecreatetruecolor($anchura,$altura);
switch ($extension) {
case 'jpeg':
$img = imagecreatefromjpeg($camino.$image_temp);
imagecopyresampled ($thumb, $img, 0, 0, 0, 0, $anchura, $altura, $datos[0], $datos[1]);
imagejpeg($thumb,$camino.$s.$image_id, $calidad);
break;
case 'png':
$img = imagecreatefrompng($camino.$image_temp);
imagecopyresampled ($thumb, $img, 0, 0, 0, 0, $anchura, $altura, $datos[0], $datos[1]);
imagepng($thumb,$camino.$s.$image_id, $calidadpng);
break;
case 'gif':
$img = imagecreatefromgif($camino.$image_temp);
imagecopyresampled ($thumb, $img, 0, 0, 0, 0, $anchura, $altura, $datos[0], $datos[1]);
imagegif($thumb,$camino.$s.$image_id);
break;
}
########################
# Copiar imagen 600 x Altura
########################
$datos2 = getimagesize($camino.$image_temp);
$anchura2="600";
$ratio2 = ($datos2[0] / $anchura2);
$altura2 = round($datos2[1] / $ratio2);
$thumb2 = imagecreatetruecolor($anchura2,$altura2);
switch ($extension) {
case 'jpeg':
$img2 = imagecreatefromjpeg($camino.$image_temp);
imagecopyresampled ($thumb2, $img2, 0, 0, 0, 0, $anchura2, $altura2, $datos2[0], $datos2[1]);
imagejpeg($thumb2,$camino.$m.$image_id, $calidad);
break;
case 'png':
$img2 = imagecreatefrompng($camino.$image_temp);
imagecopyresampled ($thumb2, $img2, 0, 0, 0, 0, $anchura2, $altura2, $datos2[0], $datos2[1]);
imagepng($thumb2,$camino.$m.$image_id, $calidadpng);
break;
case 'gif':
$img2 = imagecreatefromgif($camino.$image_temp);
imagecopyresampled ($thumb2, $img2, 0, 0, 0, 0, $anchura2, $altura2, $datos2[0], $datos2[1]);
imagegif($thumb2,$camino.$m.$image_id);
break;
}
########################
# Copiar imagen 1600 x Altura
########################
$datos3 = getimagesize($camino.$image_temp);
$anchura3="1600";
$ratio3 = ($datos3[0] / $anchura3);
$altura3 = round($datos3[1] / $ratio3);
$thumb3 = imagecreatetruecolor($anchura3,$altura3);
switch ($extension) {
case 'jpeg':
$img3 = imagecreatefromjpeg($camino.$image_temp);
imagecopyresampled ($thumb3, $img3, 0, 0, 0, 0, $anchura3, $altura3, $datos3[0], $datos3[1]);
imagejpeg($thumb3,$camino.$l.$image_id, $calidad);
break;
case 'png':
$img3 = imagecreatefrompng($camino.$image_temp);
imagecopyresampled ($thumb3, $img3, 0, 0, 0, 0, $anchura3, $altura3, $datos3[0], $datos3[1]);
imagepng($thumb3,$camino.$l.$image_id, $calidadpng);
break;
case 'gif':
$img3 = imagecreatefromgif($camino.$image_temp);
imagecopyresampled ($thumb3, $img3, 0, 0, 0, 0, $anchura3, $altura3, $datos3[0], $datos3[1]);
imagegif($thumb3,$camino.$l.$image_id);
break;
}
########################
# borrar imagen original
########################
$imagen_borrar= $camino.$image_temp;
unlink($imagen_borrar);
$gallery->setImageSmall($s.$image_id);
$gallery->setImageMedium($m.$image_id);
$gallery->setImageLarge($l.$image_id);
/* Fin Carga de imagenes */
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$gallery->setCreatedId($user_id);
$gallery->setUpdatedId($user_id);
$em = $this->getDoctrine()->getManager();
/* 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($gallery);
$em->flush();
$event = 'Images from this supplier have been uploaded.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajegallery', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage().' | transport';
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajegalleryerror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
return $id;
}
/**
* @Route("/addloungevideo/{id}", name="reservations_greenpatio_add_lounge_video")
*/
public function addLoungeVideoAction($id, EntityManagerInterface $em, Request $request) //, LoggerInterface $logger)
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$urlvideo = $request->request->get('loungevideo');
$urlvideo = $urlvideo['urlvideo'];
$loungeId = $id;
if(!empty($urlvideo)){
switch (true) {
case strpos($urlvideo, 'youtube'):
$patron = '%^ (?:https?://)? (?:www\.)? (?: youtu\.be/ | youtube\.com (?: /embed/ | /v/ | /watch\?v= ) ) ([\w-]{10,12}) ($|&).* $%x';
preg_match($patron, $urlvideo, $parte);
$urvideo_final = 'https://www.youtube.com/embed/'. $parte[1];
break;
case strpos($urlvideo, 'youtu'):
$patron = '%^ (?:https?://)? (?:www\.)? (?: youtu\.be/ | youtube\.com (?: /embed/ | /v/ | /watch\?v= ) ) ([\w-]{10,12}) ($|&).* $%x';
preg_match($patron, $urlvideo, $parte);
$urvideo_final = 'https://www.youtube.com/embed/'. $parte[1];
break;
case strpos($urlvideo, 'vimeo'):
$patron = '%^https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)(?:[?]?.*)$%im';
preg_match($patron, $urlvideo, $parte);
$urvideo_final = 'https://player.vimeo.com/video/'. $parte[3];
break;
}
if(!empty($urlvideo) && !empty($urvideo_final) ){
$video = new ReservationLoungeVideo();
$video->setCreatedId($user_id);
$video->setUpdatedId($user_id);
$video->setVideo($urvideo_final);
$video->setLoungeId($loungeId);
$video->setCreatedAt($now);
$video->setUpdatedAt($now);
$em->persist($video);
$em->flush();
}
}
if (empty($urlvideo)){
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajegalleryerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
}
/**
* @Route("/deleteloungevideo/{id}", name="reservations_greenpatio_delete_lounge_video")
*/
public function deleteLoungeVideoAction($id, EntityManagerInterface $em, Request $request) //, LoggerInterface $logger)
{
$video = $em->getRepository(ReservationLoungeVideo::class)->findOneById($id);
$idLounge = $video->getLoungeId();
try{
$em->remove($video);
$em->flush();
// $event = 'The Item has been deleted.';
$successMessage = 'El elemento ha sido eliminado.';
// $successMessage = $this->translator->trans($event);
$this->addFlash('mensajereservation', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array('id' => $idLounge));
}
/**
* @Route("/addloungeblueprints/{id}", name="reservations_greenpatio_add_lounge_blueprints")
*/
public function addLoungeBlueprintsAction($id, EntityManagerInterface $em, Request $request) //, LoggerInterface $logger)
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$picturefiles = $request->files->all();
$loungeId = $id;
$imagen = $picturefiles['loungepicturegalleryblueprints'];
$data = $loungeId;
if(!empty($imagen)){
$num = -1;
$data = $this->CargarImgGalleryAction($loungeId, $imagen, $num, $request); //, $logger);
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajegalleryerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
}
/**
* @Route("/addpicturemounting/{id}", name="reservations_greenpatio_add_lounge_picture_mounting")
*/
public function addLoungePictureMountingAction($id, EntityManagerInterface $em, Request $request) //, LoggerInterface $logger)
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$picturefiles = $request->files->all();
$loungeId = $id;
$imagen = $picturefiles['picturemounting'];
$data = $loungeId;
if(!empty($imagen)){
$num = $request->request->get('picturemounting');
$num = $num['type'];
$data = $this->CargarImgGalleryAction($loungeId, $imagen, $num, $request); //, $logger);
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajegalleryerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
}
/**
* @Route("/updatedimmensions/{id}", name="update_dimmensions")
*/
public function updateDimmensionsAction($id, EntityManagerInterface $em, Request $request)
{
$lounge = $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
$newData = $request->request->get('loungedimmensions');
$lounge->setMeters($newData['meters']);
$lounge->setLength($newData['length']);
$lounge->setWidth($newData['width']);
$lounge->setHeight($newData['height']);
$lounge->setCapSchool($newData['capSchool']);
$lounge->setCapTheater($newData['capTheater']);
$lounge->setCapCocktail($newData['capCocktail']);
$lounge->setCapBanquet($newData['capBanquet']);
$lounge->setCapImperial($newData['capImperial']);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$now = new DateTime('now');
$lounge->setUpdatedId($user_id);
$lounge->setUpdatedAt($now);
try{
$em->persist($lounge);
$em->flush();
$event = 'The Note has been created succesfully.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensaje', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeerror', $errorMessage);
}
return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
}
/**
* @Route("/addvisit", name="reservations_greenpatio_addvisit")
*/
public function addVisitAction(EntityManagerInterface $em, Request $request)
{
$visitas = $em->getRepository(ReservationVisit::class)->findAll();
$listAllReservas = $em->getRepository(Reservation::class)->findAll();
$agentsGp = array(); //arreglo con los agentes de Green Patio
$allUsers[] = $em->getRepository(User::class)->findAll();
$agentsGp = $em->getRepository(User::class)->findBy(['userrol' => [49,53]]);
return $this->render('MDS/GreenPatioBundle/reservations/add-visit.html.twig',
array(
'visitas' => $visitas,
'agentsGp' => $agentsGp,
'listAllReservas' => $listAllReservas,
)
);
}
/**
* @Route("/createvisit", name="reservations_greenpatio_createvisit")
*/
public function createVisitAction(EntityManagerInterface $em, Request $request)
{
$newRequest = $request->request->get('visit');
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
if (!empty($newRequest['date']) and !empty($newRequest['time'])){ $dateStart = new DateTime ($newRequest['date']. ' '.$newRequest['time']); } else { $dateStart = new DateTime ('now'); }
if (!empty($newRequest['time'])) {
$hourStart = substr($newRequest['time'], 0, 2);
$minStart = substr($newRequest['time'], 3, 2);
$hourEnd = substr($newRequest['time'],0,2) + 1;
$minEnd = substr($newRequest['time'],3,2);
} else {
$hourStart = '12';
$minStart = '00';
$hourEnd = '13';
$minEnd = '00';
}
if (!empty($newRequest['agent'])) { $agent = $em->getRepository(User::class)->findOneById($newRequest['agent']); } else { $agent = $em->getRepository(User::class)->findOneById(82); }
$title = '';
if (!empty($newRequest['name'])){ $title = $newRequest['name']; }
if (!empty($newRequest['idreservation'])){
$res = $em->getRepository(Reservation::class)->findOneById($newRequest['idreservation']);
if (!empty($title)) { $title = $title . ' - ' . $res->getTitle(); } else { $title = $res->getTitle(); }
}
$newVisit = new ReservationVisit();
$newVisit->setAgentId($agent->getId());
$newVisit->setDateStart($dateStart);
$newVisit->setDateEnd($dateStart);
if (!empty($newRequest['time'])) {
$newVisit->setHourStart($hourStart);
$newVisit->setMinStart($minStart);
$newVisit->setHourEnd($hourEnd);
$newVisit->setMinEnd($minEnd);
} else {
$newVisit->setHourStart($hourStart);
$newVisit->setMinStart($minStart);
$newVisit->setHourEnd($hourEnd);
$newVisit->setMinEnd($minEnd);
}
$newVisit->setLoungeName($title.' - '.'Visita '.$agent->getName());
if (!empty($newRequest['idreservation'])) { $newVisit->setIdReservation($newRequest['idreservation']); } else { $newVisit->setIdReservation(null); }
$newVisit->setType('Visit');
$newVisit->setCreatedAt(new DateTime ('now'));
$newVisit->setCreatedId($user_id);
$newVisit->setUpdatedAt(new DateTime ('now'));
$newVisit->setUpdatedId($user_id);
$location = (!empty($newRequest['location'])) ? $newRequest['location'] : 0;
$newVisit->setIdLounge($location);
$em->persist($newVisit);
$em->flush();
return $this->redirectToRoute('reservations_greenpatio_addvisit');
}
/**
* @Route("/deletevisit/{id}", name="get_reservations_deletevisit")
*/
public function deleteVisitAction($id, EntityManagerInterface $em, Request $request) {
$visit = $em->getRepository(ReservationVisit::class)->findOneById($id);
if (!empty($visit)){
$em->remove($visit);
$em->flush();
}
return $this->redirectToRoute('reservations_greenpatio_addvisit');
}
/**
* @Route("/sendconfirmationrequestmail/{id}", name="reservations_greenpatio_send_confirmation_request_mail")
* Enviar correo a Salvador y Rafael Guerrero para que la reserva (id) pase al estado confirmado
*/
public function sendConfirmationRequestMailAction($id, EntityManagerInterface $em, Request $request){
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$mailArrayTo = []; $mailAlert = [];
$mailArrayTo['salvador@avexpress.tv'] = 'salvador@avexpress.tv';
$mailArrayTo['rafael.guerrero@inout-travel.com'] = 'rafael.guerrero@inout-travel.com';
$dataGP = $this->disponibilidadGreenPatio($id);
$dataAV = $this->disponibilidadAvExpress($id);
$dataLounges = array();
foreach ($dataGP as $item){
$lounges = $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation'=>$item->getId(),'type'=>null));
foreach ($lounges as $elem){ $dataLounges[$item->getId()][] = $elem; }
}
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$agente = $em->getRepository(User::class)->findOneById($user_id);
$mailAddressFrom = $agente->getEmail();
$mailSubject = 'Confirmación de reserva: '.$reserva->getTitle();
$mensajePopup = '';
$mailBody = 'Estimado administrador,'.
'<br><br>'. $agente->getName().' '. $agente->getLastName(). ' ha solicitado la confirmación de la reserva:'.
'<br><br>'.$reserva->getTitle(). ' con ID: '.$reserva->getId().
'<br>Este evento incia el día '.$reserva->getDateStart()->format('d/m/Y').' a las '.$reserva->getDateStart()->format('H:i'). ' y finaliza el día '.$reserva->getDateEnd()->format('d/m/Y').' a las '.$reserva->getDateEnd()->format('H:i').'<br><br><br>';
if (!empty($dataGP) or !empty($dataAV)){
if(!empty($dataGP)){
$mensajePopup .= 'No se puede CONFIRMAR, conflicto con:'.'<br><br>';
// Conflictos con otros eventos en Green Patio
$mailSubject = '⚠️ ALERTA️ ‼️ DOBLE CONFIRMADO MISMA SALA' . $mailSubject;
$mailBody = $mailBody . 'Este evento coincide con la(s) reserva(s): <br>';
foreach ($dataGP as $res){
$mailBody = $mailBody . 'Reserva: '.$res->getTitle().', con ID: '.$res->getId().', fecha de inicio: '.$res->getDateStart()->format('d/m/Y').' a las '.$res->getDateStart()->format('H:i').', fecha de finalización: '.$res->getDateEnd()->format('d/m/Y').' a las '.$res->getDateEnd()->format('H:i');
if(!empty($dataLounges[$res->getId()])){
$mailBody = $mailBody .', Salas: ';
foreach ($dataLounges[$res->getId()] as $loungeItem){ $mailBody = $mailBody . $loungeItem->getLoungeName().', '; }
$mailBody = $mailBody .'<br>';
}
$mensajePopup .='Reserva: '.$res->getTitle().', con ID: '.$res->getId().'<br>';
}
$mailBody = $mailBody . '<br><br>';
}
if(!empty($dataAV)){
// Conflictos con otros eventos de AvExpress
$mailBody = $mailBody . 'Este evento coincide en AV con el expediente(s): <br>';
foreach ($dataAV as $file){
$mailBody = $mailBody . 'Expediente: '.$file->getTitle().', con ID: '.$file->getId().', fecha de inicio: '.$file->getDateStart()->format('d/m/Y H:i').', fecha de finalización: '.$file->getDateEnd()->format('d/m/Y H:i').'<br>';
}
}
$mailAlert = array('mailBody' => $mailBody, 'mailSubject' => $mailSubject);
}
$mailBody = $mailBody .'<br><br><a href="https://inout.mante.solutions/reservations-greenpatio/">CALENDARIO GREEN PATIO</a>';
$mailBody = $mailBody .'<br><br> <a href="https://inout.mante.solutions/reservations-greenpatio/adminconfirmres/y/'.$id.'">"SI"</a> deseo confirmar la reserva.';
$mailBody = $mailBody .'<br><br> <a href="https://inout.mante.solutions/reservations-greenpatio/adminconfirmres/n/'.$id.'">"NO"</a> deseo confirmar la reserva.';
$mailBody = $mailBody .'<br><br><br> <a href="https://inout.mante.solutions">"PARA QUE LOS ENLACES FUNCIONEN, ANTES DEBES INCIAR SESION"</a><br><br>';
// Se envia el correo pidiendo la confirmacion
$this->sendMailLot($mailAddressFrom, $mailArrayTo, $mailSubject, $mailBody);
//Alerta a Gabriela, Agente modificador del expediente y Mariale
if (!empty($dataGP)){
$mailArrayTo = [];
$agentAlert = $em->getRepository(User::class)->findOneById($reserva->getUpdatedBy());
if (!empty($agentAlert) and ($agentAlert->getStatus() == 1)){ $mailArrayTo[$agentAlert->getEmail()] = $agentAlert->getEmail(); }
$agentAlert = $em->getRepository(User::class)->findOneById(82); // Gabriela Bracho
if (!empty($agentAlert) and ($agentAlert->getStatus() == 1)){ $mailArrayTo[$agentAlert->getEmail()] = $agentAlert->getEmail(); }
$agentAlert = $em->getRepository(User::class)->findOneById(129); // Maria Alejandra Martinez
if (!empty($agentAlert) and ($agentAlert->getStatus() == 1)){ $mailArrayTo[$agentAlert->getEmail()] = $agentAlert->getEmail(); }
$this->sendMailLot($mailAddressFrom, $mailArrayTo, $mailSubject, $mailAlert['mailBody']);
}
if (!empty($mensajePopup)){ $this->addFlash('mensajereservationerror', $mensajePopup); }
// Sincronización con HT
if (!empty($reserva)) {
// Rafa indico que siempre se sincronice al abrir un expediente de GP
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
// Si no se ha creado aun el expediente de HT debemos crearlo
$htFile = $em->getRepository(HtFile::class)->findByReservation($reserva);
if (empty($htFile)) { return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,)); }
}
}
}
// Sincronización con Av Express
$cotizable = $this->laReservaEsCotizable($reserva->getId());
if ($cotizable) {
$AveFile = $em->getRepository(AveFiles::class)->findByReservation($reserva);
// Rafa indico que siempre se sincronice al abrir un expediente de GP
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
if (empty($AveFile)) {
// Si no se ha creado aun el expediente de Av Express debemos crearlo
return $this->redirectToRoute('sinc_gp_ave', array('id' => $id,));
}
}
}
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id, 'token' => null ));
}
/**
* @Route("/adminconfirmres/{op}/{id}", name="reservations_greenpatio_admin_confirm_res")
* Confirmacion del administrador, positiva o negativa (op) de la reserva (id)
*/
public function adminConfirmationReservationAction($op, $id, EntityManagerInterface $em, Request $request){
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$mailArrayTo = array();
$mailArrayTo['salvador@avexpress.tv'] = 'salvador@avexpress.tv';
$mailArrayTo['rafael.guerrero@inout-travel.com'] = 'rafael.guerrero@inout-travel.com';
$mailArrayTo['comercial@greenpatio.es'] = 'comercial@greenpatio.es';
$mailArrayTo['comercial2@greenpatio.es'] = 'comercial2@greenpatio.es';
// $mailArrayTo['gustavo.ayala@develup.solutions'] = 'gustavo.ayala@develup.solutions';
$agente = $em->getRepository(User::class)->findOneById($user_id);
$mailAddressFrom = $agente->getEmail();
$mailSubject = 'Confirmación de reserva: '.$reserva->getTitle();
switch ($op) {
case 'y':
// Se va a Confirmar la reserva
$reserva->setStatus('Confirmed');
$reserva->setUpdatedBy($user_id);
$reserva->setUpdatedAt(new DateTime('now'));
$em->persist($reserva);
$em->flush();
$mailBody = 'Estimado agente,'.
'<br><br>'. $agente->getName().' '. $agente->getLastName(). ' ha confirmado la reserva:'.
'<br><br>'.$reserva->getTitle(). ' con ID: '.$reserva->getId().
'<br>Este evento incia el día '.$reserva->getDateStart()->format('d/m/Y H:i'). ' y finaliza el día '.$reserva->getDateEnd()->format('d/m/Y H:i').'<br><br><br>';
// $mailBody = $mailBody .'<br><br> <a href="http://127.0.0.1:8000/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
$mailBody = $mailBody .'<br><br> <a href="https://inout.mante.solutions/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
break;
case 'n':
// No se va a Confirmar la reserva - Pasa a un editar (para ajustar fechas etc)
$reserva->setStatus('Cotizado');
$reserva->setUpdatedBy($user_id);
$reserva->setUpdatedAt(new DateTime('now'));
$em->persist($reserva);
$em->flush();
$mailBody = 'Estimado agente,'.
'<br><br>'. $agente->getName().' '. $agente->getLastName(). ' ha rechazado la confirmación de la reserva:'.
'<br><br>'.$reserva->getTitle(). ' con ID: '.$reserva->getId().
'<br>Este evento inciaba el día '.$reserva->getDateStart()->format('d/m/Y H:i'). ' y finalizaba el día '.$reserva->getDateEnd()->format('d/m/Y H:i').'<br><br><br>'.
'<br>POR FAVOR, PONGANSE EN CONTACTO PARA DETEMINAR UN NUEVO HORARIO<br><br><br>';
// $mailBody = $mailBody .'<br><br> <a href="http://127.0.0.1:8000/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
$mailBody = $mailBody .'<br><br> <a href="http://inout.mante.solutions/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
break;
default:
break;
}
// Enviar correo al agente (envia a las 2 agentes? enviar al creador de la reserva?)
$this->sendMailLot($mailAddressFrom, $mailArrayTo, $mailSubject, $mailBody);
echo 'Ha finalizado correctamente su sesión. Puede cerrar la aplicación'; exit();
}
/**
* @Route("/viewcontract/{id}", name="reservations_greenpatio_view_contract")
* Vista del contrato de la reserva (id)
*/
public function viewContractReservationAction($id, EntityManagerInterface $em, Request $request){
// El cliente es obligatorio y no puede ser null
// El contacto es obligatorio y no puede ser null, será el representante del cliente en el contrato
// En el expediente solo deben estar las salas definitivas para el contrato
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$contractOrigin = $reserva->getContract();
$dateStart = $reserva->getDateStart();
$dateEnd = $reserva->getDateEnd();
//Buscamos el representante
$representante = $reserva->getClientContact();
$representante = $em->getRepository(ClientContact::class)->findOneById($representante);
$representanteCorreo = $representante->getEmail();
$representante = $representante->getName().' '.$representante->getLastName();
//Buscamos el cliente
$client = $reserva->getClient();
$client = $em->getRepository(Client::class)->findOneById($client);
// La fecha de inicio y fin del evento incluyen montaje y desmontaje
// Determinamos el primer y ultimo dia del evento y lo modificamos en la reserva sin tocar la base de datos
$allOnlySalasReservadas = $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation'=>$id,'type'=>null));
if (!empty($allOnlySalasReservadas)){
$reserva->setDateStart($allOnlySalasReservadas[0]->getDateStart());
$reserva->setDateEnd($allOnlySalasReservadas[0]->getDateEnd());
foreach ($allOnlySalasReservadas as $item){
if ($item->getDateStart() < $reserva->getDateStart()){ $reserva->setDateStart($item->getDateStart()); }
if ($item->getDateEnd() > $reserva->getDateEnd()){ $reserva->setDateEnd($item->getDateEnd()); }
}
}
//Generamos la fecha actual
$fechaActual = new DateTime('now');
$mesActual = $fechaActual->format('m');
switch ($mesActual){
case '01': $mesActual = 'enero'; break;
case '02': $mesActual = 'febrero'; break;
case '03': $mesActual = 'marzo'; break;
case '04': $mesActual = 'abril'; break;
case '05': $mesActual = 'mayo'; break;
case '06': $mesActual = 'jumio'; break;
case '07': $mesActual = 'julio'; break;
case '08': $mesActual = 'agosto'; break;
case '09': $mesActual = 'septiembre'; break;
case '10': $mesActual = 'octubre'; break;
case '11': $mesActual = 'noviembre'; break;
case '12': $mesActual = 'diciembre'; break;
default: $mesActual = ''; break;
}
$contract00 = '';
$contract01 = '';
$contract02 = '';
$contract03 = '';
$contract04 = '';
$contract05 = '';
//Generamos la fecha de inicio
$fechaInicio = $reserva->getDateStart()->format('m');
switch ($fechaInicio){
case '01': $mesInicio = 'enero'; break;
case '02': $mesInicio = 'febrero'; break;
case '03': $mesInicio = 'marzo'; break;
case '04': $mesInicio = 'abril'; break;
case '05': $mesInicio = 'mayo'; break;
case '06': $mesInicio = 'jumio'; break;
case '07': $mesInicio = 'julio'; break;
case '08': $mesInicio = 'agosto'; break;
case '09': $mesInicio = 'septiembre'; break;
case '10': $mesInicio = 'octubre'; break;
case '11': $mesInicio = 'noviembre'; break;
case '12': $mesInicio = 'diciembre'; break;
default: $mesInicio = ''; break;
}
$fechaInicio = $reserva->getDateStart()->format('d'). ' de '.$mesInicio.' del '.$reserva->getDateStart()->format('Y').' ';
$contract06 ='';
$horaInicio = $reserva->getDateStart()->format('H:i').' ';
$contract07 ='';
//Generamos la fecha de fin
$fechaFin = $reserva->getDateEnd()->format('m');
switch ($fechaFin){
case '01': $mesFin = 'enero'; break;
case '02': $mesFin = 'febrero'; break;
case '03': $mesFin = 'marzo'; break;
case '04': $mesFin = 'abril'; break;
case '05': $mesFin = 'mayo'; break;
case '06': $mesFin = 'jumio'; break;
case '07': $mesFin = 'julio'; break;
case '08': $mesFin = 'agosto'; break;
case '09': $mesFin = 'septiembre'; break;
case '10': $mesFin = 'octubre'; break;
case '11': $mesFin = 'noviembre'; break;
case '12': $mesFin = 'diciembre'; break;
default: $mesFin = ''; break;
}
if ($reserva->getDateStart()->format('ymd') != $reserva->getDateEnd()->format('ymd')){
$fechaFin = ' el día '.$reserva->getDateEnd()->format('d'). ' de '.$mesFin.' del '.$reserva->getDateEnd()->format('Y').' a las '.$reserva->getDateEnd()->format('H:i').' ';
$contractAlfa = '';
$contract08 = $fechaFin.$contractAlfa;
} else {
// El evento empieza y termina el mismo dia
$horaFin = ' las '.$reserva->getDateEnd()->format('H:i').' ';
$contractAlfa = '';
$contract08 = $horaFin.$contractAlfa;
}
// Buscamos las salas
$allSalasReservadas = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
$arrayTextoSalas = array();
foreach ($allSalasReservadas as $item){ $arrayTextoSalas[$item->getIdLounge()] = $item->getIdLounge(); }
$textoSalas = '';
$logAllGreen = false; // Si se asigna el edificio completo no hay que verificar mas salas
foreach ($arrayTextoSalas as $item){
$sala = $em->getRepository(ReservationLoungeDetails::class)->findOneById($item);
switch ($sala->getId()){
case '1': $textoSalas = '<b>TODO EL EDIFICIO EN EXCLUSIVA</b>'; $logAllGreen = true; break;
case '16': if (empty($textoSalas)){ $textoSalas = '<b>Sala Plenaria La Imprenta, Sala Invernadero</b>'; } else { $textoSalas = $textoSalas.'<b>Sala Plenaria La Imprenta, Sala Invernadero</b>'; } break;
case '17': if (empty($textoSalas)){ $textoSalas = '<b>Sala Plenaria La Imprenta, Sala Invernadero, Sala Escenario</b>'; } else { $textoSalas = $textoSalas.'<b>Sala Plenaria La Imprenta, Sala Invernadero, Sala Escenario</b>'; } break;
default: if (!$logAllGreen){ if (empty($textoSalas)){ $textoSalas = '<b>'.$sala->getName().'</b>'; } else { $textoSalas = $textoSalas.'<b>, '.$sala->getName().'</b>'; } } break;
}
}
$contract09 = '';
$cierre = $reserva->getDateEnd()->format('H:i').' horas del día '.$reserva->getDateEnd()->format('d').' de '.$mesFin.' del '.$reserva->getDateEnd()->format('Y');
$contract10 ='';
$pax = $reserva->getPax();
$contract11 = '';
$contract12 = '</span></span><b><span lang="ES-TRAD" style="font-size:12.0pt"><o:p></o:p></span></b></font></p><p class="MsoListParagraph"><!--[if !supportLists]--><font face="Arial"><span lang="ES-TRAD" style="font-size:12.0pt">-<span style="font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; font-size: 7pt; line-height: normal;"> </span></span><!--[endif]--><span class="Hyperlink1"><span lang="ES-TRAD" style="font-size:12.0pt">Salas a utilizar: </span></span><span class="Ninguno"><b><u><span lang="ES-TRAD">';
$contract13 = '</span></u></b></span><b><span lang="ES-TRAD" style="font-size:12.0pt"><o:p></o:p></span></b></font></p>';
// Se asume que los montajes seran como maximo de dos dias
$montaje = array(); $mesInicioMontaje = ''; $mesFinMontaje = '';
foreach ($allSalasReservadas as $item){
if ($item->getType() == 'Montaje'){
if (empty($montaje)){
$montaje[0] = $item->getDateStart();
switch ($item->getDateStart()->format('m')){
case '01': $mesInicioMontaje = 'enero'; break;
case '02': $mesInicioMontaje = 'febrero'; break;
case '03': $mesInicioMontaje = 'marzo'; break;
case '04': $mesInicioMontaje = 'abril'; break;
case '05': $mesInicioMontaje = 'mayo'; break;
case '06': $mesInicioMontaje = 'jumio'; break;
case '07': $mesInicioMontaje = 'julio'; break;
case '08': $mesInicioMontaje = 'agosto'; break;
case '09': $mesInicioMontaje = 'septiembre'; break;
case '10': $mesInicioMontaje = 'octubre'; break;
case '11': $mesInicioMontaje = 'noviembre'; break;
case '12': $mesInicioMontaje = 'diciembre'; break;
default: $mesInicioMontaje = ''; break;
}
} else {
$montaje[1] = $item->getDateEnd();
switch ($item->getDateEnd()->format('m')){
case '01': $mesFinMontaje = 'enero'; break;
case '02': $mesFinMontaje = 'febrero'; break;
case '03': $mesFinMontaje = 'marzo'; break;
case '04': $mesFinMontaje = 'abril'; break;
case '05': $mesFinMontaje = 'mayo'; break;
case '06': $mesFinMontaje = 'jumio'; break;
case '07': $mesFinMontaje = 'julio'; break;
case '08': $mesFinMontaje = 'agosto'; break;
case '09': $mesFinMontaje = 'septiembre'; break;
case '10': $mesFinMontaje = 'octubre'; break;
case '11': $mesFinMontaje = 'noviembre'; break;
case '12': $mesFinMontaje = 'diciembre'; break;
default: $mesFinMontaje = ''; break;
}
}
}
}
switch (sizeof($montaje)){
case 1: $textoMontaje = $montaje[0]->format('d').' de '.$mesInicioMontaje.' del '.$montaje[0]->format('Y'); break;
case 2:
if ($mesInicioMontaje == $mesFinMontaje){
// Dos dias de montaje en el mismo mes
$textoMontaje = $montaje[0]->format('d').' y '.$montaje[1]->format('d'). ' de '.$mesInicioMontaje.' del '.$montaje[0]->format('Y');
} else {
// Dos dias de montaje con diferentes meses, ejemplo 31/03 y 01/04
$textoMontaje = $montaje[0]->format('d').' de '.$mesInicioMontaje.' y '.$montaje[1]->format('d').' de '.$mesFinMontaje.' del '.$montaje[0]->format('Y');
}
break;
default: $textoMontaje = null; break;
}
if (!empty($textoMontaje)){
$textoMontaje = '<p class="MsoListParagraph"><!--[if !supportLists]--><font face="Arial"><span lang="ES-TRAD" style="font-size:12.0pt">-<span style="font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; font-size: 7pt; line-height: normal;"> </span></span><!--[endif]--><span class="Hyperlink1"><span lang="ES-TRAD" style="font-size:12.0pt">MONTAJE: '.$textoMontaje.'</span></span><b><span lang="ES-TRAD" style="font-size:12.0pt"><o:p></o:p></span></b></font></p>';
}
// Se asume que los desmontajes seran como maximo de dos dias
$desmontaje = array(); $mesInicioDesmontaje = ''; $mesFinDesmontaje = '';
foreach ($allSalasReservadas as $item){
if ($item->getType() == 'Desmontaje'){
if (empty($desmontaje)){
$desmontaje[0] = $item->getDateStart();
switch ($item->getDateStart()->format('m')){
case '01': $mesInicioDesmontaje = 'enero'; break;
case '02': $mesInicioDesmontaje = 'febrero'; break;
case '03': $mesInicioDesmontaje = 'marzo'; break;
case '04': $mesInicioDesmontaje = 'abril'; break;
case '05': $mesInicioDesmontaje = 'mayo'; break;
case '06': $mesInicioDesmontaje = 'jumio'; break;
case '07': $mesInicioDesmontaje = 'julio'; break;
case '08': $mesInicioDesmontaje = 'agosto'; break;
case '09': $mesInicioDesmontaje = 'septiembre'; break;
case '10': $mesInicioDesmontaje = 'octubre'; break;
case '11': $mesInicioDesmontaje = 'noviembre'; break;
case '12': $mesInicioDesmontaje = 'diciembre'; break;
default: $mesInicioDesmontaje = ''; break;
}
} else {
$desmontaje[1] = $item->getDateEnd();
switch ($item->getDateEnd()->format('m')){
case '01': $mesFinDesmontaje = 'enero'; break;
case '02': $mesFinDesmontaje = 'febrero'; break;
case '03': $mesFinDesmontaje = 'marzo'; break;
case '04': $mesFinDesmontaje = 'abril'; break;
case '05': $mesFinDesmontaje = 'mayo'; break;
case '06': $mesFinDesmontaje = 'jumio'; break;
case '07': $mesFinDesmontaje = 'julio'; break;
case '08': $mesFinDesmontaje = 'agosto'; break;
case '09': $mesFinDesmontaje = 'septiembre'; break;
case '10': $mesFinDesmontaje = 'octubre'; break;
case '11': $mesFinDesmontaje = 'noviembre'; break;
case '12': $mesFinDesmontaje = 'diciembre'; break;
default: $mesFinDesmontaje = ''; break;
}
}
}
}
switch (sizeof($desmontaje)){
case 1: $textoDesmontaje = $desmontaje[0]->format('d').' de '.$mesInicioDesmontaje.' del '.$desmontaje[0]->format('Y'); break;
case 2:
if ($mesInicioDesmontaje == $mesFinDesmontaje){
// Dos dias de montaje en el mismo mes
$textoDesmontaje = $desmontaje[0]->format('d').' y '.$desmontaje[1]->format('d'). ' de '.$mesInicioDesmontaje.' del '.$desmontaje[0]->format('Y');
} else {
// Dos dias de montaje con diferentes meses, ejemplo 31/03 y 01/04
$textoDesmontaje = $desmontaje[0]->format('d').' de '.$mesInicioDesmontaje.' y '.$desmontaje[1]->format('d').' de '.$mesFinDesmontaje.' del '.$desmontaje[0]->format('Y');
}
break;
default: $textoDesmontaje = 'Mismo día al finalizar el evento desde las 17 horas hasta las 00:00 horas'; break;
}
if (!empty($textoDesmontaje)){
$textoDesmontaje = '';
}
$contract14 = '';
if (empty($mesInicioMontaje)){
switch ($dateStart->format('m')){
case '01': $mesInicioMontajeZ = 'enero'; break;
case '02': $mesInicioMontajeZ = 'febrero'; break;
case '03': $mesInicioMontajeZ = 'marzo'; break;
case '04': $mesInicioMontajeZ = 'abril'; break;
case '05': $mesInicioMontajeZ = 'mayo'; break;
case '06': $mesInicioMontajeZ = 'jumio'; break;
case '07': $mesInicioMontajeZ = 'julio'; break;
case '08': $mesInicioMontajeZ = 'agosto'; break;
case '09': $mesInicioMontajeZ = 'septiembre'; break;
case '10': $mesInicioMontajeZ = 'octubre'; break;
case '11': $mesInicioMontajeZ = 'noviembre'; break;
case '12': $mesInicioMontajeZ = 'diciembre'; break;
default: $mesInicioMontajeZ = ''; break;
}
$tiempoCedido = $dateStart->format('H:i').' horas del día '.$dateStart->format('d').' de '.$mesInicioMontajeZ.' del '.$dateStart->format('Y').' hasta las ';
} else {
$tiempoCedido = $dateStart->format('H:i').' horas del día '.$dateStart->format('d').' de '.$mesInicioMontaje.' del '.$dateStart->format('Y').' hasta las ';
}
if (empty($mesInicioDesmontaje)){
switch ($dateStart->format('m')){
case '01': $mesInicioDesmontajeZ = 'enero'; break;
case '02': $mesInicioDesmontajeZ = 'febrero'; break;
case '03': $mesInicioDesmontajeZ = 'marzo'; break;
case '04': $mesInicioDesmontajeZ = 'abril'; break;
case '05': $mesInicioDesmontajeZ = 'mayo'; break;
case '06': $mesInicioDesmontajeZ = 'jumio'; break;
case '07': $mesInicioDesmontajeZ = 'julio'; break;
case '08': $mesInicioDesmontajeZ = 'agosto'; break;
case '09': $mesInicioDesmontajeZ = 'septiembre'; break;
case '10': $mesInicioDesmontajeZ = 'octubre'; break;
case '11': $mesInicioDesmontajeZ = 'noviembre'; break;
case '12': $mesInicioDesmontajeZ = 'diciembre'; break;
default: $mesInicioDesmontajeZ = ''; break;
}
$tiempoCedido = $tiempoCedido . $dateEnd->format('H:i').' horas del día '.$dateEnd->format('d').' de '.$mesInicioDesmontajeZ.' del '.$dateEnd->format('Y');
} else {
$tiempoCedido = $tiempoCedido . $dateEnd->format('H:i').' horas del día '.$dateEnd->format('d').' de '.$mesInicioDesmontaje.' del '.$dateEnd->format('Y');
}
$contract15 = '';
// 5. Normas de Seguridad
$contract16 = '';
// 6. Coste, plazo y forma de pago
$data = $this->CalculosTotalesEditSimple($reserva->getId());
$contract17 = '';
// 8. Reserva
$contract18 = '';
// 9. Confidencialidad y publicidad
// 11. Derechos de imagen y propiedad intelectual
// 12. Prevencion de la corrupcion
// 13. Proteccion de datos personales
// 14. Responsabilidad
$contract19 = '';
// 15. Comunicaciones
$contract20 = '';
// 16. Cesión
// 17. Nulidad Parcial
// 18. Fuerza Mayor
// 19. Acuerdo Completo
$contract21 = '';
// Normas de uso
$contract22 = '';
// Logotipo de Green Patio centrado
$contract23 = '
<div class="col-md-4 col-xs-6" ></div><div class="col-md-4 col-xs-6" ><p class="MsoNormal" align="right" style="margin-bottom: background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><b><span lang="EN-US" style="font-size: 9pt;"><font face="Arial"><o:p><br></o:p></font></span></b></p><p class="MsoNormal" align="right" style="margin-bottom: 7.5pt; text-align: right; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><b><span lang="EN-US" style="font-size: 9pt;"><font face="Arial"><o:p><br></o:p></font></span></b></p><p class="MsoNormal" align="right" style="margin-bottom: 7.5pt; text-align: right; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><img src="data:image/png;base64,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fZ00cOlJabFBKCM9wqH1T8ZwI+pwdXgQ8q5GCnSwAPJnIX1P5iPDmP+VSN8o7rVJYEWZlhKB9XTUUfDUF1lzUP5R/C0IRCh3syynDg5C0NkN8+gdegLBOsorZBIcqw6sCID1mPa7OlgWllNeM7tbg1UkLHt4f1AHS0K5dsz7Sh0Moad7IJbpceQ3aFYBTHMSxn1dByuC7XsElvdr+Csnr62w/Bmky4vbot4KWKuDkaRNo8y1OlgA9f8txhU85JR9gzYqD1zvwbIfJe0Df7+F4fO0yCDk34Q0TwdpS4XG8ani142EBBU00v2GBhc0sK1xsO2Jj8MOfjTG3fVjxeTAlnlLgJHPxZfHeXLwYDkLehF6/6zgfVqBZZR3Moc9jMnDch4ul6zyGeX2k9e98LEggMo6l6pDlhHzKHhwIsNy8BW/+iPbqriskhODzHdwO8o20G1bNcxj2+LtU47sdyzDR3VwGKlTkg6WNH/+/J2jer2zZ8/epVT9sg3l5KKDlZosl+VYpp3kM/b9QcXbW1SyHVGHvIdasP3zpH5sm2HvIyN/R+RPlfvx8u4sPh8tD3N19CAJukM7I0RERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERFuKSZP+F0vlO4rFICMJAAAAAElFTkSuQmCC" alt="" style="float: left;"></p><p class="MsoNormal" style="margin-bottom: 7.5pt; text-indent: 3pt; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"></p></div></div></div></div><div class="col-md-4 col-xs-6" ></div>
';
//Generamos el contrato
$contract = $contract00.'<b>'.' '.$client->getName().'</b>'.' '.$contract01. 'CIF '.$client->getIdDocument().' '.
$contract02.'<b>'.' '.$client->getAddress().'</b>'.','.$contract03.' '.$representante.'.'.
$contract04.$reserva->getTitle().$contract05.$fechaInicio.$contract06.$horaInicio.$contract07.
$contract08.$textoSalas.$contract09.$cierre.$contract10.$pax.$contract11.$fechaInicio.
$contract12.$textoSalas.$contract13.$textoMontaje.$textoDesmontaje.$contract14.$tiempoCedido.
$contract15.$contract16.$contract17.$contract18.$contract19.$contract20.$contract21.$contract22.$contract23
;
// Si no habia contracto originalmente en la reserva se actualiza
if (empty($contractOrigin)){
$reserva->setContract($contract);
$em->persist($reserva);
$em->flush();
} else {
$contract = $contractOrigin;
}
return $this->render('MDS/GreenPatioBundle/reservations/view-contract-reservation.html.twig', array( 'id' => $id, 'contract' => $contract, ) );
}
/**
* @Route("/createdeposit/{id}", name="reservations_greenpatio_createdeposit")
*/
public function createDepositAction($id, EntityManagerInterface $em, Request $request)
{
$newRequest = $request->request->get('reservation_deposit');
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$newDeposit = new ReservationDeposit();
$newDeposit->setReservationId($id);
if (empty($newRequest['date'])) { $newDeposit->setDate(new DateTime ('now')); } else { $newDeposit->setDate(new DateTime ($newRequest['date'])); }
if (empty($newRequest['description'])) { $newDeposit->setDescription(null); } else { $newDeposit->setDescription($newRequest['description']); }
if (empty($newRequest['amount'])) { $newDeposit->setAmount(null); } else { $newDeposit->setAmount($newRequest['amount']); }
if (array_key_exists('isDone',$newRequest)) { $newDeposit->setIsDone(true); } else { $newDeposit->setIsDone(false); }
$newDeposit->setCreatedAt(new DateTime ('now'));
$newDeposit->setCreatedId($user_id);
$newDeposit->setUpdatedAt(new DateTime ('now'));
$newDeposit->setUpdatedId($user_id);
$em->persist($newDeposit);
$em->flush();
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id, 'token' => null, '_fragment' => 'btn_dpt' ));
}
/**
* @Route("/depositupdate/{id}", name="reservations_greenpatio_deposit_update")
*/
public function depositUpdateAction($id, EntityManagerInterface $em, Request $request)
{
$newRequest = $request->request->get('reservation_deposit_isdone_pending');
$deposito = $em->getRepository(ReservationDeposit::class)->findOneById($id);
if (array_key_exists('isDone',$newRequest)) { $deposito->setIsDone(true); } else { $deposito->setIsDone(false); }
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$deposito->setUpdatedAt(new DateTime ('now'));
$deposito->setUpdatedId($user_id);
$em->persist($deposito);
$em->flush();
return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $deposito->getReservationId(), 'token' => null, '_fragment' => 'btn_dpt' ));
}
/**
* @Route("/loadedreservations", name="reservations_greenpatio_loaded_reservations")
*/
public function loadedReservationsAction(EntityManagerInterface $em, Request $request)
{
$hoy = new DateTime('now');
$diaInicio = new DateTime($hoy->format('Y-m'). '-01');
// Se buscan las reservas creadas desde el inicio de mes
$parameters = array( 'diaInicio' => $diaInicio, );
$dql = 'SELECT i
FROM GreenPatioBundle:Reservation i
WHERE i.createdAt > :diaInicio';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservas = $query->getResult();
return $this->render('MDS/GreenPatioBundle/reservations/list-loaded-reservations.html.twig', array( 'reservations' => $reservas, 'itemsOfSearch' => '', ) );
}
/**
* @Route("/searchreservations", name="reservations_greenpatio_search_reservations")
*/
public function searchReservationsAction(EntityManagerInterface $em, Request $request)
{
$searchloaded = $request->request->get('searchloaded');
$dateStart = new \DateTime($searchloaded['date_start']);
$dateEnd = new \DateTime($searchloaded['date_end']);
$itemsOfSearch = ' Entre las fechas: '.$dateStart->format('d/m/Y').' y '.$dateEnd->format('d/m/Y');
// Se buscan las reservas creadas en las fechas solicitadas
$parameters = array( 'diaInicio' => $dateStart, 'diaFin' => $dateEnd, );
$dql = 'SELECT i
FROM GreenPatioBundle:Reservation i
WHERE i.createdAt BETWEEN :diaInicio AND :diaFin';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservas = $query->getResult();
return $this->render('MDS/GreenPatioBundle/reservations/list-loaded-reservations.html.twig', array( 'reservations' => $reservas, 'itemsOfSearch' => $itemsOfSearch, ) );
}
private function sendMail($mailAddressFrom, $mailAddressTo, $mailSubject, $mailBody){
$em = $this->getDoctrine()->getManager();
$agent = $em->getRepository(User::class)->findOneByEmail($mailAddressFrom);
$client = $em->getRepository(Client::class)->findOneByEmail($mailAddressTo);
if (empty($client)){ $client = $em->getRepository(ClientContact::class)->findOneByEmail($mailAddressTo); } // Si el cliente era null puede ser un client contact
if (!empty($client)){
$replyTo = array(
$client->getEmail() => $client->getName(),
$agent->getEmail() => $agent->getName().' '. $agent->getLastName(),
);
} else {
// El AddressTo es un contacto no registrado
$replyTo = array(
$mailAddressTo => $mailAddressTo,
$agent->getEmail() => $agent->getName().' '. $agent->getLastName(),
);
}
$agentMail = $mailAddressFrom;
$mailAgent = $agentMail;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $mailBody,
'firm' => $firmGmail,
);
// EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
$transporter = new \Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername('desarrollo@develup.solutions')
->setPassword('utvh hzoi wfdo ztjs');
// ->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new \Swift_Mailer($transporter);
$message = new \Swift_Message();
$message->setSubject($mailSubject)
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "Green Patio"))
->setReplyTo($agentMail)
->setTo($replyTo)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
// $mailer->send($message); Rafa dijo que no queria envío de correos con el cliente ya que se haría mediante la cotización Web (04/02/2025)
return true;
}
private function makeAlert($reservaId, $clientId, $clientMail, $agentId, $agentMail){
$em = $this->getDoctrine()->getManager();
$alertaPrevia = $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($reservaId);
$reserva = $em->getRepository(Reservation::class)->findOneById($reservaId);
$dias = $reserva->getDaysBlock();
if (empty($dias) or !(is_numeric($dias))){
$dias = 7;
}
$diasMenosDos = $dias - 2;
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
$hoyMasCinco = $hoy;
$hoyMasCinco->add(new DateInterval('P'.$diasMenosDos.'D')); // 5 dias despues, 48 horas antes de la cancelacion (o los especificados)
$hoyMasCinco->add(new DateInterval("PT2H")); // Ajustamos la diferencia con el reloj del servidor
$hoy = new \DateTime("now", NULL);
$hoyMasSiete = $hoy;
$hoyMasSiete->add(new DateInterval('P'.$dias.'D')); // Siete dias despues (o los especificados)
$hoyMasSiete->add(new DateInterval("PT2H"));
//Si no hay una alerta previa se hace la alerta
if (empty($alertaPrevia)){
$alerta = new ReservationMailAlertClient();
$alerta->setReservationId($reservaId);
$alerta->setClientId($clientId);
$alerta->setClientMail($clientMail);
$alerta->setAgentId($agentId);
$alerta->setAgentMail($agentMail);
$alerta->setAlertDateTime($hoyMasCinco); // A los 5 dias se alerta (o los especificados)
$alerta->setAlertSended(false);
$alerta->setCancelDateTime($hoyMasSiete); // A los 7 dias se cancela (o los especificados)
$alerta->setCancelSended(false);
$alerta->setOldReservationId(null); // Aqui se guardara el Id de reserva cuando se vaya a eliminar el registro (solo se pondra reservationId a 0)
$alerta->setCreatedAt($hoy);
$alerta->setCreatedId($user_id);
$em->persist($alerta);
$em->flush();
}
return true;
}
private function benefitForReservation($id){
$em = $this->getDoctrine()->getManager();
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$lounges = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
$services = $em->getRepository(ReservationService::class)->findByReservationId($id);
$payedLounges = array(); $payedServices = array(); $unPayedServices = array();
// Salas
foreach ($lounges as $item){
// Si la sala esta en ReservationInvoiceItems se encuentra facturado, en caso contraio, no lo esta o ha sido rectificado
$loungeInvoicedItem = $em->getRepository(ReservationInvoiceItems::class)->findOneByLngControlId($item->getId());
if (!empty($loungeInvoicedItem)){ $payedLounges[] = $item; } // Esta facturado el Item
}
// Servicios
foreach ($services as $item){
// Si el servicio esta en ReservationInvoiceItems se encuentra facturado, en caso contraio, no lo esta o ha sido rectificado
$serviceInvoicedItem = $em->getRepository(ReservationInvoiceItems::class)->findOneBySrvControlId($item->getId());
if (!empty($serviceInvoicedItem)){
// Esta facturado el Item
$payedServices[] = $item;
} else {
// No esta facturado el Item o fue rectificado
$unPayedServices[] = $item;
}
}
$benefit = 0; $payed = 0;
// Se suman los pagos
foreach ($payedLounges as $item){
$benefit = $benefit + (float)$item->getServicePrice();
$payed = $payed + (float)$item->getServicePrice();
}
foreach ($payedServices as $item){
$benefit = $benefit + (float)$item->getPrice();
$payed = $payed + (float)$item->getPrice();
}
// Se restan los impagos
foreach ($unPayedServices as $item){
// Se verifica el check de toinvoice por si el servicio se facturara a futuro (Requisito de Rafa)
if ($item->getToinvoice()){
$benefit += (float)$item->getPrice();
$payed += (float)$item->getPrice();
} else {
// No esta pagado y no esta marcado "Para facturar"
$benefit = $benefit - (float)$item->getPrice();
}
}
// Porcentaje de beneficio
$percBenefit = ($benefit * 100);
if (!($payed == 0)){ $percBenefit = $percBenefit / $payed; } else { $percBenefit = 0; };
return array(
'benefit' => $benefit,
'percBenefit' => $percBenefit,
'payedLounges' => $payedLounges,
'payedServices' => $payedServices,
'unPayedServices' => $unPayedServices,
);
}
private function verificarStatusInicialyFinal($id,$user_id,$estadoInicial,$estadoFinal){
$em = $this->getDoctrine()->getManager();
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
$user_logueado = $em->getRepository(User::class)->findOneById($user_id);
$newStatus = 'Pendiente';
//Este Switch ya no es necesario
switch ($estadoInicial) {
case 'Bloqueo':
// De bloqueo solo se sale si el usuario es Salvador o un Admin O si se va a Cancelar "Deleted" o "Cotizado"
// if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Deleted' or $estadoFinal == 'Cotizado'){
if ($estadoFinal == 'Deleted' or $estadoFinal == 'Cotizado'){
$newStatus = $estadoFinal;
} else {
// No se cambia el estado
$newStatus = $estadoInicial;
}
break;
case 'Pendiente':
// De Pendiente solo se sale si el usuario es Salvador o un Admin O si se va a Cancelar "Deleted"
$newStatus = $estadoFinal;
// if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Deleted'){
if ($estadoFinal == 'Deleted'){
$newStatus = $estadoFinal;
} else {
// No se cambia el estado
$newStatus = $estadoInicial;
}
break;
case 'Deleted':
// De Cancelado solo se sale si el usuario es Salvador o un Admin O "Bloqueo" o "Pendiente"
// if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente'or $estadoFinal == 'Cotizado'){
if ($estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente'or $estadoFinal == 'Cotizado'){
$newStatus = $estadoFinal;
} else {
// No se cambia el estado
$newStatus = $estadoInicial;
}
break;
case 'Cotizado':
$newStatus = $estadoFinal;
// De Cotizado solo se sale si el usuario es Salvador o un Admin O a O "Bloqueo" o "Pendiente" o "Cancelado"
// if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente' or $estadoFinal == 'Deleted'){
if ($estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente' or $estadoFinal == 'Deleted' or $estadoFinal == 'Confirmed'){
$newStatus = $estadoFinal;
}
break;
case 'Invoiced':
// De Facturado no se debe salir a menos que se rectifique
// Si todas las facturas del expediente se encuentran rectificadas pasamos al estado "Confirmado" sino seguimos en "Facturado"
$reservaInvoices = $em->getRepository(ReservationInvoice::class)->findByReservationId($id);
$estanTodasRectificadas = true;
foreach ($reservaInvoices as $item){
$reservaInvoiceRect = $em->getRepository(ReservationInvoiceRec::class)->findOneByInvoiceToRec($item->getId());
if (empty($reservaInvoiceRect)){ $estanTodasRectificadas = false; } else { $estanTodasRectificadas = ($estanTodasRectificadas and true); }
}
if ($estanTodasRectificadas){
$newStatus = 'Confirmed';
} else {
$newStatus = $estadoInicial;
}
break;
case 'Confirmed':
// Se puede ir a cualquier estado
$newStatus = $estadoFinal;
break;
default:
// No hacer nada con el campo Status
$newStatus = $estadoInicial;
break;
}
$newStatus = $estadoFinal;
return $newStatus;
}
private function disponibilidadGreenPatio($id){
// $id Id de la reserva
$em = $this->getDoctrine()->getManager();
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
// $lounges = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
//Buscamos salas que tengamos entre el inicio y fin del evento a confirmar
//Sumamos un dia ya que por solicitud de Salva deseamos saber que eventos hay un dia antes y un dia despues
$fechaInicio = new \DateTime($reserva->getDateStart()->format('Y-m-d H:i:s'));
// $fechaInicio->sub(new \DateInterval("P1D"));
$fechaFin = new \Datetime($reserva->getDateEnd()->format('Y-m-d H:i:s'));
// $fechaFin->add(new \DateInterval("P1D"));
// Los eventos que debemos verificar son los Confirmados y Facturados
// $parameters = array(
// 'reservaId' => $id,
// 'dateStart' => $fechaInicio,
// 'dateEnd' => $fechaFin,
// 'facturado' => 'Invoiced',
// 'confirmado' => 'Confirmed',
// );
// $dql = 'SELECT r
// FROM GreenPatioBundle:Reservation r
// INNER JOIN GreenPatioBundle:ReservationLoungeSimple l WITH r.id = l.idReservation
// WHERE (r.status = :facturado OR r.status = :confirmado)
// AND (not(r.id = :reservaId))
// AND ((l.dateStart >= :dateStart and l.dateStart <= :dateEnd))';
//
// $query = $em->createQuery($dql)->setParameters($parameters);
// $reservationInDates = $query->getResult();
$parameters = array(
'dateStart' => $fechaInicio,
'dateEnd' => $fechaFin,
'facturado' => 'Invoiced',
'confirmado' => 'Confirmed',
);
$dql = 'SELECT r
FROM GreenPatioBundle:Reservation r
INNER JOIN GreenPatioBundle:ReservationLoungeSimple l WITH r.id = l.idReservation
WHERE (r.status = :facturado OR r.status = :confirmado)
AND (
l.dateStart <= :dateEnd
AND l.dateEnd >= :dateStart
)';
$query = $em->createQuery($dql)->setParameters($parameters);
$reservationsInConflict = $query->getResult();
$arrayUso = [];
$arrayAlert = [];
$arrayAlertMontDesmont = []; // Nuevo array para almacenar conflictos de montaje y desmontaje
if (sizeof($reservationsInConflict) >1){
foreach ($reservationsInConflict as $resConflict) {
$loungesConflict = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($resConflict->getId());
foreach ($loungesConflict as $item) {
$type = $item->getType(); // Puede ser NULL, "Montaje" o "Desmontaje"
$dateKey = $item->getDateStart()->format('Ymd');
$loungeId = $item->getIdLounge();
$reservationId = $item->getIdReservation();
if (in_array($loungeId, [2, 4, 9])) {
// Plenaria, Invernadero y Escenario se consideran la misma sala
$arrayUso[2][$dateKey][$reservationId] = empty($type) ? 'Sala' : $type;
$arrayUso[4][$dateKey][$reservationId] = empty($type) ? 'Sala' : $type;;
$arrayUso[9][$dateKey][$reservationId] = empty($type) ? 'Sala' : $type;;
} else {
$lngDetails = $em->getRepository(ReservationLoungeDetails::class)->findOneById($loungeId);
if (empty($lngDetails->getCombo())) {
$arrayUso[$loungeId][$dateKey][$reservationId] = empty($type) ? 'Sala' : $type;
} else {
$arrayComboLounges = explode(",", $lngDetails->getCombo());
foreach ($arrayComboLounges as $indLounge) {
$arrayUso[$indLounge][$dateKey][$reservationId] = empty($type) ? 'Sala' : $type;
}
}
}
}
}
foreach ($arrayUso as $idLounge => $dates) {
foreach ($dates as $dateKey => $reservations) {
// Si el ID de la reserva está presente, obtener su dato
$datoId = isset($reservations[$id]) ? $reservations[$id] : 0;
foreach ($reservations as $reservationId => $dato) {
if ($reservationId != $id) {
if ($datoId === "Sala" && $dato === "Sala") {
$arrayAlert[$reservationId][] = array('dateKey' => $dateKey, 'idLounge' => $idLounge, 'reservationId' => $reservationId);
} elseif (($datoId === "Montaje" || $datoId === "Desmontaje") && ($dato === "Montaje" || $dato === "Desmontaje")) {
$arrayAlertMontDesmont[$reservationId][] = array('dateKey' => $dateKey, 'idLounge' => $idLounge, 'reservationId' => $reservationId);
} elseif ($datoId === "Sala" && ($dato === "Montaje" || $dato === "Desmontaje")) {
$arrayAlert[$reservationId][] = array('dateKey' => $dateKey, 'idLounge' => $idLounge, 'reservationId' => $reservationId);
} elseif (($datoId === "Montaje" || $datoId === "Desmontaje") && $dato === "Sala") {
$arrayAlert[$reservationId][] = array('dateKey' => $dateKey, 'idLounge' => $idLounge, 'reservationId' => $reservationId);
}
}
}
}
}
}
$reservationInDates = [];
if (!empty($arrayAlert)){
foreach ($arrayAlert as $key => $item){
$resvConf = $em->getRepository(Reservation::class)->findOneById($key);
$reservationInDates[] = $resvConf;
}
// La reserva no puede pasar a confirmada
$reserva->setStatus('Cotizado');
$em->persist($reserva);
$em->flush();
} else {
$mensajeWarning = '<br>';
if (!empty($arrayAlertMontDesmont)){
foreach ($arrayAlertMontDesmont as $key => $item){
$mensajeWarning .= 'Reserva ID: '. $key. '<br>';
}
$this->addFlash('mensajereservationerror', 'ADVERTENCIA, se han guardado los cambios, pero hay coincidencias en los Montajes y/o Desmontajes'. $mensajeWarning);
$reservationInDates = [];
}
}
return $reservationInDates;
}
private function disponibilidadAvExpress($id){
// $id Id de la reserva de GreenPatio que vamos a confirmar
$em = $this->getDoctrine()->getManager();
$reserva = $em->getRepository(Reservation::class)->findOneById($id);
//Sumamos un dia ya que por solicitud de Salva deseamos saber que eventos hay un dia antes y un dia despues
$fechaInicio = new \Datetime($reserva->getDateStart()->format('Y-m-d'));
$fechaInicio->sub(new \DateInterval("P1D"));
$fechaFin = new \Datetime($reserva->getDateEnd()->format('Y-m-d 23:59'));
$fechaFin->add(new \DateInterval("P1D"));
$parameters = array( 'dateStart' => $fechaInicio, 'dateEnd' => $fechaFin, );
$dql = 'SELECT i
FROM AvexpressBundle:AveFiles i
WHERE (i.dateStart <= i.dateEnd)
AND (
(i.dateStart <= :dateStart AND i.dateEnd >= :dateEnd)
OR (i.dateEnd = :dateStart)
OR (i.dateEnd > :dateStart AND i.dateEnd <= :dateEnd)
OR (i.dateStart = :dateStart)
OR (i.dateStart > :dateStart AND i.dateStart <= :dateEnd)
OR (i.dateStart = :dateEnd)
)
ORDER BY i.dateStart ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$avFilesInDates = $query->getResult();
return $avFilesInDates;
}
private function sendMailLot($mailAddressFrom, $mailArrayTo, $mailSubject, $mailBody){
$em = $this->getDoctrine()->getManager();
$agent = $em->getRepository(User::class)->findOneByEmail($mailAddressFrom);
$replyTo = array();
// Verificamos que los correos sean validos
foreach ($mailArrayTo as $item){ if (filter_var($item,FILTER_VALIDATE_EMAIL)){ $replyTo[$item] = $item; } }
$agentMail = $mailAddressFrom;
$mailAgent = $agentMail;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array( 'body' => $mailBody, 'firm' => $firmGmail, );
// EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
$transporter = new \Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername('desarrollo@develup.solutions')
->setPassword('utvh hzoi wfdo ztjs');
// ->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new \Swift_Mailer($transporter);
$message = new \Swift_Message();
$message->setSubject($mailSubject)
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($replyTo)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
return true;
}
private function notificacionReservasPorCotizar(){
// Se buscan las reservas en estado "Iniciado" y se notifica a todos los
// agentes de Green Patio, Solo se notifica 1 vez por dia
// Solo se mantendran las alertas de los ultimos 6 meses
$em = $this->getDoctrine()->getManager();
$alertas = $em->getRepository(ReservationAlertStarted::class)->findAll();
if (!empty($alertas)){ $ultimaAlerta = end($alertas); } else { $ultimaAlerta = null; }
$alertas = $em->getRepository(ReservationAlertStarted::class)->findAll();
$agentesGreenPatio = $em->getRepository(User::class)->findByUserrol(48);
$hoy = new DateTime('now');
$fechaLimite = new DateTime('now');
$fechaLimite->modify('-180 day');
if (!empty($ultimaAlerta)){ $mismaFecha = $ultimaAlerta->getAlertDate()->format('Ymd') == $hoy->format('Ymd'); } else { $mismaFecha = false; }
if ($mismaFecha){
// No se debe notificar, la ultima alerta es del dia de hoy
} else {
// Hay que notificar
if (empty($agentesGreenPatio)){ return true; }
$mailAddressFrom = $agentesGreenPatio[0]->getEmail();
$mailArrayTo = array();
foreach ($agentesGreenPatio as $agente){
$mailArrayTo[$agente->getEmail()] = $agente->getEmail();
}
$mailSubject = 'EXPENDIENTES POR COTIZAR';
$reservasIniciado = $em->getRepository(Reservation::class)->findByStatus('Iniciado');
$mailBody = null;
foreach ($reservasIniciado as $reserva){
$agenteReserva = $em->getRepository(User::class)->findOneById($reserva->getCreatedBy());
$agenteReserva = $agenteReserva->getName().' '.$agenteReserva->getLastName();
$mailBody = $mailBody. '<br>Evento: '.$reserva->getId().'<br>Nombre del Evento: '.$reserva->getTitle().'<br>Agente: '.$agenteReserva.'<br>Enlace al Evento: <a href="https://inout.mante.solutions/reservations-greenpatio/editsimple/'.$reserva->getId().'">"IR AL EXPEDIENTE"</a><br><br>';
}
if (!empty($mailBody)){
$this->sendMailLot($mailAddressFrom, $mailArrayTo, $mailSubject, $mailBody);
// Creamos la alerta del dia
$alertToday = new ReservationAlertStarted();
$alertToday->setAlertDate($hoy);
$alertToday->setMessage($mailBody);
$em->persist($alertToday);
$em->flush();
}
}
// Eliminamos las alertas con mas de 6 meses de antiguedad
foreach ($alertas as $alerta){
if ($alerta->getAlertDate() < $fechaLimite){
$em->remove($alerta);
$em->flush();
}
}
return true;
}
private function verificarCambioCliente( $idRes ){
// Solo se puede cambiar el cliente si no hay un documento emitido (factura, factura de deposito)
$em = $this->getDoctrine()->getManager();
$resInv = $em->getRepository(ReservationInvoice::class)->findByReservationId($idRes);
return empty($resInv);
}
private function reordenarSalas( $number, $idLounge ){
// number es el numero de la sala editada
$em = $this->getDoctrine()->getManager();
$number--;
$parameters = array( 'idLounge' => $idLounge, 'rankLounge' => $number, );
$dql = 'SELECT i
FROM GreenPatioBundle:ReservationLoungeDetails i
WHERE i.rankLounge > :rankLounge AND i.id <> :idLounge';
$query = $em->createQuery($dql)->setParameters($parameters);
$salasParaReordenar = $query->getResult();
foreach ($salasParaReordenar as $sala) {
$sala->setRankLounge(($sala->getRankLounge() + 1));
$em->persist($sala);
$em->flush();
}
return empty($resInv);
}
private function laReservaEsConfirmable( $id ){
$confirmable = false;
// Una reserva se puede confirmar solo cuando tiene un deposito realizado
$em = $this->getDoctrine()->getManager();
$depositos = $em->getRepository(ReservationDeposit::class)->findBy(array('reservationId' => $id, 'isDone' => true));
$depositos = true; // Rafa indica que este requisito no se usara por el momento 24/02/2025
// Si la reserva no tiene ninguna sala asignada, no se puede pasar a confirmado
$salas = $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation' => $id));
if (!empty($depositos) and !empty($salas)){ $confirmable = true; }
return $confirmable;
}
private function laReservaEsCotizable( $id ){
// Una reserva se puede cotizar solo cuando tiene al menos una sala agregada
$em = $this->getDoctrine()->getManager();
$salas = $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation' => $id));
return true; // Se pidio que siempre se sincronizara con Av
}
private function notificacionReservasPendientesDelSegundoDeposito(){
// Se buscan las reservas con depositos y se notifica a todos los
// agentes de Green Patio si no tienen el segundo deposito y faltan 30 días
// o menos para el evento, Solo se notifica 1 vez por dia
$em = $this->getDoctrine()->getManager();
$depositosHechos = $em->getRepository(ReservationDeposit::class)->findByIsDone(true);
$arrayDepositos = array();
$arrayReservasPemdientesSegunDepositos = array();
$today = new \Datetime('now');
$todayPlusMonth = new \Datetime('+ 30 days');
// Se agrupan los depositos por reservas
foreach ($depositosHechos as $item){ $arrayDepositos[$item->getReservationId()][] = $item; }
foreach ($arrayDepositos as $item){
if (sizeof($item)<2){
// Solo nos interesan reservas con un deposito
$reserva = $em->getRepository(Reservation::class)->findOneById($item[0]->getReservationId());
if ($reserva->getStatus() == 'Confirmed'){
// Solo nos interesan reservas confirmadas
if (($reserva->getDateStart() < $todayPlusMonth) and ($reserva->getDateStart()>$today)){
// Solo nos interesan reservas que inician en 30 dias
$arrayReservasPemdientesSegunDepositos[] = $reserva;
}
}
}
}
$alertas = $em->getRepository(ReservationAlertSecondDeposit::class)->findAll();
if (!empty($alertas)){ $ultimaAlerta = end($alertas); } else { $ultimaAlerta = null; }
$agentesGreenPatio = $em->getRepository(User::class)->findByUserrol(48);
$hoy = new DateTime('now');
$fechaLimite = new DateTime('now');
$fechaLimite->modify('-180 day');
if (!empty($ultimaAlerta)){ $mismaFecha = $ultimaAlerta->getAlertDate()->format('Ymd') == $hoy->format('Ymd'); } else { $mismaFecha = false; }
if ($mismaFecha){
// No se debe notificar, la ultima alerta es del dia de hoy
} else {
// Hay que notificar
if (empty($agentesGreenPatio)){ return true; }
$mailAddressFrom = $agentesGreenPatio[0]->getEmail();
$mailArrayTo = array();
foreach ($agentesGreenPatio as $agente){ $mailArrayTo[$agente->getEmail()] = $agente->getEmail(); }
$mailSubject = 'EXPENDIENTES CON DEPOSITOS PENDIENTES';
$reservasIniciado = $arrayReservasPemdientesSegunDepositos;
$mailBody = null;
foreach ($reservasIniciado as $reserva){
$agenteReserva = $em->getRepository(User::class)->findOneById($reserva->getCreatedBy());
$agenteReserva = $agenteReserva->getName().' '.$agenteReserva->getLastName();
$mailBody = $mailBody. '<br>Evento: '.$reserva->getId().'<br>Nombre del Evento: '.$reserva->getTitle().'<br>Agente: '.$agenteReserva.'<br>Enlace al Evento: <a href="https://inout.mante.solutions/reservations-greenpatio/editsimple/'.$reserva->getId().'">"IR AL EXPEDIENTE"</a><br><br>';
}
if (!empty($mailBody)){
$this->sendMailLot($mailAddressFrom, $mailArrayTo, $mailSubject, $mailBody);
// Creamos la alerta del dia
$alertToday = new ReservationAlertSecondDeposit();
$alertToday->setAlertDate($hoy);
$alertToday->setMessage($mailBody);
$em->persist($alertToday);
$em->flush();
}
}
// Eliminamos las alertas con mas de 6 meses de antiguedad
foreach ($alertas as $alerta){
if ($alerta->getAlertDate() < $fechaLimite){
$em->remove($alerta);
$em->flush();
}
}
return true;
}
};