<?php
namespace App\MDS\VenuesBundle\Controller;
use App\Entity\HtFile;
use App\Entity\ReservationLoungeWebDescription;
use App\Entity\SageArticle;
use App\Entity\SageVatRates;
use App\Entity\WidgetNotes;
use App\Form\WidgetNotesType;
use App\MDS\AvexpressBundle\Entity\AveFiles;
use App\MDS\VenuesBundle\Entity\Reservation;
use App\MDS\VenuesBundle\Entity\ReservationInvoiceItems;
use App\MDS\VenuesBundle\Entity\ReservationLoungeSimple;
use App\MDS\VenuesBundle\Entity\ReservationLoungeSimpleServiceLog;
use App\MDS\VenuesBundle\Entity\ReservationService;
use App\MDS\VenuesBundle\Entity\ReservationGpPrice;
use App\MDS\VenuesBundle\Entity\ReservationLounge;
use App\MDS\VenuesBundle\Entity\ReservationLoungeDetails;
use App\MDS\VenuesBundle\Entity\ReservationLoungeProfile;
use App\MDS\VenuesBundle\Entity\ReservationPeriod;
use App\MDS\VenuesBundle\Form\ReservationGpPriceType;
use App\MDS\VenuesBundle\Form\ReservationLoungeDetailsType;
use App\MDS\VenuesBundle\Form\ReservationLoungeProfileType;
use App\MDS\VenuesBundle\Form\ReservationPeriodType;
use App\MDS\VenuesBundle\Form\ReservationType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use DateTime;
use DatePeriod;
use DateInterval;
use Google_Client;
use Google_Service_Calendar;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\Translation\TranslatorInterface;
use App\Service\AgendaService;
use App\Service\VenueService;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class ReservationsQuoteController extends AbstractController
{
private Google_Client $googleCalendar;
private TranslatorInterface $translator;
private AgendaService $agendaService;
private SessionInterface $session;
private VenueService $venueService;
private \App\Service\ReservationService $reservationService;
private \App\Service\DocContractService $docContractService;
public function __construct(
TranslatorInterface $translator,
AgendaService $agendaService,
VenueService $venueService,
SessionInterface $session,
\App\Service\ReservationService $reservationService,
\App\Service\DocContractService $docContractService
) {
$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;
$this->agendaService = $agendaService;
$this->venueService = $venueService;
$this->session = $session;
$this->reservationService = $reservationService;
$this->docContractService = $docContractService;
}
/**
* @Route("/createsimplelounge/{id}", name="reservations_venues_create_simple_lounge")
* Crea un Reservation Lounge Simple en la cotizacion
*/
public function createSimpleLoungeAction($id, EntityManagerInterface $em, Request $request)
{
$simpleLounge = $request->request->all()['reservation_sala'] ?? [];
// Sala precargada
$loungeProfile = $em->getRepository(ReservationLoungeDetails::class)
->findOneById($simpleLounge['salaPrecargadas'] ?? null);
if (!$loungeProfile) {
$this->addFlash('mensajereservationerror', 'La sala seleccionada no existe.');
return $this->redirectToRoute('reservations_venues_edit', ['id' => $id]);
}
$loungeId = $loungeProfile->getId();
$loungeDetails = $em->getRepository(ReservationLoungeDetails::class)->findOneById($loungeId);
// Nombre de sala, necesario para Sage
$loungeName = '';
if ($loungeDetails && method_exists($loungeDetails, 'getName')) {
$loungeName = (string) $loungeDetails->getName();
} elseif (!empty($simpleLounge['loungeName'])) {
$loungeName = (string) $simpleLounge['loungeName'];
}
if ($loungeName === '') {
$this->addFlash('mensajereservationerror', 'No se pudo determinar el nombre de la sala.');
return $this->redirectToRoute('reservations_venues_edit', ['id' => $id]);
}
// ¿Existe ya esta sala en la misma reserva y rank?
$previusLoungeSimple = $em->getRepository(ReservationLoungeSimple::class)->findOneBy([
'idLounge' => $loungeId,
'idReservation' => $id,
'rankQuote' => $simpleLounge['idQuote'] ?? null
]);
// Heredar idioma si existe alguna sala previa en la reserva
$anyLoungeSimple = $em->getRepository(ReservationLoungeSimple::class)->findOneBy([
'idLounge' => $loungeId,
'idReservation' => $id
]);
$idioma = $anyLoungeSimple ? (int) $anyLoungeSimple->getLanguage() : 1;
// Descripciones web por sala/idioma con fallbacks
$loungeWebDescriptionRepo = $em->getRepository(ReservationLoungeWebDescription::class);
$loungeWebDescription = $loungeWebDescriptionRepo->findOneBy([
'lounge' => $loungeProfile,
'language' => $idioma
]) ?? ($idioma !== 1 ? $loungeWebDescriptionRepo->findOneBy([
'lounge' => $loungeProfile,
'language' => 1
]) : null) ?? $loungeWebDescriptionRepo->findOneBy(['lounge' => $loungeProfile]);
// Summary recibido del formulario (opcional)
$loungeSummaryDescription = is_array($simpleLounge) && array_key_exists('importantDescription', $simpleLounge)
? (string) $simpleLounge['importantDescription']
: null;
if (empty($previusLoungeSimple)) {
// Sin anterior, tiramos de WebDescription si existe
$loungeImportantDescGeneralText = $loungeWebDescription ? $loungeWebDescription->getImportantDescGeneralText() : '';
$loungeImportantDescSchedules = $loungeWebDescription ? $loungeWebDescription->getImportantDescSchedules() : '';
$loungeImportantDescParking = $loungeWebDescription ? $loungeWebDescription->getImportantDescParking() : '';
if (empty($loungeSummaryDescription)) {
$loungeSummaryDescription = $loungeWebDescription ? $loungeWebDescription->getImportantDescription() : '';
}
} else {
// Heredamos de la simple existente
$loungeSummaryDescription = $previusLoungeSimple->getImportantDescription();
$loungeImportantDescGeneralText = $previusLoungeSimple->getImportantDescGeneralText();
$loungeImportantDescSchedules = $previusLoungeSimple->getImportantDescSchedules();
$loungeImportantDescParking = $previusLoungeSimple->getImportantDescParking();
}
// Reserva para calcular sucoe e IVA
$reservation = $em->getRepository(Reservation::class)->findOneById($id);
if (!$reservation) {
$this->addFlash('mensajereservationerror', 'No se encontró la reserva.');
return $this->redirectToRoute('reservations_venues_edit', ['id' => $id]);
}
$sucoe = (bool) $reservation->isSucoe();
$sageVatRate = $em->getRepository(SageVatRates::class)->findOneBy([
'sageCode' => $sucoe ? '00' : '03'
]);
// Artículo Sage por nombre de sala + tipo IVA
$sageArticle = $em->getRepository(SageArticle::class)->findOneBy([
'vatType' => $sageVatRate,
'name' => $loungeName
]);
// Solo salta el error si no se ha encontrado el artículo y está el modulo de Sage activo
if (!$sageArticle && $this->session->get('_config')['msage']) {
$this->addFlash('mensajereservationerror', 'No se ha encontrado el artículo de Sage para la sala: ' . $loungeName);
return $this->redirectToRoute('reservations_venues_edit', ['id' => $id]);
}
// Normalización horas desde POST
$hourMinStart = (string) ($simpleLounge['hourStart'] ?? '');
$hourMinEnd = (string) ($simpleLounge['hourEnd'] ?? '');
// Normalización horas desde POST usando el servicio
$startData = $this->reservationService->formatTimeInput((string) ($simpleLounge['hourStart'] ?? ''));
$endData = $this->reservationService->formatTimeInput((string) ($simpleLounge['hourEnd'] ?? ''));
$hourStart = $startData['hour'];
$minStart = $startData['min'];
$hourEnd = $endData['hour'];
$minEnd = $endData['min'];
$dateStart = new \DateTime(($simpleLounge['dateStart'] ?? date('Y-m-d')) . ' ' . $startData['formatted']);
$dateEnd = new \DateTime(($simpleLounge['dateStart'] ?? date('Y-m-d')) . ' ' . $endData['formatted']); // un solo día
$servicePrice = (float) ($simpleLounge['servicePrice'] ?? 0);
$idReservation = (int) $id;
// Usuario
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado ? $user_logueado->getId() : null;
$createdAt = new \DateTime('now');
$updatedAt = new \DateTime('now');
$pax = (int) ($simpleLounge['pax'] ?? 0);
// Rank de cotización
$qb = $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
$reservationAll = $qb->where('r.idReservation = :idReservation')
->setParameter('idReservation', $id)
->orderBy('r.rankQuote', 'ASC')
->getQuery()
->getResult();
$newRankId = (!empty($reservationAll)) ? (end($reservationAll)->getRankQuote() + 1) : 1;
if (!empty($simpleLounge['idQuote']) && is_numeric($simpleLounge['idQuote'])) {
$newRankId = (int) $simpleLounge['idQuote'];
}
// Tipo: Dia de evento (null), Montaje o Desmontaje
$typeXLounge = empty($simpleLounge['type']) ? null : $simpleLounge['type'];
// Crear la entidad
$lounge = new ReservationLoungeSimple();
$lounge->setIdLounge($loungeId);
$lounge->setHourStart($hourStart);
$lounge->setMinStart($minStart);
$lounge->setHourEnd($hourEnd);
$lounge->setMinEnd($minEnd);
$lounge->setLoungeName($loungeName);
$lounge->setDateStart($dateStart);
$lounge->setDateEnd($dateEnd);
$lounge->setRankQuote($newRankId);
$lounge->setIdReservation($idReservation);
$lounge->setType($typeXLounge);
$lounge->setSageIva($sageVatRate);
$lounge->setOpIva(1);
$lounge->setCreatedAt($createdAt);
$lounge->setCreatedBy($user_id);
$lounge->setUpdatedAt($updatedAt);
$lounge->setUpdatedBy($user_id);
$lounge->setPax($pax);
$lounge->setImportantDescription($loungeSummaryDescription ?? '');
$lounge->setImportantDescGeneralText($loungeImportantDescGeneralText ?? '');
$lounge->setImportantDescSchedules($loungeImportantDescSchedules ?? '');
$lounge->setImportantDescParking($loungeImportantDescParking ?? '');
// Precio tarifario
$price = $this->reservationService->getTariffPrice($dateStart, $loungeId, $servicePrice);
$lounge->setServicePrice($price);
// Vincular la sala al artículo
$lounge->setSageArticle($sageArticle);
try {
$em->persist($lounge);
$em->flush();
$event = 'The Reservation 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);
}
//Se llama al servicio para crear la entrada en la agenda y actualizar el Pax de la agenda
$loungeNameAgenda = empty($typeXLounge) ? $loungeName : $loungeName . ' ( ' . $typeXLounge . ' ) ';
$agenda = $this->agendaService->createAgendaFromSource($idReservation, 'SALAS A UTILIZAR', null, null, $dateStart, $dateEnd, $loungeNameAgenda, $lounge->getId(), 'ReservationLoungeSimple', $user_id);
$paxAge = $this->agendaService->calculatePaxForReservation($idReservation);
$agenda = $this->agendaService->updatePaxLine($idReservation, $paxAge, $user_id);
// Actualizar fechas de la reserva usando el servicio
if ($reservation) {
$this->reservationService->updateReservationDates($reservation);
//Se llama al servicio para crear la entrada en la agenda de las fechas
$this->agendaService->updateDatesLine($idReservation, $user_id);
}
// Creamos la Snapshot de las salas y servicios del sistema (LOG)
$version = $this->venueService->createSnapshot($reservation);
// Sincronizar contratos si está confirmado
if ($reservation->getStatus() === 'Confirmed') {
$this->docContractService->autoAssignContracts($reservation, $user_logueado);
}
// Redirección para agregar servicio de limpieza
return $this->redirectToRoute('reservations_white_addservices_cleaning', [
'resid' => $id,
'loungesimpleid' => $lounge->getId(),
]);
}
/**
* @Route("/api/get-price", name="get_reservations_price_to_view", methods={"GET"})
*/
public function getPrice(Request $request)
{
$loungeId = $request->query->get('sala');
$dateStart = $request->query->get('date');
if (!$loungeId || !$dateStart) {
return new JsonResponse(['error' => 'Missing parameters'], 400);
}
try {
$dateStartObj = new \DateTime($dateStart);
} catch (\Exception $e) {
return new JsonResponse(['error' => 'Invalid date'], 400);
}
$price = $this->reservationService->getTariffPrice($dateStartObj, $loungeId, 0);
return new JsonResponse(['price' => $price]);
}
/**
* @Route("/createsimpleloungemondes/{id}", name="reservations_venues_create_simple_lounge_mondes")
* Se crea un dia de montaje o desmontaje
*/
public function createSimpleLoungeMonDesAction($id, EntityManagerInterface $em, Request $request)
{
$simpleLounge = $request->request->get('reservation_sala_mondes');
$loungeId = $simpleLounge['idLounge'];
$loungeDetails = $em->getRepository(ReservationLoungeDetails::class)->findOneById($loungeId);
$previusLoungeSimple = $em->getRepository(ReservationLoungeSimple::class)->findOneBy(array('idLounge' => $loungeId, 'idReservation' => $id, 'rankQuote' => $simpleLounge['idQuote']));
$loungeName = $loungeDetails->getName();
$hourMinStart = $simpleLounge['hourStart'];
$hourMinEnd = $simpleLounge['hourEnd'];
// Buscamos la reserva que es para saber si es sucoe o no
$reservation = $em->getRepository(Reservation::class)->findOneById($id);
$sucoe = $reservation->isSucoe();
// Si no es sucoe, cogemos el IVA del 21% y si lo es, entonces el del 0%
if (!$sucoe) {
$sageVatRate = $em->getRepository(SageVatRates::class)->findOneBy(['sageCode' => '03']);
} else {
$sageVatRate = $em->getRepository(SageVatRates::class)->findOneBy(['sageCode' => '00']);
}
$sageArticle = $em->getRepository(SageArticle::class)->findOneBy(['vatType' => $sageVatRate, 'name' => $loungeName]);
// Si no se ha encontrado el artículo de Sage.
if (empty($sageArticle)) {
$this->addFlash('mensajereservationerror', 'No se ha encontrado el artículo de Sage para la sala: ' . $loungeName);
return $this->redirectToRoute('reservations_venues_edit', array(
'id' => $id,
));
}
if (empty($previusLoungeSimple)) {
$loungeSummaryDescription = $loungeDetails->getImportantDescription();
$loungeImportantDescGeneralText = $loungeDetails->getImportantDescGeneralText();
$loungeImportantDescSchedules = $loungeDetails->getImportantDescSchedules();
$loungeImportantDescParking = $loungeDetails->getImportantDescParking();
} else {
$loungeSummaryDescription = $previusLoungeSimple->getImportantDescription();
$loungeImportantDescGeneralText = $previusLoungeSimple->getImportantDescGeneralText();
$loungeImportantDescSchedules = $previusLoungeSimple->getImportantDescSchedules();
$loungeImportantDescParking = $previusLoungeSimple->getImportantDescParking();
}
$qb = $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
$reservationAll = $qb->where('r.idReservation = :idReservation')
->setParameter('idReservation', $id)
->orderBy('r.rankQuote', 'ASC')
->getQuery()
->getResult();
$newRankId = (!empty($reservationAll)) ? (end($reservationAll)->getRankQuote() + 1) : 1;
if (!empty($simpleLounge['idQuote'])) {
if (is_numeric($simpleLounge['idQuote'])) {
$newRankId = $simpleLounge['idQuote'];
}
}
// Normalización horas desde POST usando el servicio
$startData = $this->reservationService->formatTimeInput((string) ($simpleLounge['hourStart'] ?? ''));
$endData = $this->reservationService->formatTimeInput((string) ($simpleLounge['hourEnd'] ?? ''));
$hourStart = $startData['hour'];
$minStart = $startData['min'];
$hourEnd = $endData['hour'];
$minEnd = $endData['min'];
$hourMinStart = $startData['formatted'];
$hourMinEnd = $endData['formatted'];
$dateStart = new DateTime($simpleLounge['dateStart'] . ' ' . $hourMinStart);
$dateEnd = new DateTime($simpleLounge['dateStart'] . ' ' . $hourMinEnd); // Se usa DateStart por que solo hay un dia en el formulario
$servicePrice = empty($simpleLounge['servicePrice']) ? 0 : $simpleLounge['servicePrice'];
$idReservation = $id;
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$createdAt = new DateTime('now');
$createdBy = $user_id;
$updatedAt = new DateTime('now');
$updatedBy = $user_id;
$lounge = new ReservationLoungeSimple();
if ($simpleLounge['type'] == 'Montaje') {
$lounge->setType('Montaje');
} else {
$lounge->setType('Desmontaje');
}
$pax = 0;
$lounge->setIdLounge($loungeId);
$lounge->setHourStart($hourStart);
$lounge->setMinStart($minStart);
$lounge->setHourEnd($hourEnd);
$lounge->setMinEnd($minEnd);
$lounge->setLoungeName($loungeName);
$lounge->setDateStart($dateStart);
$lounge->setDateEnd($dateEnd);
$lounge->setRankQuote(1);
$lounge->setSageIva($sageArticle->getVatType());
$lounge->setOpIva(1);
$lounge->setIdReservation($idReservation);
$lounge->setCreatedAt($createdAt);
$lounge->setCreatedBy($createdBy);
$lounge->setUpdatedAt($updatedAt);
$lounge->setUpdatedBy($updatedBy);
$lounge->setPax($pax);
$lounge->setRankQuote($newRankId);
$lounge->setImportantDescription($loungeSummaryDescription);
$lounge->setImportantDescGeneralText($loungeImportantDescGeneralText);
$lounge->setImportantDescSchedules($loungeImportantDescSchedules);
$lounge->setImportantDescParking($loungeImportantDescParking);
$price = 0; // Se asume 0 según lógica de precioPorFecha original que era inalcanzable
$servicePrice = ($price == 0) ? $servicePrice : $price;
$lounge->setServicePrice($servicePrice);
// Vincular la sala al artículo
$lounge->setSageArticle($sageArticle);
try {
$em->persist($lounge);
$em->flush();
$event = 'The Reservation 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);
}
$reservax = $em->getRepository(Reservation::class)->findOneById($idReservation);
if ($reservax) {
$this->reservationService->updateReservationDates($reservax);
// Sincronizar contratos si está confirmado
if ($reservax->getStatus() === 'Confirmed') {
$this->docContractService->autoAssignContracts($reservax, $user_logueado);
}
}
// FIN: Verificamos si es necesario actualizar las fechas de la reserva
return $this->redirectToRoute(
'reservations_venues_edit_simple',
array(
'id' => $id,
'token' => null,
'_fragment' => 'btn_quotes'
)
);
}
/**
* @Route("/duplicateday/{id}/{dayduplicate}/{idRankQuote}", name="reservations_venues_duplicate_day")
* Duplica un elemento de la cotizacion para el dia siguiente
*/
public function duplicateDayAction($id, $dayduplicate, $idRankQuote, EntityManagerInterface $em, Request $request)
{
$loungeSimples = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
$reservax = $em->getRepository(Reservation::class)->findOneById($id);
$vatRepo = $em->getRepository(SageVatRates::class);
/* Usuario logueado */
$user = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user ? $user->getId() : null;
$createdAt = new \DateTime('now');
$updatedAt = new \DateTime('now');
$createdBy = $user_id;
$updatedBy = $user_id;
if (!empty($loungeSimples)) {
foreach ($loungeSimples as $item) {
if (
$item->getDateStart() &&
$item->getDateStart()->format('d-m-Y') == $dayduplicate &&
$item->getRankQuote() == $idRankQuote
) {
// Se duplica y suma un día (sin mutar el original)
$newLoungeSimple = new ReservationLoungeSimple();
$newLoungeSimple->setDateStart((clone $item->getDateStart())->modify('+1 day'));
$newLoungeSimple->setDateEnd((clone $item->getDateEnd())->modify('+1 day'));
$newLoungeSimple->setHourStart($item->getHourStart());
$newLoungeSimple->setHourEnd($item->getHourEnd());
$newLoungeSimple->setMinStart($item->getMinStart());
$newLoungeSimple->setMinEnd($item->getMinEnd());
$newLoungeSimple->setIdLounge($item->getIdLounge());
$newLoungeSimple->setIdReservation($item->getIdReservation());
$newLoungeSimple->setLoungeName($item->getLoungeName());
$newLoungeSimple->setPax($item->getPax());
$newLoungeSimple->setServicePrice($item->getServicePrice());
// IVA (string)
$newLoungeSimple->setIva($item->getIva());
// Relación SageVatRates (entidad)
$vatEntity = method_exists($item, 'getSageIva') ? $item->getSageIva() : null;
if (!$vatEntity) {
$rawRate = $item->getIva();
if ($rawRate !== null && $rawRate !== '') {
$rate = (float) $rawRate;
// Normaliza si en BD está como fracción (0.21)
if ($rate > 1) {
$rate = $rate / 100;
}
// Ajusta 'rate' si tu campo en SageVatRates tiene otro nombre
$vatEntity = $vatRepo->findOneBy(['rate' => $rate]);
}
}
$newLoungeSimple->setSageIva($vatEntity);
$newLoungeSimple->setOpIva($item->getOpIva());
$newLoungeSimple->setType($item->getType());
$newLoungeSimple->setLoungeDescription($item->getLoungeDescription());
$newLoungeSimple->setImportantDescription($item->getImportantDescription());
$newLoungeSimple->setImportantDescGeneralText($item->getImportantDescGeneralText());
$newLoungeSimple->setImportantDescSchedules($item->getImportantDescSchedules());
$newLoungeSimple->setImportantDescParking($item->getImportantDescParking());
$newLoungeSimple->setRankQuote($idRankQuote);
$newLoungeSimple->setCreatedAt($createdAt);
$newLoungeSimple->setCreatedBy($createdBy);
$newLoungeSimple->setUpdatedAt($updatedAt);
$newLoungeSimple->setUpdatedBy($updatedBy);
try {
$em->persist($newLoungeSimple);
$em->flush();
$event = 'The Item has been duplicated.';
$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);
}
// Actualiza fechas de la reserva si procede
$boolReserva = false;
if ($newLoungeSimple->getDateStart() < $reservax->getDateStart()) {
$reservax->setDateStart($newLoungeSimple->getDateStart());
$boolReserva = true;
}
if ($reservax->getDateEnd() < $newLoungeSimple->getDateEnd()) {
$reservax->setDateEnd($newLoungeSimple->getDateEnd());
$boolReserva = true;
}
if ($boolReserva) {
$em->persist($reservax);
$em->flush();
}
}
}
} else {
// Registro antiguo: transformar a los nuevos y luego duplicar
$loungeOld = $em->getRepository(ReservationLounge::class)->findByIdReservation($id);
foreach ($loungeOld as $item) {
if ($item->getDateStart()->format('Y-m-d') == $item->getDateEnd()->format('Y-m-d')) {
// Mismo día → simple
$newLoungeSimple = new ReservationLoungeSimple();
$newLoungeSimple->setDateStart(clone $item->getDateStart());
$newLoungeSimple->setDateEnd(clone $item->getDateEnd());
$newLoungeSimple->setHourStart($item->getHourStart());
$newLoungeSimple->setHourEnd($item->getHourEnd());
$newLoungeSimple->setMinStart($item->getMinStart());
$newLoungeSimple->setMinEnd($item->getMinEnd());
$newLoungeSimple->setIdLounge($item->getIdLounge());
$newLoungeSimple->setIdReservation($item->getIdReservation());
$newLoungeSimple->setLoungeName($item->getLoungeName());
$newLoungeSimple->setPax($item->getPax());
$newLoungeSimple->setServicePrice($item->getServicePrice());
// IVA (string)
$newLoungeSimple->setIva($item->getIva());
// Resolver SageVatRates desde el string
$rawRate = $item->getIva();
$vatEnt = null;
if ($rawRate !== null && $rawRate !== '') {
$rate = (float) $rawRate;
if ($rate > 1) {
$rate = $rate / 100;
}
$vatEnt = $vatRepo->findOneBy(['rate' => $rate]);
}
$newLoungeSimple->setSageIva($vatEnt);
$newLoungeSimple->setOpIva($item->getOpIva());
$newLoungeSimple->setType($item->getType());
$newLoungeSimple->setRankQuote($item->getRankQuote());
$newLoungeSimple->setLoungeDescription($item->getLoungeDescription());
$newLoungeSimple->setImportantDescription($item->getImportantDescription());
$newLoungeSimple->setCreatedAt($createdAt);
$newLoungeSimple->setCreatedBy($createdBy);
$newLoungeSimple->setUpdatedAt($updatedAt);
$newLoungeSimple->setUpdatedBy($updatedBy);
try {
$em->persist($newLoungeSimple);
$em->flush();
$event = 'The Item has been duplicated.';
$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);
}
// Actualiza fechas de la reserva si procede
$boolReserva = false;
if ($newLoungeSimple->getDateStart() < $reservax->getDateStart()) {
$reservax->setDateStart($newLoungeSimple->getDateStart());
$boolReserva = true;
}
if ($reservax->getDateEnd() < $newLoungeSimple->getDateEnd()) {
$reservax->setDateEnd($newLoungeSimple->getDateEnd());
$boolReserva = true;
}
if ($boolReserva) {
$em->persist($reservax);
$em->flush();
}
} else {
// Varios días → trocear en simples
$firstDay = new \DateTime($item->getDateStart()->format('Y-m-d'));
$lastDay = new \DateTime($item->getDateEnd()->format('Y-m-d'));
$numDays = ($lastDay->diff($firstDay))->days + 1;
$actualDay = clone $item->getDateStart();
$actualStartDay = clone $item->getDateStart();
$actualEndDay = clone $item->getDateEnd();
for ($i = 0; $i < $numDays; $i++) {
$newLoungeSimple = new ReservationLoungeSimple();
if ($i === 0) {
// Primer día
$newLoungeSimple->setDateStart(clone $actualStartDay);
$newLoungeSimple->setDateEnd(new \DateTime($actualStartDay->format('Y-m-d') . ' 23:59'));
$newLoungeSimple->setHourStart($item->getHourStart());
$newLoungeSimple->setHourEnd('23');
$newLoungeSimple->setMinStart($item->getMinStart());
$newLoungeSimple->setMinEnd('59');
} elseif (($i + 1) === $numDays) {
// Último día
$newLoungeSimple->setDateStart(new \DateTime($actualEndDay->format('Y-m-d') . ' 00:00'));
$newLoungeSimple->setDateEnd(clone $actualEndDay);
$newLoungeSimple->setHourStart('00');
$newLoungeSimple->setHourEnd($item->getHourEnd());
$newLoungeSimple->setMinStart('00');
$newLoungeSimple->setMinEnd($item->getMinEnd());
} else {
// Día intermedio
$newLoungeSimple->setDateStart(new \DateTime($actualDay->format('Y-m-d') . ' 00:00'));
$newLoungeSimple->setDateEnd(new \DateTime($actualDay->format('Y-m-d') . ' 23:59'));
$newLoungeSimple->setHourStart('00');
$newLoungeSimple->setHourEnd('23');
$newLoungeSimple->setMinStart('00');
$newLoungeSimple->setMinEnd('59');
}
$newLoungeSimple->setIdLounge($item->getIdLounge());
$newLoungeSimple->setIdReservation($item->getIdReservation());
$newLoungeSimple->setLoungeName($item->getLoungeName());
$newLoungeSimple->setPax($item->getPax());
$newLoungeSimple->setServicePrice($item->getServicePrice());
// IVA (string) + entidad
$newLoungeSimple->setIva($item->getIva());
$rawRate = $item->getIva();
$vatEnt = null;
if ($rawRate !== null && $rawRate !== '') {
$rate = (float) $rawRate;
if ($rate > 1) {
$rate = $rate / 100;
}
$vatEnt = $vatRepo->findOneBy(['rate' => $rate]);
}
$newLoungeSimple->setSageIva($vatEnt);
$newLoungeSimple->setOpIva($item->getOpIva());
$newLoungeSimple->setType($item->getType());
$newLoungeSimple->setRankQuote($item->getRankQuote());
$newLoungeSimple->setLoungeDescription($item->getLoungeDescription());
$newLoungeSimple->setImportantDescription($item->getImportantDescription());
$newLoungeSimple->setCreatedAt($createdAt);
$newLoungeSimple->setCreatedBy($createdBy);
$newLoungeSimple->setUpdatedAt($updatedAt);
$newLoungeSimple->setUpdatedBy($updatedBy);
// Avanza el día (sin perder la referencia)
$actualDay = (clone $actualDay)->modify('+1 day');
try {
$em->persist($newLoungeSimple);
$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);
}
// Actualiza fechas de la reserva si procede
$boolReserva = false;
if ($newLoungeSimple->getDateStart() < $reservax->getDateStart()) {
$reservax->setDateStart($newLoungeSimple->getDateStart());
$boolReserva = true;
}
if ($reservax->getDateEnd() < $newLoungeSimple->getDateEnd()) {
$reservax->setDateEnd($newLoungeSimple->getDateEnd());
$boolReserva = true;
}
if ($boolReserva) {
$em->persist($reservax);
$em->flush();
}
}
}
// Re-llama al mismo controlador ahora con la nueva tabla poblada
return $this->redirectToRoute('reservations_venues_duplicate_day', [
'id' => $id,
'dayduplicate' => $dayduplicate,
]);
}
}
//Se llama al servicio para crear la entrada en la agenda y actualizar el Pax de la agenda
$agenda = $this->agendaService->createAgendaFromSource($newLoungeSimple->getIdReservation(), 'SALAS A UTILIZAR', null, null, $newLoungeSimple->getDateStart(), $newLoungeSimple->getDateEnd(), $newLoungeSimple->getLoungeName(), $newLoungeSimple->getId(), 'ReservationLoungeSimple', $updatedBy);
$reserva = $em->getRepository(Reservation::class)->findOneById($newLoungeSimple->getIdReservation());
//Se llama al servicio para crear la entrada en la agenda de las fechas
$agenda = $this->agendaService->updateDatesLine($reserva->getId(), $updatedBy);
// Creamos la Snapshot de las salas y servicios del sistema (LOG)
$version = $this->venueService->createSnapshot($reservax);
/* Obtengo usuario logueado */
$user = $this->get('security.token_storage')->getToken()->getUser();
// Sincronizar contratos si está confirmado
if ($reservax->getStatus() === 'Confirmed') {
$this->docContractService->autoAssignContracts($reservax, $user);
}
// Redirige para agregar Servicio de limpieza
return $this->redirectToRoute('reservations_white_addservices_cleaning', [
'resid' => $id,
'loungesimpleid' => isset($newLoungeSimple) ? $newLoungeSimple->getId() : null,
]);
}
/**
* @Route("/deleteitemsimple/{id}/{daydelete}", name="reservations_venues_delete_simple_lounge")
* Elimina un Reservation Simple Lounge de la cotizacion
*/
public function deleteSimpleLoungeAction($id, $daydelete, EntityManagerInterface $em, Request $request)
{
$loungeSimple = $em->getRepository(ReservationLoungeSimple::class)->findOneById($id);
if (!empty($loungeSimple)) {
//Se llama al servicio para eliminar la entrada en la agenda
$agenda = $this->agendaService->deleteAgendaBySource($loungeSimple->getId(), 'ReservationLoungeSimple');
}
$id = $loungeSimple->getIdReservation();
$reserva = $em->getRepository(Reservation::class)->findOneById($loungeSimple->getIdReservation());
try {
$em->remove($loungeSimple);
$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();
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajereservationerror', $errorMessage);
}
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
// Recalcular fechas de la reserva usando el servicio
if ($reserva) {
$this->reservationService->updateReservationDates($reserva);
// Sincronizar contratos si está confirmado
if ($reserva->getStatus() === 'Confirmed') {
$this->docContractService->autoAssignContracts($reserva, $user_logueado);
}
}
$user_id = $user_logueado->getId();
//Se llama al servicio para crear la entrada en la agenda de las fechas
$agenda = $this->agendaService->updateDatesLine($reserva->getId(), $user_id);
//Se llama al servicio para actualizar Pax en la agenda
$paxAge = $this->agendaService->calculatePaxForReservation($reserva->getId());
$agenda = $this->agendaService->updatePaxLine($reserva->getId(), $paxAge, $user_id);
// Se elimina el servicio de horas de limpieza de la sala
return $this->redirectToRoute(
'reservations_venues_delete_simple_lounge_cleaning',
array(
'idRes' => $id,
'idLng' => $loungeSimple->getIdLounge(),
'dateInAt' => $loungeSimple->getDateStart()->format('Y-m-d\TH:i'),
'dateOutAt' => $loungeSimple->getDateEnd()->format('Y-m-d\TH:i'),
)
);
}
/**
* @Route("/deletequote/{idRes}/{idQuote}", name="reservations_delete_quote")
* Eliminar una cotizancion
*/
public function deleteQuoteAction($idRes, $idQuote, EntityManagerInterface $em, Request $request)
{
$qb = $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
$reservation = $qb->where('r.rankQuote = :rankQuote')
->andWhere('r.idReservation = :idReservation')
->setParameter('idReservation', $idRes)
->setParameter('rankQuote', $idQuote)
->getQuery()
->getResult();
foreach ($reservation as $item) {
try {
if (!empty($item)) {
//Se llama al servicio para eliminar la entrada en la agenda
$agenda = $this->agendaService->deleteAgendaBySource($item->getId(), 'ReservationLoungeSimple');
}
$em->remove($item);
$em->flush();
$event = 'Se ha eliminado la cotización';
$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);
}
//Se deben eliminar todas las horas de limpieza asociadas a las salas de la cotización
$loungeDetails = $em->getRepository(ReservationLoungeDetails::class)->findOneById($item->getIdLounge());
$stringName = 'HORAS ( ' . $loungeDetails->getName() . ' )';
$serviceCatIdClean = 21;
$dateInAt = new \DateTime($item->getDateStart()->format('Y-m-d\TH:i'));
$dateOutAt = new \DateTime($item->getDateEnd()->format('Y-m-d\TH:i'));
$qb = $em->getRepository(ReservationService::class)->createQueryBuilder('rs');
$serviceClean = $qb->where('rs.reservationId = :id')
->andWhere('rs.name = :name')
->andWhere('rs.dateInAt = :dateInAt')
->andWhere('rs.dateOutAt = :dateOutAt')
->andWhere('rs.serviceCatId = :serviceCatId')
->setParameter('id', $idRes)
->setParameter('name', $stringName)
->setParameter('dateInAt', $dateInAt)
->setParameter('dateOutAt', $dateOutAt)
->setParameter('serviceCatId', $serviceCatIdClean)
->getQuery()
->getResult();
if (!empty($serviceClean)) {
// Se elimina el servicio de horas de limpieza de la sala
$em->remove($serviceClean[0]);
$em->flush();
}
}
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
//Se llama al servicio para actualizar Pax en la agenda
$paxAge = $this->agendaService->calculatePaxForReservation($idRes);
$agenda = $this->agendaService->updatePaxLine($idRes, $paxAge, $user_id);
//Se llama al servicio para actualizar Fechas en la agenda
$agenda = $this->agendaService->updateDatesLine($idRes, $user_id);
// Recalcular fechas de la reserva
$reservaEntity = $em->getRepository(Reservation::class)->find($idRes);
if ($reservaEntity) {
$this->reservationService->updateReservationDates($reservaEntity);
}
return $this->redirectToRoute(
'reservations_venues_edit_simple',
array(
'id' => $idRes,
'token' => null,
'_fragment' => 'btn_quotes'
)
);
}
/**
* @Route("/checkquote/{idRes}/{idQuote}", name="reservations_check_quote")
* Confirmación de que se ha aceptado la cotizancion, se eliminaran las otras cotizaciones del expediente
*/
public function checkQuoteAction($idRes, $idQuote, EntityManagerInterface $em, Request $request)
{
$qb = $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
$reservation = $qb->where('r.rankQuote <> :rankQuote')
->andWhere('r.idReservation = :idReservation')
->setParameter('idReservation', $idRes)
->setParameter('rankQuote', $idQuote)
->getQuery()
->getResult();
foreach ($reservation as $item) {
try {
if (!empty($item)) {
//Se llama al servicio para eliminar la entrada en la agenda
$agenda = $this->agendaService->deleteAgendaBySource($item->getId(), 'ReservationLoungeSimple');
}
$em->remove($item);
$em->flush();
$event = 'Se han eliminado las otras cotizaciones';
$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);
}
}
// Actualizar fechas de la reserva usando el servicio
$reservation = $em->getRepository(Reservation::class)->findOneById($idRes);
$this->reservationService->updateReservationDates($reservation);
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
//Se llama al servicio para actualizar Pax en la agenda
$paxAge = $this->agendaService->calculatePaxForReservation($idRes);
$agenda = $this->agendaService->updatePaxLine($idRes, $paxAge, $user_id);
//Se llama al servicio para actualizar Fechas en la agenda
$agenda = $this->agendaService->updateDatesLine($idRes, $user_id);
return $this->redirectToRoute(
'reservations_venues_edit_simple',
array(
'id' => $idRes,
'token' => null,
'_fragment' => 'btn_quotes'
)
);
}
/**
* @Route("/duplicatequote", name="reservations_duplicate_quote")
* Duplicar una cotizacion
*/
public function duplicateQuoteAction(EntityManagerInterface $em, Request $request)
{
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$hoy = new \DateTime("now", NULL);
$reqDuplicateQuote = $request->request->get('addquote');
$newLounge = $em->getRepository(ReservationLoungeDetails::class)->findOneById($reqDuplicateQuote['salaPrecargadas']);
$qb = $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
$reservationAll = $qb->where('r.idReservation = :idReservation')
->setParameter('idReservation', $reqDuplicateQuote['reservationId'])
->orderBy('r.rankQuote', 'ASC')
->getQuery()
->getResult();
$newRankId = (!empty($reservationAll)) ? (end($reservationAll)->getRankQuote() + 1) : 1;
if (empty($reqDuplicateQuote['idQuote'])) {
$reqDuplicateQuote['idQuote'] = reset($reservationAll)->getRankQuote();
} //Si no elige cotización se duplica la primera
$qb = $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
$reservation = $qb->where('r.rankQuote = :rankQuote')
->andWhere('r.idReservation = :idReservation')
->setParameter('idReservation', $reqDuplicateQuote['reservationId'])
->setParameter('rankQuote', $reqDuplicateQuote['idQuote'])
->getQuery()
->getResult();
// Descripciones web por sala/idioma con fallbacks
$loungeProfile = $newLounge;
// Heredar idioma si existe alguna sala previa en la reserva
$idioma = empty($reservationAll) ? 1: $reservationAll[0]->getLanguage();
$loungeWebDescriptionRepo = $em->getRepository(ReservationLoungeWebDescription::class);
$loungeWebDescription = $loungeWebDescriptionRepo->findOneBy([
'lounge' => $loungeProfile,
'language' => $idioma
]) ?? ($idioma !== 1 ? $loungeWebDescriptionRepo->findOneBy([
'lounge' => $loungeProfile,
'language' => 1
]) : null) ?? $loungeWebDescriptionRepo->findOneBy(['lounge' => $loungeProfile]);
$loungeImportantDescGeneralText = $loungeWebDescription ? $loungeWebDescription->getImportantDescGeneralText() : '';
$loungeImportantDescSchedules = $loungeWebDescription ? $loungeWebDescription->getImportantDescSchedules() : '';
$loungeImportantDescParking = $loungeWebDescription ? $loungeWebDescription->getImportantDescParking() : '';
$loungeSummaryDescription = $loungeWebDescription ? $loungeWebDescription->getImportantDescription() : '';
foreach ($reservation as $item) {
$newLoungeSimple = new ReservationLoungeSimple();
$newLoungeSimple->setDateStart($item->getDateStart());
$newLoungeSimple->setDateEnd($item->getDateEnd());
$newLoungeSimple->setIdReservation($reqDuplicateQuote['reservationId']);
$newLoungeSimple->setPax($item->getPax());
$newLoungeSimple->setType($item->getType());
$newLoungeSimple->setCreatedAt($hoy);
$newLoungeSimple->setCreatedBy($user_id);
$newLoungeSimple->setUpdatedAt($hoy);
$newLoungeSimple->setUpdatedBy($user_id);
$newLoungeSimple->setHourStart($item->getHourStart());
$newLoungeSimple->setMinStart($item->getMinStart());
$newLoungeSimple->setHourEnd($item->getHourEnd());
$newLoungeSimple->setMinEnd($item->getMinEnd());
$newLoungeSimple->setRankQuote($newRankId);
$newLoungeSimple->setIva($item->getIva());
$newLoungeSimple->setOpIva($item->getOpIva());
$newLoungeSimple->setIdLounge($newLounge->getId());
$newLoungeSimple->setLoungename($newLounge->getName());
// $newLoungeSimple->setLoungeDescription($item->getLoungeDescription());
$newLoungeSimple->setImportantDescription($loungeSummaryDescription);
$newLoungeSimple->setImportantDescGeneralText($loungeImportantDescGeneralText);
$newLoungeSimple->setImportantDescSchedules($loungeImportantDescSchedules);
$newLoungeSimple->setImportantDescParking($loungeImportantDescParking);
$newLoungeSimple->setLanguage($item->getLanguage());
$newLoungeSimple->setSageArticle($item->getSageArticle());
$newLoungeSimple->setSentToSage($item->isSentToSage());
$newLoungeSimple->setSageIva($item->getSageIva());
if (!empty($reqDuplicateQuote['salaPrice'])) {
$newLoungeSimple->setServicePrice($reqDuplicateQuote['salaPrice']);
} else {
$newLoungeSimple->setServicePrice($item->getServicePrice());
}
try {
$em->persist($newLoungeSimple);
$em->flush();
$event = 'Se ha agregado la nueva cotización';
$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);
}
//Se llama al servicio para crear la entrada en la agenda
$agenda = $this->agendaService->createAgendaFromSource(
$newLoungeSimple->getIdReservation(),
'SALAS A UTILIZAR',
null,
null,
$newLoungeSimple->getDateStart(),
$newLoungeSimple->getDateEnd(),
$newLoungeSimple->getLoungename(),
$newLoungeSimple->getId(),
'ReservationLoungeSimple',
$newLoungeSimple->getUpdatedBy()
);
// Se debe agregar el servicio de limpieza por cada sala que se agregue
$resLoungeSimple = $newLoungeSimple;
$service = new ReservationService();
$service->setReservationId($reqDuplicateQuote['reservationId']);
$service->setSupplierId(0);
$service->setDateInAt($resLoungeSimple->getDateStart());
$service->setDateOutAt($resLoungeSimple->getDateEnd());
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$service->setCreatedId($user_id);
$service->setUpdatedId($user_id);
$service->setCreatedAt(new \DateTime("now"));
$service->setUpdatedAt(new \DateTime("now"));
$service->setServiceCatId('21');
$service->setServiceCatName('Limpieza');
$service->setContcolor('green-300');
$service->setName('HORAS ( ' . $resLoungeSimple->getLoungeName() . ' )');
$service->setPrice('14');
$service->setCurrency('Euro');
$service->setUnits('8');
$service->setCommission('0');
$service->setPax('0');
$service->setOver('0');
$service->setIva('21');
$service->setOpIva('1');
$service->setOpCommission('1');
$service->setCommission('57.14');
$service->setViewInfo(0);
$service->setToinvoice(0);
$service->setServiceId(0);
// $em->persist($service);
// $em->flush();
}
$reserva = $em->getRepository(Reservation::class)->findOneById($reqDuplicateQuote['reservationId']);
// Creamos la Snapshot de las salas y servicios del sistema (LOG)
$version = $this->venueService->createSnapshot($reserva);
return $this->redirectToRoute(
'reservations_venues_edit_simple',
array(
'id' => $reqDuplicateQuote['reservationId'],
'token' => null,
'_fragment' => 'btn_quotes'
)
);
}
/**
* @Route("/loghistoric/{id}", name="reservations_log_historic")
* Log del historico de la cotizacion de la reserva id
*/
public function logHistoricQuoteAction($id, EntityManagerInterface $em, Request $request){
$reservaLogs = $em->getRepository(ReservationLoungeSimpleServiceLog::class)->findByReservaId($id);
return $this->render(
'MDS/VenuesBundle/reservations/list-reservations-log-historic.html.twig',
array(
'id' => $id,
'reservaLogs' => $reservaLogs,
)
);
}
/**
* @Route("/logrecover/{reservationId}/{versionId}", name="reservations_log_recover")
* Recuperar desde Log de historico una versión de una reserva. Se eliminaran salas y servicios del expediente no facturados
*/
public function logRecoverQuoteAction($reservationId, $versionId, EntityManagerInterface $em, Request $request){
$reservaLogs = $em->getRepository(ReservationLoungeSimpleServiceLog::class)->findBy(array('reservaId' => $reservationId, 'version' => $versionId));
$reservationsLounges = $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation' => $reservationId));
$reservationsLoungesInvoiced = $em->getRepository(ReservationInvoiceItems::class)->findBy(array('reservationId' => $reservationId, 'itemType' => 'LOUNGE'));
$reservationsServices = $em->getRepository(ReservationService::class)->findBy(array('reservationId' => $reservationId));
$reservationsServicesInvoiced = $em->getRepository(ReservationInvoiceItems::class)->findBy(array('reservationId' => $reservationId, 'itemType' => 'SERVICE'));
$sageIva = $em->getRepository(SageVatRates::class)->findOneBySageCode('03');
/* Obtengo usuario logueado */
$user = $this->get('security.token_storage')->getToken()->getUser();
// 1. Obtener los IDs de los items que SÍ están facturados
$invoicedLoungeIds = [];
foreach ($reservationsLoungesInvoiced as $invoiceLounge) {
$invoicedLoungeIds[] = $invoiceLounge->getLngControlId();
}
$invoicedServiceIds = [];
foreach ($reservationsServicesInvoiced as $invoiceService) {
$invoicedServiceIds[] = $invoiceService->getSrvControlId();
}
// 2. Eliminar los Lounges (Salas) que NO están facturados
foreach ($reservationsLounges as $lounge) {
if (!in_array($lounge->getId(), $invoicedLoungeIds)) {
$em->remove($lounge);
}
}
// 2.1 Eliminar los Servicios que NO están facturados
foreach ($reservationsServices as $service) {
if (!in_array($service->getId(), $invoicedServiceIds)) {
$em->remove($service);
}
}
// 3. Generar las nuevas entidades a partir del Log
foreach ($reservaLogs as $log) {
if ($log->getItemType() === 'lounge') {
$newLounge = new ReservationLoungeSimple();
$newLounge->setIdReservation($log->getReservaId());
$newLounge->setIdLounge($log->getIdLounge());
$newLounge->setLoungeName($log->getItemName());
$newLounge->setDateStart($log->getDateStart());
$newLounge->setDateEnd($log->getDateEnd());
$newLounge->setPax($log->getPax());
$newLounge->setRankQuote($log->getRankQuote());
$newLounge->setServicePrice((string)$log->getPrice());
$newLounge->setSageIva($sageIva);
$newLounge->setCreatedBy($log->getAgentId());
$newLounge->setUpdatedBy($log->getAgentId());
// Mapear el desglose de horas para la sala
if ($log->getDateStart()) {
$newLounge->setHourStart($log->getDateStart()->format('H'));
$newLounge->setMinStart($log->getDateStart()->format('i'));
}
if ($log->getDateEnd()) {
$newLounge->setHourEnd($log->getDateEnd()->format('H'));
$newLounge->setMinEnd($log->getDateEnd()->format('i'));
}
$loungeProfile = $em->getRepository(ReservationLoungeDetails::class)->findOneById($log->getIdLounge());
$idioma = 1;
// Descripciones web por sala/idioma con fallbacks
$loungeWebDescriptionRepo = $em->getRepository(ReservationLoungeWebDescription::class);
$loungeWebDescription = $loungeWebDescriptionRepo->findOneBy([
'lounge' => $loungeProfile,
'language' => $idioma
]) ?? ($idioma !== 1 ? $loungeWebDescriptionRepo->findOneBy([
'lounge' => $loungeProfile,
'language' => 1
]) : null) ?? $loungeWebDescriptionRepo->findOneBy(['lounge' => $loungeProfile]);
$loungeSummaryDescription = null;
$loungeImportantDescGeneralText = $loungeWebDescription ? $loungeWebDescription->getImportantDescGeneralText() : '';
$loungeImportantDescSchedules = $loungeWebDescription ? $loungeWebDescription->getImportantDescSchedules() : '';
$loungeImportantDescParking = $loungeWebDescription ? $loungeWebDescription->getImportantDescParking() : '';
$loungeSummaryDescription = $loungeWebDescription ? $loungeWebDescription->getImportantDescription() : '';
$newLounge->setImportantDescription($loungeSummaryDescription ?? '');
$newLounge->setImportantDescGeneralText($loungeImportantDescGeneralText ?? '');
$newLounge->setImportantDescSchedules($loungeImportantDescSchedules ?? '');
$newLounge->setImportantDescParking($loungeImportantDescParking ?? '');
$em->persist($newLounge);
} elseif ($log->getItemType() === 'service') {
$newService = new ReservationService();
$newService->setReservationId($log->getReservaId());
$newService->setServiceId($log->getItemId());
$newService->setName($log->getItemName());
$newService->setPrice((string)$log->getPrice());
$newService->setPax((string)$log->getPax());
$newService->setDateInAt($log->getDateStart());
$newService->setDateOutAt($log->getDateEnd());
// Mapeo específico de servicios
$newService->setUnits($log->getUnits() ?? '1');
$newService->setOpCommission($log->getOpCommission());
$newService->setCommission($log->getCommission() ?? '0');
$newService->setOver($log->getPriceOver());
$newService->setToinvoice($log->getToinvoice());
$newService->setViewInfo($log->getViewInfo() ?? false);
$newService->setServiceCatId($log->getServiceCatId());
$newService->setServiceCatName($log->getServiceCatName());
$newService->setCreatedId($user->getId());
$newService->setUpdatedId($user->getId());
$newService->setSageIva($sageIva);
$newService->setIva(21);
if ($log->getDateStart()) {
$newService->setHour($log->getDateStart()->format('H:i'));
}
// VALORES POR DEFECTO REQUERIDOS
$newService->setSupplierId(0);
$newService->setContcolor('#000000');
$em->persist($newService);
}
}
// 4. Ejecutar todas las eliminaciones e inserciones en la BBDD
$em->flush();
return $this->redirectToRoute(
'reservations_venues_edit_simple',
array(
'id' => $reservationId,
'token' => null,
'_fragment' => 'btn_quotes'
)
);
}
/**
* @Route("/productfileavlist/{id}", name="reservations_list_multiple_productfile_av")
* Listar productos de Av para agregar en el servicio id
*/
public function listMultipleProductAvAction( $id, Request $request){
$em = $this->getDoctrine()->getManager();
$parameters = [];
$dql = 'SELECT i
FROM AvexpressBundle:AveProduct i
ORDER BY i.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$avs = $query->getResult();
$dql = 'SELECT i
FROM AvexpressBundle:AvePackageTemplate i
ORDER BY i.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$avsPack = $query->getResult();
$data_av = [];
foreach ($avsPack as $item) {
$productNames = [];
$parameters = ['packId' => $item->getId()];
$dql = 'SELECT i
FROM AvexpressBundle:AvePackageTemplateItems i
WHERE i.packId = :packId
ORDER BY i.rankAvPack ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$avsPackProducts = $query->getResult();
foreach ($avsPackProducts as $product) { $productNames[] = $product->getProductName(); }
$packageName = $item->getName();
if (!empty($productNames)) { $packageName .= ' (' . implode(', ', $productNames) . ')'; }
$data_av[] = array(
'id' => $item->getId(),
'name' => $packageName,
'type' => 'Paquete',
'price' => $item->getPricePackage(),
);
}
foreach($avs as $av){
$data_av[] = array(
'id' => $av->getId(),
'name' => $av->getName(),
'type' => $av->getType(),
'price' => $av->getPrice(),
);
}
$resService = $em->getRepository(ReservationService::class)->findOneById($id);
return $this->render('MDS/VenuesBundle/reservations/add-services-avs.html.twig',
array(
'id' => $id,
'idRes' => empty($resService) ? 0 : $resService->getReservationId(),
'avs' => $data_av,
));
}
/**
* @Route("/productfileavadd/{id}", name="reservations_add_multiple_productfile_av")
* Agregar productos de Av para agregar en el servicio id
*/
public function addMultipleProductAvAction( $id, Request $request){
$em = $this->getDoctrine()->getManager();
$resService = $em->getRepository(ReservationService::class)->findOneById($id);
$prodSelected = $request->request->get('details');
$serviceName = '';
$servicePrice = 0;
foreach ($prodSelected as $item){
if(empty($serviceName)){
$serviceName .= $item['name'];
} else {
$serviceName .= ' + '. $item['name'];
}
$servicePrice += $item['total_price'];
}
$resService->setName($serviceName);
$resService->setPrice($servicePrice);
$resService->setToInvoice(1);
$resService->setOpIva(1);
$resService->setIva(21);
try {
$em->persist($resService);
$em->flush();
$event = 'The Reservation 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);
}
return $this->redirectToRoute('reservations_venues_edit_simple', [
'id' => $resService->getReservationId(),
'token' => null,
'_fragment' => 'btn_srv'
]);
}
/**
* @Route("/reschedule/{reservationId}/{newDate}", name="reservations_reschedule", methods={"POST"})
* Reprogramar todas las fechas del evento, incluido reservations, reservationLoungeSimple y reservationService
*/
public function rescheduleQuoteAction($reservationId, $newDate, EntityManagerInterface $em, Request $request)
{
try {
$reservation = $em->getRepository(Reservation::class)->find($reservationId);
if (!$reservation) {
return new JsonResponse(['status' => 'error', 'message' => 'Reserva no encontrada.'], 404);
}
$oldStartDate = $reservation->getDateStart();
if (!$oldStartDate) {
return new JsonResponse(['status' => 'error', 'message' => 'La reserva actual no tiene una fecha de inicio configurada.'], 400);
}
// Establecemos las horas a las 00:00:00 para calcular los días exactos sin afectar los husos horarios
$oldStartMidnight = clone $oldStartDate;
$oldStartMidnight->setTime(0, 0, 0);
$newStartMidnight = new \DateTime($newDate);
$newStartMidnight->setTime(0, 0, 0);
// Calculamos la diferencia en días
$interval = $oldStartMidnight->diff($newStartMidnight);
$daysDiff = $interval->days;
$invert = $interval->invert; // 1 si la fecha nueva es pasada, 0 si es futura
if ($daysDiff === 0) {
return new JsonResponse(['status' => 'error', 'message' => 'La fecha seleccionada es igual a la actual.'], 400);
}
// Función anónima para aplicar la suma/resta de días a una fecha conservando su hora original
$applyInterval = function(?\DateTime $date) use ($daysDiff, $invert) {
if (!$date) return null;
$clonedDate = clone $date;
$intervalStr = 'P' . $daysDiff . 'D'; // P[N]D = Period N Days
if ($invert) {
$clonedDate->sub(new \DateInterval($intervalStr));
} else {
$clonedDate->add(new \DateInterval($intervalStr));
}
return $clonedDate;
};
// 1. Reprogramar la Reserva
// Asignamos la nueva fecha (preservando la hora del inicio antiguo, si tuviera alguna)
$reservation->setDateStart($applyInterval($reservation->getDateStart()));
if ($reservation->getDateEnd()) {
$reservation->setDateEnd($applyInterval($reservation->getDateEnd()));
}
// 2. Reprogramar las Salas (ReservationLoungeSimple)
$lounges = $em->getRepository(ReservationLoungeSimple::class)->findBy(['idReservation' => $reservationId]);
foreach ($lounges as $lounge) {
$lounge->setDateStart($applyInterval($lounge->getDateStart()));
$lounge->setDateEnd($applyInterval($lounge->getDateEnd()));
}
// 3. Reprogramar los Servicios (ReservationService)
$services = $em->getRepository(ReservationService::class)->findBy(['reservationId' => $reservationId]);
foreach ($services as $service) {
$service->setDateInAt($applyInterval($service->getDateInAt()));
$service->setDateOutAt($applyInterval($service->getDateOutAt()));
}
$em->flush();
// Creamos la Snapshot de las salas y servicios del sistema (LOG)
$version = $this->venueService->createSnapshot($reservation);
return new JsonResponse([
'status' => 'success',
'message' => 'Las fechas del evento han sido reprogramadas correctamente.'
]);
} catch (\Exception $e) {
return new JsonResponse([
'status' => 'error',
'message' => 'Ocurrió un error en el servidor: ' . $e->getMessage()
], 500);
}
}
/**
* @Route("/registerFormGpWeb/{token}", name="registerformgpweb", defaults={"token"=null})
* Crear una reserva con la información que llega desde la web
* Crear la sala segun los datos ingresados
* Generar un modelo de correo electronico para enviar la propuesta de cotización al cliente
*/
public function registerFormWebApiAction($token, Request $request, EntityManagerInterface $em)
{
// ==========================================
// 0. VALIDACIONES DE USUARIO Y RESERVA
// ==========================================
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
if (!($user_logueado)){
return $this->redirectToRoute('login');
} else {
$user_id = $user_logueado->getId();
}
$reservaPrevia = $em->getRepository(Reservation::class)->findOneByToken($token);
if (!empty($reservaPrevia)){
// Ya se ha creado la reserva previamente
return $this->redirectToRoute('reservations_venues_edit_simple', array(
'id' => $reservaPrevia->getId(),
'token' => null,
'_fragment' => null
));
}
// ==========================================
// 1. DESCIFRAR Y VALIDAR EL TOKEN
// ==========================================
if (empty($token)) {
$this->addFlash('mensajereservationerror', 'No se ha proporcionado ningún token en la URL.');
// Ajusta la ruta de retorno en caso de error
return $this->redirectToRoute('reservations_greenpatio_index');
}
$base64Key = 'x4BMAcZUEQLNWgLB4NRHprTyySUZtcs4F1FCn9EKwJ4=';
$key = base64_decode($base64Key);
$parts = explode('.', $token);
if (count($parts) !== 4 || $parts[0] !== 'v1') {
$this->addFlash('mensajereservationerror', 'El formato del token no es válido.');
return $this->redirectToRoute('reservations_greenpatio_index');
}
// Función auxiliar para decodificar Base64 URL-safe
$base64UrlDecode = function($data) {
$remainder = strlen($data) % 4;
if ($remainder) {
$data .= str_repeat('=', 4 - $remainder);
}
return base64_decode(strtr($data, '-_', '+/'));
};
$iv = $base64UrlDecode($parts[1]);
$tag = $base64UrlDecode($parts[2]);
$ciphertext = $base64UrlDecode($parts[3]);
$aad = 'greenpatio-register-v1';
// Descifrar usando AES-256-GCM
$decrypted = openssl_decrypt(
$ciphertext,
'aes-256-gcm',
$key,
OPENSSL_RAW_DATA,
$iv,
$tag,
$aad
);
if ($decrypted === false) {
$this->addFlash('mensajereservationerror', 'No se pudo descifrar la información del token.');
return $this->redirectToRoute('reservations_greenpatio_index');
}
$data = json_decode($decrypted, true);
if (json_last_error() !== JSON_ERROR_NONE) {
$this->addFlash('mensajereservationerror', 'El token no contiene datos válidos.');
return $this->redirectToRoute('reservations_greenpatio_index');
}
// Opcional: Validar fecha de expiración si viene en el token
if (isset($data['expiresAt']) && time() > $data['expiresAt']) {
$this->addFlash('mensajereservationerror', 'El enlace de reserva ha expirado.');
return $this->redirectToRoute('reservations_greenpatio_index');
}
// ==========================================
// 2. EXTRAER LAS VARIABLES DEL TOKEN
// ==========================================
$yourName = $data['name'] ?? '';
$yourPhone = $data['phone'] ?? '';
$yourEmail = $data['email'] ?? '';
$yourReferral = $data['referral'] ?? '';
$eventDateString = $data['eventDate'] ?? 'now';
$yourEventDate = \DateTime::createFromFormat('d/m/Y', trim($eventDateString));
$yourAttendees = $data['attendees'] ?? null;
$eventSpace = $data['eventSpace'] ?? '';
$yourEventDetails = $data['eventDetails'] ?? '';
// ==========================================
// 3. CREAMOS LA RESERVA
// ==========================================
$hoy = new \DateTime("now", NULL);
$reserva = new Reservation();
$reserva->setTitle('Reserva ingresada en la web para el día: '. $yourEventDate->format('d/m/Y'));
$reserva->setClient(null);
$reserva->setCreatedAt($hoy);
$reserva->setPriority(1);
// $reserva->setDateStart(new \DateTime('2078-01-01'));
$reserva->setDateStart($yourEventDate);
// $reserva->setDateEnd(new \DateTime('2000-01-01'));
$reserva->setDateEnd($yourEventDate);
$reserva->setCreatedBy($user_id);
$reserva->setSupplier(4765); // Higo&Trigo
$reserva->setStatus('Iniciado');
$reserva->setUpdatedAt($hoy);
$reserva->setUpdatedBy($user_id);
$reserva->setDaysBlock(7);
if (!empty($yourAttendees) and is_numeric($yourAttendees)){ $reserva->setPax($yourAttendees); } else { $reserva->setPax(null); }
$reserva->setAccessKey(null);
$reserva->setClientContact(null);
$reserva->setContactUnregistered($yourEmail); // Desde la web es requerido
$reserva->setDays(null);
$reserva->setContract(null);
if (!empty($yourName)){ $reserva->setNameContactUnregistered($yourName); } else { $reserva->setNameContactUnregistered(null); }
if (!empty($yourPhone)){ $reserva->setPhoneContactUnregistered($yourPhone); } else { $reserva->setPhoneContactUnregistered(null); }
$reserva->setToken($token);
$reserva->setComAvGp(null);
$reserva->setComHtGp(null);
$reserva->setInfoFormWeb($yourEmail .' || '. $yourReferral .' || '. $yourEventDate->format('d/m/Y') .' || '. $yourName .' || '. $yourPhone .' || '. $yourAttendees .' || '. $eventSpace);
if (!empty($yourEventDetails)){ $reserva->setDescription($yourEventDetails); } else { $reserva->setDescription(null); }
// --- Generamos la info del correo electronico y la agregamos a la descripción para que el agente copie y pegue
$nombreArray = explode(' ', trim($yourName));
$primerNombre = $nombreArray[0];
// Definimos las URLs de los enlaces
// $urlProposal = "https://cotizacion.greenpatio.es/index.php?token=" . $reserva->getToken();
$urlProposal = "https://develup.solutions/cotizacion/?token=" . $reserva->getToken();
$urlLegends = "https://drive.google.com/file/d/1_zc43gcvyajig-VRJyNXfe-0E8bhhQGZ/view";
$urlCatering = "https://drive.google.com/drive/folders/1ihGR2yGWGgdtJeRsAI5LoUuEqkApAcXU";
// Construimos el HTML en la variable $xMail
$xMail = <<<HTML
<div style="font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #222222; line-height: 1.6;">
<p style="margin: 0;">{$yourEmail}</p>
<p style="margin: 0; margin-bottom: 20px;">PÁGINA WEB GREEN PATIO - Espacios</p>
<p>Hola {$primerNombre}, ¡un placer de saludarte!</p>
<p><em>A continuación te dejo el link con las opciones disponibles para la fecha solicitada:</em></p>
<p style="padding-left: 40px; margin-bottom: 20px;">
<strong><em style="color: #5b9e43; font-size: 16px;">CLICK AQUÍ -->:</em></strong>
<a href="{$urlProposal}" style="color: #1155cc; font-size: 18px; text-decoration: underline;">PROPOSAL</a>
</p>
<p><strong style="text-decoration: underline;"><em>HACER CLICK para ver los <span style="color: #5b9e43;">"DOSSIERES"</span> de los espacios:</em></strong></p>
<ul style="margin-top: 5px; margin-bottom: 20px;">
<li><a href="{$urlLegends}" style="color: #1155cc; font-weight: bold; text-decoration: underline;">LEGENDS BY GREEN PATIO</a></li>
</ul>
<p><strong style="text-decoration: underline;"><em>PROVEEDORES EN EXCLUSIVA:</em></strong></p>
<ul style="margin-top: 5px; margin-bottom: 20px;">
<li><a href="{$urlCatering}" style="color: #1155cc; font-weight: bold; text-decoration: underline;">Catering Higo & Trigo</a> - Te lo cotizamos desde Green Patio</li>
<li><strong>AV EXPRESS</strong> - Te lo cotiza directamente: Salvador Guerrero: <a href="tel:620956367" style="color: #222222; text-decoration: none;">620956367</a> // <a href="mailto:salvador@avexpress.tv" style="color: #222222; text-decoration: none;">salvador@avexpress.tv</a></li>
</ul>
<p><strong><span style="color: #5b9e43; text-decoration: underline;">IMPORTANTE:</span></strong></p>
<ul style="margin-top: 5px; margin-bottom: 25px;">
<li>Todas nuestras condiciones, horarios, y demás información están en la parte de <strong><span style="color: #5b9e43;">"IMPORTANTE"</span></strong> en el link enviado (justo debajo del precio de cada sala).</li>
<li>Dada la demanda de dicha fecha, en caso de desear bloqueo de la sala, será bloqueo en opción compartida, es decir: para el primer cliente que reserve en firme.</li>
</ul>
<p>Cualquier cosita no dudes en decirme,</p>
<p>Quedo atenta y mil gracias nuevamente!</p>
</div>
HTML;
$reserva->setMailToClient($xMail);
try{
$em->persist($reserva);
$em->flush();
$event = 'The Reservation 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);
}
$id = $reserva->getId();
// Normalizamos el texto antes del switc para el caso del guión largo
$eventSpace = str_replace('–', '-', $eventSpace);
switch ($eventSpace) {
case 'La Imprenta - Sala Plenaria': $simpleLounge = 2; break;
case 'La Imprenta - Invernadero': $simpleLounge = 39; break;
case 'La Imprenta - Escenario': $simpleLounge = 40; break;
case 'La Imprenta - Sala Cristal': $simpleLounge = 13; break;
case "La Imprenta - L'Atelier": $simpleLounge = 14; break;
case 'Covarrubias The One - Sala White': $simpleLounge = 24; break;
case 'Covarrubias The One - Sala Black': $simpleLounge = 25; break;
case 'Sala 25': $simpleLounge = 19; break;
case 'Lima Rooms': $simpleLounge = 3; break;
case 'Espacio Legends': $simpleLounge = 42; break;
default: $simpleLounge = 0; break;
}
$loungeDetails = $em->getRepository(ReservationLoungeDetails::class)->findOneById($simpleLounge);
$loungeId = $loungeDetails->getId();
$previusLoungeSimple = null;
$anyLoungeSimple = null;
$idioma = 1;
if($anyLoungeSimple){
$idioma = $anyLoungeSimple->getLanguage();
}
$loungeWebDescription = $em->getRepository(ReservationLoungeWebDescription::class)->findOneBy(array('lounge' => $simpleLounge, 'language' => $idioma));
$loungeName = $loungeDetails->getName();
$loungeSummaryDescription = null;
if (empty($previusLoungeSimple)) {
if (empty($loungeSummaryDescription)) { $loungeSummaryDescription = empty($loungeWebDescription) ? null : $loungeWebDescription->getImportantDescription(); }
$loungeImportantDescGeneralText = empty($loungeWebDescription) ? null : $loungeWebDescription->getImportantDescGeneralText();
$loungeImportantDescSchedules = empty($loungeWebDescription) ? null : $loungeWebDescription->getImportantDescSchedules();
$loungeImportantDescParking = empty($loungeWebDescription) ? null : $loungeWebDescription->getImportantDescParking();
}
$iva = 21;
$newRankId = 1;
$hourStart = '12'; $minStart = '00'; $hourMinStart = '12:00';
$hourEnd = '20'; $minEnd = '00'; $hourMinEnd = '20:00';
$dateStart = clone $yourEventDate; [$hour, $minute] = explode(':', $hourMinStart); $dateStart->setTime((int)$hour, (int)$minute);
$dateEnd = clone $yourEventDate; [$hour, $minute] = explode(':', $hourMinEnd); $dateEnd->setTime((int)$hour, (int)$minute);
$servicePrice = 0;
$idReservation = $id;
$createdAt = new DateTime('now');
$createdBy = $user_id;
$updatedAt = new DateTime('now');
$updatedBy = $user_id;
$pax = empty($yourAttendees) ? 0 : $yourAttendees;
$lounge = new ReservationLoungeSimple();
$lounge->setIdLounge ($loungeId);
$lounge->setHourStart ($hourStart);
$lounge->setMinStart ($minStart);
$lounge->setHourEnd ($hourEnd);
$lounge->setMinEnd ($minEnd);
$lounge->setLoungeName ($loungeName);
$lounge->setDateStart ($dateStart);
$lounge->setDateEnd ($dateEnd);
$lounge->setRankQuote(1);
$lounge->setIdReservation ($idReservation);
$lounge->setIva($iva);
$lounge->setOpIva(1);
$lounge->setCreatedAt ($createdAt);
$lounge->setCreatedBy ($createdBy);
$lounge->setUpdatedAt ($updatedAt);
$lounge->setUpdatedBy ($updatedBy);
$lounge->setPax ($pax);
$lounge->setRankQuote($newRankId);
$sageVatRate = $em->getRepository(SageVatRates::class)->findOneBy([ 'sageCode' => '03' ]);
$lounge->setSageIva($sageVatRate); // Iva de Sage al 21%
$lounge->setImportantDescription($loungeSummaryDescription);
$lounge->setImportantDescGeneralText($loungeImportantDescGeneralText);
$lounge->setImportantDescSchedules($loungeImportantDescSchedules);
$lounge->setImportantDescParking($loungeImportantDescParking);
$price = $this->precioTarifario($dateStart, $loungeId, $servicePrice);
$lounge->setServicePrice($price);
try{
$em->persist($lounge);
$em->flush();
$event = 'The Reservation 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);
}
// Agregar el servicio de limpieza
$service = new ReservationService();
$service->setReservationId($idReservation);
$service->setSupplierId(0);
$service->setDateInAt($lounge->getDateStart());
$service->setDateOutAt($lounge->getDateEnd());
$service->setCreatedId($user_id);
$service->setUpdatedId($user_id);
$service->setCreatedAt(new \DateTime("now"));
$service->setUpdatedAt(new \DateTime("now"));
$service->setServiceCatId('21');
$service->setServiceCatName('Limpieza');
$service->setContcolor('green-300');
$service->setName('HORAS ( '.$lounge->getLoungeName().' )');
$service->setPrice('14');
$service->setCurrency('Euro');
$service->setUnits('8');
$service->setCommission('0');
$service->setPax('0');
$service->setOver('0');
// Busco la reserva para saber si es sucoe o no
// $sucoe = $reserva->isSucoe();
// Sino es sucoe, cogemos el IVA del 21
// if(! $sucoe) {
// $sageVatRate = $em->getRepository(SageVatRates::class)->findOneBy(['sageCode' => '03']);
// } else {
// $sageVatRate = $em->getRepository(SageVatRates::class)->findOneBy(['sageCode' => '00']);
// }
$sageArticle = null;
// Si el módulo de Sage está activo, buscamos el artículo. Si no, lo dejamos en null y se mostrará un error en la vista.
// if ($this->session->get('_config')['msage']) {
// $sageArticle = $em->getRepository(SageArticle::class)->findOneBy(['vatType' => $sageVatRate, 'name' => $service->getServiceCatName()]);
// Si no se ha encontrado el artículo de Sage.
// if (empty($sageArticle)) {
// $this->addFlash('mensajereservationerror', 'No se ha encontrado el artículo de Sage para el servicio: ' . $service->getServiceCatName() . '. No se ha podido crear el servicio para la sala.');
// }
// }
// $service->setSageIva($sageVatRate);
$service->setOpIva('1');
$service->setOpCommission('1');
$service->setCommission('57.14');
$service->setViewInfo(0);
$service->setToinvoice(0);
$service->setServiceId(0);
// Vincular el artículo de Sage al servicio
// $service->setSageArticle($sageArticle);
$em->persist($service);
$em->flush();
// Sincronización con HT
if (!empty($reserva)) {
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
// if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
$htFile = $em->getRepository(HtFile::class)->findByReservation($reserva);
if (empty($htFile)) { return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,)); }
// }
}
}
// Sincronización con AV
if (!empty($reserva)) {
if (in_array($reserva->getStatus(), [null, '', 'Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
$aveFile = $em->getRepository(AveFiles::class)->findByReservation($reserva);
if (empty($aveFile)) { return $this->redirectToRoute('sinc_gp_ave', array('id' => $id,)); }
}
}
return $this->redirectToRoute('reservations_venues_edit_simple', array(
'id' => $id,
'token' => null,
'_fragment' => 'btn_quotes'
));
}
private function precioPorFecha($date, $loungeId)
{
return array('price' => 0, );
$em = $this->getDoctrine()->getManager();
$price0 = null;
// Buscamos por año
$parameters = array('dateYear' => $date->format('Y'), 'loungeId' => $loungeId, 'priceIsActive' => true, );
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE ((i.year1 <= :dateYear and i.year2 >= :dateYear) ) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive';
$query = $em->createQuery($dql)->setParameters($parameters);
$price1 = $query->getResult();
// Buscamos por año y mes
$parameters = array('dateYear' => $date->format('Y'), 'month' => true, 'loungeId' => $loungeId, 'priceIsActive' => true, );
switch ($date->format('m')) {
case '01': //Enero
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '02': //Febrero
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '03': //Marzo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '04': //Abril
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '05': //Mayo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '06': //Junio
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '07': //Julio
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '08': //Agosto
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '09': //Septiembre
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '10': //Octubre
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '11': //Noviembre
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case '12': //Diciembre
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
$query = $em->createQuery($dql)->setParameters($parameters);
$price2 = $query->getResult();
// Buscamos por año, mes y dia de la semana
$parameters = array('dateYear' => $date->format('Y'), 'month' => true, 'day' => true, 'loungeId' => $loungeId, 'priceIsActive' => true, );
switch ($date->format('m')) {
case '01': //Enero
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month1 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '02': //Febrero
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month2 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '03': //Marzo
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month3 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '04': //Abril
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month4 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '05': //Mayo
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month5 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '06': //Junio
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month6 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '07': //Julio
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month7 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '08': //Agosto
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month8 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '09': //Septiembre
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month9 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '10': //Octubre
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month10 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '11': //Noviembre
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month11 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
case '12': //Diciembre
switch ($date->format('l')) {
case 'Monday': //Lunes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month) AND (i.day1 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Tuesday': //Martes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month) AND (i.day2 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Wednesday': //Miercoles
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month) AND (i.day3 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Thursday': //Jueves
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month) AND (i.day4 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Friday': //Viernes
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month) AND (i.day5 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Saturday': //Sabado
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month) AND (i.day6 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
case 'Sunday': //Domingo
$dql = 'SELECT i
FROM VenuesBundle:ReservationLoungeProfile i
WHERE (
((i.year1 <= :dateYear and i.year2 >= :dateYear) or (i.year1 = :dateYear) or (i.year2 = :dateYear))
AND (i.month12 = :month) AND (i.day7 = :day)) and i.loungeId = :loungeId and i.priceIsActive = :priceIsActive
';
break;
default:
break;
}
break;
default:
break;
}
$query = $em->createQuery($dql)->setParameters($parameters);
$price3 = $query->getResult();
foreach ($price3 as $item) {
if (empty($price0)) {
$price0 = $item;
} else {
//Si los precios coinciden en fechas se tomara el que se haya cargado mas reciente en el sistema
if ($item->getCreatedAt() > $price0->getCreatedAt()) {
$price0 = $item;
}
}
}
if (empty($price0)) {
$price = 0;
} else {
$price = $price0->getPrice();
}
return array('price' => $price, );
}
/*
* Se busca el precio a Sugerir
* $dateStart Fecha
* $loungeId Id de la sala
* $servicePrice Preciointroducido por elusuario
* */
private function precioTarifario($dateStart, $loungeId, $servicePrice)
{
$em = $this->getDoctrine()->getManager();
$dateToFind = clone $dateStart;
$dateToFind->setTime(0, 0, 0);
$parameters = array(
'loungeId' => $loungeId,
'typePrice' => 'DIARIA',
'dateToFind' => $dateToFind,
);
$dql = 'SELECT p
FROM VenuesBundle:ReservationLoungeProfile p
WHERE p.typePrice = :typePrice AND p.dateStart = :dateToFind AND p.loungeId = :loungeId
ORDER BY p.levelPrice DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$loungesPeriodsDaily = $query->getResult();
$priceTarifa = empty($loungesPeriodsDaily) ? 0 : $loungesPeriodsDaily[0]->getPrice();
$price = ($servicePrice == 0) ? $priceTarifa : $servicePrice;
return $price;
}
}