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

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