src/Controller/SegHomeOfficeController.php line 206

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\GHGestionTurno;
  4. use App\Entity\GHGrupoTrabajo;
  5. use App\Entity\ParHorario;
  6. use App\Entity\SegHomeOffice;
  7. use App\Form\SegHomeOfficeType;
  8. use App\Repository\SegHomeOfficeRepository;
  9. use DateTimeZone;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Security;
  17. use function PHPUnit\Framework\matches;
  18. use Dompdf\Dompdf;
  19. #[Route('/seg/home/office')]
  20. class SegHomeOfficeController extends AbstractController {
  21.     private $code 0;
  22.     private $msj "";
  23.     private $url "";
  24.     private $html "";
  25.     private $em null;
  26.     private $documentHandler null;
  27.     private $mailerCore null;
  28.     private $entityManager;
  29.     private $token;
  30.     public function __construct(\App\Services\DocumentHandler $documentHandler\App\Services\MailerCore $mailerCore\Doctrine\ORM\EntityManagerInterface $entityManagerSecurity $token) {
  31.         $this->em $entityManager;
  32.         $this->mailerCore $mailerCore;
  33.         $this->documentHandler $documentHandler;
  34.         $this->entityManager $entityManager;
  35.         $this->token $token;
  36.     }
  37.     #[Route('/'name'app_seg_home_office_index'methods: ['GET'])]
  38.     public function index(SegHomeOfficeRepository $segHomeOfficeRepository): Response {
  39.         $entities $segHomeOfficeRepository->getAllDia($this->getUser()->getPersona()->getId(), date('Y-m-d'));
  40.         return $this->render('seg_home_office/index.html.twig', [
  41.                     'entities' => $entities,
  42.         ]);
  43.     }
  44.     #[Route('/panel_control'name'app_seg_home_office_panel_control'methods: ['GET'])]
  45.     public function panelControl(SegHomeOfficeRepository $segHomeOfficeRepository): Response {
  46.         $entities $segHomeOfficeRepository->getUsuarioProceso($this->getUser()->getPersona()->getId(), date('Y-m-d'));
  47.         return $this->render('seg_home_office/panelControl.html.twig', [
  48.             'entities' => $entities,
  49.         ]);
  50.     }
  51.     #[Route('/panel_control/historicoGrupo'name'app_seg_home_office_panel_control_historico_grupo'methods: ['GET'])]
  52.     public function panelControlHistoricoGrupo(SegHomeOfficeRepository $segHomeOfficeRepository): Response {
  53.         $idGrupos = [];
  54.         foreach ($this->getUser()->getPersona()->getGrupoTrabajoJefe() as $grupo) {
  55.             $idGrupos[] = $grupo->getId();
  56.         }
  57.         // Consulta solo si hay al menos un grupo asociado
  58.         $entities = !empty($idGrupos)
  59.             ? $segHomeOfficeRepository->getHistoricoGrupo(date('Y-m-d'), $idGrupos)
  60.             : [];
  61.         return $this->render('seg_home_office/panelControlHistorico.html.twig', [
  62.                     'entities' => $entities,
  63.         ]);
  64.     }
  65.     function evaluarDiaConexion(GHGestionTurno $turnoSegHomeOffice $registro\DateTimeInterface $fecha): void
  66.     {
  67.         $dia = (int) $fecha->format('N'); // 1 = Lunes, ..., 6 = Sábado, 7 = Domingo (que no usas)
  68.         $tieneTurno = match ($dia) {
  69.             => (bool) $turno->isLunes(),
  70.             => (bool) $turno->isMartes(),
  71.             => (bool) $turno->isMiercoles(),
  72.             => (bool) $turno->isJueves(),
  73.             => (bool) $turno->isViernes(),
  74.             => (bool) $turno->isSabado(),
  75.             default => false,
  76.         };
  77.         if ($dia >= && $dia <= 6) {
  78.             if ($tieneTurno) {
  79.                 $registro->setDiaConexion('OK');
  80.             } else {
  81.                 $registro->setDiaConexion('DIA SIN H.O');
  82.             }
  83.         }
  84.     }
  85.     #[Route('/new'name'app_seg_home_office_new'methods: ['GET''POST'])]
  86.     public function new(Request $requestEntityManagerInterface $entityManager): Response {
  87.         $homeOfice $this->em->getRepository(SegHomeOffice::class)->findOneBy(['usuario' => $this->getUser()->getPersona()->getId(), 'finConexion' => null]);
  88.         $personaConGrupo $this->em->getRepository(GHGrupoTrabajo::class)->findByColaboradorId($this->getUser()->getPersona()->getId());
  89.         $personaConTurno $this->em->getRepository(GHGestionTurno::class)->findOneBy(['colaborador' => $this->getUser()->getPersona()->getId()]);
  90.         $cerrarSesionJs $request->query->get('cerrarSesionJs');
  91.         //si la persona no tiene grupo cierra la sesion despues de 10 min
  92.         if (!$personaConGrupo){
  93.             if ($cerrarSesionJs === '1') {
  94.                 return $this->redirectToRoute('app_logout');
  95.             }else{
  96.                 $this->addFlash('danger''No tienes un grupo asignado, por favor contacta a tu jefe de grupo.');;
  97.                 return $this->redirectToRoute('app_seg_home_office_index');
  98.             }
  99.         }
  100.         //ahora si la persona si tiene un grupo pero no un turno cierrre la sesion despues de 10 min
  101.             $fecha = new \DateTime('now', new DateTimeZone('America/Bogota'));
  102.             $dia = (int) $fecha->format('N');
  103.             $tieneTurno = match ($dia) {
  104.                 => (bool) $personaConTurno->isLunes(),
  105.                 => (bool) $personaConTurno->isMartes(),
  106.                 => (bool) $personaConTurno->isMiercoles(),
  107.                 => (bool) $personaConTurno->isJueves(),
  108.                 => (bool) $personaConTurno->isViernes(),
  109.                 => (bool) $personaConTurno->isSabado(),
  110.                 default => false,
  111.             };
  112.             if ($dia >= && $dia <= && !$tieneTurno) {
  113.                 if ($cerrarSesionJs === '1') {
  114.                     return $this->redirectToRoute('app_logout');
  115.                 }else{
  116.                     $this->addFlash('danger''No tienes turno el dia de hoy, por favor contacta a tu jefe de grupo.');
  117.                     return $this->redirectToRoute('app_seg_home_office_index');
  118.                 }
  119.             }
  120.         //ahora si si tengo un grupo y un turno
  121.         else {
  122.                 $session $request->getSession();
  123.                 //si ya me loguee con mi turno del dia y pasan 10 min me cierra el home office y me saca del sistema
  124.                 if ($homeOfice !== null && !$session->get('home_office_closed')) {
  125.                     $homeOfice->setFinConexion(new \DateTime('now', new DateTimeZone('America/Bogota')));
  126.                     $homeOfice->setTipoDesconexion(2);
  127.                     $homeOfice->setDiaConexion(null);
  128.                     $homeOfice->setNotificado(false);
  129.                     $inicioConexion $homeOfice->getInicioConexion();
  130.                     $finConexion $homeOfice->getFinConexion();
  131.                     $totalTiempo $inicioConexion->diff($finConexion);
  132.                     $homeOfice->setTiempoTotal($totalTiempo->format('%H:%i:%s'));
  133.                     $entityManager->persist($homeOfice);
  134.                     $entityManager->flush();
  135.                     $session->set('home_office_closed'true); // Evita redirección repetida
  136.                     $this->addFlash('success''Conexión finalizada correctamente');
  137.                     if ($cerrarSesionJs === '1') {
  138.                         return $this->redirectToRoute('app_logout');
  139.                     } else {
  140.                         return $this->redirectToRoute('app_seg_home_office_index');
  141.                     }
  142.                 }
  143.                 $session->remove('home_office_closed');
  144.                 $intervalo rand(3060);
  145.                 $segHomeOffice = new SegHomeOffice();
  146.                 $currentDateTime = new \DateTime('now', new DateTimeZone('America/Bogota'));
  147.                 $this->evaluarDiaConexion($personaConTurno$segHomeOffice, new \DateTime('now', new \DateTimeZone('America/Bogota')));
  148.                 if ($cerrarSesionJs === '1') {
  149.                     return $this->redirectToRoute('app_logout');
  150.                 }else{
  151.                     $segHomeOffice
  152.                         ->setUsuario($this->getUser()->getPersona())
  153.                         ->setCreateAt($currentDateTime)
  154.                         ->setCreateUser($this->getUser()->getUsername())
  155.                         ->setUpdateAt($currentDateTime)
  156.                         ->setUpdateUser($this->getUser()->getUsername())
  157.                         ->setInicioConexion($currentDateTime)
  158.                         ->sethorario($entityManager->getRepository(ParHorario::class)->find(4))
  159.                         ->setIntervalo($intervalo)
  160.                         ->setNotificado(false);
  161.                     $entityManager->persist($segHomeOffice);
  162.                     $entityManager->flush();
  163.                 }
  164.         }
  165.                 $this->addFlash('success''Conexión creada correctamente');
  166.                 return $this->redirectToRoute('app_seg_home_office_index');
  167.     }
  168.     #[Route('/validar_conexion'name'app_seg_home_office_validar_conexion'methods: ['POST'])]
  169.     public function validarConexion(Request $request): JsonResponse
  170.     {
  171.         $res = ['tipo' => null];
  172.         // Obtenemos conexiones activas para hoy
  173.         $valHomeOfice $this->em
  174.             ->getRepository(SegHomeOffice::class)
  175.             ->getConexionAct($this->getUser()->getPersona()->getId(), date('Y-m-d'));
  176.         if (count($valHomeOfice) > 0) {
  177.             $homeOfice $this->em
  178.                 ->getRepository(SegHomeOffice::class)
  179.                 ->findOneBy([
  180.                     'usuario'     => $this->getUser()->getPersona()->getId(),
  181.                     'finConexion' => null,
  182.                 ]);
  183.             if ($homeOfice) {
  184.                 $intervalo = (int) $homeOfice->getIntervalo();
  185.                 $fechaBase = clone $homeOfice->getUpdateAt();
  186.                 if ($intervalo 0) {
  187.                     $dif $fechaBase->add(
  188.                         new \DateInterval(sprintf('PT%dM'$intervalo))
  189.                     );
  190.                 } else {
  191.                     $dif $fechaBase;
  192.                 }
  193.                 $ahora      = new \DateTime('now', new \DateTimeZone('America/Bogota'));
  194.                 $tiempoDiff $dif->diff($ahora);
  195.                 if ($dif >= $ahora || $tiempoDiff-><= 10) {
  196.                     $res['tipo']    = 'activo';
  197.                     $res['inter']   = $intervalo;
  198.                     $res['validar'] = false;
  199.                 } else {
  200.                     $homeOfice->setFinConexion($ahora);
  201.                     $homeOfice->setTipoDesconexion(1);
  202.                     $this->em->persist($homeOfice);
  203.                     $this->em->flush();
  204.                     $res['validar'] = true;
  205.                     $res['msj']     = 'desconectado';
  206.                 }
  207.             } else {
  208.                 $res['tipo'] = 'desconectado';
  209.             }
  210.         } else {
  211.             $res['tipo'] = 'NA';
  212.         }
  213.         return new JsonResponse($res);
  214.     }
  215.     #[Route('/gestionar'name'app_seg_home_office_gestionar'methods: ['GET'])]
  216.     public function gestionar(Request $request): Response {
  217.         $homeOfice $this->em->getRepository(SegHomeOffice::class)->findOneBy(['usuario' => $this->getUser()->getPersona()->getId(), 'finConexion' => null]);
  218.         $res = [];
  219.         if ($homeOfice) {
  220.             $homeOfice->setUpdateAt(new \DateTime('now'));
  221.             $res['msj'] = 'Conexion actualizada';
  222.             $this->em->persist($homeOfice);
  223.             $this->em->flush();
  224.         } else {
  225.             $res['msj'] = 'Imposible continuar no hay registro de conexion';
  226.         }
  227.         return new Response(json_encode($res));
  228.     }
  229.     #[Route('/detalle/30_dias/{id}'name'app_seg_home_office_detalle')]
  230.     public function historicoDetalle(SegHomeOffice $homeOfficeSegHomeOfficeRepository $repo): Response
  231.     {
  232.         $idPersona $homeOffice->getUsuario()->getId();
  233.         $referencia $homeOffice->getUsuario()->getNombres();
  234.         $historico $repo->getHistoricoDias([$idPersona], 30);
  235.         return $this->render('seg_home_office/detalle.html.twig', [
  236.             'historico' => $historico,
  237.             'referencia' => $referencia,
  238.         ]);
  239.     }
  240.     #[Route('/detalle_reporte/30_dias/{id}'name'app_seg_home_office_reporte')]
  241.     public function ReporteDetalle(SegHomeOffice $homeOfficeSegHomeOfficeRepository $repo): Response
  242.     {
  243.         $idPersona $homeOffice->getUsuario()->getId();
  244.         $historico $repo->getHistoricoDias([$idPersona], 30);
  245.         $path $this->getParameter('kernel.project_dir') . '/public_html/assets/img/brand/logos-empresas.png';
  246.         $type pathinfo($pathPATHINFO_EXTENSION);
  247.         $data file_get_contents($path);
  248.         $base64 'data:image/' $type ';base64,' base64_encode($data);
  249.         $rutaLogo $base64;
  250.         $html $this->renderView('formatos/historicoConexiones.html.twig', ['logo' => $rutaLogo'historico' => $historico]);
  251.         $dompdf = new Dompdf();
  252.         //$customPaper = array(0, 0, 220, 130);
  253.         //$dompdf->setPaper($customPaper);
  254.         $dompdf->loadHtml($html);
  255.         $dompdf->render();
  256.         return new Response(
  257.             $dompdf->stream('resume', ["Attachment" => false]),
  258.             Response::HTTP_OK,
  259.             ['Content-Type' => 'application/pdf']
  260.         );
  261.     }
  262.     public function notificacionHomeOfficeDesconexion()
  263.     {
  264.         $ultimoRegistro $this->entityManager->getRepository(SegHomeOffice::class)->ultiomoRegistroUsuario();
  265.         $ahora = new \DateTime('now', new \DateTimeZone('America/Bogota'));
  266.         $diaSemana = (int) $ahora->format('N'); // 1 = Lunes, ..., 7 = Domingo
  267.         // Solo de lunes a sábado
  268.         if ($diaSemana >= && $diaSemana <= 6) {
  269.             foreach ($ultimoRegistro as $homeOfficePersona) {
  270.                 $horario $homeOfficePersona->getHorario();
  271.                 $horaDesconexion $homeOfficePersona->getFinConexion();
  272.                 $notficado $homeOfficePersona->isNotificado();
  273.                 if (!$horario || !$horaDesconexion || $homeOfficePersona->getDiaConexion() !== null) {
  274.                     continue;
  275.                 }
  276.                 // Crear las fechas de hoy con las horas del horario
  277.                 $inicioJornada \DateTime::createFromFormat(
  278.                     'Y-m-d H:i:s',
  279.                     $ahora->format('Y-m-d') . ' ' $horario->getHoraInicio(),
  280.                     new \DateTimeZone('America/Bogota')
  281.                 );
  282.                 $finJornada \DateTime::createFromFormat(
  283.                     'Y-m-d H:i:s',
  284.                     $ahora->format('Y-m-d') . ' ' $horario->getHoraFin(),
  285.                     new \DateTimeZone('America/Bogota')
  286.                 );
  287.                 if ($ahora >= $inicioJornada && $ahora <= $finJornada) {
  288.                     $diferencia $horaDesconexion->diff($ahora);
  289.                     $minutosPasados = ($diferencia->days 24 60) + ($diferencia->60) + $diferencia->i;
  290.                     if ($minutosPasados >= 120 && !$notficado) {
  291.                         $this->mailerCore->HomeOffice('notificarDesconexionJefe', [$homeOfficePersona]);
  292.                         $homeOfficePersona->setNotificado(true);
  293.                         $this->entityManager->persist($homeOfficePersona);
  294.                     }
  295.                 }
  296.             }
  297.             $this->entityManager->flush();
  298.         }
  299.     }
  300. }