src/Controller/HomeController.php line 54

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Configuration;
  4. use App\Entity\Space;
  5. use App\Entity\User;
  6. use App\Entity\ToDoLogs;
  7. use App\Entity\WidgetNotes;
  8. use App\Form\WidgetNotesType;
  9. use App\MDS\VenuesBundle\Entity\Reservation;
  10. use App\MDS\VenuesBundle\Entity\ReservationLoungeDetails;
  11. use App\MDS\VenuesBundle\Entity\ReservationLoungeSimple;
  12. use App\MDS\VenuesBundle\Entity\ReservationVisit;
  13. use App\Service\CalendarService;
  14. use App\Service\UserNotificationService;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  22. use Symfony\Contracts\Translation\TranslatorInterface;
  23. use Google_Client;
  24. use Google_Service_Calendar;
  25. use Doctrine\ORM\Query;
  26. class HomeController extends AbstractController
  27. {
  28.     private $googleCalendar;
  29.     private $translator;
  30.     private $userNotificationService;
  31.     public function __construct(TranslatorInterface $translatorUserNotificationService $userNotificationService)
  32.     {
  33.         $redirectUri 'https://' . ($_SERVER['HTTP_HOST'] ?? '') . '/calendar/token';
  34.         $client = new Google_Client();
  35.         $client->setApplicationName('Google Calendar API');
  36.         $client->setClientId('YOUR_GOOGLE_CLIENT_ID');
  37.         $client->setClientSecret('YOUR_GOOGLE_CLIENT_SECRET');
  38.         $client->setRedirectUri($redirectUri);
  39.         $client->addScope(Google_Service_Calendar::CALENDAR);
  40.         $guzzle = new \GuzzleHttp\Client(['curl' => [CURLOPT_SSL_VERIFYPEER => false]]);
  41.         $client->setHttpClient($guzzle);
  42.         $this->googleCalendar $client;
  43.         $this->translator $translator;
  44.         $this->userNotificationService $userNotificationService;
  45.     }
  46.     /**
  47.      * @Route("/inicio", name="ruta_inicio")
  48.      */
  49.     public function inicioAction(AuthenticationUtils $authenticationUtils)
  50.     {
  51.         $em $this->getDoctrine()->getManager();
  52.         $configuration $em->getRepository(Configuration::class)->findOneBy([]);
  53.         return $this->render('login/login.html.twig', [
  54.             'last_username' => $authenticationUtils->getLastUsername(),
  55.             'error'         => $authenticationUtils->getLastAuthenticationError(),
  56.             'configuration' => $configuration,
  57.         ]);
  58.     }
  59.     /**
  60.      * @Route("/", name="homepage")
  61.      */
  62.     public function index(EntityManagerInterface $em): Response
  63.     {
  64.         $user $this->getUser();
  65.         if (!$user) return $this->redirectToRoute('ruta_inicio');
  66.         $tz   = new \DateTimeZone('Europe/Madrid');
  67.         $from = (new \DateTimeImmutable('today'$tz))->setTime(00);
  68.         $to   $from->modify('+30 days')->setTime(235959);
  69.         // 1. DETECTAR ROL "LEGENDS" Y SU ESPACIO
  70.         $isLegendUser false;
  71.         $lSpace null;
  72.         $rol $user->getSettingsRol();
  73.         if ($rol && strtoupper(trim($rol->getRol())) === 'LEGENDS') {
  74.             $isLegendUser true;
  75.             $lSpace $em->getRepository(Space::class)->createQueryBuilder('s')
  76.                 ->where('s.name LIKE :n')->setParameter('n''%LEGEND%')
  77.                 ->setMaxResults(1)->getQuery()->getOneOrNullResult();
  78.         }
  79.         /** --- TABLA RESERVAS --- */
  80.         $qbR $em->createQueryBuilder()
  81.             ->select('r')->from(Reservation::class, 'r')
  82.             ->where('r.dateStart <= :to')
  83.             ->andWhere('r.dateEnd >= :from')
  84.             ->setParameter('from'$from)->setParameter('to'$to);
  85.         if ($isLegendUser && $lSpace) {
  86.             $qbR->innerJoin(ReservationLoungeSimple::class, 'rls_f''WITH''rls_f.idReservation = r.id')
  87.                 ->innerJoin(ReservationLoungeDetails::class, 'rld_f''WITH''rld_f.id = rls_f.idLounge')
  88.                 ->andWhere('rld_f.space = :lSpace')->setParameter('lSpace'$lSpace);
  89.         }
  90.         $rowsR $qbR->orderBy('r.dateStart''ASC')->getQuery()->getResult();
  91.         $upcomingReservationsTbl = [];
  92.         foreach ($rowsR as $resObj) {
  93.             $rooms = [];
  94.             $rlsRows $em->getRepository(ReservationLoungeSimple::class)->findBy(['idReservation' => $resObj->getId()]);
  95.             foreach ($rlsRows as $rls) {
  96.                 $lounge $em->getRepository(ReservationLoungeDetails::class)->find($rls->getIdLounge());
  97.                 if ($lounge) {
  98.                     if (!$isLegendUser || ($lSpace && $lounge->getSpace() && $lounge->getSpace()->getId() === $lSpace->getId())) {
  99.                         $rooms[] = $lounge->getName();
  100.                     }
  101.                 }
  102.             }
  103.             if ($isLegendUser && empty($rooms)) continue;
  104.             $upcomingReservationsTbl[] = [
  105.                 'title' => $resObj->getTitle(), 'dateStart' => $resObj->getDateStart(),
  106.                 'dateEnd' => $resObj->getDateEnd(), 'room' => implode(', 'array_unique($rooms))
  107.             ];
  108.         }
  109.         $qbV $em->createQueryBuilder()
  110.             ->select('v')->from(ReservationVisit::class, 'v')
  111.             ->where('v.dateStart <= :to')
  112.             // Usamos COALESCE para que si no hay dateEnd, use dateStart (igual que en el calendario)
  113.             ->andWhere('COALESCE(v.dateEnd, v.dateStart) >= :from')
  114.             ->setParameter('from'$from)->setParameter('to'$to);
  115.         if ($isLegendUser && $lSpace) {
  116.             // Filtramos por las salas que pertenecen al espacio Legend
  117.             $qbV->andWhere('v.idLounge IN (SELECT d.id FROM '.ReservationLoungeDetails::class.' d WHERE d.space = :sid)')
  118.                 ->setParameter('sid'$lSpace->getId());
  119.         }
  120. //dd($qbV);
  121.         $rowsV $qbV->orderBy('v.dateStart''ASC')->getQuery()->getResult();
  122.         $upcomingVisitsTbl = [];
  123.         foreach ($rowsV as $visitObj) {
  124.             $roomName '-';
  125.             // Probamos ambos posibles getters para el ID de la sala
  126.             $idL method_exists($visitObj'getIdLounge') ? $visitObj->getIdLounge() :
  127.                 (method_exists($visitObj'getLoungeId') ? $visitObj->getLoungeId() : null);
  128.             if ($idL) {
  129.                 $lounge $em->getRepository(ReservationLoungeDetails::class)->find($idL);
  130.                 if ($lounge$roomName $lounge->getName();
  131.             }
  132.             $upcomingVisitsTbl[] = [
  133.                 'title' => $visitObj->getTitle() ?? 'Visita',
  134.                 'dateStart' => $visitObj->getDateStart(),
  135.                 'dateEnd' => $visitObj->getDateEnd(),
  136.                 'room' => $roomName
  137.             ];
  138.         }
  139.         $this->userNotificationService->checkRecentNotifications($user);
  140.         return $this->render('home/index.html.twig', [
  141.             'upcomingReservations' => $upcomingReservationsTbl,
  142.             'upcomingVisits'       => $upcomingVisitsTbl,
  143.             'from' => $from'to' => $to,
  144.             'notifications' => $this->userNotificationService->getForModal($user)
  145.         ]);
  146.     }
  147.     /**
  148.      * @Route("/calendar/global/visits", name="calendar_global_visits", methods={"GET"})
  149.      */
  150.     public function globalVisits(Request $requestCalendarService $calendarEntityManagerInterface $em): JsonResponse
  151.     {
  152.         $user $this->getUser();
  153.         $spaceId null;
  154.         if ($user && $user->getSettingsRol() && strtoupper(trim($user->getSettingsRol()->getRol())) === 'LEGENDS') {
  155.             $lSpace $em->getRepository(Space::class)->createQueryBuilder('s')
  156.                 ->where('s.name LIKE :n')->setParameter('n''%LEGEND%')
  157.                 ->setMaxResults(1)->getQuery()->getOneOrNullResult();
  158.             $spaceId $lSpace $lSpace->getId() : null;
  159.         }
  160.         $from = new \DateTimeImmutable($request->query->get('start''first day of this month'));
  161.         $to   = new \DateTimeImmutable($request->query->get('end''last day of next month'));
  162.         return new JsonResponse($calendar->getVisitsForCalendar($spaceIdnull$from$to));
  163.     }
  164.     /**
  165.      * @Route("/calendar/global/reservations", name="calendar_global_reservations", methods={"GET"})
  166.      */
  167.     public function globalReservations(Request $requestCalendarService $calendarEntityManagerInterface $em): JsonResponse
  168.     {
  169.         $user $this->getUser();
  170.         $spaceId null;
  171.         if ($user && $user->getSettingsRol() && strtoupper(trim($user->getSettingsRol()->getRol())) === 'LEGENDS') {
  172.             $lSpace $em->getRepository(Space::class)->createQueryBuilder('s')
  173.                 ->where('s.name LIKE :n')->setParameter('n''%LEGEND%')
  174.                 ->setMaxResults(1)->getQuery()->getOneOrNullResult();
  175.             $spaceId $lSpace $lSpace->getId() : null;
  176.         }
  177.         $from = new \DateTimeImmutable($request->query->get('start''first day of this month'));
  178.         $to   = new \DateTimeImmutable($request->query->get('end''last day of next month'));
  179.         return new JsonResponse($calendar->getReservationsForCalendar($spaceIdnull$from$to));
  180.     }
  181.     /**
  182.      * @Route("/ChangeLanguage/{lang}", name="change_language")
  183.      */
  184.     public function changeLanguage(Request $requeststring $lang): Response
  185.     {
  186.         $this->translator->setLocale($lang);
  187.         $request->getSession()->set('_locale'$lang);
  188.         return $this->redirect($request->headers->get('referer'));
  189.     }
  190. }