src/MDS/GreenPatioBundle/Controller/ReservationsController.php line 8161

Open in your IDE?
  1.             $ivaServ = (empty($item->getIva()) && !is_numeric($item->getIva())) ? ($neto * (21/100)) : ($neto * ($item->getIva()/100));
  2.             switch ($item->getIva()){
  3.                 // Acumula IVA
  4.                 case 21$data_iva['ivaMontoVeintiUno'] += $ivaServ; break;
  5.                 case 10$data_iva['ivaMontoDiez'] += $ivaServ; break;
  6.                 case 0: break;
  7.                 default: $data_iva['ivaMontoVeintiUno'] += $ivaServ; break;
  8.             }
  9.             $totales_neto_all += $neto;
  10.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  11.             $totales_neto_all round($totales_neto_all,2,PHP_ROUND_HALF_UP);
  12.             $data_iva['ivaMontoVeintiUno'] = round($data_iva['ivaMontoVeintiUno'],2,PHP_ROUND_HALF_UP);
  13.             $data_iva['ivaMontoDiez'] = round($data_iva['ivaMontoDiez'],2,PHP_ROUND_HALF_UP);
  14.             // Acumula netos totales e IVA
  15.             $service['neto'] += $neto;
  16.             $service['sumSubT'] += $subtotalService;
  17.             $service['sumIvas'] += $ivaServ;
  18.             // Se lleva a 2 decimales round($totales_neto_antes,2,PHP_ROUND_HALF_UP)
  19.             $service['neto'] = round($service['neto'],2,PHP_ROUND_HALF_UP);
  20.             $service['sumSubT'] = round($service['sumSubT'],2,PHP_ROUND_HALF_UP);
  21.         }
  22.         $data = array(
  23.             'totales_global_con_iva' => $lounge['sumSubT'],
  24.             'totales_global_iva' => $lounge['sumSubT'] - $lounge['neto'],
  25.             'totales_global_neto' => $lounge['neto'],
  26.             'totales_global_servicios_neto' => $service['neto'],
  27.             'totales_global_servicios_con_iva' => $service['sumSubT'],
  28.             'totales_global_servicios_iva' => $service['sumSubT'] - $service['neto'],
  29.             'sumatoria_totales_global_con_iva' => $lounge['sumSubT'] + $service['sumSubT'],
  30.             'sumatoria_totales_global_neto' => $lounge['neto'] + $service['neto'],
  31.             'sumatoria_totales_global_iva' => $lounge['sumSubT'] + $service['sumSubT'] - $lounge['neto'] - $service['neto'],
  32.         );
  33.         return $data;
  34.     }
  35.     /**
  36.      * @Route("/", name="reservations_greenpatio")
  37.      */
  38.     public function calendarReservationAction(Request $request) {
  39.         // Enviar correos a los agentes de las reservas que se deban Cotizar
  40.         $this->notificacionReservasPorCotizar();
  41.         // Enviar correos a los agentes de las reservas que tienen depositos pendientes por recibir
  42.         $this->notificacionReservasPendientesDelSegundoDeposito();
  43.         $session = new Session();
  44.         $token=$session->get('tokenGoogleCalendar');
  45.         if (!is_null($token)) {
  46.             $this->googleCalendar->setAccessToken($token);
  47.             $connectGoogle "1";
  48.         }else{
  49.             $connectGoogle "0";
  50.         }
  51.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  52.         $user_id $user_logueado->getId();
  53.         $wnotes = new WidgetNotes();
  54.         $wnotes->setDateAt(new \DateTime("now"));
  55.         $form $this->createWidgetNotesCreateForm($wnotes);
  56.         return $this->render('MDS/GreenPatioBundle/reservations/calendar-reservations.html.twig',
  57.             array(
  58.                 'form' => $form->createView(),
  59.                 'user'=> $user_id,
  60.                 'connectGoogle' => $connectGoogle,
  61.             )
  62.         );
  63.     }
  64.     private function createWidgetNotesCreateForm(WidgetNotes $entity)
  65.     {
  66.         $form $this->createForm(WidgetNotesType::class, $entity, array(
  67.             'action' => $this->generateUrl('widget_notes_calendar_create'),
  68.             'method' => 'POST'
  69.         ));
  70.         return $form;
  71.     }
  72. //    private function createWidgetNotesEditForm(WidgetNotes $entity, $id)
  73. //    {
  74. //        $form = $this->createForm(WidgetNotesType::class, $entity, array(
  75. //            'action' => $this->generateUrl('widget_notes_edit',
  76. //                array(
  77. //                    'id' => $id
  78. //                )),
  79. //            'method' => 'PUT'
  80. //        ));
  81. //
  82. //        return $form;
  83. //    }
  84.     /**
  85.      * @Route("/widget/notes/calendar/create/", name="widget_notes_calendar_create")
  86.      */
  87.     public function addNotesAction(EntityManagerInterface $emRequest $requestLoggerInterface $logger)
  88.     {
  89.         $notes $em->getRepository(WidgetNotes::class)->findAll();
  90.         $wnotes = new WidgetNotes();
  91.         $form $this->createWidgetNotesCreateForm($wnotes);
  92.         $form->handleRequest($request);
  93.         $forAgent $form->get('forAgent')->getData();
  94.         if(!is_null($forAgent)){ $wnotes->setForAgent($forAgent->getId()); }
  95.         if($form->isValid())
  96.         {
  97.             /* Obtengo usuario logueado */
  98.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  99.             $user_id $user_logueado->getId();
  100.             $wnotes->setCreatedId($user_id);
  101.             $wnotes->setUpdatedId($user_id);
  102.             /* Gestión de eventos en Log */
  103.             $user_lastname $user_logueado->getLastname();
  104.             $user_name $user_logueado->getName();
  105.             $user_email $user_logueado->getEmail();
  106.             $user_rol $user_logueado->getRoles();
  107.             $event_url $request->getPathInfo();
  108.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  109.             try{
  110.                 $em->persist($wnotes);
  111.                 $em->flush();
  112.                 $event 'The Note has been created succesfully.';
  113.                 $successMessage $this->translator->trans($event);
  114.                 $this->addFlash('mensaje'$successMessage);
  115.                 $logger->info($event_complete.' | '.$event);
  116.             } catch (\Exception $e){
  117.                 $event 'An error occurred: '.$e->getMessage();
  118.                 /* Para el log */
  119.                 $logger->error($event_complete.' | '.$event);
  120.                 /* Para el usuario */
  121.                 $errorMessage $this->translator->trans($event);
  122.                 $this->addFlash('mensajeerror'$errorMessage);
  123.             }
  124.             /* Fin Gestión de eventos en Log */
  125.         } else {
  126.             $errorMessage $this->translator->trans('Error, some fields are empty');
  127.             $this->addFlash('mensajeerror'$errorMessage);
  128.         }
  129.         return $this->redirectToRoute('homepage');
  130.     }
  131.     /**
  132.      * @Route("/list/{idgroup}", defaults={"idgroup" = 0}, name="reservations_greenpatio_index")
  133.      */
  134.     public function indexAction($idgroupEntityManagerInterface $emRequest $request) {
  135.         $parameters = array( 'statusdel' => 'Deleted' );
  136.         $dql 'SELECT i
  137.                 FROM GreenPatioBundle:Reservation i
  138.                 WHERE i.status <> :statusdel
  139.                 ORDER BY i.dateStart ASC';
  140.         $query $em->createQuery($dql)->setParameters($parameters);
  141.         $ref = array();
  142.         $reservas $query->getResult();
  143.         $reservasZero = array();
  144.         foreach ($reservas as $res){
  145.             $client $em->getRepository(Client::class)->findOneById($res->getClient());
  146.             if (!empty($client)){ $res->setClient($client->getName()); } else { $res->setClient(null); }
  147.             $res->setCreatedBy(
  148.                 ($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getName() . ' '.
  149.                 ($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getLastName());
  150.             $ref[$res->getId()] = '#'.($res->getDateStart())->format('ymd').($res->getDateEnd())->format('ymd');
  151.             switch ($res->getStatus()){
  152.                 case 'Bloqueo'$res->setStatus('BLOQUEO'); break;
  153.                 case 'Confirmed'$res->setStatus('CONFIRMADO'); break;
  154.                 case 'Invoiced'$res->setStatus('FACTURADO'); break;
  155.                 case 'Cotizado'$res->setStatus('COTIZADO'); break;
  156.                 case 'Deleted'$res->setStatus('CANCELADO'); break;
  157.                 default: $res->setStatus('INICIADO'); break;
  158.             }
  159.             $reservasZero[] = array(
  160.                 'dateStart' => $res->getDateStart(),
  161.                 'dateEnd' => $res->getDateEnd(),
  162.                 'id' => $res->getId(),
  163.                 'title' => $res->getTitle(),
  164.                 'client' => $res->getClient(),
  165.                 'createdBy' => $res->getCreatedBy(),
  166.                 'createdAt' => $res->getCreatedAt(),
  167.                 'ref' => $ref[$res->getId()],
  168.                 'status' => $res->getStatus(),
  169.             );
  170.         }
  171.         $reservas $reservasZero;
  172.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations.html.twig',
  173.             array(
  174.                 'groups' => null,
  175.                 'titleView' => '',
  176.                 'reservations' => $reservas
  177.             )
  178.         );
  179.     }
  180.     /**
  181.      * @Route("/listcanceled/{idgroup}", defaults={"idgroup" = 0}, name="reservations_canceled")
  182.      */
  183.     public function indexCanceledAction(EntityManagerInterface $em$idgroupRequest $request) {
  184.         $parameters = array( 'status' => 'Deleted' );
  185.         $dql 'SELECT i
  186.                 FROM GreenPatioBundle:Reservation i
  187.                 WHERE i.status = :status
  188.                 ORDER BY i.dateStart ASC';
  189.         $query $em->createQuery($dql)->setParameters($parameters);
  190.         $ref = array();
  191.         $reservas $query->getResult();
  192.         foreach ($reservas as $res){
  193.             $client $em->getRepository(Client::class)->findOneById($res->getClient());
  194.             if (!empty($client)){ $res->setClient($client->getName()); } else { $res->setClient(null); }
  195.             $res->setCreatedBy(
  196.                 ($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getName() . ' '.
  197.                 ($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getLastName());
  198.             $ref[$res->getId()] = '#'.($res->getDateStart())->format('ymd').($res->getDateEnd())->format('ymd');
  199.         }
  200.         $reservasZero = array();
  201.         foreach ($reservas as $res){
  202.             $reservasZero[] = array(
  203.                 'dateStart' => $res->getDateStart(),
  204.                 'dateEnd' => $res->getDateEnd(),
  205.                 'id' => $res->getId(),
  206.                 'title' => $res->getTitle(),
  207.                 'client' => $res->getClient(),
  208.                 'createdBy' => $res->getCreatedBy(),
  209.                 'createdAt' => $res->getCreatedAt(),
  210.                 'ref' => $ref[$res->getId()],
  211.                 'status' => $res->getStatus(),
  212.             );
  213.         }
  214.         $reservas $reservasZero;
  215.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations.html.twig',
  216.             array(
  217.                 'groups' => null,
  218.                 'titleView' => ' Canceladas',
  219.                 'reservations' => $reservas
  220.             )
  221.         );
  222.     }
  223.     /**
  224.      * @Route("/listquoted/{idgroup}", defaults={"idgroup" = 0}, name="reservations_quoted")
  225.      */
  226.     public function indexQuotedAction(EntityManagerInterface $em$idgroupRequest $request) {
  227.         $parameters = array( 'status' => 'Cotizado' );
  228.         $dql 'SELECT i
  229.                 FROM GreenPatioBundle:Reservation i
  230.                 WHERE i.status = :status
  231.                 ORDER BY i.createdAt ASC';
  232.         $query $em->createQuery($dql)->setParameters($parameters);
  233.         $ref = array();
  234.         $reservas $query->getResult();
  235.         foreach ($reservas as $res){
  236.             $client $em->getRepository(Client::class)->findOneById($res->getClient());
  237.             if (!empty($client)){ $res->setClient($client->getName()); } else { $res->setClient(null); }
  238.             $res->setCreatedBy(
  239.                 ($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getName() . ' '.
  240.                 ($em->getRepository(User::class)->findOneById($res->getCreatedBy()))->getLastName());
  241.             $ref[$res->getId()] = '#'.($res->getCreatedAt())->format('ymdHi');
  242.         }
  243.         $reservasZero = array();
  244.         foreach ($reservas as $res){
  245.             $data $this->CalculosTotalesEditSimple($res->getId());
  246.             $reservasZero[] = array(
  247.                 'dateStart' => $res->getDateStart(),
  248.                 'dateEnd' => $res->getDateEnd(),
  249.                 'id' => $res->getId(),
  250.                 'title' => $res->getTitle(),
  251.                 'client' => $res->getClient(),
  252.                 'sales' => $data['sumatoria_totales_global_con_iva'],
  253.                 'ref' => $ref[$res->getId()],
  254.                 'createdAt' => $res->getCreatedAt(),
  255.             );
  256.         }
  257.         $reservas $reservasZero;
  258.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-quotation.html.twig',
  259.             array(
  260.                 'groups' => null,
  261.                 'titleView' => ' Cotizadas',
  262.                 'reservations' => $reservas
  263.             )
  264.         );
  265.     }
  266.     /**
  267.      * @Route("/edit/{id}", name="reservations_greenpatio_edit")
  268.      */
  269.     public function editAction($id)
  270.     {
  271.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id'token' => null ));
  272.     }
  273.     private function createEditReservationsForm(Reservation $entity$id)
  274.     {
  275.         $form $this->createForm(ReservationType::class, $entity, array( 'action' => $this->generateUrl('reservations_update', array( 'id' => $id ) ), 'method' => 'PUT'));
  276.         return $form;
  277.     }
  278.     /**
  279.      * @Route("/update/{id}", name="reservations_update")
  280.      */
  281.     public function updateAction($idEntityManagerInterface $emRequest $request)
  282.     {
  283.         // INICIO: Si la reserva esta facturada no puede ser modificada
  284.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  285.         $oldPriority $reserva->getPriority();         // Si no es un administrador la prioridad no se debe modificar
  286.         $zeroStatus $reserva->getStatus();
  287.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  288.         $user_id $user_logueado->getId();
  289.         $hoy = new \DateTime("now"NULL);
  290.         $reserva->setUpdatedBy($user_id);
  291.         $reserva->setUpdatedAt($hoy);
  292.         $arrayRequest $request->request->get('reservation');
  293.         $boolConfirmacion false;
  294.         $clientContact $request->request->get('clientContact');
  295.         $contactUnregistered $request->request->get('contactUnregistered');
  296.         $nameContactUnregistered $request->request->get('nameContactUnregistered');
  297.         $phoneContactUnregistered $request->request->get('phoneContactUnregistered');
  298.         $reserva->setTitle($arrayRequest['title']);
  299.         $reserva->setClientContact($clientContact);
  300.         $reserva->setContactUnregistered($contactUnregistered);
  301.         if (!empty($nameContactUnregistered)){ $reserva->setNameContactUnregistered($nameContactUnregistered); }
  302.         if (!empty($phoneContactUnregistered)){ $reserva->setPhoneContactUnregistered($phoneContactUnregistered); }
  303.         if(!empty($arrayRequest['client'])){ $reserva->setClient($arrayRequest['client']); } else { $reserva->setClient(null); }
  304.         $daysBlock $arrayRequest['daysBlock'] ?? null;
  305.         if(!is_null($daysBlock) && $reserva->getDaysBlock() != $daysBlock){
  306.             if (empty($daysBlock) && $daysBlock !== 0) {
  307.                 $reserva->setDaysBlock(7);
  308.             } else {
  309.                 $reserva->setDaysBlock($daysBlock);
  310.             }
  311.         }
  312.         // Si se ha cambiado al estado "Bloqueo" se envia un correo al cliente y al agente
  313.         if (!empty($arrayRequest['status'])){
  314.             if ($arrayRequest['status'] == 'Bloqueo'){
  315.                 //Calculamos la fecha limite de bloqueo en función de los dias de bloqueo
  316.                 if(empty($reserva->getDays())){
  317.                     $now = new \DateTime("now");
  318.                     $dateLimit date"Y-m-d H:i"strtotime$now->format('Y-m-d H:i') . "+".$reserva->getDaysBlock()." days" ));
  319.                     $dateLimit = new \DateTime($dateLimit);
  320.     
  321.                     $reserva->setDays($dateLimit);
  322.                 }
  323.                 if ((!empty($reserva->getClient())) or (!empty($reserva->getClientContact())) or (!empty($reserva->getContactUnregistered()))) {
  324.                     //Solo se envia correo de notificacion del correo si hay cliente o contacto o contacto no registrado
  325.                     $client $em->getRepository(Client::class)->findOneById($reserva->getClient());
  326.                     $mailAddressTo null;
  327.                     if (!empty($mailAddressTo)) {
  328.                         $agente $em->getRepository(User::class)->findOneById($user_id);
  329.                         $mailAddressFrom $agente->getEmail();
  330.                         $mailSubject 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
  331.                         $mailBody 'Estimado cliente,' .
  332.                             '<br><br> Nos ponemos en contacto con usted para confirmarle que su reserva ha quedado registrada en Green Patio para la realización de su próximo evento.' .
  333.                             '<br>Le recordamos que esta reserva tiene una validez de ' $reserva->getDaysBlock() . ' días. Si pasado este tiempo no hemos recibido confirmación de vuestra parte, procederemos a la cancelación de la misma.' .
  334.                             '<br><br>Reserva: ' $reserva->getId() .' - '$reserva->getTitle();
  335.                         $mailBody $mailBody '<br><br><br>Muchas gracias por su colaboración.<br><br><br>';
  336.                         //Se envia el correo al cliente y al agente
  337.                         $alertaPrevia $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($reserva->getId());
  338.                         if (empty($alertaPrevia)){
  339.                             //El correo solo se enviara si no se ha enviado ya una alerta previamente
  340. //                            $this->sendMail($mailAddressFrom, $mailAddressTo, $mailSubject, $mailBody);
  341.                         }
  342.                         //Se genera el control de la alerta
  343. //                        $this->makeAlert($reserva->getId(), $reserva->getClient(), $mailAddressTo, $agente->getId(), $agente->getEmail());
  344.                     }
  345.                 }
  346.                 // Modificar la fecha de notificación
  347.                 if (!empty($arrayRequest['dateNextMailAlert'])) {
  348.                     $nextReservaMailAlert $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($id);
  349.                     if (!empty($nextReservaMailAlert)){
  350.                         // La nueva fecha tiene que ser de mañana en adelante
  351.                         if (new \Datetime($arrayRequest['dateNextMailAlert']) > new \Datetime('now')){
  352.                             if ($nextReservaMailAlert->getAlertSended() == 0){
  353.                                 // Si no se ha enviado el mensaje de alerta se modifican la alerta y la cancelacion (+2 dias)
  354.                                 $newAlertDatetime = new \DateTime($arrayRequest['dateNextMailAlert'].' 15:00');
  355.                                 $newCancelDatetime date"Y-m-d H:i"strtotime$newAlertDatetime->format('Y-m-d H:i') . "+2 days" ));
  356.                                 $newCancelDatetime = new \DateTime($newCancelDatetime);
  357.                                 $nextReservaMailAlert->setAlertDateTime($newAlertDatetime);
  358.                                 $nextReservaMailAlert->setCancelDateTime($newCancelDatetime);
  359.                                 $em->persist($nextReservaMailAlert);
  360.                                 $em->flush();
  361.                             } else {
  362.                                 // Si no se ha enviado el mensaje de cancelacion (paso a cotizacion)
  363.                                 $newCancelDatetime = new \DateTime($arrayRequest['dateNextMailAlert'].' 15:00');
  364.                                 $nextReservaMailAlert->setCancelDateTime($newCancelDatetime);
  365.                                 $em->persist($nextReservaMailAlert);
  366.                                 $em->flush();
  367.                             }
  368.                         }
  369.                     }
  370.                 }
  371.             } else{
  372.                 if(!empty($reserva->getDays())){
  373.                     $reserva->setDays(null);
  374.                 }
  375.             }
  376.             $newStatus $this->verificarStatusInicialyFinal($id,$user_id,$reserva->getStatus(),$arrayRequest['status']);
  377.             // Despues de estudiar el estatus se actualiza con el valor que puede tomar
  378.             $arrayRequest['status'] = $newStatus;
  379.             $reserva->setStatus($newStatus);
  380.             if (!($arrayRequest['status'] == 'Bloqueo')){
  381.                 // Si no es un bloqueo, tal vez se deba eliminar una alerta
  382.                 $alertaPrevia $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($id);
  383.                 if (!empty($alertaPrevia)){
  384.                     if ($arrayRequest['status'] == 'Deleted'){
  385.                         // Si se cancela y hay una alerta previa se debe enviar automaticamente correo al cliente y agente acerca de la cancelacion o desbloqueo
  386.                         $agent $em->getRepository(User::class)->findOneById($alertaPrevia->getAgentId());
  387.                         $mailAddressTo $alertaPrevia->getClientMail();
  388.                         $mailAddressFrom $alertaPrevia->getAgentMail();
  389.                         $replyTo = array(
  390.                             $alertaPrevia->getClientMail() => $alertaPrevia->getClientMail(),
  391.                             $alertaPrevia->getAgentMail() => $agent->getName().' '$agent->getLastName(),
  392.                         );
  393.                         $mailSubject 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
  394.                         $mailBody 'Estimado cliente,'.
  395.                             '<br><br>Nos ponemos en contacto con usted para informarle de que su reserva ha sido cancelada.'.
  396.                             '<br><br>Reserva: ' $reserva->getId() .' - '$reserva->getTitle();
  397.                         if (!empty($reserva->getDays())){ $mailBody $mailBody '<br>Días bloqueados: '.$reserva->getDays(); }
  398.                         $mailBody $mailBody '<br><br><br>Muchas gracias por su colaboración.<br><br><br>';
  399.                         //Se envia el correo al cliente y al agente
  400.                         $this->sendMail($mailAddressFrom$mailAddressTo$mailSubject$mailBody);
  401.                         $alertaPrevia->setOldReservationId($alertaPrevia->getReservationId());
  402.                         $alertaPrevia->setReservationId(0);
  403.                         $alertaPrevia->setCancelSended(1);
  404.                     } else {
  405.                         $alertaPrevia->setOldReservationId($alertaPrevia->getReservationId());
  406.                         $alertaPrevia->setReservationId(0);
  407.                     }
  408.                     $em->persist($alertaPrevia);
  409.                     $em->flush();
  410.                 }
  411.             }
  412.         }
  413.         $boolConfirmacion = ($boolConfirmacion and ($reserva->getStatus() == 'Pendiente'));  // Si se pidio cambiar el estado y se quedo en Pendiente y es un usario de GreenPatio (rol 48)
  414.         $reserva->setContract($arrayRequest['contract']);
  415.         $reserva->setDescription($arrayRequest['description']);
  416.         if(!empty($arrayRequest['advancePayment'])){ $reserva->setAdvancePayment($arrayRequest['advancePayment']); } else { $reserva->setAdvancePayment(0); }
  417.         if(!empty($arrayRequest['deposit'])){ $reserva->setDeposit($arrayRequest['deposit']); } else { $reserva->setDeposit(0); }
  418.         if(!empty($arrayRequest['pax'])){ $reserva->setPax($arrayRequest['pax']); } else { $reserva->setPax(null); }
  419.         if(!empty($arrayRequest['idProposal'])){ $reserva->setIdProposal($arrayRequest['idProposal']); } else { $reserva->setIdProposal(null); }
  420.         if (!empty($arrayRequest['cateringName'])){ $reserva->setCateringName($arrayRequest['cateringName']); }
  421.         if(is_null($arrayRequest['priority']) or empty($arrayRequest['priority']) or ($arrayRequest['priority'] == 0)){ $reserva->setPriority(1); } else { $reserva->setPriority($arrayRequest['priority']); }
  422.         if ($user_logueado->getRole() == 'ROLE_USER'){
  423.             // La opcion o prioridad solo la pueden modificar los administradores para evitar competencias entre lo agentes
  424.             $reserva->setPriority($oldPriority);
  425.         }
  426.         if(empty($reserva->getStatus())){$reserva->setStatus('Cotizado');}      //El estado de reserva en vacio es que esta en el proceso de cotizacion
  427.         // Actualizamos las fechas de la reserva
  428.         $resLoungeSimples $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  429.         $newStart null$newEnd null;
  430.         foreach ($resLoungeSimples as $item) {
  431.             $dateStart $item->getDateStart();
  432.             $dateEnd $item->getDateEnd();
  433.             if ($newStart === null || $dateStart $newStart) { $newStart $dateStart; }
  434.             if ($newEnd === null || $dateEnd $newEnd) { $newEnd $dateEnd; }
  435.         }
  436.         if (!empty($newStart) and !empty($newEnd)){
  437.             $reserva->setDateStart($newStart);
  438.             $reserva->setDateEnd($newEnd);
  439.         }
  440.         try{
  441.             $em->persist($reserva);
  442.             $em->flush();
  443. //            $event = 'The Reservation has been Updated. Now';
  444.             $successMessage 'La reserva ha sido actualizada.';
  445. //            $successMessage = $this->translator->trans($event);
  446.             $this->addFlash('mensajereservation'$successMessage);
  447.         } catch (\Exception $e){
  448.             $event 'An error occurred: '.$e->getMessage();
  449.             /* Para el usuario */
  450.             $errorMessage $this->translator->trans($event);
  451.             $this->addFlash('mensajereservationerror'$errorMessage);
  452.         }
  453.         // Se debe solicitar la confirmación de la reserva
  454.         if ($boolConfirmacion){ return $this->redirectToRoute('reservations_greenpatio_send_confirmation_request_mail', array( 'id' => $id'initStatus' => $zeroStatus )); }
  455.         // Si han confirmado se debe notificar a Salvador y a Rafa, no para que confirmen sino para que esten informados
  456.         if ($reserva->getStatus() == 'Confirmed'){ return $this->redirectToRoute('reservations_greenpatio_send_confirmation_request_mail', array( 'id' => $id'initStatus' => $zeroStatus  )); }
  457.         // Sincronización con HT
  458.         if (!empty($reserva)) {
  459.             // Rafa indico que siempre se sincronice al abrir un expediente de GP
  460.             if (in_array($reserva->getStatus(), [null'''Confirmed''Invoiced''Iniciado''Cotizado''Bloqueo'])) {
  461.                 if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
  462.                     // Si no se ha creado aun el expediente de HT debemos crearlo
  463.                     $htFile $em->getRepository(HtFile::class)->findByReservation($reserva);
  464.                     if (empty($htFile)) {
  465.                         return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,));
  466.                     }
  467.                 }
  468.             }
  469.         }
  470.         // Sincronización con Av Express
  471.         $cotizable $this->laReservaEsCotizable($reserva->getId());
  472.         if ($cotizable) {
  473.             // Rafa indico que siempre se sincronice al abrir un expediente de GP
  474.             if (in_array($reserva->getStatus(), [null'''Confirmed''Invoiced''Iniciado''Cotizado''Bloqueo'])) {
  475.                 $AveFile $em->getRepository(AveFiles::class)->findByReservation($reserva);
  476.                 if (empty($AveFile)) {
  477.                     // Si no se ha creado aun el expediente de Av Express debemos crearlo
  478.                     return $this->redirectToRoute('sinc_gp_ave', array('id' => $id,));
  479.                 }
  480.             }
  481.         }
  482.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id'token' => null ));
  483.     }
  484.     /**
  485.      * @Route("/events", name="get_reservations")
  486.      */
  487.     public function reservationSelectAction(Request $request)
  488.     {
  489.         $em $this->getDoctrine()->getManager();
  490.         $fechaInicio = new \DateTime('first day of January last year');
  491.         $qb $em->getRepository(ReservationLoungeSimple::class)->createQueryBuilder('r');
  492.         $reservation $qb->where('r.dateStart >= :fechaInicio')
  493.             ->andWhere('r.idLounge < :idLounge')
  494.             ->setParameter('fechaInicio'$fechaInicio)
  495.             ->setParameter('idLounge'22)
  496.             ->getQuery()
  497.             ->getResult();
  498.         $qb $em->getRepository(ReservationVisit::class)->createQueryBuilder('v');
  499.         $visitas $qb->where('v.dateStart >= :fechaInicio')
  500.                     ->andWhere('v.idLounge = 0')
  501.                     ->setParameter('fechaInicio'$fechaInicio)
  502.                     ->getQuery()
  503.                     ->getResult();
  504.         $arrayFechaVisitas = [];
  505.         //Se agrupan las visitas por fechas
  506.         foreach ($visitas as $item) { $arrayFechaVisitas[$item->getDateStart()->format('Y-m-d')][] = $item; }
  507.         $newArrayVisitas = [];
  508.         //Se agrupan las visitas por agente
  509.         foreach ($arrayFechaVisitas as $fecha) {
  510.             foreach ($fecha as $item) {
  511.                 //Se van concatenando los titulos de las visitas en una sola
  512.                 $loungeNameTemp '';
  513.                 $item->setLoungeName($loungeNameTemp $item->getDateStart()->format('H:i') . ' ' $item->getLoungeName() . '<br>');
  514.                 $newArrayVisitas[$item->getDateStart()->format('Y-m-d') . '-' $item->getAgentId()] = $item;
  515.             }
  516.         }
  517.         $visitas $newArrayVisitas;
  518.         $xArray = [];
  519.         foreach ($arrayFechaVisitas as $elem) { foreach ($elem as $item) { $xArray[] = $item; } }
  520.         foreach ($xArray as $item) { array_push($reservation$item); }
  521.         $datos = [];
  522.         $datosMontaje = [];
  523.         $datosDesMontaje = [];
  524.         if (!empty($reservation)) {
  525.             foreach ($reservation as $reservaSala) {
  526.                 if (!empty($reservaSala->getIdReservation())) {
  527.                     $reserva $em->getRepository(Reservation::class)->findOneById($reservaSala->getIdReservation());
  528.                     if ($reservaSala->getType() == 'Visit') {
  529.                         $reserva->setStatus('Visit');
  530.                     }
  531.                 } else {
  532.                     // Estamos con una visita
  533.                     $reserva = new Reservation();
  534.                     $reserva->setComAvGp(10);                       // Valor por defecto de ComAvGg
  535.                     $reserva->setStatus('Visit');
  536.                     $reserva->setTitle($reservaSala->getLoungeName());
  537.                 }
  538.                 if ($reservaSala->getDateStart()->format('d') == $reservaSala->getDateEnd()->format('d')) {
  539.                     $tooltip $reserva->getTitle() . ' - <b><h3>' $reservaSala->getLoungeName() . "</h3></b> Del " $reservaSala->getDateStart()->format('d/m') . ' desde ' $reservaSala->getHourStart() . ":" $reservaSala->getMinStart() . " a " $reservaSala->getHourEnd() . ":" $reservaSala->getMinEnd();
  540.                 } else {
  541.                     $tooltip $reserva->getTitle() . ' - <b><h3>' $reservaSala->getLoungeName() . "</h3></b> Del " $reservaSala->getDateStart()->format('d/m') . ' desde ' $reservaSala->getHourStart() . ":" $reservaSala->getMinStart() . " al " $reservaSala->getDateEnd()->format('d/m') . ' hasta ' $reservaSala->getHourEnd() . ":" $reservaSala->getMinEnd();
  542.                 }
  543.                 $logicoVisita false;
  544.                 if (!is_null($reserva->getStatus())) {
  545.                     switch ($reserva->getStatus()) {
  546.                         case 'Bloqueo'//naranja
  547.                             $color "#ffaa00";
  548.                             break;
  549.                         case 'Confirmed'//verde
  550.                             $color "#13ad27";
  551.                             break;
  552.                         case 'Invoiced'//verde
  553.                             $color "#13ad27";
  554.                             break;
  555.                         case 'Deleted'//rojo
  556.                             $color "#ff0000";
  557.                             break;
  558.                         case 'Cotizado'//Rojo claro
  559.                             $color "#faafc3";
  560.                             break;
  561.                         case 'Reservado'//verde, se ha adelantado un pago parcial
  562.                             $color "#13ad27";
  563.                             break;
  564.                         case 'Visit'//Azul Almudena (id user 77), Rosa Gaby
  565.                             $logicoVisita true;
  566.                             if ($reservaSala->getAgentId() == 77) {
  567.                                 $color "#22cbf5";
  568.                             } else {
  569.                                 $color "#f5229a";
  570.                             }
  571.                             break;
  572.                         default: //naranja
  573.                             $color "";
  574.                             break;
  575.                     }
  576.                     if (!empty($reservaSala->getType()) and !($reservaSala->getType() == 'Visit')) {
  577.                         //Es un montaje o desmontaje
  578.                         $color "#a5b8a2";
  579.                         // Si es un montaje o desmontaje pero esta cancelado debe prevalecer el color de cancelado
  580.                         if ($reserva->getStatus() == 'Deleted') {
  581.                             $color "#ff0000";
  582.                         }
  583.                         if (($reservaSala->getIdLounge() == 22) or  ($reservaSala->getIdLounge() == 23) or
  584.                         ($reservaSala->getIdLounge() == 24) or ($reservaSala->getIdLounge() == 25)){
  585.                             //Ajustamos el color a una sala de covarrubia
  586.                             switch ($color) {
  587.                                 case '#ffaa00'$color "#b873bf"; break; //naranja (bloqueo) => morado
  588.                                 case '#13ad27'$color "#017362"; break; //verde (Confirmed) => verde olivo
  589.                                 case '#ff0000'$color "#ff0000"; break; //rojo
  590.                                 case '#faafc3'$color "#faafc3"; break; //Rojo claro
  591.                                 default: break; //no modificar el color
  592.                             }
  593.                         }
  594.                     }
  595.                 }
  596.                 $pago1 "";
  597.                 $pago2 "";
  598.                 $ht "";
  599.                 if (!($reserva->getStatus() == 'Visit')) {
  600.                     $paymentsAll $em->getRepository(ReservationPaymentsClient::class)->findOneByReservationId($reserva->getId());
  601.                 } else {
  602.                     $paymentsAll null;
  603.                 }
  604.                 if (!empty($paymentsAll)) {
  605.                     $pago2 "<i class='icon-coin-euro' style='color: #000 !important;'></i>";      //Hay pagos parciales
  606.                 }
  607.                 if (!($reserva->getStatus() == 'Visit')) {
  608.                     $facturas $em->getRepository(ReservationInvoice::class)->findByReservationId($reserva->getId());
  609.                 }
  610.                 if (!empty($facturas)) {
  611.                     foreach ($facturas as $factura) {
  612.                         if ($factura->getMaster() == "master") {
  613.                             $pago1 "<i class='icon-thumbs-up3' style='color: #000 !important;'></i>";// Se ha pagado la totalidad
  614.                         }
  615.                         if ($factura->getMaster() != "master") {
  616.                             $pago2 "<i class='icon-coin-euro' style='color: #000 !important;'></i>";      //Hay pagos parciales
  617.                         }
  618.                     }
  619.                 }
  620.                 if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
  621.                     $ht "<a style='color: #000 !important;'><strong>H&T</strong></a>";      // Es una reserva con servicio de Catering Higo & Trigo
  622.                 }
  623.                 // Pagos parciales y totales
  624.                 if (!empty($reserva)) {
  625.                     if (!$logicoVisita) {
  626.                         $datos[] = array(
  627. //                            "title" => $reservaSala->getDateStart()->format('H:i') . ' ' . $pago2 . $pago1 . $ht . ' ' . $reservaSala->getType() . '<br>' . $reservaSala->getLoungeName() . '<br>' . '<br>' . $reserva->getTitle(),
  628.                             "title" => $reservaSala->getDateStart()->format('H:i') . ' ' $pago2 $pago1 $ht ' ' $reservaSala->getType() .' '$reservaSala->getLoungeName() . '<br>' $reserva->getTitle(),
  629.                             "titleOne" => $reservaSala->getDateStart()->format('H:i') . ' ' $pago2 $pago1 $ht ' ' $reservaSala->getType(),
  630.                             "titleTwo" => $reservaSala->getLoungeName(),
  631.                             "titleThree" => '' '<br>' $reserva->getTitle(),
  632.                             "type" => $reservaSala->getType(),
  633.                             "id" => $reserva->getId(),
  634.                             "tooltip" => $tooltip,
  635.                             "start" => $reservaSala->getDateStart(),
  636.                             "end" => $reservaSala->getDateEnd(),
  637.                             "color" => $color,
  638.                             "loungeId" => $reservaSala->getIdLounge(),
  639.                             "url" => "/reservations-greenpatio/edit/" $reserva->getId(),
  640.                             "status" => $reserva->getStatus(),
  641.                         );
  642.                     } else {
  643.                         // Es una visita
  644.                         $datos[] = array(
  645.                             "title" => $reservaSala->getLoungeName(),
  646.                             "titleOne" => $reservaSala->getDateStart()->format('H:i') . ' ' ' ' $reservaSala->getType() . '<br>',
  647.                             "titleTwo" => $reservaSala->getLoungeName(),
  648.                             "titleThree" => '' '<br>' '<br>' $reserva->getTitle(),
  649.                             "type" => $reservaSala->getType(),
  650.                             "id" => $reservaSala->getId() . 'V',
  651.                             "tooltip" => $tooltip,
  652.                             "start" => $reservaSala->getDateStart(),
  653.                             "end" => $reservaSala->getDateEnd(),
  654.                             "color" => $color,
  655.                             "loungeId" => $reservaSala->getIdLounge(),
  656.                             "url" => '/reservations-greenpatio/addvisit',
  657.                             "status" => $reserva->getStatus(),
  658.                             "agentId" => $reservaSala->getAgentId(),
  659.                         );
  660.                     }
  661.                 } else {
  662.                     $datos = [];
  663.                 }
  664.             }
  665.         }
  666.         $newDatos = array();
  667.         // INICIO: Se unen las salas en una sola reserva por ID de reserva
  668.         foreach ($datos as $dato) {
  669.             // Inicializamos el arreglo para crear los indices
  670.             switch ($dato['color']){
  671.                 case '#a5b8a2': if ($dato['type'] == 'Montaje'){ $newDatos[$dato['id'].'M'] = null; } else { $newDatos[$dato['id'].'D'] = null; } break;      //Montaje o Desmontaje
  672.                 default: $newDatos[$dato['id']] = null; break;      //Dia de reserva o Visita (la visita ya viene con su indice #V )
  673.             }
  674.         }
  675.         foreach ($datos as $dato) {
  676.             switch ($dato['color']){
  677.                                             //Montaje o Desmontaje
  678.                 case '#a5b8a2':
  679.                     if ($dato['type'] == "Montaje") {
  680.                         if (!empty($newDatos[$dato['id'] . 'M'])) {
  681. //                            if ($newDatos[$dato['id'] . 'M']['start'] > $dato['start']) { $newDatos[$dato['id'] . 'M']['start'] = $dato['start']; }
  682. //                            if ($newDatos[$dato['id'] . 'M']['end'] < $dato['end']) { $newDatos[$dato['id'] . 'M']['end'] = $dato['end']; }
  683.                             // El Montaje esta ocupando mas de 1 dia, se deben unir los dias de montaje si estamos tratando la misma sala (no se deben unir montajes de salas diferentes)
  684.                             if ($newDatos[$dato['id'] . 'M']['loungeId'] == $dato['loungeId']) {
  685.                                 if ($newDatos[$dato['id'] . 'M']['start'] > $dato['start']) { $newDatos[$dato['id'] . 'M']['start'] = $dato['start']; }
  686.                                 if ($newDatos[$dato['id'] . 'M']['end'] < $dato['end']) { $newDatos[$dato['id'] . 'M']['end'] = $dato['end']; }
  687.                             } else {
  688.                                 if (array_key_exists($dato['id'] . 'M'.$dato['loungeId'],$newDatos)){
  689.                                     if ($newDatos[$dato['id'] . 'M'.$dato['loungeId']]['start'] > $dato['start']) { $newDatos[$dato['id'] . 'M'.$dato['loungeId']]['start'] = $dato['start']; }
  690.                                     if ($newDatos[$dato['id'] . 'M'.$dato['loungeId']]['end'] < $dato['end']) { $newDatos[$dato['id'] . 'M'.$dato['loungeId']]['end'] = $dato['end']; }
  691.                                 } else {
  692.                                     $newDatos[$dato['id'] . 'M'.$dato['loungeId']] = $dato;
  693.                                 }
  694.                             }
  695.                         } else {
  696.                             $newDatos[$dato['id'] . 'M'] = $dato;
  697.                         }
  698.                     } else {
  699.                         if ($dato['type'] == "Desmontaje") {
  700.                             if (!empty($newDatos[$dato['id'] . 'D'])) {
  701.                                 // El Desmontaje esta ocupando mas de 1 dia, se deben unir los dias de desmontaje
  702.                                 if ($newDatos[$dato['id'] . 'D']['start'] > $dato['start']) { $newDatos[$dato['id'] . 'D']['start'] = $dato['start']; }
  703.                                 if ($newDatos[$dato['id'] . 'D']['end'] < $dato['end']) { $newDatos[$dato['id'] . 'D']['end'] = $dato['end']; }
  704.                             } else {
  705.                                 $newDatos[$dato['id'] . 'D'] = $dato;
  706.                             }
  707.                         }
  708.                     }
  709.                     break;
  710.                                             //Visita Almudena (id user 77)
  711.                 case '#22cbf5':
  712.                     if ($dato['type'] == "Visit") {
  713.                         $newDatos[$dato['start']->format('Ymd').'V77'.$dato['id']] = $dato;
  714.                         if (!empty($newDatos[$dato['start']->format('Ymd').'V77'])) {
  715.                             // Hay varias visitas ese mismo dia para el agente
  716. //                            $newDatos[$dato['start']->format('Ymd').'V77']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V77']['tooltip'] . $dato['tooltip'];
  717.                         } else {
  718. //                            $newDatos[$dato['start']->format('Ymd').'V77'] = $dato;
  719.                         }
  720.                     }
  721.                     break;
  722.                                             //Visita Gabriela (id user 82)
  723.                 case '#f5229a':
  724.                     if ($dato['type'] == "Visit") {
  725.                         $newDatos[$dato['start']->format('Ymd').'V82'.$dato['id']] = $dato;
  726.                         if (!empty($newDatos[$dato['start']->format('Ymd').'V82'])) {
  727.                             // Hay varias visitas ese mismo dia para el agente
  728. //                            $newDatos[$dato['start']->format('Ymd').'V82']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V82']['tooltip'] . $dato['tooltip'];
  729.                         } else {
  730. //                            $newDatos[$dato['start']->format('Ymd').'V82'] = $dato;
  731.                         }
  732.                     }
  733.                     break;
  734.                 //Visita María (id user 120)
  735.                 case '#157cc2':
  736.                     if ($dato['type'] == "Visit") {
  737.                         $newDatos[$dato['start']->format('Ymd').'V120'.$dato['id']] = $dato;
  738.                         if (!empty($newDatos[$dato['start']->format('Ymd').'V120'])) {
  739.                             // Hay varias visitas ese mismo dia para el agente
  740. //                            $newDatos[$dato['start']->format('Ymd').'V120']['tooltip'] = $newDatos[$dato['start']->format('Ymd').'V120']['tooltip'] . $dato['tooltip'];
  741.                         } else {
  742. //                            $newDatos[$dato['start']->format('Ymd').'V120'] = $dato;
  743.                         }
  744.                     }
  745.                     break;
  746.                                             //Reserva color naranja Bloqueo
  747.                 case '#ffaa00':
  748.                     if (empty($newDatos[$dato['id']])){
  749.                         $newDatos[$dato['id']] = $dato;
  750.                     } else {
  751.                         // Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
  752.                         if ($newDatos[$dato['id']]['start'] > $dato['start']) { $newDatos[$dato['id']]['start'] = $dato['start']; }
  753.                         if ($newDatos[$dato['id']]['end'] < $dato['end']) { $newDatos[$dato['id']]['end'] = $dato['end']; }
  754.                         $newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' $dato['tooltip'];
  755.                         // Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
  756.                         if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
  757.                             // No se encontro la cadena, debemos agregar
  758.                             $newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' .'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'$dato['titleTwo'];
  759.                             $newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
  760.                         }
  761.                     }
  762.                     break;
  763.                                             //Reserva color Rojo claro Cotizado
  764.                 case '#faafc3':
  765.                     if (empty($newDatos[$dato['id']])){
  766.                         $newDatos[$dato['id']] = $dato;
  767.                     } else {
  768.                         // Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
  769.                         if ($newDatos[$dato['id']]['start'] > $dato['start']) { $newDatos[$dato['id']]['start'] = $dato['start']; }
  770.                         if ($newDatos[$dato['id']]['end'] < $dato['end']) { $newDatos[$dato['id']]['end'] = $dato['end']; }
  771.                         $newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' $dato['tooltip'];
  772.                         // Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
  773.                         if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
  774.                             // No se encontro la cadena, debemos agregar
  775.                             $newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' .'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'$dato['titleTwo'];
  776.                             $newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
  777.                         }
  778.                     }
  779.                     break;
  780.                                             //Reserva color Rojo Reserva Cancelada
  781.                 case '#ff0000':
  782.                                             //Las canceladas no se muestran en el calendario
  783.                     break;
  784.                                             //Reserva color Verde Reserva Confirmada, Facturada, (se ha adelantado un pago parcial)
  785.                 case '#13ad27':
  786.                     if (empty($newDatos[$dato['id']])){
  787.                         $newDatos[$dato['id']] = $dato;
  788.                     } else {
  789.                         // Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
  790.                         if ($newDatos[$dato['id']]['start'] > $dato['start']) { $newDatos[$dato['id']]['start'] = $dato['start']; }
  791.                         if ($newDatos[$dato['id']]['end'] < $dato['end']) { $newDatos[$dato['id']]['end'] = $dato['end']; }
  792.                         $newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' $dato['tooltip'];
  793.                         // Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
  794.                         if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
  795.                             // No se encontro la cadena, debemos agregar
  796.                             $newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'$dato['titleTwo'];
  797.                             $newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
  798.                         }
  799.                     }
  800.                     break;
  801.                 
  802.                 //Reserva color Verde Reserva Confirmada, Facturada, (Covarrubias)
  803.                 case '#017362':
  804.                     if ($newDatos[$dato['id']]['end'] < $dato['end']) {
  805.                         if (empty($newDatos[$dato['id']])){
  806.                                 $newDatos[$dato['id']]['end'] = $dato['end'];
  807.                             $newDatos[$dato['id']] = $dato;
  808.                         } else {
  809.                             // Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
  810.                             if ($newDatos[$dato['id']]['start'] > $dato['start']) { $newDatos[$dato['id']]['start'] = $dato['start']; }
  811.                             if ($newDatos[$dato['id']]['end'] < $dato['end']) { $newDatos[$dato['id']]['end'] = $dato['end']; }
  812.                             $newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' $dato['tooltip'];
  813.                             // Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
  814.                             if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
  815.                                 // No se encontro la cadena, debemos agregar
  816.                                 $newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'$dato['titleTwo'];
  817.                                 $newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
  818.                             }
  819.                         }
  820.                     }
  821.                 break;
  822.                                             //Se pondra color a negro para resaltar este cualquier caso que no haya sido considerado (status Pendiente)
  823.                 default:
  824.                     if (empty($newDatos[$dato['id']])){
  825.                         $newDatos[$dato['id']] = $dato;
  826.                     } else {
  827.                         // Se verifican la actualizacion de incio y fin, para tener el menor inicio y el mayor fin
  828.                         if ($newDatos[$dato['id']]['start'] > $dato['start']) { $newDatos[$dato['id']]['start'] = $dato['start']; }
  829.                         if ($newDatos[$dato['id']]['end'] < $dato['end']) { $newDatos[$dato['id']]['end'] = $dato['end']; }
  830.                         $newDatos[$dato['id']]['tooltip'] = $newDatos[$dato['id']]['tooltip'] . ' | ' $dato['tooltip'];
  831.                         // Verificamos si la sala ya ha sido previamente agregada a la lista de salas para no repetirla
  832.                         if (strpos($newDatos[$dato['id']]['title'], $dato['titleTwo']) === false) {
  833.                             // No se encontro la cadena, debemos agregar
  834.                             $newDatos[$dato['id']]['titleTwo'] = $newDatos[$dato['id']]['titleTwo'] . '<br>' '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'$dato['titleTwo'];
  835.                             $newDatos[$dato['id']]['title'] = $newDatos[$dato['id']]['titleOne'] . $newDatos[$dato['id']]['titleTwo'] . $newDatos[$dato['id']]['titleThree'];
  836.                         }
  837.                     }
  838.                     // Se pone en color negro para resaltar este caso que no esta entrando en ninguno de los casos anteriores
  839.                     $newDatos[$dato['id']]['color'] = '#000000';
  840.                     if ($dato['type'] == "Visit") {
  841.                         // Si no es una de los agentes regulares (Gaby, Angie, Cristina) se busca el color del usuario configurado en el perfil
  842.                         $elAgente $em->getRepository(User::class)->findOneById($dato['agentId']);
  843.                         $elAgenteColor = !empty($elAgente) ? $elAgente->getColor() : null;
  844.                         if (!empty($elAgenteColor)){ $newDatos[$dato['id']]['color'] = $elAgenteColor; }
  845.                     }
  846.                     break;
  847.             }
  848.         }
  849.         $datos0 = array();
  850.         foreach ($newDatos as $key => $item) {
  851.             if (!empty($item['id'])) {
  852.                 $datos0[$key] = array('title' => $item['title'],
  853.                     'titleOne' => $item['titleOne'],
  854.                     'titleTwo' => $item['titleTwo'],
  855.                     'titleThree' => $item['titleThree'],
  856.                     'type' => $item['type'],
  857.                     'id' => $item['id'],
  858.                     'tooltip' => $item['tooltip'],
  859.                     'start' => $item['start'],
  860.                     'end' => $item['end'],
  861.                     'color' => $item['color'],
  862.                     'loungeId' => $item['loungeId'],
  863.                     'url' => $item['url']);
  864.             }
  865.         }
  866.         $newDatos $datos0;
  867.         $datos = [];
  868.         foreach ($newDatos as $item) {
  869.             if ($item['color'] != '#ff0000') {
  870.                 // No se agregan al calendario los elementos eliminados oelementos vacios
  871.                 if (!empty($item)) {
  872.                     //INICIO: Verificamos por huecos dentro de la reserva
  873.                     if (empty($item['type'])) {
  874.                         // solo las reservas se van a verificar en este if
  875.                         if ((date_diff($item['start'], $item['end'])->d) > 1) {    //el evento tiene mas de 2 dias, puede haber huecos
  876.                             $resSimples $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($item['id']);
  877.                             $period = new DatePeriod(
  878.                                 $item['start'],
  879.                                 new DateInterval('P1D'),
  880.                                 $item['end']
  881.                             );
  882.                             $arrayPeriod = [];
  883.                             foreach ($period as $key => $value) { $arrayPeriod[] = $value; }
  884.                             $logAllDiasEnReserva false;
  885.                             $logDiaEnReserva false;
  886.                             //Verificamos que cada dia tenga su reserva de sala para que no haya hueco
  887.                             foreach ($arrayPeriod as $day) {
  888.                                 foreach ($resSimples as $resSimple) {
  889.                                     if ($resSimple->getDateStart()->format('Y-m-d') == $day->format('Y-m-d')) {
  890.                                         $logDiaEnReserva true;
  891.                                         break;
  892.                                     }
  893.                                 }
  894.                                 if (!$logDiaEnReserva) {
  895.                                     //Un dia no se encontraba, hay un hueco
  896.                                     foreach ($resSimples as $resDayToAdd) {
  897.                                         if (empty($resDayToAdd->getType())) {       // Solo se deben agregar salsa los montajes y desmontajes aqui no van
  898.                                             $item['start'] = $resDayToAdd->getDateStart();
  899.                                             $item['end'] = $resDayToAdd->getDateEnd();
  900.                                             $br '<br>';
  901.                                             $br strpos($item['title'], $br);
  902.                                             $tempText substr($item['title'], $br 4);
  903.                                             $item['title'] = $resDayToAdd->getDateStart()->format('H:i') . ' ' '<br>' $tempText;
  904.                                             $datos[] = $item;
  905.                                         }
  906.                                     }
  907.                                     break;
  908.                                 } else {
  909.                                     //Se debe evaluar el siguiente dia
  910.                                     $logDiaEnReserva false;
  911.                                     if ($day->format('Y-m-d') == (end($arrayPeriod))->format('Y-m-d')) {   //Si es el ultimo elemento evaluado, todos los dias se encontraban en Reservas Simple
  912.                                         $logAllDiasEnReserva true;
  913.                                     }
  914.                                 }
  915.                             }
  916.                             if ($logAllDiasEnReserva) {
  917.                                 $datos[] = $item;
  918.                             }
  919.                         } else {
  920.                             // El evento es de 1 o 2 dias, no hay posibilidad de hueco
  921.                             $datos[] = $item;
  922.                         }
  923.                     } else {
  924.                         //Es Visita Las visitas son las unicas entradas que no tienen hueco
  925.                         if ($item['type'] == 'Visit'){
  926.                             $datos[] = $item;
  927.                         } else {
  928.                             // es montaje o desmontaje, se va verificar por huecos
  929.                             if ((date_diff($item['start'], $item['end'])->d) > 1) {    //el item tiene mas de 2 dias, puede haber huecos
  930.                                 $parameters = array( 'id' => $item['id'], 'type' => $item['type'], );
  931.                                 $dql 'SELECT i
  932.                                         FROM GreenPatioBundle:ReservationLoungeSimple i
  933.                                         WHERE  i.idReservation = :id
  934.                                           and i.type = :type';
  935.                                 $query $em->createQuery($dql)->setParameters($parameters);
  936.                                 $resSimples $query->getResult();
  937.                                 $period = new DatePeriod(
  938.                                     $item['start'],
  939.                                     new DateInterval('P1D'),
  940.                                     $item['end']
  941.                                 );
  942.                                 $arrayPeriod = [];
  943.                                 foreach ($period as $key => $value) { $arrayPeriod[] = $value; }
  944.                                 $logAllDiasEnReserva false;
  945.                                 $logDiaEnReserva false;
  946.                                 //Verificamos que cada dia tenga su reserva de sala para que no haya hueco
  947.                                 foreach ($arrayPeriod as $day) {
  948.                                     foreach ($resSimples as $resSimple) {
  949.                                         if ($resSimple->getDateStart()->format('Y-m-d') == $day->format('Y-m-d')) {
  950.                                             $logDiaEnReserva true;
  951.                                             break;
  952.                                         }
  953.                                     }
  954.                                     if (!$logDiaEnReserva) {
  955.                                         //Un dia no se encontraba, hay un hueco
  956.                                         foreach ($resSimples as $resDayToAdd) {
  957.                                             if (!empty($resDayToAdd->getType())) {       // Solo se deben agregar montajes y desmontajes aqui
  958.                                                 $item['start'] = $resDayToAdd->getDateStart();
  959.                                                 $item['end'] = $resDayToAdd->getDateEnd();
  960.                                                 $br '<br>';
  961.                                                 $br strpos($item['title'], $br);
  962.                                                 $tempText substr($item['title'], $br 4);
  963.                                                 $item['title'] = $resDayToAdd->getDateStart()->format('H:i') . ' ' '<br>' $tempText;
  964.                                                 $datos[] = $item;
  965.                                             }
  966.                                         }
  967.                                         break;
  968.                                     } else {
  969.                                         //Se debe evaluar el siguiente dia
  970.                                         $logDiaEnReserva false;
  971.                                         if ($day->format('Y-m-d') == (end($arrayPeriod))->format('Y-m-d')) {   //Si es el ultimo elemento evaluado, todos los dias se encontraban en Reservas Simple
  972.                                             $logAllDiasEnReserva true;
  973.                                         }
  974.                                     }
  975.                                 }
  976.                                 if ($logAllDiasEnReserva) { $datos[] = $item; }
  977.                             } else {
  978.                                 // El montaje o desmontaje es de 1 o 2 dias, no hay posibilidad de hueco
  979.                                 $datos[] = $item;
  980.                             }
  981.                         }
  982.                     }
  983.                     //FIN: Verificamos por huecos dentro de la reserva
  984.                 }
  985.             }
  986.         }
  987.         $return = array( 'reservation' => $datos, );
  988.         $response = new JsonResponse($return);
  989.         return $response;
  990.     }
  991.     /**
  992.      * @Route("/delete/{id}", name="reservations_delete")
  993.      */
  994.     public function deleteAction($idEntityManagerInterface $emRequest $request)
  995.     {
  996.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  997.         $hoy = new \DateTime("now"NULL);
  998.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  999.         $user_id $user_logueado->getId();
  1000.         $reserva->setUpdatedBy($user_id);
  1001.         $reserva->setUpdatedAt($hoy);
  1002.         $reserva->setStatus('Deleted');
  1003.         try{
  1004.             $em->persist($reserva);
  1005.             $em->flush();
  1006.             $successMessage 'La reserva ha sido actualizada.';
  1007. //            $successMessage = $this->translator->trans($event);
  1008.             $this->addFlash('mensajereservation'$successMessage);
  1009.         } catch (\Exception $e){
  1010.             $event 'An error occurred: '.$e->getMessage();
  1011.             $errorMessage $this->translator->trans($event);
  1012.             $this->addFlash('mensajereservationerror'$errorMessage);
  1013.         }
  1014.         return $this->redirectToRoute('reservations_greenpatio_index');
  1015.     }
  1016.     /**
  1017.      * @Route("/listgpprices", name="reservations_greenpatio_prices")
  1018.      */
  1019.     public function indexPricesAction(EntityManagerInterface $emRequest $request) {
  1020.         $prices $em->getRepository(ReservationLoungeProfile::class)->findBy(
  1021.             array(),
  1022.             array('id' => 'ASC')
  1023.         );
  1024.         $data = [];
  1025.         foreach ($prices as $price){
  1026.             $periodSql $em->getRepository(ReservationPeriod::class)->findOneById($price->getPeriodId());
  1027.             $price->setPeriodId($periodSql->getName());
  1028.             $loungeTemp $em->getRepository(ReservationLoungeDetails::class)->findOneById($price->getLoungeId());
  1029.             if(!is_null($loungeTemp)){ $price->setLoungeId($loungeTemp->getName()); }
  1030.             $data[] = $price;
  1031.         }
  1032.         $reserv = new ReservationLoungeProfile();
  1033.         $form $this->createReservationLoungeProfileCreateForm($reserv);
  1034.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-gp-prices.html.twig',
  1035.             array(
  1036.                 'groups' => null,
  1037.                 'prices' => $data,
  1038.                 'form' => $form->createView()
  1039.             )
  1040.         );
  1041.     }
  1042.     /**
  1043.      * @Route("/deletegpprice/{id}", name="reservations_price_delete")
  1044.      */
  1045.     public function deletePriceAction($idEntityManagerInterface $emRequest $request)
  1046.     {
  1047.         $price $em->getRepository(ReservationLoungeProfile::class)->findOneById($id);
  1048.         try{
  1049.             $em->remove($price);
  1050.             $em->flush();
  1051.             $event 'The Item has been Deleted.';
  1052.             $successMessage $this->translator->trans($event);
  1053.             $this->addFlash('mensajereservation'$successMessage);
  1054.         } catch (\Exception $e){
  1055.             $event 'An error occurred: '.$e->getMessage();
  1056.             /* Para el usuario */
  1057.             $errorMessage $this->translator->trans($event);
  1058.             $this->addFlash('mensajereservationerror'$errorMessage);
  1059.         }
  1060.         return $this->redirectToRoute('reservations_greenpatio_prices');
  1061.     }
  1062.     /**
  1063.      * @Route("/addgpprice/",  name="reservations_greenpatio_addgpprice")
  1064.      */
  1065.     public function addReservationGpPriceAction(EntityManagerInterface $emRequest $request)
  1066.     {
  1067.         $reserv = new ReservationLoungeProfile();
  1068.         $form $this->createReservationLoungeProfileCreateForm($reserv);
  1069.         $gpPrices $em->getRepository(ReservationLoungeProfile::class)->findAll();
  1070.         return $this->render('MDS/GreenPatioBundle/reservations/add-reservations-gp-price.html.twig', array('form' => $form->createView(), 'gpPrices' => $gpPrices ));
  1071.     }
  1072.     private function createReservationLoungeProfileCreateForm(ReservationLoungeProfile $entity)
  1073.     {
  1074.         $form $this->createForm(ReservationLoungeProfileType::class, $entity, array(
  1075.             'action' => $this->generateUrl('reservations_greenpatio_price_create'),
  1076.             'method' => 'POST'
  1077.         ));
  1078.         return $form;
  1079.     }
  1080.     /**
  1081.      * @Route("/creategpprice", name="reservations_greenpatio_price_create")
  1082.      */
  1083.     public function createGpPriceAction(EntityManagerInterface $emRequest $request){
  1084.         $reservaGpPrice = new ReservationLoungeProfile();
  1085.         $form $this->createReservationLoungeProfileCreateForm($reservaGpPrice);
  1086.         $form->handleRequest($request);
  1087.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1088.         $user_id $user_logueado->getId();
  1089.         $hoy = new \DateTime("now"NULL);
  1090.         $reservaGpPrice->setCreatedAt($hoy);
  1091.         $reservaGpPrice->setCreatedId($user_id);
  1092.         $reservaGpPrice->setUpdatedAt($hoy);
  1093.         $reservaGpPrice->setUpdatedId($user_id);
  1094.         $periodSql $em->getRepository(ReservationPeriod::class)->findOneById($form->get('periodId')->getData());
  1095.         if (!empty($periodSql)){ $descTemp $periodSql->getName(); } else { $descTemp null; }
  1096.         $reservaGpPrice->setPeriodId($reservaGpPrice->getPeriodId()->getId());
  1097.         $reservaGpPrice->setLoungeId($reservaGpPrice->getLoungeId()->getId());
  1098.         if ((!is_null($reservaGpPrice->getLoungeId())) and (!is_null($descTemp))){
  1099.             $descriptionSql $em->getRepository(ReservationLoungeDetails::class)->findOneById($form->get('loungeId')->getData());
  1100.             $description $descriptionSql->getName().' - '.$descTemp;
  1101.             $reservaGpPrice->setDescription($description);
  1102.         } else {
  1103.             $reservaGpPrice->setDescription(null);
  1104.         }
  1105.         if($form->isValid())
  1106.         {
  1107.             try{
  1108.                 $em->persist($reservaGpPrice);
  1109.                 $em->flush();
  1110.                 $event 'The Item Price has been created.';
  1111.                 $successMessage $this->translator->trans($event);
  1112.                 $this->addFlash('mensajereservation'$successMessage);
  1113.             } catch (\Exception $e){
  1114.                 $event 'An error occurred: '.$e->getMessage();
  1115.                 $errorMessage $this->translator->trans($event);
  1116.                 $this->addFlash('mensajereservationerror'$errorMessage);
  1117.             }
  1118.         } else {
  1119.             $errorMessage $this->translator->trans('Error, some fields are empty');
  1120.             $this->addFlash('mensajereservationerror'$errorMessage);
  1121.         }
  1122.         return $this->redirectToRoute('reservations_greenpatio_prices');
  1123.     }
  1124.     /**
  1125.      * @Route("/getReservationLoungeProfile", name="get_reservation_lounge_profile")
  1126.      */
  1127.     public function getReservationLoungeProfileAction(EntityManagerInterface $emRequest $request) {
  1128.         $codProfile $_POST['idprofile'];
  1129.         $salasPorPerfil $em->getRepository(ReservationLoungeProfile::class)->findBy( array( 'periodId' => $codProfile ) );
  1130.         $datos = [];
  1131.         if (!empty($salasPorPerfil)){
  1132.             foreach($salasPorPerfil as $sala){
  1133.                 $datos[] = array(
  1134.                     "id" => $sala->getId(),
  1135.                     "idlounge" => $sala->getLoungeId(),
  1136.                     "nameDescription" => $sala->getDescription(),
  1137.                     "price" => $sala->getPrice(),
  1138.                 );
  1139.             }
  1140.         }
  1141.         $return = array( 'salasPerfil' => $datos'id' => $codProfile, );
  1142.         $response = new JsonResponse($return);
  1143.         return $response;
  1144.     }
  1145.     /**
  1146.      * @Route("/getReservationPeriod", name="get_reservation_Period")
  1147.      */
  1148.     public function getReservationPeriodAction(EntityManagerInterface $emRequest $request) {
  1149.         $id $_POST['id'];
  1150.         $period $em->getRepository(ReservationPeriod::class)->findOneById($id);
  1151.         $datos = array();
  1152.         if (!empty($period)){
  1153.             $datos = array(
  1154.                 "id" => $period->getId(),
  1155.                 "hourStart" => is_null($period->getHourStart())?"":$period->getHourStart()->format('H:i'),
  1156.                 "hourEnd" => is_null($period->getHourEnd())?"":$period->getHourEnd()->format('H:i'),
  1157.             );
  1158.         }
  1159.         $return $datos;
  1160.         $response = new JsonResponse($return);
  1161.         return $response;
  1162.     }
  1163.     /**
  1164.      * @Route("/getReservationLoungePrice", name="get_reservation_lounge_price")
  1165.      */
  1166.     public function getReservationLoungePriceAction(EntityManagerInterface $emRequest $request) {
  1167.         $id $_POST['id'];
  1168.         $precio $em->getRepository(ReservationLoungeProfile::class)->findOneById($id);
  1169.         $datos = array();
  1170.         if (!empty($precio)){ $datos = array( "id" => $precio->getId(), "price" => $precio->getPrice() ); }
  1171.         $return $datos;
  1172.         $response = new JsonResponse($return);
  1173.         return $response;
  1174.     }
  1175.     /**
  1176.      * @Route("/addloungedetails/",  name="reservations_greenpatio_addloungedetails")
  1177.      */
  1178.     public function addReservationLoungeDetailsActionRequest $request)
  1179.     {
  1180.         $lounge = new ReservationLoungeDetails();
  1181.         $form $this->createReservationLoungeDetailsCreateForm($lounge);
  1182.         return $this->render('MDS/GreenPatioBundle/reservations/add-reservations-lounge-details.html.twig', array('form' => $form->createView() ));
  1183.     }
  1184.     private function createReservationLoungeDetailsCreateForm(ReservationLoungeDetails $entity)
  1185.     {
  1186.         $form $this->createForm(ReservationLoungeDetailsType::class, $entity, array(
  1187.             'action' => $this->generateUrl('reservations_greenpatio_lounge_details_create'),
  1188.             'method' => 'POST'
  1189.         ));
  1190.         return $form;
  1191.     }
  1192.     /**
  1193.      * @Route("/createloungedetails", name="reservations_greenpatio_lounge_details_create")
  1194.      */
  1195.     public function createLoungeDetailsAction(EntityManagerInterface $emRequest $request)
  1196.     {
  1197.         $lounge = new ReservationLoungeDetails();
  1198.         $form $this->createReservationLoungeDetailsCreateForm($lounge);
  1199.         $form->handleRequest($request);
  1200.         /* Obtengo usuario logueado */
  1201.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1202.         $user_id $user_logueado->getId();
  1203.         $hoy = new \DateTime("now"NULL);
  1204.         $lounge->setCreatedAt($hoy);
  1205.         $lounge->setCreatedId($user_id);
  1206.         $lounge->setUpdatedAt($hoy);
  1207.         $lounge->setUpdatedId($user_id);
  1208.         if($form->isValid()){
  1209.             try{
  1210.                 $em->persist($lounge);
  1211.                 $em->flush();
  1212.                 $event 'The Lounge has been created.';
  1213.                 $successMessage $this->translator->trans($event);
  1214.                 $this->addFlash('mensajereservation'$successMessage);
  1215.                 $this->reordenarSalas($lounge->getRankLounge(), $lounge->getId());
  1216.             } catch (\Exception $e){
  1217.                 $event 'An error occurred: '.$e->getMessage();
  1218.                 /* Para el usuario */
  1219.                 $errorMessage $this->translator->trans($event);
  1220.                 $this->addFlash('mensajereservationerror'$errorMessage);
  1221.             }
  1222.         } else {
  1223.             $errorMessage $this->translator->trans('Error, some fields are empty');
  1224.             $this->addFlash('mensajereservationerror'$errorMessage);
  1225.         }
  1226.         return $this->redirectToRoute('reservations_greenpatio_list_lounges');
  1227.     }
  1228.     /**
  1229.      * @Route("/listloungedetails", name="reservations_greenpatio_list_lounges")
  1230.      */
  1231.     public function indexLoungesAction(EntityManagerInterface $emRequest $request) {
  1232.         $salas $em->getRepository(ReservationLoungeDetails::class)->findAll();
  1233.         $lounge = new ReservationLoungeDetails();
  1234.         $form $this->createReservationLoungeDetailsCreateForm($lounge);
  1235.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-lounges-details.html.twig',
  1236.             array(
  1237.                 'groups' => null,
  1238.                 'salas' => $salas,
  1239.                 'form' => $form->createView()
  1240.             )
  1241.         );
  1242.     }
  1243.     /**
  1244.      * @Route("/editloungedetails/{id}", name="reservations_lounge_details")
  1245.      */
  1246.     public function editLoungeDetailsAction($idEntityManagerInterface $emRequest $request)
  1247.     {
  1248.         $lounge $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
  1249.         
  1250.         $loungeContracts $em->getRepository(DocContractModel::class)->findBy(array('companyId' => 7'modelId' => $id));
  1251.         $contractsByLanguage = [];
  1252.         foreach ($loungeContracts as $contract) {
  1253.             $contractsByLanguage[$contract->getLanguage()] = $contract;
  1254.         }
  1255.         $loungePictures $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id'title' => null,));
  1256.         $loungeVideos $em->getRepository(ReservationLoungeVideo::class)->findByLoungeId($id);
  1257.         $loungeDescriptions $em->getRepository(ReservationLoungeDescription::class)->findByLoungeId($id);
  1258.         $loungeWebDescriptions $em->getRepository(ReservationLoungeWebDescription::class)->findByLounge($lounge);
  1259.         $descriptionsByLanguage = [];
  1260.         foreach ($loungeWebDescriptions as $description) {
  1261.             $descriptionsByLanguage[$description->getLanguage()] = $description;
  1262.         }
  1263.         /* Obtengo usuario logueado */
  1264.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1265.         $user_id $user_logueado->getId();
  1266.         /* Gestión de eventos en Log */
  1267.         $user_lastname $user_logueado->getLastname();
  1268.         $user_name $user_logueado->getName();
  1269.         $user_email $user_logueado->getEmail();
  1270.         $user_rol $user_logueado->getRoles();
  1271.         $event_url $request->getPathInfo();
  1272.         $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  1273.         $hoy = new \DateTime("now"NULL);
  1274.         $form $this->createEditReservationLoungeDetailsForm($lounge$id);
  1275.         // Para evitar le duplicidad de idiomas en las descripciones
  1276.         $loungeDescriptionsPreexistentes $em->getRepository(ReservationLoungeDescription::class)->findByLoungeId($id);
  1277.         $idiomasPreexistentes = array();
  1278.         foreach ($loungeDescriptionsPreexistentes as $item){ $idiomasPreexistentes[] = $item->getLanguage(); }
  1279.         $datos_videos = array();
  1280.         foreach ($loungeVideos as $video){
  1281.             $urvideo_final '<iframe class="embed-responsive-item" src="'.$video->getVideo().'"></iframe>';
  1282.             $datos_videos[] = array(
  1283.                 'id' => $video->getId(),
  1284.                 'urlvideo' => $urvideo_final
  1285.             );
  1286.         }
  1287.         $blueprints $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id'title' => 'Blueprint', ) );
  1288.         $pictTeatro $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id'title' => 'Teatro', ) );
  1289.         if (sizeof($pictTeatro) == 0) {$pictTeatro null;}
  1290.         $pictCoctel $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id'title' => 'Coctel', ) );
  1291.         if (sizeof($pictCoctel) == 0) {$pictCoctel null;}
  1292.         $pictEscuela $em->getRepository(ReservationLoungePicture::class)->findBy( array('loungeId' => $id'title' => 'Escuela', ) );
  1293.         if (sizeof($pictEscuela) == 0) {$pictEscuela null;}
  1294.         $picsMontaje = array (
  1295.             'pictTeatro' => $pictTeatro,
  1296.             'pictCoctel' => $pictCoctel,
  1297.             'pictEscuela' => $pictEscuela
  1298.         );
  1299.         if(empty($picsMontaje['pictTeatro']) and empty($picsMontaje['pictCoctel']) and empty($picsMontaje['pictEscuela'])){ $picsMontaje null; }
  1300.         $loungedimmensions $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
  1301.         return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-lounge-details.html.twig',
  1302.             array(
  1303.                 'id' => $id,
  1304.                 'hoy' => $hoy,
  1305.                 'lounge' => $lounge,
  1306.                 'loungeContracts' => $contractsByLanguage,
  1307.                 'descriptions' => $loungeDescriptions,
  1308.                 'loungeWebDesctiptions' => $descriptionsByLanguage,
  1309.                 'languagesWeb' => LanguageConstants::getAvailableLanguages(),
  1310.                 'pictures' => $loungePictures,
  1311.                 'blueprints' => $blueprints,
  1312.                 'picsMontaje' => $picsMontaje,
  1313.                 'loungedimmensions' => $loungedimmensions,
  1314.                 'videos' => $datos_videos,
  1315.                 'idiomasPreexistentes' => $idiomasPreexistentes,
  1316.                 'form' => $form->createView()
  1317.             ));
  1318.     }
  1319.     private function createEditReservationLoungeDetailsForm(ReservationLoungeDetails $entity$id)
  1320.     {
  1321.         $form $this->createForm(ReservationLoungeDetailsType::class, $entity,
  1322.             array(
  1323.                 'action' => $this->generateUrl('reservations_lounge_details_update',
  1324.                     array(
  1325.                         'id' => $id,
  1326.                         'price' => $entity
  1327.                     )
  1328.                 ), 'method' => 'PUT'));
  1329.         return $form;
  1330.     }
  1331.     /**
  1332.      * @Route("/updateloungedetails/{id}", name="reservations_lounge_details_update")
  1333.      */
  1334.     public function updateLoungeDetailsAction($idRequest $request)
  1335.     {
  1336.         $em $this->getDoctrine()->getManager();
  1337.         $lounge $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
  1338.         $lounge->setName($request->request->get('mds_greenpatiobundle_reservationloungedetails')['name']);
  1339.         $preNumber $lounge->getRankLounge();
  1340.         $postNumber $request->request->get('mds_greenpatiobundle_reservationloungedetails')['rankLounge'];
  1341.         $hoy = new \DateTime("now"NULL);
  1342.         $form $this->createEditReservationLoungeDetailsForm($lounge$id);
  1343.         $form->handleRequest($request);
  1344.         if($form->isValid())
  1345.         {
  1346.             /* Obtengo usuario logueado */
  1347.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1348.             $user_id $user_logueado->getId();
  1349.             /* Gestión de eventos en Log */
  1350.             $user_lastname $user_logueado->getLastname();
  1351.             $user_name $user_logueado->getName();
  1352.             $user_email $user_logueado->getEmail();
  1353.             $user_rol $user_logueado->getRoles();
  1354.             $event_url $request->getPathInfo();
  1355.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  1356.             $lounge->setUpdatedId($user_id);
  1357.             $lounge->setUpdatedAt($hoy);
  1358.             try{
  1359.                 // Reordenar salas si se ha cambiado el rank number de la sala
  1360.                 if (!( $preNumber == $postNumber)){ $this->reordenarSalas($postNumber$lounge->getId()); }
  1361.                 $em->persist($lounge);
  1362.                 $em->flush();
  1363.                 $event 'The lounge has been Updated. Now';
  1364.                 $successMessage $this->translator->trans($event);
  1365.                 $this->addFlash('mensajereservation'$successMessage);
  1366.             } catch (\Exception $e){
  1367.                 $event 'An error occurred: '.$e->getMessage();
  1368.                 /* Para el usuario */
  1369.                 $errorMessage $this->translator->trans($event);
  1370.                 $this->addFlash('mensajereservationerror'$errorMessage);
  1371.             }
  1372.             /* Fin Gestión de eventos en Log */
  1373.             return $this->redirectToRoute('reservations_greenpatio_list_lounges');
  1374.         } else {
  1375.             $errorMessage $this->translator->trans('Error, some fields are empty');
  1376.             $this->addFlash('mensajereservationerror'$errorMessage);
  1377.         }
  1378.         return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-lounge-details.html.twig',
  1379.             array(
  1380.                 'id' => $lounge->getId(),
  1381.                 'lounge' => $lounge,
  1382.                 'form' => $form->createView()
  1383.             )
  1384.         );
  1385.     }
  1386.     /**
  1387.      * @Route("/deleteloungedetails/{id}", name="reservations_lounge_details_delete")
  1388.      */
  1389.     public function deleteLoungeDetailsAction($idEntityManagerInterface $emRequest $request)
  1390.     {
  1391.         $lounge $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
  1392.         try{
  1393.             $em->remove($lounge);
  1394.             $em->flush();
  1395.             // INICIO: Eliminamos los precios asociados a la sala
  1396.                 $profiles $em->getRepository(ReservationLoungeProfile::class)->findByLoungeId($id);
  1397.                 foreach ($profiles as $item){
  1398.                     $em->remove($item);
  1399.                     $em->flush();
  1400.                 }
  1401.             // FIN: Eliminamos los precios asociados a la sala
  1402.             $event 'The Reservation has been Deleted. Now';
  1403.             $successMessage $this->translator->trans($event);
  1404.             $this->addFlash('mensajereservation'$successMessage);
  1405.         } catch (\Exception $e){
  1406.             $event 'An error occurred: '.$e->getMessage();
  1407.             /* Para el usuario */
  1408.             $errorMessage $this->translator->trans($event);
  1409.             $this->addFlash('mensajereservationerror'$errorMessage);
  1410.         }
  1411.         /* Fin Gestión de eventos en Log */
  1412.         return $this->redirectToRoute('reservations_greenpatio_list_lounges');
  1413.     }
  1414.     /**
  1415.      * @Route("/deleteloungeelement/{idlounge}/{idtype}/{idelement}", name="reservations_lounge_element_delete")
  1416.      */
  1417.     public function deleteLoungeElementAction($idlounge$idtype$idelementEntityManagerInterface $emRequest $request)
  1418.     {
  1419.         switch ($idtype){
  1420.             case 1$item $em->getRepository(ReservationLoungeDescription::class)->findOneById($idelement); break;      //Descripcion
  1421.             case 2$item $em->getRepository(ReservationLoungePicture::class)->findOneById($idelement); break;      //Imagenes
  1422.             case 3$item $em->getRepository(ReservationLoungeVideo::class)->findOneById($idelement); break;      //Videos
  1423.             default: $item null; break;
  1424.         }
  1425.         try{
  1426.             $em->remove($item);
  1427.             $em->flush();
  1428.             $event 'The Item has been Deleted. Now';
  1429.             $successMessage $this->translator->trans($event);
  1430.             $this->addFlash('mensajereservation'$successMessage);
  1431.         } catch (\Exception $e){
  1432.             $event 'An error occurred: '.$e->getMessage();
  1433.             /* Para el usuario */
  1434.             $errorMessage $this->translator->trans($event);
  1435.             $this->addFlash('mensajereservationerror'$errorMessage);
  1436.         }
  1437.         /* Fin Gestión de eventos en Log */
  1438.         return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $idlounge ));
  1439.     }
  1440.     /**
  1441.      *@Route("/exclamation", name="get_exclamation")
  1442.      */
  1443.     public function exclamationAction(EntityManagerInterface $emRequest $request) {
  1444.         $dateStar $request->request->get('dateStar');
  1445.         $dateEnd $request->request->get('dateEnd');
  1446.         $hourStar $request->request->get('hourStar');
  1447.         $hourEnd $request->request->get('hourEnd');
  1448.         $profileId $request->request->get('profileId');
  1449.         $mountingDate $request->request->get('mountingDate');
  1450.         $mountingHourStart $request->request->get('mountingHourStart');
  1451.         $removalDate $request->request->get('removalDate');
  1452.         $removalHourEnd $request->request->get('removalHourEnd');
  1453.         // INICIO: Si hay montaje o desmontaje  en el evento nuevo las fechas a utilizar son estas y no las del evento
  1454.         if (!empty($mountingDate)){
  1455.             $dateStar $mountingDate;
  1456.             if (!empty($mountingHourStart)){ $hourStar $mountingHourStart; }
  1457.         }
  1458.         if (!empty($removalDate)){
  1459.             $dateEnd $removalDate;
  1460.             if (!empty($removalHourEnd)){ $hourEnd $removalHourEnd; }
  1461.         }
  1462.         // FIN: Si hay montaje o desmontaje  en el evento nuevo las fechas a utilizar son estas y no las del evento
  1463.         $loungeId $em->getRepository(ReservationLoungeProfile::class)->findOneById($profileId);
  1464.         $newdateStar $dateStar.' '.$hourStar.':00';
  1465.         $newdateEnd $dateEnd .' '.$hourEnd.':00';
  1466.         $parameters = array(
  1467.             'dateStar' => $newdateStar,
  1468.             'dateEnd' => $newdateEnd,
  1469.             'idLounge' => $loungeId->getLoungeId(),
  1470.         );
  1471.         $dql 'SELECT i
  1472.                     FROM GreenPatioBundle:ReservationLounge i
  1473.                     WHERE  i.dateStart >= :dateStar
  1474.                       and i.dateStart <= :dateEnd
  1475.                       and i.idLounge = :idLounge';
  1476.         $query $em->createQuery($dql)->setParameters($parameters);
  1477.         $reservationLounge1 $query->getResult();
  1478.         $dql 'SELECT i
  1479.                     FROM GreenPatioBundle:ReservationLounge i
  1480.                     WHERE  i.dateEnd >= :dateStar
  1481.                       and i.dateEnd <= :dateEnd
  1482.                       and i.idLounge = :idLounge';
  1483.         $query $em->createQuery($dql)->setParameters($parameters);
  1484.         $reservationLounge2 $query->getResult();
  1485.         $parameters = array(
  1486.             'dateStar' => $newdateStar,
  1487.             'idLounge' => $loungeId->getLoungeId()
  1488.         );
  1489.         $dql 'SELECT i
  1490.                     FROM GreenPatioBundle:ReservationLounge i
  1491.                     WHERE  :dateStar >= i.dateStart
  1492.                       and :dateStar <= i.dateEnd
  1493.                       and i.idLounge = :idLounge';
  1494.         $query $em->createQuery($dql)->setParameters($parameters);
  1495.         $reservationLounge3 $query->getResult();
  1496.         $parameters = array(
  1497.             'dateEnd' => $newdateEnd,
  1498.             'idLounge' => $loungeId->getLoungeId(),
  1499.         );
  1500.         $dql 'SELECT i
  1501.                     FROM GreenPatioBundle:ReservationLounge i
  1502.                     WHERE  :dateEnd >= i.dateStart
  1503.                       and :dateEnd <= i.dateEnd
  1504.                       and i.idLounge = :idLounge';
  1505.         $query $em->createQuery($dql)->setParameters($parameters);
  1506.         $reservationLounge4 $query->getResult();
  1507.         // INICIO: Si hay montaje o desmontaje  en los eventos de la BD, las fechas a utilizar son estas y no las del evento
  1508.         $parameters = array(
  1509.             'dateStar' => $newdateStar,
  1510.             'dateEnd' => $newdateEnd,
  1511.             'idLounge' => $loungeId->getLoungeId(),
  1512.         );
  1513.         $dql 'SELECT i
  1514.                     FROM GreenPatioBundle:ReservationLounge i
  1515.                     WHERE  i.mountingDate >= :dateStar
  1516.                       and i.mountingDate <= :dateEnd
  1517.                       and i.idLounge = :idLounge';
  1518.         $query $em->createQuery($dql)->setParameters($parameters);
  1519.         $reservationLounge5 $query->getResult();
  1520.         // FIN: Si hay montaje o desmontaje  en los eventos de la BD, las fechas a utilizar son estas y no las del evento
  1521.         $reservationLounge array_merge($reservationLounge1,$reservationLounge2,$reservationLounge3,$reservationLounge4);
  1522.         $data = array();
  1523.         foreach ($reservationLounge as $res){
  1524.             $reservation $em->getRepository(Reservation::class)->findOneById($res->getIdReservation());
  1525.             if (!is_null($reservation->getIdProposal() )){
  1526.                 $proposal $em->getRepository(Proposal::class)->findOneById($reservation->getIdProposal());
  1527.                 $user $em->getRepository(User::class)->findOneById($proposal->getAgentId());
  1528.                 $data[] = array(
  1529.                     'name' => 'Id Proposal',
  1530.                     'idproposal' => $proposal->getId(),
  1531.                     'title' => $proposal->getTitle(),
  1532.                     'Agent' => $user->getName().' '.$user->getLastname(),
  1533.                 );
  1534.             } else {
  1535.                 $user $em->getRepository(User::class)->findOneById($reservation->getCreatedBy());
  1536.                 $data[] = array(
  1537.                     'name' => 'Id Green Patio',
  1538.                     'idproposal' => $reservation->getId(),
  1539.                     'title' => $reservation->getTitle(),
  1540.                     'Agent' => $user->getName().' '.$user->getLastname(),
  1541.                 );
  1542.             }
  1543.         }
  1544.         $return = array( 'reservation' => $data, );
  1545.         $response = new JsonResponse($return);
  1546.         return $response;
  1547.     }
  1548.     /**
  1549.      * @Route("/addperiod/",  name="reservations_greenpatio_addperiod")
  1550.      */
  1551.     public function addReservationPeriodActionRequest $request)
  1552.     {
  1553.         $period = new ReservationPeriod();
  1554.         $form $this->createReservationperiodCreateForm($period);
  1555.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-period.html.twig', array('form' => $form->createView() ));
  1556.     }
  1557.     private function createReservationperiodCreateForm(Reservationperiod $entity)
  1558.     {
  1559.         $form $this->createForm(ReservationPeriodType::class, $entity, array(
  1560.             'action' => $this->generateUrl('reservations_greenpatio_period_create'),
  1561.             'method' => 'POST'
  1562.         ));
  1563.         return $form;
  1564.     }
  1565.     /**
  1566.      * @Route("/createperiod", name="reservations_greenpatio_period_create")
  1567.      */
  1568.     public function createPeriodAction(EntityManagerInterface $emRequest $request)
  1569.     {
  1570.         $period = new ReservationPeriod();
  1571.         $form $this->createReservationPeriodCreateForm($period);
  1572.         $form->handleRequest($request);
  1573.         /* Obtengo usuario logueado */
  1574.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1575.         $user_id $user_logueado->getId();
  1576.         $hoy = new \DateTime("now"NULL);
  1577.         $period->setCreatedAt($hoy);
  1578.         $period->setCreatedId($user_id);
  1579.         $period->setUpdatedAt($hoy);
  1580.         $period->setUpdatedId($user_id);
  1581.         if($form->isValid())
  1582.         {
  1583.             try{
  1584.                 $em->persist($period);
  1585.                 $em->flush();
  1586.                 $event 'The Period has been created.';
  1587.                 $successMessage $this->translator->trans($event);
  1588.                 $this->addFlash('mensajereservation'$successMessage);
  1589.             } catch (\Exception $e){
  1590.                 $event 'An error occurred: '.$e->getMessage();
  1591.                 /* Para el usuario */
  1592.                 $errorMessage $this->translator->trans($event);
  1593.                 $this->addFlash('mensajereservationerror'$errorMessage);
  1594.             }
  1595.         } else {
  1596.             $errorMessage $this->translator->trans('Error, some fields are empty');
  1597.             $this->addFlash('mensajereservationerror'$errorMessage);
  1598.         }
  1599.         return $this->redirectToRoute('reservations_greenpatio_list_period');
  1600.     }
  1601.     /**
  1602.      * @Route("/listperiod", name="reservations_greenpatio_list_period")
  1603.      */
  1604.     public function indexPeriodAction(EntityManagerInterface $emRequest $request) {
  1605.         $periods $em->getRepository(ReservationPeriod::class)->findAll();
  1606.         $period = new ReservationPeriod();
  1607.         $form $this->createReservationPeriodCreateForm($period);
  1608.         return $this->render('MDS/GreenPatioBundle/reservations/list-reservations-period.html.twig',
  1609.             array(
  1610.                 'groups' => null,
  1611.                 'form' => $form->createView(),
  1612.                 'periods' => $periods
  1613.             )
  1614.         );
  1615.     }
  1616.     /**
  1617.      * @Route("/deleteperiod/{id}", name="reservations_period_delete")
  1618.      */
  1619.     public function deletePeriodAction(EntityManagerInterface $em$idRequest $request)
  1620.     {
  1621.         $period $em->getRepository(ReservationPeriod::class)->findOneById($id);
  1622.         try{
  1623.             $em->remove($period);
  1624.             $em->flush();
  1625.             $event 'The Reservation has been Deleted. Now';
  1626.             $successMessage $this->translator->trans($event);
  1627.             $this->addFlash('mensajereservation'$successMessage);
  1628.         } catch (\Exception $e){
  1629.             $event 'An error occurred: '.$e->getMessage();
  1630.             /* Para el usuario */
  1631.             $errorMessage $this->translator->trans($event);
  1632.             $this->addFlash('mensajereservationerror'$errorMessage);
  1633.         }
  1634.         /* Fin Gestión de eventos en Log */
  1635.         return $this->redirectToRoute('reservations_greenpatio_list_period');
  1636.     }
  1637.     /**
  1638.      * @Route("/editperiod/{id}", name="reservations_edit_period")
  1639.      */
  1640.     public function editPeriodAction($idEntityManagerInterface $emRequest $request)
  1641.     {
  1642.         $period $em->getRepository(ReservationPeriod::class)->findOneById($id);
  1643.         /* Obtengo usuario logueado */
  1644.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1645.         /* Gestión de eventos en Log */
  1646.         $user_lastname $user_logueado->getLastname();
  1647.         $user_name $user_logueado->getName();
  1648.         $user_email $user_logueado->getEmail();
  1649.         $user_rol $user_logueado->getRoles();
  1650.         $event_url $request->getPathInfo();
  1651.         $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  1652.         $hoy = new \DateTime("now"NULL);
  1653.         $form $this->createEditPeriodForm($period$id);
  1654.         return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-period.html.twig',
  1655.             array(
  1656.                 'id' => $id,
  1657.                 'hoy' => $hoy,
  1658.                 'period' => $period,
  1659.                 'form' => $form->createView()
  1660.             ));
  1661.     }
  1662.     private function createEditPeriodForm(ReservationPeriod $entity$id)
  1663.     {
  1664.         $form $this->createForm(ReservationPeriodType::class, $entity,
  1665.             array(
  1666.                 'action' => $this->generateUrl('reservations_period_update',
  1667.                     array(
  1668.                         'id' => $id,
  1669.                         'period' => $entity
  1670.                     )
  1671.                 ), 'method' => 'PUT'));
  1672.         return $form;
  1673.     }
  1674.     /**
  1675.      * @Route("/updateperiod/{id}", name="reservations_period_update")
  1676.      */
  1677.     public function updatePeriodAction($idEntityManagerInterface $emRequest $request)
  1678.     {
  1679.         $period $em->getRepository(ReservationPeriod::class)->findOneById($id);
  1680.         $newName $request->request->get('mds_greenpatiobundle_reservationperiod')['name'];
  1681.         $period->setName($newName);
  1682.         $hoy = new \DateTime("now"NULL);
  1683.         $form $this->createEditPeriodForm($period$id);
  1684.         $form->handleRequest($request);
  1685.         if($form->isValid())
  1686.         {
  1687.             /* Obtengo usuario logueado */
  1688.             $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1689.             $user_id $user_logueado->getId();
  1690.             /* Gestión de eventos en Log */
  1691.             $user_lastname $user_logueado->getLastname();
  1692.             $user_name $user_logueado->getName();
  1693.             $user_email $user_logueado->getEmail();
  1694.             $user_rol $user_logueado->getRoles();
  1695.             $event_url $request->getPathInfo();
  1696.             $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  1697.             $period->setUpdatedId($user_id);
  1698.             $period->setUpdatedAt($hoy);
  1699.             try{
  1700.                 $em->persist($period);
  1701.                 $em->flush();
  1702.                 $event 'The period has been Updated. Now';
  1703.                 $successMessage $this->translator->trans($event);
  1704.                 $this->addFlash('mensajereservation'$successMessage);
  1705.             } catch (\Exception $e){
  1706.                 $event 'An error occurred: '.$e->getMessage();
  1707.                 /* Para el usuario */
  1708.                 $errorMessage $this->translator->trans($event);
  1709.                 $this->addFlash('mensajereservationerror'$errorMessage);
  1710.             }
  1711.             /* Fin Gestión de eventos en Log */
  1712.             return $this->redirectToRoute('reservations_greenpatio_list_period');
  1713.         } else {
  1714.             $errorMessage $this->translator->trans('Error, some fields are empty');
  1715.             $this->addFlash('mensajereservationerror'$errorMessage);
  1716.         }
  1717.         return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-period.html.twig',
  1718.             array(
  1719.                 'id' => $id,
  1720.                 'hoy' => $hoy,
  1721.                 'period' => $period,
  1722.                 'form' => $form->createView()
  1723.             )
  1724.         );
  1725.     }
  1726.     /**
  1727.      * @Route("/getperiodos/",  name="reservations_greenpatio_get_periods")
  1728.      */
  1729.     public function addReservationPeriodsAction(EntityManagerInterface $emRequest $request)
  1730.     {
  1731.         $periods $em->getRepository(ReservationPeriod::class)->findAll();
  1732.         $data = array();
  1733.         foreach ($periods as $items){ $data[] = array( 'id' => $items->getId(), 'name' => $items->getName(), ); }
  1734.         $return = array( 'periods' => $data, );
  1735.         $response = new JsonResponse($return);
  1736.         return $response;
  1737.     }
  1738.     /**
  1739.      * @Route("/addsimple/",  name="reservations_greenpatio_add_simple")
  1740.      */
  1741.     public function addReservationSimpleAction(EntityManagerInterface $emRequest $request)
  1742.     {
  1743.         $reserv = new Reservation();
  1744.         $reserv->setComAvGp(10);                       // Valor por defecto de ComAvGg
  1745.         $form $this->createReservationCreateForm($reserv);
  1746.         $parameters = array();
  1747.         $dql 'SELECT p
  1748.                 FROM App:ClientContact p
  1749.                 ORDER BY p.name ASC ';
  1750.         $query $em->createQuery($dql)->setParameters($parameters);
  1751.         $clientsContact $query->getResult();
  1752.         return $this->render('MDS/GreenPatioBundle/reservations/add-reservations-simple.html.twig',
  1753.             array(
  1754.                 'form' => $form->createView(),
  1755.                 'clientsContact' => $clientsContact,
  1756.             ));
  1757.     }
  1758.     private function createReservationCreateForm(Reservation $entity)
  1759.     {
  1760.         $form $this->createForm(ReservationType::class, $entity, array(
  1761.             'action' => $this->generateUrl('reservations_greenpatio_create_simple'),
  1762.             'method' => 'POST'
  1763.         ));
  1764.         return $form;
  1765.     }
  1766.     /**
  1767.      * @Route("/createsimple", name="reservations_greenpatio_create_simple")
  1768.      */
  1769.     public function createSimpleAction(EntityManagerInterface $emRequest $request)
  1770.     {
  1771.         $clientContact $request->request->get('clientContact');
  1772.         $contactUnregistered $request->request->get('contactUnregistered');
  1773.         $nameContactUnregistered $request->request->get('nameContactUnregistered');
  1774.         $phoneContactUnregistered $request->request->get('phoneContactUnregistered');
  1775.         $reserva = new Reservation();
  1776.         $reserva->setComAvGp(10);                       // Valor por defecto de ComAvGg
  1777.         $form $this->createReservationCreateForm($reserva);
  1778.         $form->handleRequest($request);
  1779.         /* Obtengo usuario logueado */
  1780.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  1781.         $user_id $user_logueado->getId();
  1782.         $hoy = new \DateTime("now"NULL);
  1783.         if($form->isValid())
  1784.         {
  1785.             $reserva->setUpdatedBy($user_id);
  1786.             $reserva->setUpdatedAt($hoy);
  1787.             // El proveedor de catering no es obligatorio
  1788.             if (is_null($reserva->getCateringName())){
  1789.                 $reserva->setSupplier(4765);
  1790.                 $reserva->setCateringName('HIGO & TRIGO, S.L.');        // Por defecto se desea el Catering de Higo&Trigo
  1791.             } else {
  1792.                 $reserva->setSupplier($reserva->getCateringName()->getId());
  1793.                 $reserva->setCateringName($reserva->getCateringName()->getName());
  1794.             }
  1795.             if (!empty($reserva->getClient())){
  1796.                 $reserva->setClient($reserva->getClient()->getId());
  1797.             }
  1798.             $reserva->setCreatedAt($hoy);
  1799.             $reserva->setCreatedBy($user_id);
  1800.             if(empty($reserva->getDaysBlock()) or !(is_numeric($reserva->getDaysBlock()))){
  1801.                 $reserva->setDaysBlock(7);
  1802.             }
  1803.             if(is_null($reserva->getPriority()) or empty($reserva->getPriority()) or ($reserva->getPriority() == 'Auto')){
  1804.                 $reserva->setPriority(1);
  1805.             } else {
  1806.                 // Se ha establecido una prioridad y todas las prioridades que coincidan con este evento deben ser alteradas
  1807.                 // PENDIENTE A HABLAR CON RAFA
  1808.             }
  1809.             // No hay salas, se asigna a la reserva la fecha del dia actual
  1810.             $reserva->setDateStart(new \DateTime('2078-01-01'));
  1811.             $reserva->setDateEnd(new \DateTime('2000-01-01'));
  1812.             if(!empty($clientContact)){ $reserva->setClientContact($clientContact); }
  1813.             if(!empty($contactUnregistered)){
  1814. //                if (filter_var($contactUnregistered, FILTER_VALIDATE_EMAIL)) {          // Validamos el correo electronico
  1815.                     $reserva->setContactUnregistered($contactUnregistered);
  1816. //                }
  1817.             }
  1818.             if(!empty($nameContactUnregistered)){
  1819.                 $reserva->setNameContactUnregistered($nameContactUnregistered);
  1820.             }
  1821.             if(!empty($phoneContactUnregistered)){
  1822.                 $reserva->setPhoneContactUnregistered($phoneContactUnregistered);
  1823.             }
  1824.             if(empty($reserva->getStatus())){
  1825.                 $reserva->setStatus('Iniciado');
  1826.             } else {
  1827.                 //No se debe crear un evento con estado confirmado. Salva y Rafa seran quienes confirmen los eventos
  1828.                 if(($reserva->getStatus() == 'Confirmed')){
  1829. //                    $reserva->setStatus('Cotizado');              //Ya no es necesario que Rafa o Salva confirmen
  1830.                 }
  1831.             }
  1832.             // Genera un token único utilizando la función uniqid() de PHP
  1833.             $token uniqid();
  1834.             $reserva->setToken($token);
  1835.             try{
  1836.                 $em->persist($reserva);
  1837.                 $em->flush();
  1838.                 $event 'The Reservation has been created.';
  1839.                 $successMessage $this->translator->trans($event);
  1840.                 $this->addFlash('mensajereservation'$successMessage);
  1841.             } catch (\Exception $e){
  1842.                 $event 'An error occurred: '.$e->getMessage();
  1843.                 $errorMessage $this->translator->trans($event);
  1844.                 $this->addFlash('mensajereservationerror'$errorMessage);
  1845.             }
  1846.             //Envio de correo al cliente y al agente si es un bloqueo
  1847.             if(is_null($reserva->getStatus())){
  1848.                 $reserva->setStatus('Cotizado');
  1849.                 $em->persist($reserva);
  1850.                 $em->flush();
  1851.             } else {
  1852.                 if (($reserva->getStatus() == 'Bloqueo')) {
  1853.                     if(empty($reserva->getDays())){
  1854.                         $now = new \DateTime("now");
  1855.                         $dateLimit date"Y-m-d H:i"strtotime$now->format('Y-m-d H:i') . "+".$reserva->getDaysBlock()." days" ));
  1856.                         $dateLimit = new \DateTime($dateLimit);
  1857.         
  1858.                         $reserva->setDays($dateLimit);
  1859.                     }
  1860.                     if ((!empty($reserva->getClient())) or (!empty($reserva->getClientContact())) or (!empty($reserva->getContactUnregistered()))) {
  1861.                         //Solo se envia correo de notificacion del correo si hay cliente o contacto o contacto no registrado
  1862.                         $client $em->getRepository(Client::class)->findOneById($reserva->getClient());
  1863.                         $mailAddressTo null;
  1864.                         // if (!empty($client) and (!empty($client->getEmail()))){ $mailAddressTo = $client->getEmail(); }         // Si hay cliente con correo se le envia a este
  1865.                         // if (!empty($reserva->getClientContact())){
  1866.                         //     $contacto = $em->getRepository(ClientContact::class)->findOneById($reserva->getClientContact());
  1867.                         //     if (!empty($contacto) and (!empty($contacto->getEmail()))){ $mailAddressTo = $contacto->getEmail(); }   // Si hay un contacto seleccionado tiene prioridad sobre el contacto de cliente
  1868.                         // }
  1869.                         // if (!empty($reserva->getContactUnregistered())){ $mailAddressTo = $reserva->getContactUnregistered(); }     // Si hay correo de contacto no registrado este tiene prioridad sobre todos
  1870.                         if (!empty($mailAddressTo)) {
  1871.                             $agente $em->getRepository(User::class)->findOneById($user_id);
  1872.                             $mailAddressFrom $agente->getEmail();
  1873.                             $mailSubject 'Notificación de Bloqueo - Reserva de espacio en Green Patio';
  1874.                             $mailBody 'Estimado cliente,' .
  1875.                                 '<br><br> Nos ponemos en contacto con usted para confirmarle que su reserva ha quedado registrada en Green Patio para la realización de su próximo evento.' .
  1876.                                 '<br>Le recordamos que esta reserva tiene una validez de ' $reserva->getDaysBlock() . ' días. Si pasado este tiempo no hemos recibido confirmación de vuestra parte, procederemos a la cancelación de la misma.' .
  1877.                                 '<br><br>Reserva: ' $reserva->getId() .' - '$reserva->getTitle();
  1878.                             $mailBody $mailBody '<br><br><br>Muchas gracias por su colaboración.<br><br><br>';
  1879.                             //Se envia el correo al cliente y al agente
  1880.                             $this->sendMail($mailAddressFrom$mailAddressTo$mailSubject$mailBody);
  1881.                             //Se genera el control de la alerta
  1882.                             $this->makeAlert($reserva->getId(), $reserva->getClient(), $mailAddressTo$agente->getId(), $agente->getEmail());
  1883.                         }
  1884.                     }
  1885.                 }
  1886.             }
  1887.         } else {
  1888.             $errorMessagebase $this->translator->trans('Error, some fields are empty');
  1889.             $this->addFlash('mensajetracingerror'$errorMessagebase);
  1890.             $periods $em->getRepository(ReservationPeriod::class)->findAll();
  1891.             return $this->render('MDS/GreenPatioBundle/reservations/add-reservations.html.twig',
  1892.                 array(
  1893.                     'form' => $form->createView(),
  1894.                     'periods' => $periods,
  1895.                 ));
  1896.         }
  1897.         $id $reserva->getId();
  1898.         // Sincronización con HT
  1899.         if (!empty($reserva)) {
  1900.             // Rafa indico que siempre se sincronice al abrir un expediente de GP
  1901.             if (in_array($reserva->getStatus(), [null'''Confirmed''Invoiced''Iniciado''Cotizado''Bloqueo'])) {
  1902. //            if ($reserva->getStatus() == 'Confirmed' or $reserva->getStatus() ==  'Invoiced' or $reserva->getStatus() == 'Iniciado' or $reserva->getStatus() == 'Cotizado' or $reserva->getStatus() ==  'Bloqueo') {
  1903.                 if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
  1904.                     // Si no se ha creado aun el expediente de HT debemos crearlo
  1905.                     $htFile $em->getRepository(HtFile::class)->findByReservation($reserva);
  1906.                     if (empty($htFile)) { return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,)); }
  1907.                 }
  1908.             }
  1909.         }
  1910.         // Sincronización con Av Express
  1911.         $cotizable $this->laReservaEsCotizable($reserva->getId());
  1912.         if ($cotizable) {
  1913.             // Rafa indico que siempre se sincronice al abrir un expediente de GP
  1914.             if (in_array($reserva->getStatus(), [null'''Confirmed''Invoiced''Iniciado''Cotizado''Bloqueo'])) {
  1915. //            if (in_array($reserva->getStatus(), ['Confirmed', 'Invoiced', 'Iniciado', 'Cotizado', 'Bloqueo'])) {
  1916.                 $AveFile $em->getRepository(AveFiles::class)->findByReservation($reserva);
  1917.                 if (empty($AveFile)) {
  1918.                     // Si no se ha creado aun el expediente de Av Express debemos crearlo
  1919.                     return $this->redirectToRoute('sinc_gp_ave', array('id' => $id,));
  1920.                 }
  1921.             }
  1922.         }
  1923.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id'token' => null ));
  1924.     }
  1925.     /**
  1926.      * @Route("/editsimple/{id}",  name="reservations_greenpatio_edit_simple")
  1927.      */
  1928.     public function editReservationSimpleItemsAction($idEntityManagerInterface $emRequest $request)
  1929.     {
  1930.         $lounges $em->getRepository(ReservationLoungeDetails::class)->findAll();
  1931.         $loungesSimple $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  1932.         $services $em->getRepository(ReservationService::class)->findByReservationId($id);
  1933.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  1934.         $lounge = new ReservationLounge();
  1935.         $lounge->setIdReservation($id);
  1936.         $monDesmon = new ReservationLounge();
  1937.         $monDesmon->setIdReservation($id);
  1938.         $form1 $this->createReservationCreateForm($reserva);
  1939.         $form2 $this->createReservationLoungeCreateForm($lounge);
  1940.         $form3 $this->createReservationLoungeMonDesCreateForm($monDesmon);
  1941.         $arrayLoungesByDay = []; $arrayLoungesInFile = [];
  1942.         $arrayLoungesByDay = [];
  1943.         $arrayLoungesInFile = [];
  1944.         if (!empty($loungesSimple)) {
  1945.             foreach ($loungesSimple as $item) {
  1946.                 // Arreglo por día
  1947.                 $dateStart $item->getDateStart()->format('Ymd');
  1948.                 $arrayLoungesByDay[$item->getRankQuote()][$dateStart][] = $item;
  1949.                 ksort($arrayLoungesByDay[$item->getRankQuote()]);
  1950.                 // Arreglo en archivo
  1951. //                if (empty($item->getType())) {
  1952.                     $arrayLoungesInFile[$item->getRankQuote()][$item->getIdLounge()] = array(
  1953.                         'rankQuote' => $item->getRankQuote(),
  1954.                         'idLounge' => $item->getIdLounge(),
  1955.                         'loungeName' => $item->getLoungeName(),
  1956.                         'loungeImportantDescription' => $item->getImportantDescription(),
  1957.                         'loungeImportantDescGeneralText' => $item->getImportantDescGeneralText(),
  1958.                         'loungeImportantDescSchedules' => $item->getImportantDescSchedules(),
  1959.                         'loungeImportantDescParking' => $item->getImportantDescParking(),
  1960.                         'loungeDocContract' => empty($loungeContract) ? ''$loungeContract->getContractualDocument(),
  1961.                         'loungeDocBookingData' => empty($loungeContract) ? ''$loungeContract->getBookingData(),
  1962.                         'loungeDocDateAt' => empty($loungeContract) ? ''$loungeContract->getDateAt(),
  1963.                         'loungeDocClientProxy' => empty($loungeContract) ? ''$loungeContract->getClientProxy(),
  1964.                         'loungeDocClientJob' => empty($loungeContract) ? ''$loungeContract->getClientJob(),
  1965.                         'loungeDocFullContract' => empty($dataContract['fullContract']) ? ''$dataContract['fullContract'],
  1966.                         'language' => $item->getLanguage(),
  1967.                     );
  1968. //                }
  1969.             }
  1970.         } elseif (!empty($loungesSimple)) {
  1971.             foreach ($loungesSimple as $item) {
  1972.                 $itemTemp = clone $item;
  1973.                 $tempDateStart = clone $item->getDateStart();
  1974.                 $tempDateEnd = clone $item->getDateEnd();
  1975.                 $days = ($tempDateEnd $tempDateStart) ? $tempDateEnd->diff($tempDateStart)->days 1;
  1976.                 for ($i 0$i $days$i++) {
  1977.                     $fecha = clone $tempDateStart;
  1978.                     $fecha->modify("+$i days");
  1979.                     $dateTemp $fecha->format('Ymd');
  1980.                     $arrayLoungesByDay[$item->getRankQuote()][$dateTemp][] = $item;
  1981.                 }
  1982.                 ksort($arrayLoungesByDay[$item->getRankQuote()]);
  1983.             }
  1984.         }
  1985.         // FIN: Se forma el arreglo para las salas dia a dia
  1986.         $numeroItems sizeof($arrayLoungesByDay);
  1987.         $data $this->CalculosTotalesEditSimple($reserva->getId());
  1988.         $client $em->getRepository(Client::class)->findOneById($reserva->getClient());
  1989.         if (!empty($client)){ $clientId $client->getId(); } else { $clientId 0; }
  1990.         $clients $em->getRepository(Client::class)->findAll();
  1991.         /* CONSULTAMOS PARA SUMAR  */
  1992.         $parameters = array( 'tags' => 'CATERING''company' => 'HIGO & TRIGO, S.L.',  );
  1993.         $dql 'SELECT p
  1994.                 FROM App\Entity\Supplier p
  1995.                 WHERE (p.tags LIKE :tags) AND (p.company <> :company) 
  1996.                 ORDER BY p.company ASC ';
  1997.         $query $em->createQuery($dql)->setParameters($parameters);
  1998.         $caterings $query->getResult();
  1999.         // Agregamos el catering de Higo & Trigo de primero
  2000.         $catHigoTrigo $em->getRepository(Supplier::class)->findOneById(4765);
  2001.         array_unshift($caterings$catHigoTrigo);
  2002.         $userCreatedBy $em->getRepository(User::class)->findOneById($reserva->getCreatedBy());
  2003.         $createdBy $userCreatedBy->getName().' '.$userCreatedBy->getLastName();
  2004.         $parameters = [];
  2005.         $dql 'SELECT p
  2006.                 FROM GreenPatioBundle:ReservationLoungeDetails p
  2007.                 ORDER BY p.rankLounge ASC ';
  2008.         $query $em->createQuery($dql)->setParameters($parameters);
  2009.         $loungesPre $query->getResult();
  2010.         $loungesNames $em->getRepository(ReservationLoungeDetails::class)->findAll();
  2011.         $query $em->createQuery('SELECT s.id, s.company FROM App\Entity\Supplier s');
  2012.         $listSupplier $query->getResult();
  2013.         $em $this->getDoctrine()->getManager();
  2014.         $invoiced $em->getRepository(ReservationInvoice::class)->findByReservationId($id);
  2015.         $invoicedRec $em->getRepository(ReservationInvoiceRec::class)->findByReservationId($id);
  2016.         foreach ($invoicedRec as $item){ array_push($invoiced$item); }
  2017.         $invoicedCvr $em->getRepository(CvrReservationInvoice::class)->findByReservationId($id);
  2018.         $invoicedBlv $em->getRepository(BlvReservationInvoice::class)->findByReservationId($id);
  2019.         $invoicedLine = empty($invoicedCvr) ? (empty($invoicedBlv) ? 'GP' 'BLV') : 'CVR';
  2020.         foreach ($invoicedCvr as $item){ array_push($invoiced$item); }
  2021.         $invoicedCvrRec $em->getRepository(CvrReservationInvoiceRec::class)->findByReservationId($id);
  2022.         foreach ($invoicedCvrRec as $item){ array_push($invoiced$item); }
  2023.         foreach ($invoicedBlv as $item){ array_push($invoiced$item); }
  2024.         $invoicedBlvRec $em->getRepository(BlvReservationInvoiceRec::class)->findByReservationId($id);
  2025.         foreach ($invoicedBlvRec as $item){ array_push($invoiced$item); }
  2026.         $sumatoriaTotalNet 0$sumatoriaTotalVat 0$sumatoriaTotal 0;
  2027.         $resultados = array( 'totalNeto' => 0'vat' => 0'total' => 0, );
  2028.         foreach ($invoiced as $idArray => $item){
  2029.             $reserva $em->getRepository(Reservation::class)->findOneById($item->getReservationId());
  2030.             $invoiced[$idArray]->setNumber($reserva->getTitle());
  2031.             $client $em->getRepository(Client::class)->findOneById($reserva->getClient());
  2032.             if(!empty($client)){ $invoiced[$idArray]->setPrefix($client->getName()); } else { $invoiced[$idArray]->setPrefix(''); }
  2033.             if ($item->getType() == 'Invoice Deposit'){
  2034.                 // INICIO: Verificamos el uso de la factura de deposito dentro de una factura, en este caso se usa el valor absoluto del balance para evitar la resta doble
  2035.                 $paymentItem $em->getRepository(ReservationPaymentsClient::class)->findOneByInvoiceId($item->getId());
  2036.                 if (!empty($paymentItem)){
  2037.                     $invoiceElementItem $em->getRepository(ReservationInvoiceItems::class)->findOneByPayControlId($paymentItem->getId());
  2038.                     if (!empty($invoiceElementItem)) {
  2039.                         // Solo nos interesa evaluar las facturas y no las facturas de deposito
  2040.                         $invoiceOfItem $em->getRepository(ReservationInvoice::class)->findOneById($invoiceElementItem->getInvoiceId());
  2041.                         if (!empty($invoiceOfItem)) { if ($invoiceOfItem->getType() == 'Invoice') { $invoiced[$idArray]->setBalance(0); } }
  2042.                     }
  2043.                 }
  2044.                 // FIN: Verificamos el uso de la factura de deposito dentro de una factura, en este caso se usa el valor absoluto del balance para evitar la resta doble
  2045.                 $invoicedDepositItems $em->getRepository(ReservationInvoiceDepositItems::class)->findByControlId($item->getMaster());
  2046.                 foreach ($invoicedDepositItems as $itemDep){
  2047.                     $invoiced[$idArray]->setTotalNet($invoiced[$idArray]->getTotalNet() + $itemDep->getAmount());
  2048.                     $invoiced[$idArray]->setVat($invoiced[$idArray]->getVat() + (($itemDep->getAmount() * $itemDep->getIva())/100));
  2049.                     $invoiced[$idArray]->setTotal($invoiced[$idArray]->getTotal() + ($itemDep->getAmount() + (($itemDep->getAmount() * $itemDep->getIva())/100)));
  2050.                 }
  2051.             }
  2052.             // Valores Netos
  2053.             if ($item->getType()=='Invoice'){
  2054.                 $sumatoriaTotalNet $sumatoriaTotalNet $item->getTotalNet();
  2055.             } else {
  2056.                 if ($item->getType()=='Invoice Deposit'){
  2057.                     //Factura de deposito
  2058.                     $sumatoriaTotalNet $sumatoriaTotalNet 0;  //$item->getTotalNet();   // Las facturas de deposito no deben computar en este calculo
  2059.                 } else {
  2060.                     if ($item->getType()=='Invoice Deposit Rec'){
  2061.                         //Factura de Deposito rectificativa
  2062.                         $sumatoriaTotalNet $sumatoriaTotalNet 0;
  2063.                     } else {
  2064.                         //Factura rectificativa
  2065.                         $sumatoriaTotalNet $sumatoriaTotalNet $item->getTotalNet();     // Se han llenado de datos negativos las rectificativas, solo es necesario sumar
  2066.                     }
  2067.                 }
  2068.             }
  2069.             //Valores Iva
  2070.             if ($item->getType()=='Invoice') {
  2071.                 $sumatoriaTotalVat $sumatoriaTotalVat $item->getVat();
  2072.             } else {
  2073.                 if ($item->getType()=='Invoice Deposit'){
  2074.                     //Factura de deposito
  2075.                     $sumatoriaTotalVat $sumatoriaTotalVat 0;  //$item->getVat();  // Las facturas de deposito no deben computar en este calculo
  2076.                 } else {
  2077.                     if ($item->getType()=='Invoice Deposit Rec'){
  2078.                         //Factura de Deposito rectificativa
  2079.                         $sumatoriaTotalNet $sumatoriaTotalNet 0;
  2080.                     } else {
  2081.                         //Factura rectificativa
  2082.                         $sumatoriaTotalVat $sumatoriaTotalVat $item->getVat();      // Se han llenado de datos negativos las rectificativas, solo es necesario sumar
  2083.                     }
  2084.                 }
  2085.             }
  2086.             if (($item->getType()=='Invoice Deposit') or ($item->getType()=='Invoice Deposit Rec')) {
  2087.                 $sumatoriaTotal $sumatoriaTotal 0;                              // Las facturas de deposito o de deposito rectificativas no deben computar en este calculo
  2088.             } else {
  2089.                 $sumatoriaTotal $sumatoriaTotal $item->getTotal();
  2090.             }
  2091.             $resultados = array( 'totalNeto' => $sumatoriaTotalNet'vat' => $sumatoriaTotalVat'total' => $sumatoriaTotal, );
  2092.         }
  2093.         $paymentsAll $em->getRepository(ReservationPaymentsClient::class)->findByReservationId($id);
  2094.         // Verificamos pagos aun sin facturar
  2095.         $paymentNotIvoiced = [];
  2096.         foreach ($paymentsAll as $item){
  2097.             $isInvoiced $em->getRepository(ReservationInvoiceItems::class)->findBy(array('reservationId' => $id'payControlId' => $item->getId()));
  2098.             if (empty($isInvoiced)){ array_push($paymentNotIvoiced$item); }
  2099.         }
  2100.         //Buscamos los agentes y seleccionamos por defecto el usuario logeado
  2101.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2102.         $user_id $user_logueado->getId();
  2103.         $parameters = array( 'clientId' => $clientId, );
  2104.         $dql 'SELECT p
  2105.                 FROM App:ClientContact p
  2106.                 WHERE p.clientId = :clientId
  2107.                 ORDER BY p.name ASC ';
  2108.         $query $em->createQuery($dql)->setParameters($parameters);
  2109.         $clientsContact $query->getResult();
  2110.         // Fecha de notificacion en caso de ser un bloqueo
  2111.         $reservationMailAlertClient $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($id);
  2112.         $nextMailAlert null;
  2113.         if (!empty($reservationMailAlertClient)){
  2114.             if (!($reservationMailAlertClient->getAlertSended())){
  2115.                 // La proxima fecha es la de la alerta
  2116.                 $nextMailAlert $reservationMailAlertClient->getAlertDateTime();
  2117.             } else {
  2118.                 if (!($reservationMailAlertClient->getCancelSended())){
  2119.                     // La proxima fecha es la de la cancelacion (paso a cotización)
  2120.                     $nextMailAlert $reservationMailAlertClient->getCancelDateTime();
  2121.                 }
  2122.             }
  2123.         }
  2124.         $parameters = array( 'status' => 1, );
  2125.         $dql 'SELECT c
  2126.                 FROM  App\Entity\User c
  2127.                 WHERE c.status = :status
  2128.                 ORDER BY c.name ASC ';
  2129.         $query $em->createQuery($dql)->setParameters($parameters);
  2130.         $allUsersActive $query->getResult();
  2131.         //Agregamos los FreeLance
  2132.         $freeLances $em->getRepository(ExternalUser::class)->findAll();
  2133.         foreach ($freeLances as $item){
  2134.             $item->setTeam(($item->getId() * (-1)));
  2135.             $allUsersActive[] = $item;
  2136.         }
  2137.         // Buscamos todos los servicios y los separmos por facturados y no facturados
  2138.         $datax $this->benefitForReservation($id);
  2139.         // Se quitan los clientes que no son de Green Patio
  2140. //        $parameters = array();
  2141. //        $dql = 'SELECT p
  2142. //                FROM App:Client p
  2143. //                WHERE p.isClientGreenPatio = TRUE
  2144. //                ORDER BY p.name ASC ';
  2145. //
  2146. //        $query = $em->createQuery($dql)->setParameters($parameters);
  2147. //        $clients = $query->getResult();
  2148.         $parameters = [];
  2149.         $dql 'SELECT p.id, p.name
  2150.         FROM App:Client p
  2151.         WHERE p.isClientGreenPatio = TRUE
  2152.         ORDER BY p.name ASC';
  2153.         $query $em->createQuery($dql)->setParameters($parameters);
  2154.         $clients $query->getArrayResult();
  2155.         $depositsAll $em->getRepository(ReservationDeposit::class)->findByReservationId($id);
  2156.         $confirmable $this->laReservaEsConfirmable($id);
  2157.         $cotizable $this->laReservaEsCotizable($id);
  2158.         $htFile in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $em->getRepository(HtFile::class)->findOneByReservation($reserva) : null;
  2159.         $aveFile in_array($user_logueado->getUserrol(),[9,23,24,37,47,53]) ? $em->getRepository(AveFiles::class)->findOneByReservation($reserva) : null;
  2160.         if ($reserva) { $urlCotizacion "https://cotizacion.greenpatio.es/index.php?token=".$reserva->getToken(); }
  2161.         $viewContract false;
  2162.         //Generamos el arreglo de contratos
  2163.         if (in_array($reserva->getStatus(), ['Confirmed''Invoiced'])) { $viewContract true; }
  2164.         $languagesWeb LanguageConstants::getAvailableLanguages();
  2165.         return $this->render('MDS/GreenPatioBundle/reservations/edit-reservations-simple.html.twig',
  2166.             array(
  2167.                 'form' => $form1->createView(),
  2168.                 'form2' => $form2->createView(),
  2169.                 'form3' => $form3->createView(),
  2170.                 'id' => $id,
  2171.                 'clients' => $clients,
  2172.                 'clientId' => $clientId,
  2173.                 'caterings' => $caterings,
  2174.                 'loungesPre' => $loungesPre,
  2175.                 'loungesNames' => $loungesNames,
  2176.                 'arrayLoungesInFile' => $arrayLoungesInFile,
  2177.                 'facturas' => $invoiced,
  2178.                 'numeroItems' => $numeroItems,
  2179.                 'arrayLoungesByDay' => $arrayLoungesByDay,
  2180.                 'totales_global_con_iva' => $data['totales_global_con_iva'],
  2181.                 'totales_global_iva' => $data['totales_global_iva'],
  2182.                 'totales_global_neto' => $data['totales_global_neto'],
  2183.                 'totales_global_servicios_con_iva' => $data['totales_global_servicios_con_iva'],
  2184.                 'totales_global_servicios_neto' => $data['totales_global_servicios_neto'],
  2185.                 'totales_global_servicios_iva' => $data['totales_global_servicios_iva'],
  2186.                 'sumatoria_totales_global_con_iva' => $data['sumatoria_totales_global_con_iva'],
  2187.                 'sumatoria_totales_global_neto' => $data['sumatoria_totales_global_neto'],
  2188.                 'sumatoria_totales_global_iva' => $data['sumatoria_totales_global_iva'],
  2189.                 'reserva' => $reserva,
  2190.                 'createdBy' => $createdBy,
  2191.                 'arraySalas' => null,
  2192.                 'lounges' => $lounges,
  2193.                 'salasReserva' => $lounges,
  2194.                 'periods' => null,
  2195.                 'services' => $services,
  2196.                 'loungesNumbers' => sizeof($lounges),
  2197.                 'listSupplier' => $listSupplier,
  2198.                 'resultados' => $resultados,
  2199.                 'paymentsAll' => $paymentsAll,
  2200.                 'paymentNotIvoiced' => $paymentNotIvoiced,
  2201.                 'allUsersActive' => $allUsersActive,
  2202.                 'userLog' => $user_id,
  2203.                 'clientsContact' => $clientsContact,
  2204.                 'nextMailAlert' => $nextMailAlert,
  2205.                 'benefit' => $datax['benefit'],
  2206.                 'percBenefit' => $datax['percBenefit'],
  2207.                 'payedLounges' => $datax['payedLounges'],
  2208.                 'payedServices' => $datax['payedServices'],
  2209.                 'unPayedServices' => $datax['unPayedServices'],
  2210.                 'depositsAll' => $depositsAll,
  2211.                 'confirmable' => $confirmable,
  2212.                 'cotizable' => $cotizable,
  2213.                 'invoicedLine' => $invoicedLine,
  2214.                 'htFile' => $htFile,
  2215.                 'aveFile' => $aveFile,
  2216.                 'urlCotizacion' => $urlCotizacion,
  2217.                 'viewContract' => $viewContract,
  2218.                 'languagesWeb' => $languagesWeb,
  2219.             ));
  2220.     }
  2221.     private function createReservationLoungeCreateForm(ReservationLounge $entity)
  2222.     {
  2223.         $form $this->createForm(ReservationLoungeType::class, $entity, array(
  2224.             'action' => $this->generateUrl('reservations_greenpatio_create_simple_lounge', array( 'id' => $entity->getIdReservation(), ) ),
  2225.             'method' => 'POST'
  2226.         ));
  2227.         return $form;
  2228.     }
  2229.     private function createReservationLoungeMonDesCreateForm(ReservationLounge $entity)
  2230.     {
  2231.         $form $this->createForm(ReservationLoungeType::class, $entity, array(
  2232.             'action' => $this->generateUrl('reservations_greenpatio_create_simple_lounge_mondes', array( 'id' => $entity->getIdReservation(), )),
  2233.             'method' => 'POST'
  2234.         ));
  2235.         return $form;
  2236.     }
  2237.     /**
  2238.      * @Route("/contract/{id}", name="reservations_contract")
  2239.      */
  2240.     public function goContractAction($idEntityManagerInterface $emRequest $request){
  2241.         $reservationLounge $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  2242.         $arrayLounges =[];
  2243.         //Buscamos el modelo de contrato mas reciente de las salas de la reserva
  2244.         foreach ($reservationLounge as $item){ $arrayLounges[$item->getIdLounge()] = $item->getIdLounge(); }
  2245.         if (!empty($arrayLounges)) { $parameters['stringLounges'] = $arrayLounges; } else { $parameters['stringLounges'] = []; }
  2246.         $dql 'SELECT p
  2247.                 FROM App:DocContractModel p
  2248.                 WHERE p.modelId IN (:stringLounges)
  2249.                 ORDER BY p.updatedAt DESC';
  2250.         $query $em->createQuery($dql)->setParameter('stringLounges'$parameters['stringLounges']);
  2251.         $contractModel $query->getResult();
  2252.         if(!empty($contractModel)){ $loungeId $contractModel[0]->getModelId(); } else { $loungeId 0; }
  2253.         $dataContract $this->docContractService->contractReservation($id,$loungeId);
  2254.         return $this->render('MDS/GreenPatioBundle/reservations/print-contract-gp.html.twig', array( 'dataContract' => $dataContract['fullContract'], ));
  2255.     }
  2256.     /**
  2257.      * @Route("/updateloungegrid", name="reservations_greenpatio_updateloungegrid")
  2258.      */
  2259.     public function updateLoungeGridAction(EntityManagerInterface $emRequest $request)
  2260.     {
  2261.         $loungeGrid $request->request->get('lounge');
  2262.         $reservationGlobalLounge $request->request->get('reservation_global_lounge');
  2263.         $id $request->request->get('reservationId');     //aqui se guardara el ID de la reserva
  2264.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  2265.         // Movemos las fechas de la reserva para que tomen los valosres de las salas
  2266.         $reserva->setDateStart(new DateTime('2999-01-01'));
  2267.         $reserva->setDateEnd(new DateTime('2000-01-01'));
  2268.         $now = new DateTime('now');
  2269.         /* Obtengo usuario logueado */
  2270.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2271.         $user_id $user_logueado->getId();
  2272.         foreach ($loungeGrid as $idreservationlounge => $loungeData) {
  2273.             foreach ($loungeData as $dia => $items) {
  2274.                 foreach ($items as $name => $item) {
  2275.                     $reservationLounge $em->getRepository(ReservationLoungeSimple::class)->findOneById($idreservationlounge);
  2276.                     if (empty($reservationLounge)) { $reservationLounge = new ReservationLoungeSimple(); }
  2277.                     // Autocompletacion HH:mm en Start
  2278.                     switch (strlen($item['dateHourMinStart'])) {
  2279.                         case 0:
  2280.                             // Vacio
  2281.                             $hourStart '00';
  2282.                             $minStart '00';
  2283.                             $hourMinStart '00:00';
  2284.                             break;
  2285.                         case 1:
  2286.                             // H  -> 0H:00
  2287.                             if (is_numeric($item['dateHourMinStart'])) {
  2288.                                 $hourStart '0' $item['dateHourMinStart'];
  2289.                                 $minStart '00';
  2290.                                 $hourMinStart $hourStart ':' $minStart;
  2291.                             } else {
  2292.                                 $hourStart '00';
  2293.                                 $minStart '00';
  2294.                                 $hourMinStart '00:00';
  2295.                             }
  2296.                             break;
  2297.                         case 2:
  2298.                             // HH  -> HH:00
  2299.                             if (is_numeric($item['dateHourMinStart'])) {
  2300.                                 $hourStart $item['dateHourMinStart'];
  2301.                                 $minStart '00';
  2302.                                 $hourMinStart $hourStart ':' $minStart;
  2303.                             } else {
  2304.                                 $hourStart '00';
  2305.                                 $minStart '00';
  2306.                                 $hourMinStart '00:00';
  2307.                             }
  2308.                             break;
  2309.                         case 3:
  2310.                             // Hmm  -> 0H:mm
  2311.                             if (is_numeric($item['dateHourMinStart'])) {
  2312.                                 $hourStart '0' substr($item['dateHourMinStart'], 01);
  2313.                                 $minStart substr($item['dateHourMinStart'], 12);
  2314.                                 $hourMinStart $hourStart ':' $minStart;
  2315.                             } else {
  2316.                                 $hourStart '00';
  2317.                                 $minStart '00';
  2318.                                 $hourMinStart '00:00';
  2319.                             }
  2320.                             break;
  2321.                         case 4:
  2322.                             // HHmm  -> HH:mm
  2323.                             if (is_numeric($item['dateHourMinStart'])) {
  2324.                                 $hourStart substr($item['dateHourMinStart'], 02);
  2325.                                 $minStart substr($item['dateHourMinStart'], 22);
  2326.                                 $hourMinStart $hourStart ':' $minStart;
  2327.                             } else {
  2328.                                 $hourStart '00';
  2329.                                 $minStart '00';
  2330.                                 $hourMinStart '00:00';
  2331.                             }
  2332.                             break;
  2333.                         case 5:
  2334.                             // HH:mm
  2335.                             if (is_numeric(substr($item['dateHourMinStart'], 02)) and (substr($item['dateHourMinStart'], 21) == ':') and is_numeric(substr($item['dateHourMinStart'], 02))) {
  2336.                                 $hourStart substr($item['dateHourMinStart'], 02);
  2337.                                 $minStart substr($item['dateHourMinStart'], 32);
  2338.                                 $hourMinStart $hourStart ':' $minStart;
  2339.                             } else {
  2340.                                 $hourStart '00';
  2341.                                 $minStart '00';
  2342.                                 $hourMinStart '00:00';
  2343.                             }
  2344.                             break;
  2345.                         default:
  2346.                             // XXXXyyy
  2347.                             $hourStart '00';
  2348.                             $minStart '00';
  2349.                             $hourMinStart '00:00';
  2350.                             break;
  2351.                     }
  2352.                     // Autocompletacion HH:mm en End
  2353.                     switch (strlen($item['dateHourMinEnd'])) {
  2354.                         case 0:
  2355.                             // Vacio
  2356.                             $hourEnd '00';
  2357.                             $minEnd '00';
  2358.                             $hourMinEnd '00:00';
  2359.                             break;
  2360.                         case 1:
  2361.                             // H  -> 0H:00
  2362.                             if (is_numeric($item['dateHourMinEnd'])) {
  2363.                                 $hourEnd '0' $item['dateHourMinEnd'];
  2364.                                 $minEnd '00';
  2365.                                 $hourMinEnd $hourEnd ':' $minEnd;
  2366.                             } else {
  2367.                                 $hourEnd '00';
  2368.                                 $minEnd '00';
  2369.                                 $hourMinEnd '00:00';
  2370.                             }
  2371.                             break;
  2372.                         case 2:
  2373.                             // HH  -> HH:00
  2374.                             if (is_numeric($item['dateHourMinEnd'])) {
  2375.                                 $hourEnd $item['dateHourMinEnd'];
  2376.                                 $minEnd '00';
  2377.                                 $hourMinEnd $hourEnd ':' $minEnd;
  2378.                             } else {
  2379.                                 $hourEnd '00';
  2380.                                 $minEnd '00';
  2381.                                 $hourMinEnd '00:00';
  2382.                             }
  2383.                             break;
  2384.                         case 3:
  2385.                             // Hmm  -> 0H:mm
  2386.                             if (is_numeric($item['dateHourMinEnd'])) {
  2387.                                 $hourEnd '0' substr($item['dateHourMinEnd'], 01);
  2388.                                 $minEnd substr($item['dateHourMinEnd'], 12);
  2389.                                 $hourMinEnd $hourEnd ':' $minEnd;
  2390.                             } else {
  2391.                                 $hourEnd '00';
  2392.                                 $minEnd '00';
  2393.                                 $hourMinEnd '00:00';
  2394.                             }
  2395.                             break;
  2396.                         case 4:
  2397.                             // HHmm  -> HH:mm
  2398.                             if (is_numeric($item['dateHourMinEnd'])) {
  2399.                                 $hourEnd substr($item['dateHourMinEnd'], 02);
  2400.                                 $minEnd substr($item['dateHourMinEnd'], 22);
  2401.                                 $hourMinEnd $hourEnd ':' $minEnd;
  2402.                             } else {
  2403.                                 $hourEnd '00';
  2404.                                 $minEnd '00';
  2405.                                 $hourMinEnd '00:00';
  2406.                             }
  2407.                             break;
  2408.                         case 5:
  2409.                             // HH:mm
  2410.                             if (is_numeric(substr($item['dateHourMinEnd'], 02)) and (substr($item['dateHourMinEnd'], 21) == ':') and is_numeric(substr($item['dateHourMinEnd'], 02))) {
  2411.                                 $hourEnd substr($item['dateHourMinEnd'], 02);
  2412.                                 $minEnd substr($item['dateHourMinEnd'], 32);
  2413.                                 $hourMinEnd $hourEnd ':' $minEnd;
  2414.                             } else {
  2415.                                 $hourEnd '00';
  2416.                                 $minEnd '00';
  2417.                                 $hourMinEnd '00:00';
  2418.                             }
  2419.                             break;
  2420.                         default:
  2421.                             // XXXXyyy
  2422.                             $hourEnd '00';
  2423.                             $minEnd '00';
  2424.                             $hourMinEnd '00:00';
  2425.                             break;
  2426.                     }
  2427.                     $dateStart $item['newDate'] . ' ' $hourMinStart;
  2428.                     $dateEnd $item['newDate'] . ' ' $hourMinEnd;
  2429.                     $loungeDetails $em->getRepository(ReservationLoungeDetails::class)->findOneByName($name);
  2430.                     $price $item['price'];
  2431.                     $ivaNew $item['iva'];
  2432.                     $pax 0;
  2433.                     $type null;
  2434.                     if (array_key_exists('iva'$item)) {
  2435.                         if (empty($item['iva']) && !is_numeric($item['iva'])) {
  2436.                             $ivaNew 21;
  2437.                             $this->addFlash('mensajereservationerror''Revisa el IVA de la sala: '.$reservationLounge->getLoungeName());
  2438.                         } else {
  2439.                             $ivaNew $item['iva'];
  2440.                         }
  2441.                     }
  2442.                     if (isset($item['pax'])) { $pax $item['pax']; if (empty($pax)){$pax 0;} } else { $type $item['type']; }
  2443.                     $reservationLounge->setIdReservation($id);
  2444.                     if ((!empty($loungeDetails)) and (isset($reservationGlobalLounge[$loungeDetails->getId()]))){
  2445.                         $reservationLounge->setIdLounge($loungeDetails->getId());
  2446.                         //Actualizamos el Resumen Descriptivo
  2447.                         $reservationLounge->setImportantDescription($reservationGlobalLounge[$loungeDetails->getId()]['importantDescription']);
  2448.                         $reservationLounge->setImportantDescGeneralText($reservationGlobalLounge[$loungeDetails->getId()]['importantDescGeneralText']);
  2449.                         $reservationLounge->setImportantDescSchedules($reservationGlobalLounge[$loungeDetails->getId()]['importantDescSchedules']);
  2450.                         $reservationLounge->setImportantDescParking($reservationGlobalLounge[$loungeDetails->getId()]['importantDescParking']);
  2451.                     } else {
  2452.                         // No se encontro el elemento por Nombre (Se ha modificado el campo nombre de la sala, probablemente por ser una DEVOLUCION)
  2453.                         $reservationLounge->setIdLounge(0);
  2454.                     }
  2455.                     $reservationLounge->setDateStart(new DateTime($dateStart));
  2456.                     $reservationLounge->setDateEnd(new DateTime($dateEnd));
  2457.                     $reservationLounge->setType($type);
  2458.                     $reservationLounge->setPax($pax);
  2459.                     $reservationLounge->setServicePrice($price);
  2460.                     $reservationLounge->setIva($ivaNew);
  2461.                     $reservationLounge->setOpIva(1);
  2462.                     $reservationLounge->setLoungeName($name);
  2463.                     $reservationLounge->setHourStart($hourStart);
  2464.                     $reservationLounge->setMinStart($minStart);
  2465.                     $reservationLounge->setHourEnd($hourEnd);
  2466.                     $reservationLounge->setMinEnd($minEnd);
  2467.                     if (array_key_exists('language',$reservationGlobalLounge)){ $reservationLounge->setLanguage($reservationGlobalLounge['language']); } else { $reservationLounge->setLanguage(1); }
  2468.                     $reservationLounge->setUpdatedBy($user_id);
  2469.                     $reservationLounge->setCreatedBy($user_id);
  2470.                     try {
  2471.                         $em->persist($reservationLounge);
  2472.                         $em->flush();
  2473.                         $successMessage 'The Item has been updated.';
  2474.                         $this->addFlash('mensajereservation'$successMessage);
  2475.                     } catch (\Exception $e) {
  2476.                         $event 'An error occurred: ' $e->getMessage();
  2477.                         $errorMessage $this->translator->trans($event);
  2478.                         $this->addFlash('mensajereservationerror'$errorMessage);
  2479.                     }
  2480.                     // INICIO: Verificamos si es necesario actualizar las fechas de la reserva
  2481.                     $boolReserva false;
  2482.                     if ($reservationLounge->getDateStart() < $reserva->getDateStart()){
  2483.                         $reserva->setDateStart($reservationLounge->getDateStart());
  2484.                         $boolReserva true;
  2485.                     }
  2486.                     if ($reserva->getDateEnd() < $reservationLounge->getDateEnd()){
  2487.                         $reserva->setDateEnd($reservationLounge->getDateEnd());
  2488.                         $boolReserva true;
  2489.                     }
  2490.                     if ($boolReserva){
  2491.                         $em->persist($reserva);
  2492.                         $em->flush();
  2493.                     }
  2494.                     // FIN: Verificamos si es necesario actualizar las fechas de la reserva
  2495.                     // INICIO: Verificamos si es necesario actualizar el contrato de la reserva
  2496.                     $loungeContract $em->getRepository(DocContract::class)->findBy(array('companyId' => 7'fileId' => $id'modelId' => $reservationLounge->getIdLounge()));
  2497.                     if (empty($loungeContract)){
  2498.                         $loungeContract = new DocContract();
  2499.                         $loungeContract->setCompanyId(7);
  2500.                         $loungeContract->setModelId($reservationLounge->getIdLounge());
  2501.                         if (!empty($reserva->getClient())){ $loungeContract->setClientId($reserva->getClient()); }
  2502.                         $loungeContract->setFileId($reserva->getId());
  2503.                         $loungeContract->setCreatedId($user_id);
  2504.                         $loungeContract->setCreatedAt($now);
  2505.                     } else {
  2506.                         $loungeContract $loungeContract[0];
  2507.                     }
  2508.                     if ((isset($reservationGlobalLounge[$loungeDetails->getId()]))) {
  2509.                         $loungeContract->setContractualDocument($reservationGlobalLounge[$loungeDetails->getId()]['contract']);
  2510.                         $loungeContract->setBookingData($reservationGlobalLounge[$loungeDetails->getId()]['booking']);
  2511.                         $loungeContract->setDateAt(new DateTime($reservationGlobalLounge[$loungeDetails->getId()]['othersDateContract']));
  2512.                         $loungeContract->setClientProxy($reservationGlobalLounge[$loungeDetails->getId()]['othersClientProxy']);
  2513.                         $loungeContract->setClientJob($reservationGlobalLounge[$loungeDetails->getId()]['othersClientJob']);
  2514.                         $loungeContract->setUpdatedId($user_id);
  2515.                         $loungeContract->setUpdatedAt($now);
  2516.                     }
  2517.                     if (in_array($reserva->getStatus(), ['Confirmed''Invoiced'])) {       // Solo hacer el contrato si est confirmado o facturado
  2518.                         $em->persist($loungeContract);
  2519.                         $em->flush();
  2520.                     }
  2521.                 }
  2522.             }
  2523.         }
  2524.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id'token' => null'_fragment' => 'btn_quotes' ));
  2525.     }
  2526.     /**
  2527.      * @Route("/deleteitemservice/{idService}/{idReservation}", name="reservations_greenpatio_deleteitemservice")
  2528.      */
  2529.     public function deleteItemServiceAction($idService$idReservationEntityManagerInterface $emRequest $request)
  2530.     {
  2531.         $service $em->getRepository(ReservationService::class)->findOneById($idService);
  2532.         $em->remove($service);
  2533.         $em->flush();
  2534.         $event 'The Item has been deleted.';
  2535.         $successMessage $this->translator->trans($event);
  2536.         $this->addFlash('mensajereservation'$successMessage);
  2537.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $idReservation'token' => null ));
  2538.     }
  2539.     /**
  2540.      * @Route("/updateservicegrid/{id}", name="reservations_greenpatio_updateservicegrid")
  2541.      */
  2542.     public function updateServiceGridAction($idEntityManagerInterface $emRequest $request)
  2543.     {
  2544.         $services $request->request->get('services');
  2545.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2546.         $user_id $user_logueado->getId();
  2547.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  2548.         $comAvGp $request->request->get('comAvGp');
  2549.         $comHtGp $request->request->get('comHtGp');
  2550.         if (!empty($comAvGp)){
  2551.             if ($reserva->getComAvGp() !== $comAvGp){
  2552.                 $reserva->setComAvGp($comAvGp);
  2553.                 $em->persist($reserva);
  2554.                 $em->flush();
  2555.             }
  2556.         }
  2557.         if (!empty($comHtGp)){
  2558.             if ($reserva->getComHtGp() !== $comHtGp){
  2559.                 $reserva->setComHtGp($comHtGp);
  2560.                 $em->persist($reserva);
  2561.                 $em->flush();
  2562.             }
  2563.         }
  2564.         foreach ($services as $idService => $service) {
  2565.             $serviceOriginal $em->getRepository(ReservationService::class)->findOneById($idService);
  2566.             if (empty($serviceOriginal)){ $serviceOriginal = new ReservationService(); }
  2567.             $serviceOriginal->setSupplierId($service['supplier']);
  2568.             if ($serviceOriginal->getServiceCatId() == 15){
  2569.                 // Asistencia
  2570.                 if (array_key_exists('agent',$service)){
  2571.                     if (!empty($service['agent']) and ($service['agent'] > 0)){
  2572.                         $userx $em->getRepository("App\Entity\User")->findOneById($service['agent']);
  2573.                         $serviceOriginal->setName($userx->getName().' '.$userx->getLastName());
  2574.                         $serviceOriginal->setAssistantId($service['agent']);
  2575.                     } else {
  2576.                         //Asistencia de un FreeLance
  2577.                         if (!empty($service['agent']) and ($service['agent'] < 0)){
  2578.                             // FreeLance registrado en el sistema
  2579.                             $idUserFree = ($service['agent'] * (-1));
  2580.                             $userx $em->getRepository(ExternalUser::class)->findOneById($idUserFree);
  2581.                             $serviceOriginal->setName($userx->getName().' '.$userx->getLastName());
  2582.                             $serviceOriginal->setAssistantId($service['agent']);
  2583.                         } else {
  2584.                             $serviceOriginal->setName($service['name']);
  2585.                             $serviceOriginal->setAssistantId(null);
  2586.                         }
  2587.                     }
  2588.                 }
  2589.             } else {
  2590.                 $serviceOriginal->setName($service['name']);
  2591.             }
  2592.             $price $service['price'];
  2593.             if ($price === null) {
  2594.                 $priceToSet 0;
  2595.             } else {
  2596.                 $price str_replace('.'''$price);
  2597.                 $price str_replace(',''.'$price);
  2598.                 if (is_numeric($price)) {
  2599.                     $priceToSet $price;
  2600.                 } else {
  2601.                     $priceToSet $serviceOriginal->getPrice();
  2602.                 }
  2603.             }
  2604.             $serviceOriginal->setPrice($priceToSet);
  2605.             $serviceOriginal->setCurrency($service['currency']);
  2606.             $serviceOriginal->setUnits($service['units']);
  2607.             $serviceOriginal->setPax($service['pax']);
  2608.             $serviceOriginal->setOpCommission($service['opCommission']);
  2609.             $commission $service['commission'];
  2610.             if ($commission === null) {
  2611.                 $commissionToSet 0;
  2612.             } else {
  2613.                 $commission str_replace(',''.'$commission);
  2614.                 if (is_numeric($commission)) {
  2615.                     $commissionToSet $commission;
  2616.                 } else {
  2617.                     $commissionToSet $serviceOriginal->getCommission();
  2618.                 }
  2619.             }
  2620.             $serviceOriginal->setCommission($commissionToSet);
  2621.             $serviceOriginal->setOpOver($service['opOver']);
  2622.             $over $service['over'];
  2623.             if ($over === null) {
  2624.                 $overToSet 0;
  2625.             } else {
  2626.                 $over str_replace('.'''$over);
  2627.                 $over str_replace(',''.'$over);
  2628.                 if (is_numeric($over)) {
  2629.                     $overToSet $over;
  2630.                 } else {
  2631.                     $overToSet $serviceOriginal->getOver();
  2632.                 }
  2633.             }
  2634.             $serviceOriginal->setOver($overToSet);
  2635.             $serviceOriginal->setOpIva($service['opIva']);
  2636.             $serviceOriginal->setIva($service['iva']);
  2637.             if (array_key_exists('toinvoice',$service)){ $serviceOriginal->setToinvoice(true); } else { $serviceOriginal->setToinvoice(false); }
  2638.             if (array_key_exists('viewinfo',$service)){ $serviceOriginal->setViewInfo(true); } else { $serviceOriginal->setViewInfo(false); }
  2639.             $serviceOriginal->setDateInAt(new DateTime($service['dateInAt']. ' ' $service['start']));
  2640.             $serviceOriginal->setDateOutAt(new DateTime($service['dateOutAt']. ' ' $service['end']));
  2641.             $serviceOriginal->setUpdatedId($user_id);
  2642.             $serviceOriginal->setUpdatedAt(new DateTime('now'));
  2643.             try{
  2644.                 $em->persist($serviceOriginal);
  2645.                 $em->flush();
  2646.                 $event 'The Item has been updated.';
  2647.                 $successMessage $this->translator->trans($event);
  2648.                 $this->addFlash('mensajereservation'$successMessage);
  2649.             } catch (\Exception $e){
  2650.                 $event 'An error occurred: '.$e->getMessage();
  2651.                 $errorMessage $this->translator->trans($event);
  2652.                 $this->addFlash('mensajereservationerror'$errorMessage);
  2653.             }
  2654.             if(($serviceOriginal->getServiceCatId()==11) and ($serviceOriginal->getSupplierId()==4765)){
  2655.                 //Es un Catering de Higo&Trigo
  2656.                 $reserva->setCateringName('HIGO & TRIGO, S.L.');
  2657.                 $em->persist($reserva);
  2658.                 $em->flush();
  2659.             }
  2660.         }
  2661.         // Sincronización con HT
  2662.         if (!empty($reserva)) {
  2663.             // Rafa indico que siempre se sincronice al abrir un expediente de GP
  2664.             if (in_array($reserva->getStatus(), [null'''Confirmed''Invoiced''Iniciado''Cotizado''Bloqueo'])) {
  2665.                 if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
  2666.                     // Si no se ha creado aun el expediente de HT debemos crearlo
  2667.                     $htFile $em->getRepository(HtFile::class)->findByReservation($reserva);
  2668.                     if (empty($htFile)) {
  2669.                         return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,));
  2670.                     }
  2671.                 }
  2672.             }
  2673.         }
  2674.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id'token' => null'_fragment' => 'btn_srv' ));
  2675.     }
  2676.     /**
  2677.      * @Route("/addloungegeneral", name="reservations_greenpatio_add_lounge_general")
  2678.      */
  2679.     public function addLoungeGeneralAction(EntityManagerInterface $emRequest $request)
  2680.     {
  2681.         $lounge $request->request->get('lounge_price');
  2682.         $yaExisteLounge $em->getRepository(ReservationLoungeDetails::class)->findOneByName($lounge['name']);
  2683.         if (!empty($yaExisteLounge)){
  2684.             //Si ya existe la sala con ese nombre se envia a la pantalla de edicion de la sala en cuestion
  2685.             $id $yaExisteLounge->getId();
  2686.             return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $id ));
  2687.         }
  2688.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2689.         $user_id $user_logueado->getId();
  2690.         $now = new DateTime('now');
  2691.         $loungeNew = new ReservationLoungeDetails();
  2692.         $loungeNew->setName($lounge['name']);
  2693.         $loungeNew->setMeters($lounge['meters']);
  2694.         $loungeNew->setLength($lounge['length']);
  2695.         $loungeNew->setWidth($lounge['width']);
  2696.         $loungeNew->setHeight($lounge['height']);
  2697.         $loungeNew->setCapSchool($lounge['capschool']);
  2698.         $loungeNew->setCapTheater ($lounge['captheater']);
  2699.         $loungeNew->setCapCocktail($lounge['capcocktail']);
  2700.         $loungeNew->setCapBanquet ($lounge['capbanquet']);
  2701.         $loungeNew->setCapImperial($lounge['capimperial']);
  2702.         $loungeNew->setCreatedId($user_id);
  2703.         $loungeNew->setCreatedAt($now);
  2704.         $loungeNew->setUpdatedId($user_id);
  2705.         $loungeNew->setUpdatedAt($now);
  2706.         try {
  2707.             $em->persist($loungeNew);
  2708.             $em->flush();
  2709.             $event 'The Item has been created.';
  2710.             $successMessage $this->translator->trans($event);
  2711.             $this->addFlash('mensajereservation'$successMessage);
  2712.         } catch (\Exception $e) {
  2713.             $event 'An error occurred: ' $e->getMessage();
  2714.             $errorMessage $this->translator->trans($event);
  2715.             $this->addFlash('mensajereservationerror'$errorMessage);
  2716.         }
  2717.         if (!empty($loungeNew->getId())){
  2718.             // Esto pertenece a otra entidad
  2719.             $loungeNewDescription = new ReservationLoungeDescription();
  2720.             $loungeNewDescription->setLoungeId($loungeNew->getId());
  2721.             $loungeNewDescription->setLanguage($lounge['language']);
  2722.             $loungeNewDescription->setDescription($lounge['description']);
  2723.             $loungeNewDescription->setCreatedId($user_id);
  2724.             $loungeNewDescription->setCreatedAt($now);
  2725.             $loungeNewDescription->setUpdatedId($user_id);
  2726.             $loungeNewDescription->setUpdatedAt($now);
  2727.             try {
  2728.                 $em->persist($loungeNewDescription);
  2729.                 $em->flush();
  2730.                 $event 'The Item has been created.';
  2731.                 $successMessage $this->translator->trans($event);
  2732.                 $this->addFlash('mensajereservation'$successMessage);
  2733.             } catch (\Exception $e) {
  2734.                 $event 'An error occurred: ' $e->getMessage();
  2735.                 $errorMessage $this->translator->trans($event);
  2736.                 $this->addFlash('mensajereservationerror'$errorMessage);
  2737.             }
  2738.             return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $loungeNew->getId() ));
  2739.         }
  2740.         return $this->redirectToRoute('reservations_greenpatio_edit_general');
  2741.     }
  2742.     /**
  2743.      * @Route("/addloungedescription/{id}", name="reservations_greenpatio_add_lounge_description")
  2744.      */
  2745.     public function addLoungeDescriptionAction($idRequest $request)
  2746.     {
  2747.         $em $this->getDoctrine()->getManager();
  2748.         /* Obtengo usuario logueado */
  2749.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2750.         $user_id $user_logueado->getId();
  2751.         $now = new DateTime('now');
  2752.         $loungeDescriptoin $request->request->get('lounge_description');
  2753.         if (empty($loungeDescriptoin['language']) or empty($loungeDescriptoin['description'])){ return $this->redirectToRoute('reservations_lounge_details', array('id' => $id)); }
  2754.         $newLoungeDescription = new reservationLoungeDescription();
  2755.         $newLoungeDescription->setLoungeId($id);
  2756.         $newLoungeDescription->setLanguage($loungeDescriptoin['language']);
  2757.         $newLoungeDescription->setDescription($loungeDescriptoin['description']);
  2758.         $newLoungeDescription->setCreatedId($user_id);
  2759.         $newLoungeDescription->setUpdatedId($user_id);
  2760.         $newLoungeDescription->setCreatedAt($now);
  2761.         $newLoungeDescription->setUpdatedAt($now);
  2762.         try {
  2763.             $em->persist($newLoungeDescription);
  2764.             $em->flush();
  2765.             $event 'The Item has been created.';
  2766.             $successMessage 'El elemento ha sido creado.';
  2767.             $this->addFlash('mensajereservation'$successMessage);
  2768.         } catch (\Exception $e) {
  2769.             $event 'An error occurred: ' $e->getMessage();
  2770.             $errorMessage $this->translator->trans($event);
  2771.             $this->addFlash('mensajereservationerror'$errorMessage);
  2772.         }
  2773.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
  2774.     }
  2775.     /**
  2776.      * @Route("/addwebinfo/{id}", name="reservations_greenpatio_add_web_info")
  2777.      * Actualiza la información de la sala a presentar en la web, que esta almacenada por defecto
  2778.      * Actualiza la información del contrato
  2779.      */
  2780.     public function addLoungeWebInfoAction($idEntityManagerInterface $emRequest $request)
  2781.     {
  2782.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2783.         $user_id $user_logueado->getId();
  2784.         $now = new \DateTimeImmutable('now');
  2785.         $lounge $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
  2786.         if (empty($lounge)) {
  2787.             $this->addFlash('mensajereservationerror''Error, no se ha encontrado la sala con ID: '.$id);
  2788.             return $this->redirectToRoute('reservations_greenpatio_edit_general');
  2789.         }
  2790.         $loungeWebDescription $request->request->get('lounge_web_description') ?? [];
  2791.         foreach ($loungeWebDescription as $key => $descriptions) {
  2792.             $loungeDetail $em->getRepository(ReservationLoungeWebDescription::class)->findOneBy(array('lounge' => $lounge'language' => $key));
  2793.             if (empty($loungeDetail)) {
  2794.                 $loungeDetail = new ReservationLoungeWebDescription();
  2795.                 $loungeDetail->setLounge($lounge);
  2796.                 $loungeDetail->setLanguage($key);
  2797.                 $loungeDetail->setCreatedId($user_logueado);
  2798.             }
  2799.             $loungeDetail->setImportantDescription($descriptions['importantDescription']);
  2800.             $loungeDetail->setImportantDescGeneralText($descriptions['importantDescGeneralText']);
  2801.             $loungeDetail->setImportantDescSchedules($descriptions['importantDescSchedules']);
  2802.             $loungeDetail->setImportantDescParking($descriptions['importantDescParking']);
  2803.             $loungeDetail->setUpdatedId($user_logueado);
  2804.             $em->persist($loungeDetail);
  2805.             
  2806.             $loungeContract $em->getRepository(DocContractModel::class)->findOneBy(array('modelId' => $id'companyId' => 7'language' => $key));
  2807.             if (empty($loungeContract)){
  2808.                 $loungeContract = new DocContractModel();
  2809.                 $loungeContract->setModelId($id);
  2810.                 $loungeContract->setLanguage($key);
  2811.                 $loungeContract->setCompanyId(7);
  2812.                 $loungeContract->setCreatedId($user_id);
  2813.             }
  2814.             $loungeContract->setContractualDocument($descriptions['contractualDocument']);
  2815.             $loungeContract->setUpdatedId($user_id);
  2816.     
  2817.             $em->persist($loungeContract);
  2818.         }
  2819.         $em->flush();
  2820.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
  2821.     }
  2822.     /**
  2823.      * @Route("/updatedescritiongrid/{id}", name="reservations_greenpatio_updatedescriptiongrid")
  2824.      */
  2825.     public function updateDescriptionGridAction($idRequest $request)
  2826.     {
  2827.         $descriptions $request->request->get('description');
  2828.         $em $this->getDoctrine()->getManager();
  2829.         /* Obtengo usuario logueado */
  2830.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2831.         $user_id $user_logueado->getId();
  2832.         foreach ($descriptions as $idDesc => $description) {
  2833.             $descriptionOriginal $em->getRepository(ReservationLoungeDescription::class)->findOneById($idDesc);
  2834.             $descriptionOriginal->setLanguage($description['language']);
  2835.             $descriptionOriginal->setDescription($description['text']);
  2836.             $descriptionOriginal->setUpdatedId($user_id);
  2837.             $descriptionOriginal->setUpdatedAt(new DateTime('now'));
  2838.             try{
  2839.                 $em->persist($descriptionOriginal);
  2840.                 $em->flush();
  2841.                 $event 'The Item has been updated.';
  2842.                 $successMessage 'El elemento ha sido actualizado.';
  2843.                 $this->addFlash('mensajereservation'$successMessage);
  2844.             } catch (\Exception $e){
  2845.                 $event 'An error occurred: '.$e->getMessage();
  2846.                 $errorMessage $this->translator->trans($event);
  2847.                 $this->addFlash('mensajereservationerror'$errorMessage);
  2848.             }
  2849.         }
  2850.         return $this->redirectToRoute('reservations_lounge_details', array( 'id' => $id ));
  2851.     }
  2852.     /**
  2853.      * @Route("/addloungepicture/{id}", name="reservations_greenpatio_add_lounge_picture")
  2854.      */
  2855.     public function addLoungePictureAction($idEntityManagerInterface $emRequest $request//, LoggerInterface $logger)
  2856.     {
  2857.         /* Obtengo usuario logueado */
  2858.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2859.         $user_id $user_logueado->getId();
  2860.         $now = new DateTime('now');
  2861.         $picturefiles $request->files->all();
  2862.         $loungeId $id;
  2863.         $imagenes $picturefiles['loungepicturegallery'];
  2864.         $data $loungeId;
  2865.         if(!empty($imagenes['image1']) || !empty($imagenes['image2']) || !empty($imagenes['image3']) || !empty($imagenes['image4']) || !empty($imagenes['image5'])){
  2866.             $num 0;
  2867.             foreach($imagenes as $img){
  2868.                 $num $num;
  2869.                 if (!is_null($img)){ $data $this->CargarImgGalleryAction($loungeId$img$num$request); } //, $logger);
  2870.             }
  2871.         } else {
  2872.             $errorMessage $this->translator->trans('Error, some fields are empty');
  2873.             $this->addFlash('mensajegalleryerror'$errorMessage);
  2874.         }
  2875.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
  2876.     }
  2877.     protected function CargarImgGalleryAction($loungeId$image$numRequest $request//, LoggerInterface $logger)
  2878.     {
  2879.         $gallery = new ReservationLoungePicture();
  2880.         $gallery->setLoungeId($loungeId);
  2881.         $gallery->setCreatedAt(new DateTime('now'));
  2882.         $gallery->setUpdatedAt(new DateTime('now'));
  2883.         $gallery->setTitle(null);
  2884.         if ($num == -1){$gallery->setTitle('Blueprint');}
  2885.         if ($num == 'TEATRO'){$gallery->setTitle('Teatro');}
  2886.         if ($num == 'COCTEL'){$gallery->setTitle('Coctel');}
  2887.         if ($num == 'ESCUELA'){$gallery->setTitle('Escuela');}
  2888.         $id $loungeId;
  2889.         /* Carga de imagenes */
  2890.         $calidad "90";
  2891.         $calidadpng "9";
  2892.         $imageName md5(rand() * time());
  2893.         $camino "assets/images/greenpatio/lounges/";
  2894.         $extension $image->guessExtension();
  2895.         $entrada 'si';
  2896.         $image_id $imageName.'.'.$extension;
  2897.         $image_temp $id.'-'.$imageName.'.'.$extension;
  2898.         $image->move($camino$image_temp);
  2899.         // Nombres image
  2900.         $s="small-";
  2901.         $m="medium-";
  2902.         $l="large-";
  2903.         ########################
  2904.         # Copiar imagen 300 x Altura
  2905.         ########################
  2906.         $datos getimagesize($camino.$image_temp);
  2907.         $anchura "300";
  2908.         $altura "190";
  2909.         $thumb imagecreatetruecolor($anchura,$altura);
  2910.         switch ($extension) {
  2911.             case 'jpeg':
  2912.                 $img imagecreatefromjpeg($camino.$image_temp);
  2913.                 imagecopyresampled ($thumb$img0000$anchura$altura$datos[0], $datos[1]);
  2914.                 imagejpeg($thumb,$camino.$s.$image_id$calidad);
  2915.                 break;
  2916.             case 'png':
  2917.                 $img imagecreatefrompng($camino.$image_temp);
  2918.                 imagecopyresampled ($thumb$img0000$anchura$altura$datos[0], $datos[1]);
  2919.                 imagepng($thumb,$camino.$s.$image_id$calidadpng);
  2920.                 break;
  2921.             case 'gif':
  2922.                 $img imagecreatefromgif($camino.$image_temp);
  2923.                 imagecopyresampled ($thumb$img0000$anchura$altura$datos[0], $datos[1]);
  2924.                 imagegif($thumb,$camino.$s.$image_id);
  2925.                 break;
  2926.         }
  2927.         ########################
  2928.         # Copiar imagen 600 x Altura
  2929.         ########################
  2930.         $datos2 getimagesize($camino.$image_temp);
  2931.         $anchura2="600";
  2932.         $ratio2 = ($datos2[0] / $anchura2);
  2933.         $altura2 round($datos2[1] / $ratio2);
  2934.         $thumb2 imagecreatetruecolor($anchura2,$altura2);
  2935.         switch ($extension) {
  2936.             case 'jpeg':
  2937.                 $img2 imagecreatefromjpeg($camino.$image_temp);
  2938.                 imagecopyresampled ($thumb2$img20000$anchura2$altura2$datos2[0], $datos2[1]);
  2939.                 imagejpeg($thumb2,$camino.$m.$image_id$calidad);
  2940.                 break;
  2941.             case 'png':
  2942.                 $img2 imagecreatefrompng($camino.$image_temp);
  2943.                 imagecopyresampled ($thumb2$img20000$anchura2$altura2$datos2[0], $datos2[1]);
  2944.                 imagepng($thumb2,$camino.$m.$image_id$calidadpng);
  2945.                 break;
  2946.             case 'gif':
  2947.                 $img2 imagecreatefromgif($camino.$image_temp);
  2948.                 imagecopyresampled ($thumb2$img20000$anchura2$altura2$datos2[0], $datos2[1]);
  2949.                 imagegif($thumb2,$camino.$m.$image_id);
  2950.                 break;
  2951.         }
  2952.         ########################
  2953.         # Copiar imagen 1600 x Altura
  2954.         ########################
  2955.         $datos3 getimagesize($camino.$image_temp);
  2956.         $anchura3="1600";
  2957.         $ratio3 = ($datos3[0] / $anchura3);
  2958.         $altura3 round($datos3[1] / $ratio3);
  2959.         $thumb3 imagecreatetruecolor($anchura3,$altura3);
  2960.         switch ($extension) {
  2961.             case 'jpeg':
  2962.                 $img3 imagecreatefromjpeg($camino.$image_temp);
  2963.                 imagecopyresampled ($thumb3$img30000$anchura3$altura3$datos3[0], $datos3[1]);
  2964.                 imagejpeg($thumb3,$camino.$l.$image_id$calidad);
  2965.                 break;
  2966.             case 'png':
  2967.                 $img3 imagecreatefrompng($camino.$image_temp);
  2968.                 imagecopyresampled ($thumb3$img30000$anchura3$altura3$datos3[0], $datos3[1]);
  2969.                 imagepng($thumb3,$camino.$l.$image_id$calidadpng);
  2970.                 break;
  2971.             case 'gif':
  2972.                 $img3 imagecreatefromgif($camino.$image_temp);
  2973.                 imagecopyresampled ($thumb3$img30000$anchura3$altura3$datos3[0], $datos3[1]);
  2974.                 imagegif($thumb3,$camino.$l.$image_id);
  2975.                 break;
  2976.         }
  2977.         ########################
  2978.         # borrar imagen original
  2979.         ########################
  2980.         $imagen_borrar$camino.$image_temp;
  2981.         unlink($imagen_borrar);
  2982.         $gallery->setImageSmall($s.$image_id);
  2983.         $gallery->setImageMedium($m.$image_id);
  2984.         $gallery->setImageLarge($l.$image_id);
  2985.         /* Fin Carga de imagenes */
  2986.         /* Obtengo usuario logueado */
  2987.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  2988.         $user_id $user_logueado->getId();
  2989.         $gallery->setCreatedId($user_id);
  2990.         $gallery->setUpdatedId($user_id);
  2991.         $em $this->getDoctrine()->getManager();
  2992.         /* Gestión de eventos en Log */
  2993.         $user_lastname $user_logueado->getLastname();
  2994.         $user_name $user_logueado->getName();
  2995.         $user_email $user_logueado->getEmail();
  2996.         $user_rol $user_logueado->getRoles();
  2997.         $event_url $request->getPathInfo();
  2998.         $event_complete $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
  2999.         try{
  3000.             $em->persist($gallery);
  3001.             $em->flush();
  3002.             $event 'Images from this supplier have been uploaded.';
  3003.             $successMessage $this->translator->trans($event);
  3004.             $this->addFlash('mensajegallery'$successMessage);
  3005.         } catch (\Exception $e){
  3006.             $event 'An error occurred: '.$e->getMessage().' | transport';
  3007.             /* Para el usuario */
  3008.             $errorMessage $this->translator->trans($event);
  3009.             $this->addFlash('mensajegalleryerror'$errorMessage);
  3010.         }
  3011.         /* Fin Gestión de eventos en Log */
  3012.         return $id;
  3013.     }
  3014.     /**
  3015.      * @Route("/addloungevideo/{id}", name="reservations_greenpatio_add_lounge_video")
  3016.      */
  3017.     public function addLoungeVideoAction($idEntityManagerInterface $emRequest $request//, LoggerInterface $logger)
  3018.     {
  3019.         /* Obtengo usuario logueado */
  3020.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3021.         $user_id $user_logueado->getId();
  3022.         $now = new DateTime('now');
  3023.         $urlvideo $request->request->get('loungevideo');
  3024.         $urlvideo $urlvideo['urlvideo'];
  3025.         $loungeId $id;
  3026.         if(!empty($urlvideo)){
  3027.             switch (true) {
  3028.                 case strpos($urlvideo'youtube'):
  3029.                     $patron '%^ (?:https?://)? (?:www\.)? (?: youtu\.be/ | youtube\.com (?: /embed/ | /v/ | /watch\?v= ) ) ([\w-]{10,12}) ($|&).* $%x';
  3030.                     preg_match($patron$urlvideo$parte);
  3031.                     $urvideo_final 'https://www.youtube.com/embed/'$parte[1];
  3032.                     break;
  3033.                 case strpos($urlvideo'youtu'):
  3034.                     $patron '%^ (?:https?://)? (?:www\.)? (?: youtu\.be/ | youtube\.com (?: /embed/ | /v/ | /watch\?v= ) ) ([\w-]{10,12}) ($|&).* $%x';
  3035.                     preg_match($patron$urlvideo$parte);
  3036.                     $urvideo_final 'https://www.youtube.com/embed/'$parte[1];
  3037.                     break;
  3038.                 case strpos($urlvideo'vimeo'):
  3039.                     $patron '%^https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)(?:[?]?.*)$%im';
  3040.                     preg_match($patron$urlvideo$parte);
  3041.                     $urvideo_final 'https://player.vimeo.com/video/'$parte[3];
  3042.                     break;
  3043.             }
  3044.             if(!empty($urlvideo) && !empty($urvideo_final) ){
  3045.                 $video = new ReservationLoungeVideo();
  3046.                 $video->setCreatedId($user_id);
  3047.                 $video->setUpdatedId($user_id);
  3048.                 $video->setVideo($urvideo_final);
  3049.                 $video->setLoungeId($loungeId);
  3050.                 $video->setCreatedAt($now);
  3051.                 $video->setUpdatedAt($now);
  3052.                 $em->persist($video);
  3053.                 $em->flush();
  3054.             }
  3055.         }
  3056.         if (empty($urlvideo)){
  3057.             $errorMessage $this->translator->trans('Error, some fields are empty');
  3058.             $this->addFlash('mensajegalleryerror'$errorMessage);
  3059.         }
  3060.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
  3061.     }
  3062.     /**
  3063.      * @Route("/deleteloungevideo/{id}", name="reservations_greenpatio_delete_lounge_video")
  3064.      */
  3065.     public function deleteLoungeVideoAction($idEntityManagerInterface $emRequest $request//, LoggerInterface $logger)
  3066.     {
  3067.         $video $em->getRepository(ReservationLoungeVideo::class)->findOneById($id);
  3068.         $idLounge $video->getLoungeId();
  3069.         try{
  3070.             $em->remove($video);
  3071.             $em->flush();
  3072.             $successMessage 'El elemento ha sido eliminado.';
  3073.             $this->addFlash('mensajereservation'$successMessage);
  3074.         } catch (\Exception $e){
  3075.             $event 'An error occurred: '.$e->getMessage();
  3076.             $errorMessage $this->translator->trans($event);
  3077.             $this->addFlash('mensajereservationerror'$errorMessage);
  3078.         }
  3079.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $idLounge));
  3080.     }
  3081.     /**
  3082.      * @Route("/addloungeblueprints/{id}", name="reservations_greenpatio_add_lounge_blueprints")
  3083.      */
  3084.     public function addLoungeBlueprintsAction($idEntityManagerInterface $emRequest $request//, LoggerInterface $logger)
  3085.     {
  3086.         /* Obtengo usuario logueado */
  3087.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3088.         $user_id $user_logueado->getId();
  3089.         $now = new DateTime('now');
  3090.         $picturefiles $request->files->all();
  3091.         $loungeId $id;
  3092.         $imagen $picturefiles['loungepicturegalleryblueprints'];
  3093.         $data $loungeId;
  3094.         if(!empty($imagen)){
  3095.             $num = -1;
  3096.             $data $this->CargarImgGalleryAction($loungeId$imagen$num$request); //, $logger);
  3097.         } else {
  3098.             $errorMessage $this->translator->trans('Error, some fields are empty');
  3099.             $this->addFlash('mensajegalleryerror'$errorMessage);
  3100.         }
  3101.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
  3102.     }
  3103.    /**
  3104.      * @Route("/addpicturemounting/{id}", name="reservations_greenpatio_add_lounge_picture_mounting")
  3105.      */
  3106.     public function addLoungePictureMountingAction($idEntityManagerInterface $emRequest $request//, LoggerInterface $logger)
  3107.     {
  3108.         /* Obtengo usuario logueado */
  3109.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3110.         $user_id $user_logueado->getId();
  3111.         $now = new DateTime('now');
  3112.         $picturefiles $request->files->all();
  3113.         $loungeId $id;
  3114.         $imagen $picturefiles['picturemounting'];
  3115.         $data $loungeId;
  3116.         if(!empty($imagen)){
  3117.             $num $request->request->get('picturemounting');
  3118.             $num $num['type'];
  3119.             $data $this->CargarImgGalleryAction($loungeId$imagen$num$request); //, $logger);
  3120.         }else{
  3121.             $errorMessage $this->translator->trans('Error, some fields are empty');
  3122.             $this->addFlash('mensajegalleryerror'$errorMessage);
  3123.         }
  3124.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
  3125.     }
  3126.    /**
  3127.      * @Route("/updatedimmensions/{id}", name="update_dimmensions")
  3128.      */
  3129.     public function updateDimmensionsAction($idEntityManagerInterface $emRequest $request)
  3130.     {
  3131.         $lounge $em->getRepository(ReservationLoungeDetails::class)->findOneById($id);
  3132.         $newData $request->request->get('loungedimmensions');
  3133.         $lounge->setMeters($newData['meters']);
  3134.         $lounge->setLength($newData['length']);
  3135.         $lounge->setWidth($newData['width']);
  3136.         $lounge->setHeight($newData['height']);
  3137.         $lounge->setCapSchool($newData['capSchool']);
  3138.         $lounge->setCapTheater($newData['capTheater']);
  3139.         $lounge->setCapCocktail($newData['capCocktail']);
  3140.         $lounge->setCapBanquet($newData['capBanquet']);
  3141.         $lounge->setCapImperial($newData['capImperial']);
  3142.         /* Obtengo usuario logueado */
  3143.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3144.         $user_id $user_logueado->getId();
  3145.         $now = new DateTime('now');
  3146.         $lounge->setUpdatedId($user_id);
  3147.         $lounge->setUpdatedAt($now);
  3148.         try{
  3149.             $em->persist($lounge);
  3150.             $em->flush();
  3151.             $event 'The Note has been created succesfully.';
  3152.             $successMessage $this->translator->trans($event);
  3153.             $this->addFlash('mensaje'$successMessage);
  3154.         } catch (\Exception $e){
  3155.             $event 'An error occurred: '.$e->getMessage();
  3156.             /* Para el usuario */
  3157.             $errorMessage $this->translator->trans($event);
  3158.             $this->addFlash('mensajeerror'$errorMessage);
  3159.         }
  3160.         return $this->redirectToRoute('reservations_lounge_details', array('id' => $id));
  3161.     }
  3162.     /**
  3163.      * @Route("/addvisit", name="reservations_greenpatio_addvisit")
  3164.      */
  3165.     public function addVisitAction(EntityManagerInterface $emRequest $request)
  3166.     {
  3167.         $visitas $em->getRepository(ReservationVisit::class)->findAll();
  3168.         $qb $em->createQueryBuilder();
  3169.         $qb->select('r.id, r.title')
  3170.             ->from(Reservation::class, 'r');
  3171.         $listAllReservas $qb->getQuery()->getArrayResult();
  3172.         $agentsGp = array();     //arreglo con los agentes de Green Patio
  3173.         $allUsers[] = $em->getRepository(User::class)->findAll();
  3174.         $agentsGp $em->getRepository(User::class)->findBy(['userrol' => [49,53]]);
  3175.         return $this->render('MDS/GreenPatioBundle/reservations/add-visit.html.twig',
  3176.             array(
  3177.                 'visitas' => $visitas,
  3178.                 'agentsGp' => $agentsGp,
  3179.                 'listAllReservas' => $listAllReservas,
  3180.             )
  3181.         );
  3182.     }
  3183.     /**
  3184.      * @Route("/createvisit", name="reservations_greenpatio_createvisit")
  3185.      */
  3186.     public function createVisitAction(EntityManagerInterface $emRequest $request)
  3187.     {
  3188.         $newRequest $request->request->get('visit');
  3189.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3190.         $user_id $user_logueado->getId();
  3191.         if (!empty($newRequest['date']) and !empty($newRequest['time'])){ $dateStart = new DateTime ($newRequest['date']. ' '.$newRequest['time']); } else { $dateStart = new DateTime ('now'); }
  3192.         if (!empty($newRequest['time'])) {
  3193.             $hourStart substr($newRequest['time'], 02);
  3194.             $minStart substr($newRequest['time'], 32);
  3195.             $hourEnd substr($newRequest['time'],0,2) + 1;
  3196.             $minEnd substr($newRequest['time'],3,2);
  3197.         } else {
  3198.             $hourStart '12';
  3199.             $minStart '00';
  3200.             $hourEnd '13';
  3201.             $minEnd '00';
  3202.         }
  3203.         if (!empty($newRequest['agent'])) { $agent $em->getRepository(User::class)->findOneById($newRequest['agent']); } else { $agent $em->getRepository(User::class)->findOneById(82); }
  3204.         $title '';
  3205.         if (!empty($newRequest['name'])){ $title $newRequest['name']; }
  3206.         if (!empty($newRequest['idreservation'])){
  3207.             $res $em->getRepository(Reservation::class)->findOneById($newRequest['idreservation']);
  3208.             if (!empty($title)) { $title $title ' - ' $res->getTitle(); } else { $title $res->getTitle(); }
  3209.         }
  3210.         $newVisit = new ReservationVisit();
  3211.         $newVisit->setAgentId($agent->getId());
  3212.         $newVisit->setDateStart($dateStart);
  3213.         $newVisit->setDateEnd($dateStart);
  3214.         if (!empty($newRequest['time'])) {
  3215.             $newVisit->setHourStart($hourStart);
  3216.             $newVisit->setMinStart($minStart);
  3217.             $newVisit->setHourEnd($hourEnd);
  3218.             $newVisit->setMinEnd($minEnd);
  3219.         } else {
  3220.             $newVisit->setHourStart($hourStart);
  3221.             $newVisit->setMinStart($minStart);
  3222.             $newVisit->setHourEnd($hourEnd);
  3223.             $newVisit->setMinEnd($minEnd);
  3224.         }
  3225.         $newVisit->setLoungeName($title.' - '.'Visita '.$agent->getName());
  3226.         if (!empty($newRequest['idreservation'])) { $newVisit->setIdReservation($newRequest['idreservation']); } else { $newVisit->setIdReservation(null); }
  3227.         $newVisit->setType('Visit');
  3228.         $newVisit->setCreatedAt(new DateTime ('now'));
  3229.         $newVisit->setCreatedId($user_id);
  3230.         $newVisit->setUpdatedAt(new DateTime ('now'));
  3231.         $newVisit->setUpdatedId($user_id);
  3232.         $location = (!empty($newRequest['location'])) ? $newRequest['location'] : 0;
  3233.         $newVisit->setIdLounge($location);
  3234.         $em->persist($newVisit);
  3235.         $em->flush();
  3236.         return $this->redirectToRoute('reservations_greenpatio_addvisit');
  3237.     }
  3238.     /**
  3239.      * @Route("/deletevisit/{id}", name="get_reservations_deletevisit")
  3240.      */
  3241.     public function deleteVisitAction($idEntityManagerInterface $emRequest $request) {
  3242.         $visit $em->getRepository(ReservationVisit::class)->findOneById($id);
  3243.         if (!empty($visit)){
  3244.             $em->remove($visit);
  3245.             $em->flush();
  3246.         }
  3247.         return $this->redirectToRoute('reservations_greenpatio_addvisit');
  3248.     }
  3249.     /**
  3250.      * @Route("/sendconfirmationrequestmail/{id}/{initStatus}", name="reservations_greenpatio_send_confirmation_request_mail")
  3251.      * Enviar correo a Salvador y Rafael Guerrero para que la reserva (id) pase al estado confirmado. Con un status previo de initStatus
  3252.      */
  3253.     public function sendConfirmationRequestMailAction($id$initStatusEntityManagerInterface $emRequest $request){
  3254.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3255.         $user_id $user_logueado->getId();
  3256.         $mailArrayTo = []; $mailAlert = [];
  3257.         $mailArrayTo['salvador@avexpress.tv'] = 'salvador@avexpress.tv';
  3258.         $mailArrayTo['rafael.guerrero@inout-travel.com'] = 'rafael.guerrero@inout-travel.com';
  3259.         $dataGP $this->disponibilidadGreenPatio($id$initStatus);
  3260.         $dataAV $this->disponibilidadAvExpress($id);
  3261.         $dataLounges = array();
  3262.         foreach ($dataGP as $item){
  3263.             $lounges $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation'=>$item->getId(),'type'=>null));
  3264.             foreach ($lounges as $elem){ $dataLounges[$item->getId()][] = $elem; }
  3265.         }
  3266.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  3267.         $agente $em->getRepository(User::class)->findOneById($user_id);
  3268.         $mailAddressFrom $agente->getEmail();
  3269.         $mailSubject 'Confirmación de reserva: '.$reserva->getTitle();
  3270.         $mensajePopup '';
  3271.         $mailBody 'Estimado administrador,'.
  3272.             '<br><br>'$agente->getName().' '$agente->getLastName(). ' ha solicitado la confirmación de la reserva:'.
  3273.             '<br><br>'.$reserva->getTitle(). ' con ID: '.$reserva->getId().
  3274.             '<br>Este evento incia el día '.$reserva->getDateStart()->format('d/m/Y').' a las '.$reserva->getDateStart()->format('H:i'). ' y finaliza el día '.$reserva->getDateEnd()->format('d/m/Y').' a las '.$reserva->getDateEnd()->format('H:i').'<br><br><br>';
  3275.         if (!empty($dataGP) or !empty($dataAV)){
  3276.             if(!empty($dataGP)){
  3277.                 $mensajePopup .= 'No se puede CONFIRMAR, conflicto con:'.'<br><br>';
  3278.                 // Conflictos con otros eventos en Green Patio
  3279.                 $mailSubject '⚠️ ALERTA️ ‼️ DOBLE CONFIRMADO MISMA SALA' $mailSubject;
  3280.                 $mailBody $mailBody 'Este evento coincide con la(s) reserva(s): <br>';
  3281.                 foreach ($dataGP as $res){
  3282.                     $mailBody $mailBody 'Reserva: '.$res->getTitle().', con ID: '.$res->getId().', fecha de inicio: '.$res->getDateStart()->format('d/m/Y').' a las '.$res->getDateStart()->format('H:i').', fecha de finalización: '.$res->getDateEnd()->format('d/m/Y').' a las '.$res->getDateEnd()->format('H:i');
  3283.                     if(!empty($dataLounges[$res->getId()])){
  3284.                         $mailBody $mailBody .', Salas: ';
  3285.                         foreach ($dataLounges[$res->getId()] as $loungeItem){ $mailBody $mailBody $loungeItem->getLoungeName().', '; }
  3286.                         $mailBody $mailBody .'<br>';
  3287.                     }
  3288.                     $mensajePopup .='Reserva: '.$res->getTitle().', con ID: '.$res->getId().'<br>';
  3289.                 }
  3290.                 $mailBody $mailBody '<br><br>';
  3291.             }
  3292.             if(!empty($dataAV)){
  3293.                 // Conflictos con otros eventos de AvExpress
  3294.                 $mailBody $mailBody 'Este evento coincide en AV con el expediente(s): <br>';
  3295.                 foreach ($dataAV as $file){
  3296.                     $mailBody $mailBody 'Expediente: '.$file->getTitle().', con ID: '.$file->getId().', fecha de inicio: '.$file->getDateStart()->format('d/m/Y H:i').', fecha de finalización: '.$file->getDateEnd()->format('d/m/Y H:i').'<br>';
  3297.                 }
  3298.             }
  3299.             $mailAlert = array('mailBody' => $mailBody'mailSubject' => $mailSubject);
  3300.         }
  3301.         $mailBody $mailBody .'<br><br><a href="https://inout.mante.solutions/reservations-greenpatio/">CALENDARIO GREEN PATIO</a>';
  3302.         $mailBody $mailBody .'<br><br> <a href="https://inout.mante.solutions/reservations-greenpatio/adminconfirmres/y/'.$id.'">"SI"</a> deseo confirmar la reserva.';
  3303.         $mailBody $mailBody .'<br><br> <a href="https://inout.mante.solutions/reservations-greenpatio/adminconfirmres/n/'.$id.'">"NO"</a> deseo confirmar la reserva.';
  3304.         $mailBody $mailBody .'<br><br><br> <a href="https://inout.mante.solutions">"PARA QUE LOS ENLACES FUNCIONEN, ANTES DEBES INCIAR SESION"</a><br><br>';
  3305.         // Se envia el correo pidiendo la confirmacion
  3306.         $this->sendMailLot($mailAddressFrom$mailArrayTo$mailSubject$mailBody);
  3307.         //Alerta a Gabriela, Agente modificador del expediente y Mariale
  3308.         if (!empty($dataGP)){
  3309.             $mailArrayTo = [];
  3310.             $agentAlert $em->getRepository(User::class)->findOneById($reserva->getUpdatedBy());
  3311.             if (!empty($agentAlert) and ($agentAlert->getStatus() == 1)){ $mailArrayTo[$agentAlert->getEmail()] = $agentAlert->getEmail(); }
  3312.             $agentAlert $em->getRepository(User::class)->findOneById(82);         // Gabriela Bracho
  3313.             if (!empty($agentAlert) and ($agentAlert->getStatus() == 1)){ $mailArrayTo[$agentAlert->getEmail()] = $agentAlert->getEmail(); }
  3314.             $agentAlert $em->getRepository(User::class)->findOneById(129);         // Maria Alejandra Martinez
  3315.             if (!empty($agentAlert) and ($agentAlert->getStatus() == 1)){ $mailArrayTo[$agentAlert->getEmail()] = $agentAlert->getEmail(); }
  3316.             $this->sendMailLot($mailAddressFrom$mailArrayTo$mailSubject$mailAlert['mailBody']);
  3317.         }
  3318.         if (!empty($mensajePopup)){ $this->addFlash('mensajereservationerror'$mensajePopup); }
  3319.         // Sincronización con HT
  3320.         if (!empty($reserva)) {
  3321.             // Rafa indico que siempre se sincronice al abrir un expediente de GP
  3322.             if (in_array($reserva->getStatus(), [null'''Confirmed''Invoiced''Iniciado''Cotizado''Bloqueo'])) {
  3323.                 if ($reserva->getCateringName() == 'HIGO & TRIGO, S.L.') {
  3324.                     // Si no se ha creado aun el expediente de HT debemos crearlo
  3325.                     $htFile $em->getRepository(HtFile::class)->findByReservation($reserva);
  3326.                     if (empty($htFile)) { return $this->redirectToRoute('sinc_gp_ht', array('id' => $id,)); }
  3327.                 }
  3328.             }
  3329.         }
  3330.         // Sincronización con Av Express
  3331.         $cotizable $this->laReservaEsCotizable($reserva->getId());
  3332.         if ($cotizable) {
  3333.             $AveFile $em->getRepository(AveFiles::class)->findByReservation($reserva);
  3334.             // Rafa indico que siempre se sincronice al abrir un expediente de GP
  3335.             if (in_array($reserva->getStatus(), [null'''Confirmed''Invoiced''Iniciado''Cotizado''Bloqueo'])) {
  3336.                 if (empty($AveFile)) {
  3337.                     // Si no se ha creado aun el expediente de Av Express debemos crearlo
  3338.                     return $this->redirectToRoute('sinc_gp_ave', array('id' => $id,));
  3339.                 }
  3340.             }
  3341.         }
  3342.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id'token' => null ));
  3343.     }
  3344.     /**
  3345.      * @Route("/adminconfirmres/{op}/{id}", name="reservations_greenpatio_admin_confirm_res")
  3346.      * Confirmacion del administrador, positiva o negativa (op) de la reserva (id)
  3347.      */
  3348.     public function adminConfirmationReservationAction($op$idEntityManagerInterface $emRequest $request){
  3349.         /* Obtengo usuario logueado */
  3350.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3351.         $user_id $user_logueado->getId();
  3352.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  3353.         $mailArrayTo = array();
  3354.         $mailArrayTo['salvador@avexpress.tv'] = 'salvador@avexpress.tv';
  3355.         $mailArrayTo['rafael.guerrero@inout-travel.com'] = 'rafael.guerrero@inout-travel.com';
  3356.         $mailArrayTo['comercial@greenpatio.es'] = 'comercial@greenpatio.es';
  3357.         $mailArrayTo['comercial2@greenpatio.es'] = 'comercial2@greenpatio.es';
  3358. //        $mailArrayTo['gustavo.ayala@develup.solutions'] = 'gustavo.ayala@develup.solutions';
  3359.         $agente $em->getRepository(User::class)->findOneById($user_id);
  3360.         $mailAddressFrom $agente->getEmail();
  3361.         $mailSubject 'Confirmación de reserva: '.$reserva->getTitle();
  3362.         switch ($op) {
  3363.             case 'y':
  3364.                 // Se va a Confirmar la reserva
  3365.                 $reserva->setStatus('Confirmed');
  3366.                 $reserva->setUpdatedBy($user_id);
  3367.                 $reserva->setUpdatedAt(new DateTime('now'));
  3368.                 $em->persist($reserva);
  3369.                 $em->flush();
  3370.                 $mailBody 'Estimado agente,'.
  3371.                     '<br><br>'$agente->getName().' '$agente->getLastName(). ' ha confirmado la reserva:'.
  3372.                     '<br><br>'.$reserva->getTitle(). ' con ID: '.$reserva->getId().
  3373.                     '<br>Este evento incia el día '.$reserva->getDateStart()->format('d/m/Y H:i'). ' y finaliza el día '.$reserva->getDateEnd()->format('d/m/Y H:i').'<br><br><br>';
  3374. //                $mailBody = $mailBody .'<br><br> <a href="http://127.0.0.1:8000/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
  3375.                 $mailBody $mailBody .'<br><br> <a href="https://inout.mante.solutions/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
  3376.                 break;
  3377.             case 'n':
  3378.                 // No se va a Confirmar la reserva - Pasa a un editar (para ajustar fechas etc)
  3379.                 $reserva->setStatus('Cotizado');
  3380.                 $reserva->setUpdatedBy($user_id);
  3381.                 $reserva->setUpdatedAt(new DateTime('now'));
  3382.                 $em->persist($reserva);
  3383.                 $em->flush();
  3384.                 $mailBody 'Estimado agente,'.
  3385.                     '<br><br>'$agente->getName().' '$agente->getLastName(). ' ha rechazado la confirmación de la reserva:'.
  3386.                     '<br><br>'.$reserva->getTitle(). ' con ID: '.$reserva->getId().
  3387.                     '<br>Este evento inciaba el día '.$reserva->getDateStart()->format('d/m/Y H:i'). ' y finalizaba el día '.$reserva->getDateEnd()->format('d/m/Y H:i').'<br><br><br>'.
  3388.                     '<br>POR FAVOR, PONGANSE EN CONTACTO PARA DETEMINAR UN NUEVO HORARIO<br><br><br>';
  3389. //                $mailBody = $mailBody .'<br><br> <a href="http://127.0.0.1:8000/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
  3390.                 $mailBody $mailBody .'<br><br> <a href="http://inout.mante.solutions/reservations-greenpatio/editsimple/'.$id.'">Ir a la reserva</a>';
  3391.                 break;
  3392.             default:
  3393.                 break;
  3394.         }
  3395.         // Enviar correo al agente (envia a las 2 agentes? enviar al creador de la reserva?)
  3396.         $this->sendMailLot($mailAddressFrom$mailArrayTo$mailSubject$mailBody);
  3397.         echo 'Ha finalizado correctamente su sesión. Puede cerrar la aplicación'; exit();
  3398.     }
  3399.     /**
  3400.      * @Route("/viewcontract/{id}", name="reservations_greenpatio_view_contract")
  3401.      * Vista del contrato de la reserva (id)
  3402.      */
  3403.     public function viewContractReservationAction($idEntityManagerInterface $emRequest $request){
  3404.         // El cliente es obligatorio y no puede ser null
  3405.         // El contacto es obligatorio y no puede ser null, será el representante del cliente en el contrato
  3406.         // En el expediente solo deben estar las salas definitivas para el contrato
  3407.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  3408.         $contractOrigin $reserva->getContract();
  3409.         $dateStart $reserva->getDateStart();
  3410.         $dateEnd $reserva->getDateEnd();
  3411.         //Buscamos el representante
  3412.         $representante $reserva->getClientContact();
  3413.         $representante $em->getRepository(ClientContact::class)->findOneById($representante);
  3414.         $representanteCorreo $representante->getEmail();
  3415.         $representante $representante->getName().' '.$representante->getLastName();
  3416.         //Buscamos el cliente
  3417.         $client $reserva->getClient();
  3418.         $client $em->getRepository(Client::class)->findOneById($client);
  3419.         // La fecha de inicio y fin del evento incluyen montaje y desmontaje
  3420.         // Determinamos el primer y ultimo dia del evento y lo modificamos en la reserva sin tocar la base de datos
  3421.         $allOnlySalasReservadas $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation'=>$id,'type'=>null));
  3422.         if (!empty($allOnlySalasReservadas)){
  3423.             $reserva->setDateStart($allOnlySalasReservadas[0]->getDateStart());
  3424.             $reserva->setDateEnd($allOnlySalasReservadas[0]->getDateEnd());
  3425.             foreach ($allOnlySalasReservadas as $item){
  3426.                 if ($item->getDateStart() < $reserva->getDateStart()){ $reserva->setDateStart($item->getDateStart()); }
  3427.                 if ($item->getDateEnd() > $reserva->getDateEnd()){ $reserva->setDateEnd($item->getDateEnd()); }
  3428.             }
  3429.         }
  3430.         //Generamos la fecha actual
  3431.         $fechaActual = new DateTime('now');
  3432.         $mesActual $fechaActual->format('m');
  3433.         switch ($mesActual){
  3434.             case '01'$mesActual 'enero'; break;
  3435.             case '02'$mesActual 'febrero'; break;
  3436.             case '03'$mesActual 'marzo'; break;
  3437.             case '04'$mesActual 'abril'; break;
  3438.             case '05'$mesActual 'mayo'; break;
  3439.             case '06'$mesActual 'jumio'; break;
  3440.             case '07'$mesActual 'julio'; break;
  3441.             case '08'$mesActual 'agosto'; break;
  3442.             case '09'$mesActual 'septiembre'; break;
  3443.             case '10'$mesActual 'octubre'; break;
  3444.             case '11'$mesActual 'noviembre'; break;
  3445.             case '12'$mesActual 'diciembre'; break;
  3446.             default:   $mesActual ''; break;
  3447.         }
  3448.         $contract00 '';
  3449.         $contract01 '';
  3450.         $contract02 '';
  3451.         $contract03 '';
  3452.         $contract04 '';
  3453.         $contract05 '';
  3454.         //Generamos la fecha de inicio
  3455.         $fechaInicio $reserva->getDateStart()->format('m');
  3456.         switch ($fechaInicio){
  3457.             case '01'$mesInicio 'enero'; break;
  3458.             case '02'$mesInicio 'febrero'; break;
  3459.             case '03'$mesInicio 'marzo'; break;
  3460.             case '04'$mesInicio 'abril'; break;
  3461.             case '05'$mesInicio 'mayo'; break;
  3462.             case '06'$mesInicio 'jumio'; break;
  3463.             case '07'$mesInicio 'julio'; break;
  3464.             case '08'$mesInicio 'agosto'; break;
  3465.             case '09'$mesInicio 'septiembre'; break;
  3466.             case '10'$mesInicio 'octubre'; break;
  3467.             case '11'$mesInicio 'noviembre'; break;
  3468.             case '12'$mesInicio 'diciembre'; break;
  3469.             default:   $mesInicio ''; break;
  3470.         }
  3471.         $fechaInicio $reserva->getDateStart()->format('d'). ' de '.$mesInicio.' del '.$reserva->getDateStart()->format('Y').' ';
  3472.         $contract06 ='';
  3473.         $horaInicio $reserva->getDateStart()->format('H:i').' ';
  3474.         $contract07 ='';
  3475.         //Generamos la fecha de fin
  3476.         $fechaFin $reserva->getDateEnd()->format('m');
  3477.         switch ($fechaFin){
  3478.             case '01'$mesFin 'enero'; break;
  3479.             case '02'$mesFin 'febrero'; break;
  3480.             case '03'$mesFin 'marzo'; break;
  3481.             case '04'$mesFin 'abril'; break;
  3482.             case '05'$mesFin 'mayo'; break;
  3483.             case '06'$mesFin 'jumio'; break;
  3484.             case '07'$mesFin 'julio'; break;
  3485.             case '08'$mesFin 'agosto'; break;
  3486.             case '09'$mesFin 'septiembre'; break;
  3487.             case '10'$mesFin 'octubre'; break;
  3488.             case '11'$mesFin 'noviembre'; break;
  3489.             case '12'$mesFin 'diciembre'; break;
  3490.             default:   $mesFin ''; break;
  3491.         }
  3492.         if ($reserva->getDateStart()->format('ymd') != $reserva->getDateEnd()->format('ymd')){
  3493.             $fechaFin ' el día '.$reserva->getDateEnd()->format('d'). ' de '.$mesFin.' del '.$reserva->getDateEnd()->format('Y').' a las '.$reserva->getDateEnd()->format('H:i').' ';
  3494.             $contractAlfa '';
  3495.             $contract08 $fechaFin.$contractAlfa;
  3496.         } else {
  3497.             // El evento empieza y termina el mismo dia
  3498.             $horaFin ' las '.$reserva->getDateEnd()->format('H:i').' ';
  3499.             $contractAlfa '';
  3500.             $contract08 $horaFin.$contractAlfa;
  3501.         }
  3502.         // Buscamos las salas
  3503.         $allSalasReservadas $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  3504.         $arrayTextoSalas = [];
  3505.         foreach ($allSalasReservadas as $item){ $arrayTextoSalas[$item->getIdLounge()] = $item->getIdLounge(); }
  3506.         $textoSalas '';
  3507.         $logAllGreen false;       // Si se asigna el edificio completo no hay que verificar mas salas
  3508.         foreach ($arrayTextoSalas as $item){
  3509.             $sala $em->getRepository(ReservationLoungeDetails::class)->findOneById($item);
  3510.             switch ($sala->getId()){
  3511.                 case '1'$textoSalas '<b>TODO EL EDIFICIO EN EXCLUSIVA</b>'$logAllGreen true; break;
  3512.                 case '16': if (empty($textoSalas)){ $textoSalas '<b>Sala Plenaria La Imprenta, Sala Invernadero</b>'; } else { $textoSalas $textoSalas.'<b>Sala Plenaria La Imprenta, Sala Invernadero</b>'; } break;
  3513.                 case '17': if (empty($textoSalas)){ $textoSalas '<b>Sala Plenaria La Imprenta, Sala Invernadero, Sala Escenario</b>'; } else { $textoSalas $textoSalas.'<b>Sala Plenaria La Imprenta, Sala Invernadero, Sala Escenario</b>'; } break;
  3514.                 default: if (!$logAllGreen){ if (empty($textoSalas)){ $textoSalas '<b>'.$sala->getName().'</b>'; } else { $textoSalas $textoSalas.'<b>, '.$sala->getName().'</b>'; } } break;
  3515.             }
  3516.         }
  3517.         $contract09 '';
  3518.         $cierre $reserva->getDateEnd()->format('H:i').' horas del día '.$reserva->getDateEnd()->format('d').' de '.$mesFin.' del '.$reserva->getDateEnd()->format('Y');
  3519.         $contract10 ='';
  3520.         $pax $reserva->getPax();
  3521.         $contract11 '';
  3522.         $contract12 '</span></span><b><span lang="ES-TRAD" style="font-size:12.0pt"><o:p></o:p></span></b></font></p><p class="MsoListParagraph"><!--[if !supportLists]--><font face="Arial"><span lang="ES-TRAD" style="font-size:12.0pt">-<span style="font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; font-size: 7pt; line-height: normal;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></span><!--[endif]--><span class="Hyperlink1"><span lang="ES-TRAD" style="font-size:12.0pt">Salas a utilizar: </span></span><span class="Ninguno"><b><u><span lang="ES-TRAD">';
  3523.         $contract13 '</span></u></b></span><b><span lang="ES-TRAD" style="font-size:12.0pt"><o:p></o:p></span></b></font></p>';
  3524.         // Se asume que los montajes seran como maximo de dos dias
  3525.         $montaje = []; $mesInicioMontaje ''$mesFinMontaje '';
  3526.         foreach ($allSalasReservadas as $item){
  3527.             if ($item->getType() == 'Montaje'){
  3528.                 if (empty($montaje)){
  3529.                     $montaje[0] = $item->getDateStart();
  3530.                     switch ($item->getDateStart()->format('m')){
  3531.                         case '01'$mesInicioMontaje 'enero'; break;
  3532.                         case '02'$mesInicioMontaje 'febrero'; break;
  3533.                         case '03'$mesInicioMontaje 'marzo'; break;
  3534.                         case '04'$mesInicioMontaje 'abril'; break;
  3535.                         case '05'$mesInicioMontaje 'mayo'; break;
  3536.                         case '06'$mesInicioMontaje 'jumio'; break;
  3537.                         case '07'$mesInicioMontaje 'julio'; break;
  3538.                         case '08'$mesInicioMontaje 'agosto'; break;
  3539.                         case '09'$mesInicioMontaje 'septiembre'; break;
  3540.                         case '10'$mesInicioMontaje 'octubre'; break;
  3541.                         case '11'$mesInicioMontaje 'noviembre'; break;
  3542.                         case '12'$mesInicioMontaje 'diciembre'; break;
  3543.                         default:   $mesInicioMontaje ''; break;
  3544.                     }
  3545.                 } else {
  3546.                     $montaje[1] = $item->getDateEnd();
  3547.                     switch ($item->getDateEnd()->format('m')){
  3548.                         case '01'$mesFinMontaje 'enero'; break;
  3549.                         case '02'$mesFinMontaje 'febrero'; break;
  3550.                         case '03'$mesFinMontaje 'marzo'; break;
  3551.                         case '04'$mesFinMontaje 'abril'; break;
  3552.                         case '05'$mesFinMontaje 'mayo'; break;
  3553.                         case '06'$mesFinMontaje 'jumio'; break;
  3554.                         case '07'$mesFinMontaje 'julio'; break;
  3555.                         case '08'$mesFinMontaje 'agosto'; break;
  3556.                         case '09'$mesFinMontaje 'septiembre'; break;
  3557.                         case '10'$mesFinMontaje 'octubre'; break;
  3558.                         case '11'$mesFinMontaje 'noviembre'; break;
  3559.                         case '12'$mesFinMontaje 'diciembre'; break;
  3560.                         default:   $mesFinMontaje ''; break;
  3561.                     }
  3562.                 }
  3563.             }
  3564.         }
  3565.         switch (sizeof($montaje)){
  3566.             case 1$textoMontaje $montaje[0]->format('d').' de '.$mesInicioMontaje.' del '.$montaje[0]->format('Y'); break;
  3567.             case 2:
  3568.                 if ($mesInicioMontaje == $mesFinMontaje){
  3569.                     // Dos dias de montaje en el mismo mes
  3570.                     $textoMontaje $montaje[0]->format('d').' y '.$montaje[1]->format('d'). ' de '.$mesInicioMontaje.' del '.$montaje[0]->format('Y');
  3571.                 } else {
  3572.                     // Dos dias de montaje con diferentes meses, ejemplo 31/03 y 01/04
  3573.                     $textoMontaje $montaje[0]->format('d').' de '.$mesInicioMontaje.' y '.$montaje[1]->format('d').' de '.$mesFinMontaje.' del '.$montaje[0]->format('Y');
  3574.                 }
  3575.                 break;
  3576.             default: $textoMontaje null; break;
  3577.         }
  3578.         if (!empty($textoMontaje)){
  3579.             $textoMontaje '<p class="MsoListParagraph"><!--[if !supportLists]--><font face="Arial"><span lang="ES-TRAD" style="font-size:12.0pt">-<span style="font-variant-numeric: normal; font-variant-east-asian: normal; font-stretch: normal; font-size: 7pt; line-height: normal;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></span><!--[endif]--><span class="Hyperlink1"><span lang="ES-TRAD" style="font-size:12.0pt">MONTAJE: '.$textoMontaje.'</span></span><b><span lang="ES-TRAD" style="font-size:12.0pt"><o:p></o:p></span></b></font></p>';
  3580.         }
  3581.         // Se asume que los desmontajes seran como maximo de dos dias
  3582.         $desmontaje = array(); $mesInicioDesmontaje ''$mesFinDesmontaje '';
  3583.         foreach ($allSalasReservadas as $item){
  3584.             if ($item->getType() == 'Desmontaje'){
  3585.                 if (empty($desmontaje)){
  3586.                     $desmontaje[0] = $item->getDateStart();
  3587.                     switch ($item->getDateStart()->format('m')){
  3588.                         case '01'$mesInicioDesmontaje 'enero'; break;
  3589.                         case '02'$mesInicioDesmontaje 'febrero'; break;
  3590.                         case '03'$mesInicioDesmontaje 'marzo'; break;
  3591.                         case '04'$mesInicioDesmontaje 'abril'; break;
  3592.                         case '05'$mesInicioDesmontaje 'mayo'; break;
  3593.                         case '06'$mesInicioDesmontaje 'jumio'; break;
  3594.                         case '07'$mesInicioDesmontaje 'julio'; break;
  3595.                         case '08'$mesInicioDesmontaje 'agosto'; break;
  3596.                         case '09'$mesInicioDesmontaje 'septiembre'; break;
  3597.                         case '10'$mesInicioDesmontaje 'octubre'; break;
  3598.                         case '11'$mesInicioDesmontaje 'noviembre'; break;
  3599.                         case '12'$mesInicioDesmontaje 'diciembre'; break;
  3600.                         default:   $mesInicioDesmontaje ''; break;
  3601.                     }
  3602.                 } else {
  3603.                     $desmontaje[1] = $item->getDateEnd();
  3604.                     switch ($item->getDateEnd()->format('m')){
  3605.                         case '01'$mesFinDesmontaje 'enero'; break;
  3606.                         case '02'$mesFinDesmontaje 'febrero'; break;
  3607.                         case '03'$mesFinDesmontaje 'marzo'; break;
  3608.                         case '04'$mesFinDesmontaje 'abril'; break;
  3609.                         case '05'$mesFinDesmontaje 'mayo'; break;
  3610.                         case '06'$mesFinDesmontaje 'jumio'; break;
  3611.                         case '07'$mesFinDesmontaje 'julio'; break;
  3612.                         case '08'$mesFinDesmontaje 'agosto'; break;
  3613.                         case '09'$mesFinDesmontaje 'septiembre'; break;
  3614.                         case '10'$mesFinDesmontaje 'octubre'; break;
  3615.                         case '11'$mesFinDesmontaje 'noviembre'; break;
  3616.                         case '12'$mesFinDesmontaje 'diciembre'; break;
  3617.                         default:   $mesFinDesmontaje ''; break;
  3618.                     }
  3619.                 }
  3620.             }
  3621.         }
  3622.         switch (sizeof($desmontaje)){
  3623.             case 1$textoDesmontaje $desmontaje[0]->format('d').' de '.$mesInicioDesmontaje.' del '.$desmontaje[0]->format('Y'); break;
  3624.             case 2:
  3625.                 if ($mesInicioDesmontaje == $mesFinDesmontaje){
  3626.                     // Dos dias de montaje en el mismo mes
  3627.                     $textoDesmontaje $desmontaje[0]->format('d').' y '.$desmontaje[1]->format('d'). ' de '.$mesInicioDesmontaje.' del '.$desmontaje[0]->format('Y');
  3628.                 } else {
  3629.                     // Dos dias de montaje con diferentes meses, ejemplo 31/03 y 01/04
  3630.                     $textoDesmontaje $desmontaje[0]->format('d').' de '.$mesInicioDesmontaje.' y '.$desmontaje[1]->format('d').' de '.$mesFinDesmontaje.' del '.$desmontaje[0]->format('Y');
  3631.                 }
  3632.                 break;
  3633.             default: $textoDesmontaje 'Mismo día al finalizar el evento desde las 17 horas hasta las 00:00 horas'; break;
  3634.         }
  3635.         if (!empty($textoDesmontaje)){
  3636.             $textoDesmontaje '';
  3637.         }
  3638.         $contract14 '';
  3639.         if (empty($mesInicioMontaje)){
  3640.             switch ($dateStart->format('m')){
  3641.                 case '01'$mesInicioMontajeZ 'enero'; break;
  3642.                 case '02'$mesInicioMontajeZ 'febrero'; break;
  3643.                 case '03'$mesInicioMontajeZ 'marzo'; break;
  3644.                 case '04'$mesInicioMontajeZ 'abril'; break;
  3645.                 case '05'$mesInicioMontajeZ 'mayo'; break;
  3646.                 case '06'$mesInicioMontajeZ 'jumio'; break;
  3647.                 case '07'$mesInicioMontajeZ 'julio'; break;
  3648.                 case '08'$mesInicioMontajeZ 'agosto'; break;
  3649.                 case '09'$mesInicioMontajeZ 'septiembre'; break;
  3650.                 case '10'$mesInicioMontajeZ 'octubre'; break;
  3651.                 case '11'$mesInicioMontajeZ 'noviembre'; break;
  3652.                 case '12'$mesInicioMontajeZ 'diciembre'; break;
  3653.                 default:   $mesInicioMontajeZ ''; break;
  3654.             }
  3655.             $tiempoCedido $dateStart->format('H:i').' horas del día '.$dateStart->format('d').' de '.$mesInicioMontajeZ.' del '.$dateStart->format('Y').' hasta las ';
  3656.         } else {
  3657.             $tiempoCedido $dateStart->format('H:i').' horas del día '.$dateStart->format('d').' de '.$mesInicioMontaje.' del '.$dateStart->format('Y').' hasta las ';
  3658.         }
  3659.         if (empty($mesInicioDesmontaje)){
  3660.             switch ($dateStart->format('m')){
  3661.                 case '01'$mesInicioDesmontajeZ 'enero'; break;
  3662.                 case '02'$mesInicioDesmontajeZ 'febrero'; break;
  3663.                 case '03'$mesInicioDesmontajeZ 'marzo'; break;
  3664.                 case '04'$mesInicioDesmontajeZ 'abril'; break;
  3665.                 case '05'$mesInicioDesmontajeZ 'mayo'; break;
  3666.                 case '06'$mesInicioDesmontajeZ 'jumio'; break;
  3667.                 case '07'$mesInicioDesmontajeZ 'julio'; break;
  3668.                 case '08'$mesInicioDesmontajeZ 'agosto'; break;
  3669.                 case '09'$mesInicioDesmontajeZ 'septiembre'; break;
  3670.                 case '10'$mesInicioDesmontajeZ 'octubre'; break;
  3671.                 case '11'$mesInicioDesmontajeZ 'noviembre'; break;
  3672.                 case '12'$mesInicioDesmontajeZ 'diciembre'; break;
  3673.                 default:   $mesInicioDesmontajeZ ''; break;
  3674.             }
  3675.             $tiempoCedido $tiempoCedido $dateEnd->format('H:i').' horas del día '.$dateEnd->format('d').' de '.$mesInicioDesmontajeZ.' del '.$dateEnd->format('Y');
  3676.         } else {
  3677.             $tiempoCedido $tiempoCedido $dateEnd->format('H:i').' horas del día '.$dateEnd->format('d').' de '.$mesInicioDesmontaje.' del '.$dateEnd->format('Y');
  3678.         }
  3679.         $contract15 '';
  3680.         // 5. Normas de Seguridad
  3681.         $contract16 '';
  3682.         // 6. Coste, plazo y forma de pago
  3683.         $data $this->CalculosTotalesEditSimple($reserva->getId());
  3684.         $contract17 '';
  3685.         // 8. Reserva
  3686.         $contract18 '';
  3687.         // 9. Confidencialidad y publicidad
  3688.         // 11. Derechos de imagen y propiedad intelectual
  3689.         // 12. Prevencion de la corrupcion
  3690.         // 13. Proteccion de datos personales
  3691.         // 14. Responsabilidad
  3692.         $contract19 '';
  3693.         // 15. Comunicaciones
  3694.         $contract20 '';
  3695.         // 16. Cesión
  3696.         // 17. Nulidad Parcial
  3697.         // 18. Fuerza Mayor
  3698.         // 19. Acuerdo Completo
  3699.         $contract21 '';
  3700.         // Normas de uso
  3701.         $contract22 '';
  3702.         // Logotipo de Green Patio centrado
  3703.         $contract23 '
  3704.         <div class="col-md-4 col-xs-6" ></div><div class="col-md-4 col-xs-6" ><p class="MsoNormal" align="right" style="margin-bottom: background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><b><span lang="EN-US" style="font-size: 9pt;"><font face="Arial"><o:p><br></o:p></font></span></b></p><p class="MsoNormal" align="right" style="margin-bottom: 7.5pt; text-align: right; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><b><span lang="EN-US" style="font-size: 9pt;"><font face="Arial"><o:p><br></o:p></font></span></b></p><p class="MsoNormal" align="right" style="margin-bottom: 7.5pt; text-align: right; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"><img src="data:image/png;base64,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fZ00cOlJabFBKCM9wqH1T8ZwI+pwdXgQ8q5GCnSwAPJnIX1P5iPDmP+VSN8o7rVJYEWZlhKB9XTUUfDUF1lzUP5R/C0IRCh3syynDg5C0NkN8+gdegLBOsorZBIcqw6sCID1mPa7OlgWllNeM7tbg1UkLHt4f1AHS0K5dsz7Sh0Moad7IJbpceQ3aFYBTHMSxn1dByuC7XsElvdr+Csnr62w/Bmky4vbot4KWKuDkaRNo8y1OlgA9f8txhU85JR9gzYqD1zvwbIfJe0Df7+F4fO0yCDk34Q0TwdpS4XG8ani142EBBU00v2GBhc0sK1xsO2Jj8MOfjTG3fVjxeTAlnlLgJHPxZfHeXLwYDkLehF6/6zgfVqBZZR3Moc9jMnDch4ul6zyGeX2k9e98LEggMo6l6pDlhHzKHhwIsNy8BW/+iPbqriskhODzHdwO8o20G1bNcxj2+LtU47sdyzDR3VwGKlTkg6WNH/+/J2jer2zZ8/epVT9sg3l5KKDlZosl+VYpp3kM/b9QcXbW1SyHVGHvIdasP3zpH5sm2HvIyN/R+RPlfvx8u4sPh8tD3N19CAJukM7I0RERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERFuKSZP+F0vlO4rFICMJAAAAAElFTkSuQmCC" alt="" style="float: left;"></p><p class="MsoNormal" style="margin-bottom: 7.5pt; text-indent: 3pt; background-image: initial; background-position: initial; background-size: initial; background-repeat: initial; background-attachment: initial; background-origin: initial; background-clip: initial;"></p></div></div></div></div><div class="col-md-4 col-xs-6" ></div>
  3705.         ';
  3706.             //Generamos el contrato
  3707.         $contract $contract00.'<b>'.' '.$client->getName().'</b>'.' '.$contract01'CIF '.$client->getIdDocument().' '.
  3708.             $contract02.'<b>'.' '.$client->getAddress().'</b>'.','.$contract03.' '.$representante.'.'.
  3709.             $contract04.$reserva->getTitle().$contract05.$fechaInicio.$contract06.$horaInicio.$contract07.
  3710.             $contract08.$textoSalas.$contract09.$cierre.$contract10.$pax.$contract11.$fechaInicio.
  3711.             $contract12.$textoSalas.$contract13.$textoMontaje.$textoDesmontaje.$contract14.$tiempoCedido.
  3712.             $contract15.$contract16.$contract17.$contract18.$contract19.$contract20.$contract21.$contract22.$contract23
  3713.         ;
  3714.         // Si no habia contracto originalmente en la reserva se actualiza
  3715.         if (empty($contractOrigin)){
  3716.             $reserva->setContract($contract);
  3717.             $em->persist($reserva);
  3718.             $em->flush();
  3719.         } else {
  3720.             $contract $contractOrigin;
  3721.         }
  3722.         return $this->render('MDS/GreenPatioBundle/reservations/view-contract-reservation.html.twig', array( 'id' => $id'contract' => $contract, ) );
  3723.     }
  3724.     /**
  3725.      * @Route("/createdeposit/{id}", name="reservations_greenpatio_createdeposit")
  3726.      */
  3727.     public function createDepositAction($idEntityManagerInterface $emRequest $request)
  3728.     {
  3729.         $newRequest $request->request->get('reservation_deposit');
  3730.         /* Obtengo usuario logueado */
  3731.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3732.         $user_id $user_logueado->getId();
  3733.         $newDeposit = new ReservationDeposit();
  3734.         $newDeposit->setReservationId($id);
  3735.         if (empty($newRequest['date'])) { $newDeposit->setDate(new DateTime ('now')); } else { $newDeposit->setDate(new DateTime ($newRequest['date'])); }
  3736.         if (empty($newRequest['description'])) { $newDeposit->setDescription(null); } else { $newDeposit->setDescription($newRequest['description']); }
  3737.         if (empty($newRequest['amount'])) { $newDeposit->setAmount(null); } else { $newDeposit->setAmount($newRequest['amount']); }
  3738.         if (array_key_exists('isDone',$newRequest)) { $newDeposit->setIsDone(true); } else { $newDeposit->setIsDone(false); }
  3739.         $newDeposit->setCreatedAt(new DateTime ('now'));
  3740.         $newDeposit->setCreatedId($user_id);
  3741.         $newDeposit->setUpdatedAt(new DateTime ('now'));
  3742.         $newDeposit->setUpdatedId($user_id);
  3743.         $em->persist($newDeposit);
  3744.         $em->flush();
  3745.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $id'token' => null'_fragment' => 'btn_dpt' ));
  3746.     }
  3747.     /**
  3748.      * @Route("/depositupdate/{id}", name="reservations_greenpatio_deposit_update")
  3749.      */
  3750.     public function depositUpdateAction($idEntityManagerInterface $emRequest $request)
  3751.     {
  3752.         $newRequest $request->request->get('reservation_deposit_isdone_pending');
  3753.         $deposito $em->getRepository(ReservationDeposit::class)->findOneById($id);
  3754.         if (array_key_exists('isDone',$newRequest)) { $deposito->setIsDone(true); } else { $deposito->setIsDone(false); }
  3755.         /* Obtengo usuario logueado */
  3756.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3757.         $user_id $user_logueado->getId();
  3758.         $deposito->setUpdatedAt(new DateTime ('now'));
  3759.         $deposito->setUpdatedId($user_id);
  3760.         $em->persist($deposito);
  3761.         $em->flush();
  3762.         return $this->redirectToRoute('reservations_greenpatio_edit_simple', array( 'id' => $deposito->getReservationId(), 'token' => null'_fragment' => 'btn_dpt' ));
  3763.     }
  3764.     /**
  3765.      * @Route("/loadedreservations", name="reservations_greenpatio_loaded_reservations")
  3766.      */
  3767.     public function loadedReservationsAction(EntityManagerInterface $emRequest $request)
  3768.     {
  3769.         $hoy = new DateTime('now');
  3770.         $diaInicio = new DateTime($hoy->format('Y-m'). '-01');
  3771.         // Se buscan las reservas creadas desde el inicio de mes
  3772.         $parameters = array( 'diaInicio' => $diaInicio, );
  3773.         $dql 'SELECT i
  3774.                 FROM GreenPatioBundle:Reservation i
  3775.                 WHERE  i.createdAt > :diaInicio';
  3776.         $query $em->createQuery($dql)->setParameters($parameters);
  3777.         $reservas $query->getResult();
  3778.         return $this->render('MDS/GreenPatioBundle/reservations/list-loaded-reservations.html.twig', array( 'reservations' => $reservas'itemsOfSearch' => '', ) );
  3779.     }
  3780.     /**
  3781.      * @Route("/searchreservations", name="reservations_greenpatio_search_reservations")
  3782.      */
  3783.     public function searchReservationsAction(EntityManagerInterface $emRequest $request)
  3784.     {
  3785.         $searchloaded $request->request->get('searchloaded');
  3786.         $dateStart = new \DateTime($searchloaded['date_start']);
  3787.         $dateEnd = new \DateTime($searchloaded['date_end']);
  3788.         $itemsOfSearch ' Entre las fechas: '.$dateStart->format('d/m/Y').' y '.$dateEnd->format('d/m/Y');
  3789.         // Se buscan las reservas creadas en las fechas solicitadas
  3790.         $parameters = array( 'diaInicio' => $dateStart'diaFin' => $dateEnd, );
  3791.         $dql 'SELECT i
  3792.                 FROM GreenPatioBundle:Reservation i
  3793.                 WHERE  i.createdAt BETWEEN :diaInicio AND :diaFin';
  3794.         $query $em->createQuery($dql)->setParameters($parameters);
  3795.         $reservas $query->getResult();
  3796.         return $this->render('MDS/GreenPatioBundle/reservations/list-loaded-reservations.html.twig', array( 'reservations' => $reservas'itemsOfSearch' => $itemsOfSearch, ) );
  3797.     }
  3798.     /**
  3799.      * Cambia las descripciones de las reservas al idioma seleccionado
  3800.      * @Route("/changeLanguage/{id}/{idLanguage}", name="reservations_greenpatio_change_language", methods={"GET"})
  3801.      */
  3802.     public function changeLanguageAction(int $idint $idLanguageEntityManagerInterface $emSerializerInterface $serializerInterface): JsonResponse
  3803.     {
  3804.         $descriptions $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation' => $id));
  3805.         $idiomas = array();
  3806.         foreach ($descriptions as $description) {
  3807.             $loungeDetails $em->getRepository(ReservationLoungeDetails::class)->findOneById($description->getIdLounge());
  3808.             $idiomas[$description->getIdLounge()] = $em->getRepository(ReservationLoungeWebDescription::class)->findOneBy(array('lounge' => $loungeDetails'language' => $idLanguage));
  3809.         }
  3810.         $idiomas $serializerInterface->serialize($idiomas'json', [
  3811.             'groups' => ['reservation_lounge_web_description:read']
  3812.         ]);
  3813.         $idiomas json_decode($idiomastrue);
  3814.         return $this->json([
  3815.             'status' => JsonResponse::HTTP_OK,
  3816.             'idiomas' => $idiomas,
  3817.         ], JsonResponse::HTTP_OK);
  3818.     }
  3819.     private function sendMail($mailAddressFrom$mailAddressTo$mailSubject$mailBody){
  3820.         $em $this->getDoctrine()->getManager();
  3821.         $agent $em->getRepository(User::class)->findOneByEmail($mailAddressFrom);
  3822.         $client $em->getRepository(Client::class)->findOneByEmail($mailAddressTo);
  3823.         if (empty($client)){ $client $em->getRepository(ClientContact::class)->findOneByEmail($mailAddressTo); }     // Si el cliente era null puede ser un client contact
  3824.         if (!empty($client)){
  3825.             $replyTo = array(
  3826.                 $client->getEmail() => $client->getName(),
  3827.                 $agent->getEmail() => $agent->getName().' '$agent->getLastName(),
  3828.             );
  3829.         } else {
  3830.             // El AddressTo es un contacto no registrado
  3831.             $replyTo = array(
  3832.                 $mailAddressTo => $mailAddressTo,
  3833.                 $agent->getEmail() => $agent->getName().' '$agent->getLastName(),
  3834.             );
  3835.         }
  3836.         $agentMail $mailAddressFrom;
  3837.         $mailAgent $agentMail;
  3838.         //Se prepara el correo con los agentes a notificar
  3839.         $firmGmail $agent->getFirmGmail();
  3840.         $data = array(
  3841.             'body' => $mailBody,
  3842.             'firm' => $firmGmail,
  3843.         );
  3844.         // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  3845.         $transporter = new \Swift_SmtpTransport();
  3846.         $transporter->setHost('smtp.gmail.com')
  3847.             ->setEncryption('ssl')//ssl / tls
  3848.             ->setPort(465)// 465 / 587
  3849.             ->setUsername('desarrollo@develup.solutions')
  3850.             ->setPassword('utvh hzoi wfdo ztjs');
  3851. //            ->setPassword('MeDITeRRANeAN_Develup30102023#');
  3852.         $mailer = new \Swift_Mailer($transporter);
  3853.         $message = new \Swift_Message();
  3854.         $message->setSubject($mailSubject)
  3855.             ->setSender($agentMail)
  3856.             ->setFrom(array("desarrollo@develup.solutions" => "Green Patio"))
  3857.             ->setReplyTo($agentMail)
  3858.             ->setTo($replyTo)
  3859.             ->setBody(
  3860.                 $this->renderView(
  3861.                     'mail/structure-mail.html.twig',
  3862.                     array('data' => $data)
  3863.                 ),
  3864.                 'text/html'
  3865.             );
  3866. //        $mailer->send($message);          Rafa dijo que no queria envío de correos con el cliente ya que se haría mediante la cotización Web (04/02/2025)
  3867.         return true;
  3868.     }
  3869.     private function makeAlert($reservaId$clientId$clientMail$agentId$agentMail){
  3870.         $em $this->getDoctrine()->getManager();
  3871.         $alertaPrevia $em->getRepository(ReservationMailAlertClient::class)->findOneByReservationId($reservaId);
  3872.         $reserva $em->getRepository(Reservation::class)->findOneById($reservaId);
  3873.         $dias $reserva->getDaysBlock();
  3874.         if (empty($dias) or !(is_numeric($dias))){
  3875.             $dias 7;
  3876.         }
  3877.         $diasMenosDos $dias 2;
  3878.         /* Obtengo usuario logueado */
  3879.         $user_logueado $this->get('security.token_storage')->getToken()->getUser();
  3880.         $user_id $user_logueado->getId();
  3881.         $hoy = new \DateTime("now"NULL);
  3882.         $hoyMasCinco $hoy;
  3883.         $hoyMasCinco->add(new DateInterval('P'.$diasMenosDos.'D'));                   // 5 dias despues, 48 horas antes de la cancelacion (o los especificados)
  3884.         $hoyMasCinco->add(new DateInterval("PT2H"));                                  // Ajustamos la diferencia con el reloj del servidor
  3885.         $hoy = new \DateTime("now"NULL);
  3886.         $hoyMasSiete $hoy;
  3887.         $hoyMasSiete->add(new DateInterval('P'.$dias.'D'));                           // Siete dias despues (o los especificados)
  3888.         $hoyMasSiete->add(new DateInterval("PT2H"));
  3889.         //Si no hay una alerta previa se hace la alerta
  3890.         if (empty($alertaPrevia)){
  3891.             $alerta = new ReservationMailAlertClient();
  3892.             $alerta->setReservationId($reservaId);
  3893.             $alerta->setClientId($clientId);
  3894.             $alerta->setClientMail($clientMail);
  3895.             $alerta->setAgentId($agentId);
  3896.             $alerta->setAgentMail($agentMail);
  3897.             $alerta->setAlertDateTime($hoyMasCinco);                // A los 5 dias se alerta (o los especificados)
  3898.             $alerta->setAlertSended(false);
  3899.             $alerta->setCancelDateTime($hoyMasSiete);               // A los 7 dias se cancela (o los especificados)
  3900.             $alerta->setCancelSended(false);
  3901.             $alerta->setOldReservationId(null);                     // Aqui se guardara el Id de reserva cuando se vaya a eliminar el registro (solo se pondra reservationId a 0)
  3902.             $alerta->setCreatedAt($hoy);
  3903.             $alerta->setCreatedId($user_id);
  3904.             $em->persist($alerta);
  3905.             $em->flush();
  3906.         }
  3907.         return true;
  3908.     }
  3909.     private function benefitForReservation($id){
  3910.         $em $this->getDoctrine()->getManager();
  3911.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  3912.         $lounges $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  3913.         $services $em->getRepository(ReservationService::class)->findByReservationId($id);
  3914.         $payedLounges = array(); $payedServices = array(); $unPayedServices = array();
  3915.         // Salas
  3916.         foreach ($lounges as $item){
  3917.             // Si la sala esta en ReservationInvoiceItems se encuentra facturado, en caso contraio, no lo esta o ha sido rectificado
  3918.             $loungeInvoicedItem $em->getRepository(ReservationInvoiceItems::class)->findOneByLngControlId($item->getId());
  3919.             if (!empty($loungeInvoicedItem)){ $payedLounges[] = $item; }                       // Esta facturado el Item
  3920.         }
  3921.         // Servicios
  3922.         foreach ($services as $item){
  3923.             // Si el servicio esta en ReservationInvoiceItems se encuentra facturado, en caso contraio, no lo esta o ha sido rectificado
  3924.             $serviceInvoicedItem $em->getRepository(ReservationInvoiceItems::class)->findOneBySrvControlId($item->getId());
  3925.             if (!empty($serviceInvoicedItem)){
  3926.                 // Esta facturado el Item
  3927.                 $payedServices[] = $item;
  3928.             } else {
  3929.                 // No esta facturado el Item o fue rectificado
  3930.                 $unPayedServices[] = $item;
  3931.             }
  3932.         }
  3933.         $benefit 0$payed 0;
  3934.         // Se suman los pagos
  3935.         foreach ($payedLounges as $item){
  3936.             $benefit $benefit + (float)$item->getServicePrice();
  3937.             $payed $payed + (float)$item->getServicePrice();
  3938.         }
  3939.         foreach ($payedServices as $item){
  3940.             $benefit $benefit + (float)$item->getPrice();
  3941.             $payed $payed + (float)$item->getPrice();
  3942.         }
  3943.         // Se restan los impagos
  3944.         foreach ($unPayedServices as $item){
  3945.             // Se verifica el check de toinvoice por si el servicio se facturara a futuro (Requisito de Rafa)
  3946.             if ($item->getToinvoice()){
  3947.                 $benefit += (float)$item->getPrice();
  3948.                 $payed += (float)$item->getPrice();
  3949.             } else {
  3950.                 // No esta pagado y no esta marcado "Para facturar"
  3951.                 $benefit $benefit - (float)$item->getPrice();
  3952.             }
  3953.         }
  3954.         // Porcentaje de beneficio
  3955.         $percBenefit = ($benefit 100);
  3956.         if (!($payed == 0)){ $percBenefit $percBenefit $payed; } else { $percBenefit 0; };
  3957.         return array(
  3958.             'benefit' => $benefit,
  3959.             'percBenefit' => $percBenefit,
  3960.             'payedLounges' => $payedLounges,
  3961.             'payedServices' => $payedServices,
  3962.             'unPayedServices' => $unPayedServices,
  3963.         );
  3964.     }
  3965.     private function verificarStatusInicialyFinal($id,$user_id,$estadoInicial,$estadoFinal){
  3966.         $em $this->getDoctrine()->getManager();
  3967.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  3968.         $user_logueado $em->getRepository(User::class)->findOneById($user_id);
  3969.         $newStatus 'Pendiente';
  3970.         //Este Switch ya no es necesario
  3971.         switch ($estadoInicial) {
  3972.             case 'Bloqueo':
  3973.                 // De bloqueo solo se sale si el usuario es Salvador o un Admin O si se va a Cancelar "Deleted" o "Cotizado"
  3974. //                if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Deleted' or $estadoFinal == 'Cotizado'){
  3975.                 if ($estadoFinal == 'Deleted' or $estadoFinal == 'Cotizado'){
  3976.                     $newStatus $estadoFinal;
  3977.                 } else {
  3978.                     // No se cambia el estado
  3979.                     $newStatus $estadoInicial;
  3980.                 }
  3981.                 break;
  3982.             case 'Pendiente':
  3983.                 // De Pendiente solo se sale si el usuario es Salvador o un Admin O si se va a Cancelar "Deleted"
  3984.                 $newStatus $estadoFinal;
  3985. //                if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Deleted'){
  3986.                 if ($estadoFinal == 'Deleted'){
  3987.                     $newStatus $estadoFinal;
  3988.                 } else {
  3989.                     // No se cambia el estado
  3990.                     $newStatus $estadoInicial;
  3991.                 }
  3992.                 break;
  3993.             case 'Deleted':
  3994.                 // De Cancelado solo se sale si el usuario es Salvador o un Admin O "Bloqueo" o "Pendiente"
  3995. //                if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente'or $estadoFinal == 'Cotizado'){
  3996.                 if ($estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente'or $estadoFinal == 'Cotizado'){
  3997.                     $newStatus $estadoFinal;
  3998.                 } else {
  3999.                     // No se cambia el estado
  4000.                     $newStatus $estadoInicial;
  4001.                 }
  4002.                 break;
  4003.             case 'Cotizado':
  4004.                 $newStatus $estadoFinal;
  4005.                 // De Cotizado solo se sale si el usuario es Salvador o un Admin O a  O "Bloqueo" o "Pendiente" o "Cancelado"
  4006. //                if (($user_logueado->getRole() == 'ROLE_ADMIN') or ($user_id == 14) or $estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente' or $estadoFinal == 'Deleted'){
  4007.                 if ($estadoFinal == 'Bloqueo' or $estadoFinal == 'Pendiente' or $estadoFinal == 'Deleted' or $estadoFinal == 'Confirmed'){
  4008.                     $newStatus $estadoFinal;
  4009.                 }
  4010.                 break;
  4011.             case 'Invoiced':
  4012.                 // De Facturado no se debe salir a menos que se rectifique
  4013.                 // Si todas las facturas del expediente se encuentran rectificadas pasamos al estado "Confirmado" sino seguimos en "Facturado"
  4014.                 $reservaInvoices $em->getRepository(ReservationInvoice::class)->findByReservationId($id);
  4015.                 $estanTodasRectificadas true;
  4016.                 foreach ($reservaInvoices as $item){
  4017.                     $reservaInvoiceRect $em->getRepository(ReservationInvoiceRec::class)->findOneByInvoiceToRec($item->getId());
  4018.                     if (empty($reservaInvoiceRect)){ $estanTodasRectificadas false; } else { $estanTodasRectificadas = ($estanTodasRectificadas and true); }
  4019.                 }
  4020.                 if ($estanTodasRectificadas){
  4021.                     $newStatus 'Confirmed';
  4022.                 } else {
  4023.                     $newStatus $estadoInicial;
  4024.                 }
  4025.                 break;
  4026.             case 'Confirmed':
  4027.                 // Se puede ir a cualquier estado
  4028.                 $newStatus $estadoFinal;
  4029.                 break;
  4030.             default:
  4031.                 // No hacer nada con el campo Status
  4032.                 $newStatus $estadoInicial;
  4033.                 break;
  4034.         }
  4035.         $newStatus $estadoFinal;
  4036.         return $newStatus;
  4037.     }
  4038.     private function disponibilidadGreenPatio($id$initStatus){
  4039.         // $id Id de la reserva
  4040.         $em $this->getDoctrine()->getManager();
  4041.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  4042. //        $lounges = $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($id);
  4043.         //Buscamos salas que tengamos entre el inicio y fin del evento a confirmar
  4044.         //Sumamos un dia ya que por solicitud de Salva deseamos saber que eventos hay un dia antes y un dia despues
  4045.         $fechaInicio = new \DateTime($reserva->getDateStart()->format('Y-m-d H:i:s'));
  4046. //        $fechaInicio->sub(new \DateInterval("P1D"));
  4047.         $fechaFin = new \Datetime($reserva->getDateEnd()->format('Y-m-d H:i:s'));
  4048. //        $fechaFin->add(new \DateInterval("P1D"));
  4049.         // Los eventos que debemos verificar son los Confirmados y Facturados
  4050.         $parameters = array(
  4051.             'dateStart' => $fechaInicio,
  4052.             'dateEnd' => $fechaFin,
  4053.             'facturado' => 'Invoiced',
  4054.             'confirmado' => 'Confirmed',
  4055.         );
  4056.         $dql 'SELECT r
  4057.         FROM GreenPatioBundle:Reservation r
  4058.         INNER JOIN GreenPatioBundle:ReservationLoungeSimple l WITH r.id = l.idReservation
  4059.         WHERE (r.status = :facturado OR r.status = :confirmado) 
  4060.         AND (
  4061.             l.dateStart <= :dateEnd 
  4062.             AND l.dateEnd >= :dateStart
  4063.         )';
  4064.         $query $em->createQuery($dql)->setParameters($parameters);
  4065.         $reservationsInConflict $query->getResult();
  4066.         $arrayUso = [];
  4067.         $arrayAlert = [];
  4068.         $arrayAlertMontDesmont = [];                // Nuevo array para almacenar conflictos de montaje y desmontaje
  4069.         if (sizeof($reservationsInConflict) >1){
  4070.             foreach ($reservationsInConflict as $resConflict) {
  4071.                 $loungesConflict $em->getRepository(ReservationLoungeSimple::class)->findByIdReservation($resConflict->getId());
  4072.                 foreach ($loungesConflict as $item) {
  4073.                     $type $item->getType();                               // Puede ser NULL, "Montaje" o "Desmontaje"
  4074.                     $dateKey $item->getDateStart()->format('Ymd');
  4075.                     $loungeId $item->getIdLounge();
  4076.                     $reservationId $item->getIdReservation();
  4077.                     if (in_array($loungeId, [249])) {
  4078.                         // Plenaria, Invernadero y Escenario se consideran la misma sala
  4079.                         $arrayUso[2][$dateKey][$reservationId] = empty($type) ? 'Sala' $type;
  4080.                         $arrayUso[4][$dateKey][$reservationId] = empty($type) ? 'Sala' $type;;
  4081.                         $arrayUso[9][$dateKey][$reservationId] = empty($type) ? 'Sala' $type;;
  4082.                     } else {
  4083.                         $lngDetails $em->getRepository(ReservationLoungeDetails::class)->findOneById($loungeId);
  4084.                         if (empty($lngDetails->getCombo())) {
  4085.                             $arrayUso[$loungeId][$dateKey][$reservationId] = empty($type) ? 'Sala' $type;
  4086.                         } else {
  4087.                             $arrayComboLounges explode(","$lngDetails->getCombo());
  4088.                             foreach ($arrayComboLounges as $indLounge) {
  4089.                                 $arrayUso[$indLounge][$dateKey][$reservationId] = empty($type) ? 'Sala' $type;
  4090.                             }
  4091.                         }
  4092.                     }
  4093.                 }
  4094.             }
  4095.             foreach ($arrayUso as $idLounge => $dates) {
  4096.                 foreach ($dates as $dateKey => $reservations) {
  4097.                     // Si el ID de la reserva está presente, obtener su dato
  4098.                     $datoId = isset($reservations[$id]) ? $reservations[$id] : 0;
  4099.                     foreach ($reservations as $reservationId => $dato) {
  4100.                         if ($reservationId != $id) {
  4101.                             if ($datoId === "Sala" && $dato === "Sala") {
  4102.                                 $arrayAlert[$reservationId][] = array('dateKey' => $dateKey'idLounge' => $idLounge'reservationId' => $reservationId);
  4103.                             } elseif (($datoId === "Montaje" || $datoId === "Desmontaje") && ($dato === "Montaje" || $dato === "Desmontaje")) {
  4104.                                 $arrayAlertMontDesmont[$reservationId][] = array('dateKey' => $dateKey'idLounge' => $idLounge'reservationId' => $reservationId);
  4105.                             } elseif ($datoId === "Sala" && ($dato === "Montaje" || $dato === "Desmontaje")) {
  4106.                                 $arrayAlert[$reservationId][] = array('dateKey' => $dateKey'idLounge' => $idLounge'reservationId' => $reservationId);
  4107.                             } elseif (($datoId === "Montaje" || $datoId === "Desmontaje") && $dato === "Sala") {
  4108.                                 $arrayAlert[$reservationId][] = array('dateKey' => $dateKey'idLounge' => $idLounge'reservationId' => $reservationId);
  4109.                             }
  4110.                         }
  4111.                     }
  4112.                 }
  4113.             }
  4114.         }
  4115.         $reservationInDates = [];
  4116.         if (!empty($arrayAlert)){
  4117.             foreach ($arrayAlert as $key => $item){
  4118.                 $resvConf $em->getRepository(Reservation::class)->findOneById($key);
  4119.                 $reservationInDates[] = $resvConf;
  4120.             }
  4121.             // La reserva no puede pasar a confirmada
  4122.             $reserva->setStatus($initStatus);                       // $initStatus dejara el valor del status sin modificar
  4123.             $em->persist($reserva);
  4124.             $em->flush();
  4125.         } else {
  4126.             $mensajeWarning '<br>';
  4127.             if (!empty($arrayAlertMontDesmont)){
  4128.                 foreach ($arrayAlertMontDesmont as $key => $item){
  4129.                     $mensajeWarning .= 'Reserva ID: '$key'<br>';
  4130.                 }
  4131.                 $this->addFlash('mensajereservationerror''ADVERTENCIA, se han guardado los cambios, pero hay coincidencias en los Montajes y/o Desmontajes'$mensajeWarning);
  4132.                 $reservationInDates = [];
  4133.             }
  4134.         }
  4135.         return $reservationInDates;
  4136.     }
  4137.     private function disponibilidadAvExpress($id){
  4138.         // $id Id de la reserva de GreenPatio que vamos a confirmar
  4139.         $em $this->getDoctrine()->getManager();
  4140.         $reserva $em->getRepository(Reservation::class)->findOneById($id);
  4141.         //Sumamos un dia ya que por solicitud de Salva deseamos saber que eventos hay un dia antes y un dia despues
  4142.         $fechaInicio = new \Datetime($reserva->getDateStart()->format('Y-m-d'));
  4143.         $fechaInicio->sub(new \DateInterval("P1D"));
  4144.         $fechaFin = new \Datetime($reserva->getDateEnd()->format('Y-m-d 23:59'));
  4145.         $fechaFin->add(new \DateInterval("P1D"));
  4146.         $parameters = array( 'dateStart' => $fechaInicio'dateEnd' => $fechaFin, );
  4147.         $dql 'SELECT i
  4148.                 FROM AvexpressBundle:AveFiles i
  4149.                 WHERE (i.dateStart <= i.dateEnd) 
  4150.                   AND (
  4151.                       (i.dateStart <= :dateStart AND i.dateEnd >= :dateEnd)
  4152.                       OR (i.dateEnd = :dateStart)
  4153.                       OR (i.dateEnd > :dateStart AND i.dateEnd <= :dateEnd)
  4154.                       OR (i.dateStart = :dateStart)
  4155.                       OR (i.dateStart > :dateStart AND i.dateStart <= :dateEnd)
  4156.                       OR (i.dateStart = :dateEnd)
  4157.                   )
  4158.                 ORDER BY i.dateStart ASC';
  4159.         $query $em->createQuery($dql)->setParameters($parameters);
  4160.         $avFilesInDates $query->getResult();
  4161.         return $avFilesInDates;
  4162.     }
  4163.     private function sendMailLot($mailAddressFrom$mailArrayTo$mailSubject$mailBody){
  4164.         $em $this->getDoctrine()->getManager();
  4165.         $agent $em->getRepository(User::class)->findOneByEmail($mailAddressFrom);
  4166.         $replyTo = array();
  4167.         // Verificamos que los correos sean validos
  4168.         foreach ($mailArrayTo as $item){ if (filter_var($item,FILTER_VALIDATE_EMAIL)){ $replyTo[$item] = $item; } }
  4169.         $agentMail $mailAddressFrom;
  4170.         $mailAgent $agentMail;
  4171.         //Se prepara el correo con los agentes a notificar
  4172.         $firmGmail $agent->getFirmGmail();
  4173.         $data = array( 'body' => $mailBody'firm' => $firmGmail, );
  4174.         // EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
  4175.         $transporter = new \Swift_SmtpTransport();
  4176.         $transporter->setHost('smtp.gmail.com')
  4177.             ->setEncryption('ssl')//ssl / tls
  4178.             ->setPort(465)// 465 / 587
  4179.             ->setUsername('desarrollo@develup.solutions')
  4180.             ->setPassword('utvh hzoi wfdo ztjs');
  4181. //            ->setPassword('MeDITeRRANeAN_Develup30102023#');
  4182.         $mailer = new \Swift_Mailer($transporter);
  4183.         $message = new \Swift_Message();
  4184.         $message->setSubject($mailSubject)
  4185.             ->setSender($agentMail)
  4186.             ->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
  4187.             ->setReplyTo($agentMail)
  4188.             ->setTo($replyTo)
  4189.             ->setBody(
  4190.                 $this->renderView(
  4191.                     'mail/structure-mail.html.twig',
  4192.                     array('data' => $data)
  4193.                 ),
  4194.                 'text/html'
  4195.             );
  4196.         $mailer->send($message);
  4197.         return true;
  4198.     }
  4199.     private function notificacionReservasPorCotizar(){
  4200.         // Se buscan las reservas en estado "Iniciado" y se notifica a todos los
  4201.         // agentes de Green Patio, Solo se notifica 1 vez por dia
  4202.         // Solo se mantendran las alertas de los ultimos 6 meses
  4203.         $em $this->getDoctrine()->getManager();
  4204.         $alertas $em->getRepository(ReservationAlertStarted::class)->findAll();
  4205.         if (!empty($alertas)){ $ultimaAlerta end($alertas); } else { $ultimaAlerta null; }
  4206.         $alertas $em->getRepository(ReservationAlertStarted::class)->findAll();
  4207.         $agentesGreenPatio $em->getRepository(User::class)->findByUserrol(48);
  4208.         $hoy = new DateTime('now');
  4209.         $fechaLimite = new DateTime('now');
  4210.         $fechaLimite->modify('-180 day');
  4211.         if (!empty($ultimaAlerta)){ $mismaFecha $ultimaAlerta->getAlertDate()->format('Ymd') == $hoy->format('Ymd'); } else { $mismaFecha false; }
  4212.         if ($mismaFecha){
  4213.             // No se debe notificar, la ultima alerta es del dia de hoy
  4214.         } else {
  4215.             // Hay que notificar
  4216.             if (empty($agentesGreenPatio)){ return true; }
  4217.             $mailAddressFrom $agentesGreenPatio[0]->getEmail();
  4218.             $mailArrayTo = array();
  4219.             foreach ($agentesGreenPatio as $agente){
  4220.                 $mailArrayTo[$agente->getEmail()] = $agente->getEmail();
  4221.             }
  4222.             $mailSubject 'EXPENDIENTES POR COTIZAR';
  4223.             $reservasIniciado $em->getRepository(Reservation::class)->findByStatus('Iniciado');
  4224.             $mailBody null;
  4225.             foreach ($reservasIniciado as $reserva){
  4226.                 $agenteReserva $em->getRepository(User::class)->findOneById($reserva->getCreatedBy());
  4227.                 $agenteReserva $agenteReserva->getName().' '.$agenteReserva->getLastName();
  4228.                 $mailBody $mailBody'<br>Evento: '.$reserva->getId().'<br>Nombre del Evento: '.$reserva->getTitle().'<br>Agente: '.$agenteReserva.'<br>Enlace al Evento: <a href="https://inout.mante.solutions/reservations-greenpatio/editsimple/'.$reserva->getId().'">"IR AL EXPEDIENTE"</a><br><br>';
  4229.             }
  4230.             if (!empty($mailBody)){
  4231.                 $this->sendMailLot($mailAddressFrom$mailArrayTo$mailSubject$mailBody);
  4232.                 // Creamos la alerta del dia
  4233.                 $alertToday = new ReservationAlertStarted();
  4234.                 $alertToday->setAlertDate($hoy);
  4235.                 $alertToday->setMessage($mailBody);
  4236.                 $em->persist($alertToday);
  4237.                 $em->flush();
  4238.             }
  4239.         }
  4240.         // Eliminamos las alertas con mas de 6 meses de antiguedad
  4241.         foreach ($alertas as $alerta){
  4242.             if ($alerta->getAlertDate() < $fechaLimite){
  4243.                 $em->remove($alerta);
  4244.                 $em->flush();
  4245.             }
  4246.         }
  4247.         return true;
  4248.     }
  4249.     private function reordenarSalas$number$idLounge ){
  4250.         // number es el numero de la sala editada
  4251.         $em $this->getDoctrine()->getManager();
  4252.         $number--;
  4253.         $parameters = array( 'idLounge' => $idLounge'rankLounge' => $number, );
  4254.         $dql 'SELECT i
  4255.                 FROM GreenPatioBundle:ReservationLoungeDetails i
  4256.                 WHERE  i.rankLounge > :rankLounge AND i.id <> :idLounge';
  4257.         $query $em->createQuery($dql)->setParameters($parameters);
  4258.         $salasParaReordenar $query->getResult();
  4259.         foreach ($salasParaReordenar as $sala) {
  4260.             $sala->setRankLounge(($sala->getRankLounge() + 1));
  4261.             $em->persist($sala);
  4262.             $em->flush();
  4263.         }
  4264.         return empty($resInv);
  4265.     }
  4266.     private function laReservaEsConfirmable$id ){
  4267.         $confirmable false;
  4268.         // Una reserva se puede confirmar solo cuando tiene un deposito realizado
  4269.         $em $this->getDoctrine()->getManager();
  4270.         $depositos $em->getRepository(ReservationDeposit::class)->findBy(array('reservationId' => $id'isDone' => true));
  4271.         $depositos true;      // Rafa indica que este requisito no se usara por el momento 24/02/2025
  4272.         // Si la reserva no tiene ninguna sala asignada, no se puede pasar a confirmado
  4273.         $salas $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation' => $id));
  4274.         if (!empty($depositos) and !empty($salas)){ $confirmable true; }
  4275.         return $confirmable;
  4276.     }
  4277.     private function laReservaEsCotizable$id ){
  4278.         // Una reserva se puede cotizar solo cuando tiene al menos una sala agregada
  4279.         $em $this->getDoctrine()->getManager();
  4280.         $salas $em->getRepository(ReservationLoungeSimple::class)->findBy(array('idReservation' => $id));
  4281.         return true;            // Se pidio que siempre se sincronizara con Av
  4282.     }
  4283.     private function notificacionReservasPendientesDelSegundoDeposito(){
  4284.         // Se buscan las reservas con depositos y se notifica a todos los
  4285.         // agentes de Green Patio si no tienen el segundo deposito y faltan 30 días
  4286.         // o menos para el evento, Solo se notifica 1 vez por dia
  4287.         $em $this->getDoctrine()->getManager();
  4288.         $depositosHechos $em->getRepository(ReservationDeposit::class)->findByIsDone(true);
  4289.         $arrayDepositos = array();
  4290.         $arrayReservasPemdientesSegunDepositos = array();
  4291.         $today = new \Datetime('now');
  4292.         $todayPlusMonth = new \Datetime('+ 30 days');
  4293.         // Se agrupan los depositos por reservas
  4294.         foreach ($depositosHechos as $item){ $arrayDepositos[$item->getReservationId()][] = $item; }
  4295.         foreach ($arrayDepositos as $item){
  4296.             if (sizeof($item)<2){
  4297.                 // Solo nos interesan reservas con un deposito
  4298.                 $reserva $em->getRepository(Reservation::class)->findOneById($item[0]->getReservationId());
  4299.                 if ($reserva->getStatus() == 'Confirmed'){
  4300.                     // Solo nos interesan reservas confirmadas
  4301.                     if (($reserva->getDateStart() < $todayPlusMonth) and ($reserva->getDateStart()>$today)){
  4302.                      // Solo nos interesan reservas que inician en 30 dias
  4303.                         $arrayReservasPemdientesSegunDepositos[] = $reserva;
  4304.                     }
  4305.                 }
  4306.             }
  4307.         }
  4308.         $alertas $em->getRepository(ReservationAlertSecondDeposit::class)->findAll();
  4309.         if (!empty($alertas)){ $ultimaAlerta end($alertas); } else { $ultimaAlerta null; }
  4310.         $agentesGreenPatio $em->getRepository(User::class)->findByUserrol(48);
  4311.         $hoy = new DateTime('now');
  4312.         $fechaLimite = new DateTime('now');
  4313.         $fechaLimite->modify('-180 day');
  4314.         if (!empty($ultimaAlerta)){ $mismaFecha $ultimaAlerta->getAlertDate()->format('Ymd') == $hoy->format('Ymd'); } else { $mismaFecha false; }
  4315.         if ($mismaFecha){
  4316.             // No se debe notificar, la ultima alerta es del dia de hoy
  4317.         } else {
  4318.             // Hay que notificar
  4319.             if (empty($agentesGreenPatio)){ return true; }
  4320.             $mailAddressFrom $agentesGreenPatio[0]->getEmail();
  4321.             $mailArrayTo = array();
  4322.             foreach ($agentesGreenPatio as $agente){ $mailArrayTo[$agente->getEmail()] = $agente->getEmail(); }
  4323.             $mailSubject 'EXPENDIENTES CON DEPOSITOS PENDIENTES';
  4324.             $reservasIniciado $arrayReservasPemdientesSegunDepositos;
  4325.             $mailBody null;
  4326.             foreach ($reservasIniciado as $reserva){
  4327.                 $agenteReserva $em->getRepository(User::class)->findOneById($reserva->getCreatedBy());
  4328.                 $agenteReserva $agenteReserva->getName().' '.$agenteReserva->getLastName();
  4329.                 $mailBody $mailBody'<br>Evento: '.$reserva->getId().'<br>Nombre del Evento: '.$reserva->getTitle().'<br>Agente: '.$agenteReserva.'<br>Enlace al Evento: <a href="https://inout.mante.solutions/reservations-greenpatio/editsimple/'.$reserva->getId().'">"IR AL EXPEDIENTE"</a><br><br>';
  4330.             }
  4331.             if (!empty($mailBody)){
  4332.                 $this->sendMailLot($mailAddressFrom$mailArrayTo$mailSubject$mailBody);
  4333.                 // Creamos la alerta del dia
  4334.                 $alertToday = new ReservationAlertSecondDeposit();
  4335.                 $alertToday->setAlertDate($hoy);
  4336.                 $alertToday->setMessage($mailBody);
  4337.                 $em->persist($alertToday);
  4338.                 $em->flush();
  4339.             }
  4340.         }
  4341.         // Eliminamos las alertas con mas de 6 meses de antiguedad
  4342.         foreach ($alertas as $alerta){
  4343.             if ($alerta->getAlertDate() < $fechaLimite){
  4344.                 $em->remove($alerta);
  4345.                 $em->flush();
  4346.             }
  4347.         }
  4348.         return true;
  4349.     }
  4350. };