src/Controller/DashboardController.php line 103

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\DTO\DashboardBuscarDto;
  4. use App\DTO\DashboardLocalizacionDto;
  5. use App\DTO\DashboardTemperaturaDto;
  6. use App\DTO\DashboardTemperaturaResultadoDto;
  7. use App\DTO\DTOTemperaturaGeneral;
  8. use App\DTO\DocumentoTributarioListarDto;
  9. use App\Form\DashboardBuscarFormType;
  10. use App\Form\DashboardDatosFormType;
  11. use App\Form\DashboardLocalizacionFormType;
  12. use App\Form\DashboardTemperaturaFormType;
  13. use App\Repository\BitacoraTemperaturaRepository;
  14. use App\Repository\ClienteRepository;
  15. use App\Repository\GeneradorTemperaturaRangoRepository;
  16. use App\Repository\MatrizTransitoRepository;
  17. use App\Repository\OrdenRepository;
  18. use App\Repository\RegionRepository;
  19. use App\Repository\RutaRepository;
  20. use App\Repository\TipoCargaRepository;
  21. use App\Repository\TipoEstadoOrdenRepository;
  22. use App\Repository\VehiculoRepository;
  23. use App\Repository\ViaTransporteRepository;
  24. use Doctrine\ORM\EntityManagerInterface;
  25. use Doctrine\Common\Collections\ArrayCollection;
  26. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  27. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\Routing\Annotation\Route;
  31. use Symfony\Component\HttpFoundation\JsonResponse;
  32. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  33. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  34. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  35. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  36. use Symfony\Component\Security\Core\Security;
  37. use App\Services\BaseOptimizadaHelper;
  38. use Psr\Log\LoggerInterface;
  39. class DashboardController extends AbstractController
  40. {
  41.     private $security;
  42.     private $entityManager;
  43.     private $session;
  44.     private $logger;
  45.     private $clienteRepository;
  46.     private $generadorTemperaturaRangoRepository;
  47.     private $matrizTransitoRepository;
  48.     private $ordenRepository;
  49.     private $regionRepository;
  50.     private $rutaRepository;
  51.     private $tipoCargaRepository;
  52.     private $tipoEstadoOrdenRepository;
  53.     private $vehiculoRepository;
  54.     private $viaTransporteRepository;
  55.     public function __construct(Security $securityEntityManagerInterface $entityManager
  56.         SessionInterface $session,
  57.         LoggerInterface $logger,
  58.         BitacoraTemperaturaRepository $bitacoraTemperaturaRepository
  59.         ClienteRepository $clienteRepository
  60.         GeneradorTemperaturaRangoRepository $generadorTemperaturaRangoRepository,
  61.         MatrizTransitoRepository $matrizTransitoRepository,
  62.         OrdenRepository $ordenRepository,
  63.         RegionRepository $regionRepository,
  64.         RutaRepository $rutaRepository,
  65.         TipoCargaRepository $tipoCargaRepository,
  66.         TipoEstadoOrdenRepository $tipoEstadoOrdenRepository,
  67.         VehiculoRepository $vehiculoRepository,
  68.         ViaTransporteRepository $viaTransporteRepository
  69.         )
  70.     {
  71.         date_default_timezone_set("America/Santiago");
  72.         $this->security $security;
  73.         $this->entityManager $entityManager;
  74.         $this->session $session;
  75.         $this->logger $logger;
  76.         $this->bitacoraTemperaturaRepository $bitacoraTemperaturaRepository;
  77.         $this->clienteRepository $clienteRepository;
  78.         $this->generadorTemperaturaRangoRepository $generadorTemperaturaRangoRepository;
  79.         $this->matrizTransitoRepository $matrizTransitoRepository;
  80.         $this->ordenRepository $ordenRepository;
  81.         $this->regionRepository $regionRepository;
  82.         $this->rutaRepository $rutaRepository;
  83.         $this->tipoCargaRepository $tipoCargaRepository;
  84.         $this->tipoEstadoOrdenRepository $tipoEstadoOrdenRepository;
  85.         $this->vehiculoRepository $vehiculoRepository;
  86.         $this->viaTransporteRepository $viaTransporteRepository;
  87.         if(!$this->session->isStarted()) //Starting the session if not done yet
  88.         {
  89.             $this->session->start();
  90.         }
  91.     }
  92.     /**
  93.      * @Route("/", name="app_admin_index")
  94.      * @IsGranted("ROLE_USER")
  95.      */
  96.     public function index(Request $request): Response
  97.     
  98.         try{
  99.             //return $this->render("admin/mantencion.html.twig");
  100.             return $this->render('admin/main.html.twig');
  101.         }
  102.         catch(\Exception $e){
  103.             $this->logger->error($e->getMessage(), [
  104.                 'exception' => $e,
  105.                 'trace'  => $e->getTraceAsString(), 
  106.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  107.                 'method' => $request->getMethod(), // GET, POST, etc.
  108.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  109.                 'params' => $request->request->all()
  110.             ]);
  111.             $this->addFlash('danger',$e->getMessage());
  112.             return $this->redirectToRoute('app_admin_index');
  113.         }        
  114.     }
  115.     /**
  116.      * @Route("/dashboard/", name="dashboard")
  117.      * @IsGranted("ROLE_USER")
  118.      */
  119.     public function dashboard(Request $request): Response
  120.     {
  121.         try
  122.         {
  123.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'null);
  124.             return $this->render('dashboard/index.html.twig');
  125.         }
  126.         catch(\Exception $e){
  127.             $this->logger->error($e->getMessage(), [
  128.                 'exception' => $e,
  129.                 'trace'  => $e->getTraceAsString(), 
  130.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  131.                 'method' => $request->getMethod(), // GET, POST, etc.
  132.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  133.                 'params' => $request->request->all()
  134.             ]);
  135.             $this->addFlash('danger',$e->getMessage());
  136.             return $this->redirectToRoute('app_admin_index');
  137.         }
  138.     }
  139.     /**
  140.      * @Route("/dashboard/inicial/", name="dashboard_inicial")
  141.      * @IsGranted("ROLE_USER")
  142.      */
  143.     public function dashboard_inicial(Request $request): Response
  144.     {
  145.         try
  146.         {
  147.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  148.             if(!$dto)
  149.             {
  150.                 $dto = new DashboardBuscarDto();
  151.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  152.                 $dto->fechaHasta = (new \DateTime('today'));
  153.             }
  154.             else
  155.             {
  156.                 if($dto->supermandante)
  157.                 {
  158.                     $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  159.                 }
  160.                 if($dto->cliente)
  161.                 {
  162.                     if(!is_array($dto->cliente))
  163.                     {
  164.                         $dto->cliente $this->entityManager->merge($dto->cliente); 
  165.                     }
  166.                     else
  167.                     {
  168.                         $posicion 0;
  169.                         foreach($dto->cliente as $item_cliente){
  170.                             $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  171.                             $posicion++;
  172.                         }
  173.                     }
  174.                 }
  175.                 else
  176.                 {
  177.                     $dto->cliente = array();
  178.                 }
  179.                 if($dto->clienteFinal)
  180.                 {
  181.                     if(!is_array($dto->clienteFinal))
  182.                     {
  183.                         $dto->clienteFinal $this->entityManager->merge($dto->clienteFinal); 
  184.                     }
  185.                     else
  186.                     {
  187.                         $posicion 0;
  188.                         foreach($dto->clienteFinal as $item_cliente){
  189.                             $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  190.                             $posicion++;
  191.                         }
  192.                     }
  193.                 }
  194.                 else
  195.                 {
  196.                     $dto->clienteFinal = array();
  197.                 }
  198.                 if($dto->tipoCarga)
  199.                 {
  200.                     $dto->tipoCarga $this->entityManager->merge($dto->tipoCarga); 
  201.                 }
  202.                 if($dto->region)
  203.                 {
  204.                     $dto->region $this->entityManager->merge($dto->region); 
  205.                 }
  206.                 if($dto->viaTransporte)
  207.                 {
  208.                     $dto->viaTransporte $this->entityManager->merge($dto->viaTransporte); 
  209.                 }
  210.                 
  211.             }
  212.             $form $this->createForm(DashboardBuscarFormType::class, $dto);
  213.             $form->handleRequest($request);
  214.             if ($form->isSubmitted() && $form->isValid()) {
  215.                 $dto->tipoCarga null;
  216.                 $dto->tipoEstadoOrden null;
  217.                 $dto->region null;
  218.                 $dto->viaTransporte null;
  219.             }
  220.             if($this->security->isGranted('ROLE_CLIENTE'))
  221.             {
  222.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  223.                 {
  224.                     $dto->cliente = array();
  225.                     $user $this->security->getUser();
  226.                     if (!$user) {
  227.                         throw new \LogicException('No se identifica el usuario actual');
  228.                     }
  229.                     foreach($user->getClientes() as $item_cliente)
  230.                     {
  231.                         $dto->cliente[] = $item_cliente;
  232.                     }
  233.                 }
  234.             }
  235.             if($this->security->isGranted('ROLE_TEVA'))
  236.             {
  237.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  238.                 {
  239.                     $dto->cliente = array();
  240.                     $clientes $this->clienteRepository->findBy(array('activo' => 1'integracionTeva' => 1), array());
  241.                     foreach($clientes as $item_cliente)
  242.                     {
  243.                         $dto->cliente[] = $item_cliente;
  244.                     }
  245.                 }
  246.             }
  247.             $cliente_final = array();
  248.             if($dto->clienteFinal)
  249.             {
  250.                 foreach($dto->clienteFinal as $item_cliente_final)
  251.                 {
  252.                     $cliente_final[] = $item_cliente_final;
  253.                 }
  254.             }
  255.             if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
  256.             {
  257.                 if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
  258.                 {
  259.                     $user $this->security->getUser();
  260.                     if (!$user) {
  261.                         throw new \LogicException('No se identifica el usuario actual');
  262.                     }
  263.                     $cliente_final $user->getClientesFinales();
  264.                 }
  265.             }
  266.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'$dto);
  267.             $lista $this->ordenRepository->findPorDashboardBuscarDto($dto$cliente_finalTRUE);
  268.             $resumen $this->dashboard_get_datos_resumen($dto$cliente_final);            
  269.             $regiones $this->ordenRepository->getDashboadRegiones($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  270.             $fechas $this->ordenRepository->getDashboadFechas($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  271.             
  272.             $dto_gd = new DocumentoTributarioListarDto();
  273.             $dto_gd->fechaSolicitudInicial $dto->fechaDesde;
  274.             $dto_gd->fechaSolicitudFinal $dto->fechaHasta;
  275.             $dto_gd->folio null;
  276.             $dto_gd->supermandante $dto->supermandante;
  277.             $dto_gd->cliente $dto->cliente;
  278.             $dto_gd->clienteFinal $cliente_final;
  279.             $dto_gd->estadoDocumentoTributario null;
  280.             $dto_gd->agencia null;
  281.             $dto_gd->tipoDocumentoGestionDocumental null;
  282.             $dto_gd->region $dto->region;
  283.             
  284.             $baseOptimizadaHelper = new BaseOptimizadaHelper();
  285.             $total_gd $baseOptimizadaHelper->getSpGestionDocumentalListTodosCount($dto_gd$cliente_final);
  286.                
  287.             return $this->render('dashboard/inicial.html.twig', array(
  288.                 'form' => $form->createView(),
  289.                 'filtros' => $dto->getFiltros(),
  290.                 'resumen' => $resumen,
  291.                 'regiones' => $regiones,
  292.                 'fechas' => $fechas,
  293.                 'lista' => $lista,
  294.                 'total_gd' => $total_gd['total']
  295.             ));
  296.         }
  297.         catch(\Exception $e){
  298.             $this->addFlash('danger',$e->getMessage());
  299.            return $this->redirectToRoute('app_admin_index');
  300.         }
  301.     }
  302.      /**
  303.      * @Route("/dashboard/seleccionar-tipo-estado-orden/",name="dashboard_seleccionar_tipo_estado_orden")
  304.      * @param Request $request
  305.      */
  306.     public function dashboard_seleccionar_tipo_estado_orden(Request $request)
  307.     {
  308.         try
  309.         {
  310.             $tipoEstadoOrdenId $request->query->get("tipo_estado_orden_id");
  311.             $tipoEstadoOrden $this->tipoEstadoOrdenRepository->findOneById($tipoEstadoOrdenId);
  312.             if(!$tipoEstadoOrden)
  313.             {
  314.                 $this->addFlash('danger','No se encuentra información de tipo de estado');
  315.                 return $this->redirectToRoute('dashboard_inicial');
  316.             }
  317.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  318.             if(!$dto)
  319.             {
  320.                 $dto = new DashboardBuscarDto();
  321.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  322.                 $dto->fechaHasta = (new \DateTime('today'));
  323.             }
  324.             else
  325.             {
  326.                 if($dto->supermandante)
  327.                 {
  328.                     $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  329.                 }
  330.                 if($dto->cliente)
  331.                 {
  332.                     $posicion 0;
  333.                     foreach($dto->cliente as $item_cliente){
  334.                         $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  335.                         $posicion++;
  336.                     }
  337.                 }
  338.                 if($dto->clienteFinal)
  339.                 {
  340.                     $posicion 0;
  341.                     foreach($dto->clienteFinal as $item_cliente){
  342.                         $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  343.                         $posicion++;
  344.                     }
  345.                 }
  346.             }
  347.             
  348.             $dto->tipoEstadoOrden $tipoEstadoOrdenId;
  349.             $dto->tipoEstadoOrdenNombre $tipoEstadoOrden->getNombre();
  350.             if($this->security->isGranted('ROLE_CLIENTE'))
  351.             {
  352.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  353.                 {
  354.                     $dto->cliente = array();
  355.                     $user $this->security->getUser();
  356.                     if (!$user) {
  357.                         throw new \LogicException('No se identifica el usuario actual');
  358.                     }
  359.                     foreach($user->getClientes() as $item_cliente)
  360.                     {
  361.                         $dto->cliente[] = $item_cliente;
  362.                     }
  363.                 }
  364.             }
  365.             if($this->security->isGranted('ROLE_TEVA'))
  366.             {
  367.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  368.                 {
  369.                     $dto->cliente = array();
  370.                     $clientes $this->clienteRepository->findBy(array('activo' => 1'integracionTeva' => 1), array());
  371.                     foreach($clientes as $item_cliente)
  372.                     {
  373.                         $dto->cliente[] = $item_cliente;
  374.                     }
  375.                 }
  376.             }
  377.             $cliente_final = array();
  378.             if($dto->clienteFinal)
  379.             {
  380.                 foreach($dto->clienteFinal as $item_cliente_final)
  381.                 {
  382.                     $cliente_final[] = $item_cliente_final;
  383.                 }
  384.             }
  385.             if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
  386.             {
  387.                 if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
  388.                 {
  389.                     $user $this->security->getUser();
  390.                     if (!$user) {
  391.                         throw new \LogicException('No se identifica el usuario actual');
  392.                     }
  393.                     $cliente_final $user->getClientesFinales();
  394.                 }
  395.             }
  396.             //$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
  397.             //return $this->redirectToRoute('dashboard_inicial');
  398.             $lista $this->ordenRepository->findPorDashboardBuscarDto($dto$cliente_finalTRUE);
  399.         
  400.             return $this->render('dashboard/tipo_estado_orden.html.twig', array(
  401.                 'lista' => $lista,
  402.             ));
  403.         }
  404.         catch(\Exception $e){
  405.             $this->logger->error($e->getMessage(), [
  406.                 'exception' => $e,
  407.                 'trace'  => $e->getTraceAsString(), 
  408.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  409.                 'method' => $request->getMethod(), // GET, POST, etc.
  410.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  411.                 'params' => $request->request->all()
  412.             ]);
  413.             $this->addFlash('danger',$e->getMessage());
  414.             return $this->redirectToRoute('dashboard_inicial');
  415.         }
  416.     }
  417.     
  418.     /**
  419.      * @Route("/dashboard/seleccionar-tipo-estado-orden/excel/", name="dashboard_seleccionar_tipo_estado_orden_excel")
  420.      * @IsGranted("ROLE_USER")
  421.      */
  422.     public function dashboard_seleccionar_tipo_estado_orden_excel(Request $request): Response
  423.     {
  424.         try{      
  425.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  426.             if(!$dto)
  427.             {
  428.                 $dto = new DashboardBuscarDto();
  429.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  430.                 $dto->fechaHasta = (new \DateTime('today'));
  431.             }
  432.             else
  433.             {
  434.                 if($dto->supermandante)
  435.                 {
  436.                     $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  437.                 }
  438.                 if($dto->cliente)
  439.                 {
  440.                     $posicion 0;
  441.                     foreach($dto->cliente as $item_cliente){
  442.                         $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  443.                         $posicion++;
  444.                     }
  445.                 }
  446.                 if($dto->clienteFinal)
  447.                 {
  448.                     $posicion 0;
  449.                     foreach($dto->clienteFinal as $item_cliente){
  450.                         $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  451.                         $posicion++;
  452.                     }
  453.                 }
  454.             }
  455.             if($this->security->isGranted('ROLE_CLIENTE'))
  456.             {
  457.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  458.                 {
  459.                     $dto->cliente = array();
  460.                     $user $this->security->getUser();
  461.                     if (!$user) {
  462.                         throw new \LogicException('No se identifica el usuario actual');
  463.                     }
  464.                     foreach($user->getClientes() as $item_cliente)
  465.                     {
  466.                         $dto->cliente[] = $item_cliente;
  467.                     }
  468.                 }
  469.             }
  470.             if($this->security->isGranted('ROLE_TEVA'))
  471.             {
  472.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  473.                 {
  474.                     $dto->cliente = array();
  475.                     $clientes $this->clienteRepository->findBy(array('activo' => 1'integracionTeva' => 1), array());
  476.                     foreach($clientes as $item_cliente)
  477.                     {
  478.                         $dto->cliente[] = $item_cliente;
  479.                     }
  480.                 }
  481.             }
  482.             $cliente_final = array();
  483.             if($dto->clienteFinal)
  484.             {
  485.                 foreach($dto->clienteFinal as $item_cliente_final)
  486.                 {
  487.                     $cliente_final[] = $item_cliente_final;
  488.                 }
  489.             }
  490.             if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
  491.             {
  492.                 if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
  493.                 {
  494.                     $user $this->security->getUser();
  495.                     if (!$user) {
  496.                         throw new \LogicException('No se identifica el usuario actual');
  497.                     }
  498.                     $cliente_final $user->getClientesFinales();
  499.                 }
  500.             }
  501.             $lista $this->ordenRepository->findPorDashboardBuscarDto($dto$cliente_finalTRUE);
  502.             if(!$lista)
  503.             {
  504.                 $this->addFlash("error"'No se encuentra ordenes coincidentes');
  505.             }
  506.             $ahora = new \DateTime('now');
  507.             $spreadsheet = new Spreadsheet();
  508.             /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  509.             $sheet $spreadsheet->getActiveSheet();
  510.             $sheet->setShowGridlines(false);
  511.             $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  512.             $drawing->setName('logo');
  513.             $drawing->setDescription('logo');
  514.             $drawing->setPath('media/logo_transfarma_verde.png'); // put your path and image here
  515.             $drawing->setCoordinates('A1');
  516.             $drawing->setWorksheet($sheet);
  517.             $sheet->setCellValue('A6''DASHBOARD');
  518.             $sheet->getStyle('A6')->getFont()->setBoldtrue );
  519.             $sheet->setCellValue('A7'$ahora->format('d-m-Y H:i'));
  520.             $sheet->mergeCells("A6:Q6"); 
  521.             $sheet->mergeCells("A7:Q7"); 
  522.                                 
  523.             $sheet->setCellValue('A9''Nro');
  524.             $sheet->setCellValue('B9''Codigo de Barra');
  525.             $sheet->setCellValue('C9''Fecha de Solicitud');
  526.             $sheet->setCellValue('D9''Estado');
  527.             $sheet->setCellValue('E9''Origen');
  528.             $sheet->setCellValue('F9''Destino');
  529.             $sheet->setCellValue('G9''Comuna');
  530.             $sheet->setCellValue('H9''Región');
  531.             $sheet->setCellValue('I9''Documento');
  532.             $sheet->setCellValue('J9''Orden de Compra');
  533.             $sheet->setCellValue('K9''Tipo de Servicio');
  534.             $sheet->setCellValue('L9''Tipo de Carga');
  535.             $sheet->setCellValue('M9''Tipo de Transporte');
  536.             $sheet->setCellValue('N9''Via de Transporte');
  537.             $sheet->setCellValue('O9''Requiere Cedible');
  538.             $sheet->setCellValue('P9''Seguro');
  539.             $sheet->setCellValue('Q9''Cenabast');
  540.             $sheet->setCellValue('R9''Muestra Médica');
  541.             $sheet->setCellValue('S9''Peso Fisico');
  542.             $sheet->setCellValue('T9''Peso Vol.');
  543.             $sheet->setCellValue('U9''Peso Max. (Transfarma)');
  544.             $sheet->setCellValue('V9''Bultos');
  545.             if(!$this->security->isGranted('ROLE_CLIENTE'))
  546.             {
  547.                 $sheet->setCellValue('W9''Kilos (Operador)');
  548.             }
  549.        
  550.             $fila 9;
  551.             $i 0;
  552.             foreach($lista as $item)
  553.             {
  554.                 $i++;
  555.                 $fila++;
  556.                 $sheet->setCellValue('A'.$fila$i);
  557.                 $sheet->setCellValue('B'.$fila$item->getCodigoBarra());
  558.                 $sheet->setCellValue('C'.$fila$item->getFechaSolicitud()->format('d-m-Y'));
  559.                 $sheet->setCellValue('D'.$fila$item->getEstadoOrden());
  560.                 $sheet->setCellValue('E'.$fila$item->getDireccionOrigen());
  561.                 $sheet->setCellValue('F'.$fila$item->getDireccionDestino());
  562.                 if($item->getDireccionDestino()->getComuna())
  563.                 {
  564.                     $sheet->setCellValue('G'.$fila$item->getDireccionDestino()->getComuna());
  565.                     if($item->getDireccionDestino()->getComuna()->getRegion())
  566.                     {
  567.                         $sheet->setCellValue('H'.$fila$item->getDireccionDestino()->getComuna()->getRegion());
  568.                     }
  569.                 }
  570.                 $sheet->setCellValue('I'.$fila$item->getTipoDocumento().' '.$item->getFolioTipoDocumento());
  571.                 $sheet->setCellValue('J'.$fila$item->getFolioOrdenCompra());
  572.                 $sheet->setCellValue('K'.$fila$item->getTipoServicio());
  573.                 $sheet->setCellValue('L'.$fila$item->getTipoCarga());
  574.                 $sheet->setCellValue('M'.$fila$item->getTipoTransporte());
  575.                 $sheet->setCellValue('N'.$fila$item->getViaTransporte());
  576.                 $sheet->setCellValue('O'.$fila$item->getRequiereCedible() ? 'SI' 'NO');
  577.                 $sheet->setCellValue('P'.$fila$item->getSeguro() ? 'SI' 'NO');
  578.                 $sheet->setCellValue('Q'.$fila$item->isCenabast() ? 'SI' 'NO');
  579.                 $sheet->setCellValue('R'.$fila$item->isMuestraMedica() ? 'SI' 'NO');
  580.                 $sheet->setCellValue('S'.$fila$item->getSumaPeso());
  581.                 $sheet->setCellValue('T'.$fila$item->getSumaPesoVol());
  582.                 $sheet->setCellValue('U'.$fila$item->getSumaPesoMax());
  583.                 $sheet->setCellValue('V'.$fila$item->getSumaBultos());
  584.                 if(!$this->security->isGranted('ROLE_CLIENTE'))
  585.                 {
  586.                     $sheet->setCellValue('W'.$fila$item->getUrbanoPeso());
  587.                 }
  588.             }
  589.             //$sheet->setAutoFilter($sheet->calculateWorksheetDimension());
  590.             $sheet->getColumnDimension('A')->setAutoSize(true);
  591.             $sheet->getColumnDimension('B')->setAutoSize(true);
  592.             $sheet->getColumnDimension('C')->setAutoSize(true);
  593.             $sheet->getColumnDimension('D')->setAutoSize(true);
  594.             $sheet->getColumnDimension('E')->setAutoSize(true);
  595.             $sheet->getColumnDimension('F')->setAutoSize(true);
  596.             $sheet->getColumnDimension('G')->setAutoSize(true);
  597.             $sheet->getColumnDimension('H')->setAutoSize(true);
  598.             $sheet->getColumnDimension('I')->setAutoSize(true);
  599.             $sheet->getColumnDimension('J')->setAutoSize(true);
  600.             $sheet->getColumnDimension('K')->setAutoSize(true);
  601.             $sheet->getColumnDimension('L')->setAutoSize(true);
  602.             $sheet->getColumnDimension('M')->setAutoSize(true);
  603.             $sheet->getColumnDimension('N')->setAutoSize(true);
  604.             $sheet->getColumnDimension('O')->setAutoSize(true);
  605.             $sheet->getColumnDimension('P')->setAutoSize(true);
  606.             $sheet->getColumnDimension('Q')->setAutoSize(true);
  607.             $sheet->getColumnDimension('R')->setAutoSize(true);
  608.             $sheet->getColumnDimension('S')->setAutoSize(true);
  609.             $sheet->getColumnDimension('T')->setAutoSize(true);
  610.             $sheet->getColumnDimension('U')->setAutoSize(true);
  611.             $sheet->getColumnDimension('V')->setAutoSize(true);
  612.             $sheet->getColumnDimension('W')->setAutoSize(true);
  613.             $sheet->getStyle('A9:W9')->getFont()->setBoldtrue );
  614.             $sheet->getStyle('A9:W9')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  615.             $sheet->getStyle('A9:W9')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FF426384');
  616.             // Create your Office 2007 Excel (XLSX Format)
  617.             $writer = new Xlsx($spreadsheet);
  618.             
  619.             // Create a Temporary file in the system
  620.             $fileName 'TRF-DASHBOARD-'.($ahora->format('Ymd-Hi')).'.xlsx';
  621.             $temp_file tempnam($this->getParameter('kernel.project_dir').'/temp/'$fileName);
  622.             
  623.             // Create the excel file in the tmp directory of the system
  624.             $writer->save($temp_file);
  625.             
  626.             // Return the excel file as an attachment
  627.             return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE);
  628.             
  629.         } catch(\Exception $e){
  630.             $this->logger->error($e->getMessage(), [
  631.                 'exception' => $e,
  632.                 'trace'  => $e->getTraceAsString(), 
  633.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  634.                 'method' => $request->getMethod(), // GET, POST, etc.
  635.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  636.                 'params' => $request->request->all()
  637.             ]);
  638.             $this->addFlash('danger',$e->getMessage());
  639.             return $this->redirectToRoute('app_admin_index');
  640.         }
  641.     }
  642.     private function dashboard_get_datos_resumen(DashboardBuscarDto $dto$cliente_final)
  643.     {
  644.         $resumen $this->ordenRepository->getDashboadResumen($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  645.         $envios_total 0;
  646.         $envios_entregados 0;
  647.         $envios_parciales 0;
  648.         $envios_error 0;
  649.         $envios_no_entregados 0;
  650.         $envios_devueltos 0;
  651.         $metricas_kilos_total 0;
  652.         $metricas_bultos_total 0;
  653.         $metricas_kilos_promedio 0;
  654.         $metricas_bultos_promedio 0;
  655.         $metricas_envios_promedio 0;
  656.         $sla_no_entregados 0;
  657.         $sla_entregados 0;
  658.         $sla_parciales 0;
  659.         $via_transporte_terrestre 0;
  660.         $via_transporte_aereo 0;
  661.         $kilos_transporte_terrestre 0;
  662.         $kilos_transporte_aereo 0;
  663.         $tipo_carga_ambiente 0;
  664.         $tipo_carga_refrigerado 0;
  665.         $tipo_carga_congelado 0;
  666.         $tipo_carga_temperatura_controlada 0;
  667.         $tiempo_entrega_promedio 0;
  668.         $tiempo_entrega_tipo_carga_ambiente 0;
  669.         $tiempo_entrega_tipo_carga_refrigerado 0;
  670.         $tiempo_entrega_tipo_carga_congelado 0;
  671.         $tiempo_entrega_tipo_carga_temperatura_controlada 0;
  672.         $total_documentos_tributarios 0;
  673.         if($resumen)
  674.         {
  675.             $envios_total $resumen["envios_total"];
  676.             $envios_entregados $resumen["envios_entregados"];
  677.             $envios_parciales $resumen["envios_parciales"];
  678.             $envios_error $resumen["envios_error"];
  679.             $envios_no_entregados $resumen["envios_no_entregados"];
  680.             $envios_devueltos $resumen["envios_devueltos"];
  681.             $metricas_kilos_total $resumen["metricas_kilos_total"];
  682.             $metricas_bultos_total $resumen["metricas_bultos_total"];
  683.             $metricas_kilos_promedio $resumen["metricas_kilos_promedio"];
  684.             $metricas_bultos_promedio $resumen["metricas_bultos_promedio"];
  685.             $metricas_envios_promedio $resumen["metricas_envios_promedio"];
  686.             $sla_no_entregados $resumen["sla_no_entregados"];
  687.             $sla_entregados $resumen["sla_entregados"];
  688.             $sla_parciales $resumen["sla_parciales"];
  689.             $via_transporte_terrestre $resumen["via_transporte_terrestre"];
  690.             $via_transporte_aereo $resumen["via_transporte_aereo"];
  691.             $kilos_transporte_terrestre $resumen["kilos_transporte_terrestre"];
  692.             $kilos_transporte_aereo $resumen["kilos_transporte_aereo"];
  693.             $tipo_carga_ambiente $resumen["tipo_carga_ambiente"];
  694.             $tipo_carga_refrigerado $resumen["tipo_carga_refrigerado"];
  695.             $tipo_carga_congelado $resumen["tipo_carga_congelado"];
  696.             $tipo_carga_temperatura_controlada $resumen["tipo_carga_temperatura_controlada"];
  697.             $tiempo_entrega_promedio $resumen["tiempo_entrega_promedio"];
  698.             $tiempo_entrega_tipo_carga_ambiente $resumen["tiempo_entrega_tipo_carga_ambiente"];
  699.             $tiempo_entrega_tipo_carga_refrigerado $resumen["tiempo_entrega_tipo_carga_refrigerado"];
  700.             $tiempo_entrega_tipo_carga_congelado $resumen["tiempo_entrega_tipo_carga_congelado"];
  701.             $tiempo_entrega_tipo_carga_temperatura_controlada $resumen["tiempo_entrega_tipo_carga_temperatura_controlada"];
  702.             $total_documentos_tributarios $resumen["total_documentos_tributarios"];
  703.         }
  704.         $tiempo_entrega_promedio_d 0;
  705.         $tiempo_entrega_promedio_h 0;
  706.         $tiempo_entrega_promedio_m 0;
  707.         $tiempo_entrega_tipo_carga_ambiente_d 0;
  708.         $tiempo_entrega_tipo_carga_ambiente_h 0;
  709.         $tiempo_entrega_tipo_carga_ambiente_m 0;
  710.         $tiempo_entrega_tipo_carga_refrigerado_d 0;
  711.         $tiempo_entrega_tipo_carga_refrigerado_h 0;
  712.         $tiempo_entrega_tipo_carga_refrigerado_m 0;
  713.         $tiempo_entrega_tipo_carga_congelado_d 0;
  714.         $tiempo_entrega_tipo_carga_congelado_h 0;
  715.         $tiempo_entrega_tipo_carga_congelado_m 0;
  716.         $tiempo_entrega_tipo_carga_temperatura_controlada_d 0;
  717.         $tiempo_entrega_tipo_carga_temperatura_controlada_h 0;
  718.         $tiempo_entrega_tipo_carga_temperatura_controlada_m 0;
  719.         if($tiempo_entrega_promedio)
  720.         {
  721.             $tiempo_entrega_promedio_d floor($tiempo_entrega_promedio 1440);
  722.             $tiempo_entrega_promedio_h floor(($tiempo_entrega_promedio - ($tiempo_entrega_promedio_d 1440)) / 60);
  723.             $tiempo_entrega_promedio_m = ($tiempo_entrega_promedio 60);
  724.         }
  725.         if($tiempo_entrega_tipo_carga_ambiente)
  726.         {
  727.             $tiempo_entrega_tipo_carga_ambiente_d floor($tiempo_entrega_tipo_carga_ambiente 1440);
  728.             $tiempo_entrega_tipo_carga_ambiente_h floor(($tiempo_entrega_tipo_carga_ambiente - ($tiempo_entrega_tipo_carga_ambiente_d 1440)) / 60);
  729.             $tiempo_entrega_tipo_carga_ambiente_m = ($tiempo_entrega_tipo_carga_ambiente 60);
  730.         }
  731.         if($tiempo_entrega_tipo_carga_refrigerado)
  732.         {
  733.             $tiempo_entrega_tipo_carga_refrigerado_d floor($tiempo_entrega_tipo_carga_refrigerado 1440);
  734.             $tiempo_entrega_tipo_carga_refrigerado_h floor(($tiempo_entrega_tipo_carga_refrigerado - ($tiempo_entrega_tipo_carga_refrigerado_d 1440)) / 60);
  735.             $tiempo_entrega_tipo_carga_refrigerado_m = ($tiempo_entrega_tipo_carga_refrigerado 60);
  736.         }
  737.         if($tiempo_entrega_tipo_carga_congelado)
  738.         {
  739.             $tiempo_entrega_tipo_carga_congelado_d floor($tiempo_entrega_tipo_carga_congelado 1440);
  740.             $tiempo_entrega_tipo_carga_congelado_h floor(($tiempo_entrega_tipo_carga_congelado - ($tiempo_entrega_tipo_carga_congelado_d 1440)) / 60);
  741.             $tiempo_entrega_tipo_carga_congelado_m = ($tiempo_entrega_tipo_carga_congelado 60);
  742.         }
  743.         if($tiempo_entrega_tipo_carga_temperatura_controlada)
  744.         {
  745.             $tiempo_entrega_tipo_carga_temperatura_controlada_d floor($tiempo_entrega_tipo_carga_temperatura_controlada 1440);
  746.             $tiempo_entrega_tipo_carga_temperatura_controlada_h floor(($tiempo_entrega_tipo_carga_temperatura_controlada - ($tiempo_entrega_tipo_carga_temperatura_controlada_d 1440)) / 60);
  747.             $tiempo_entrega_tipo_carga_temperatura_controlada_m = ($tiempo_entrega_tipo_carga_temperatura_controlada 60);
  748.         }
  749.         return array(
  750.             'envios_total' => $envios_total,
  751.             'envios_entregados' => $envios_entregados,
  752.             'envios_parciales' => $envios_parciales,
  753.             'envios_error' => $envios_error,
  754.             'envios_no_entregados' => $envios_no_entregados,
  755.             'envios_devueltos' => $envios_devueltos,
  756.             'metricas_kilos_total' => $metricas_kilos_total,
  757.             'metricas_bultos_total' => $metricas_bultos_total,
  758.             'metricas_kilos_promedio' => $metricas_kilos_promedio,
  759.             'metricas_bultos_promedio' => $metricas_bultos_promedio,
  760.             'metricas_envios_promedio' => $metricas_envios_promedio,
  761.             'sla_no_entregados' => $sla_no_entregados,
  762.             'sla_entregados' => $sla_entregados,
  763.             'sla_parciales' => $sla_parciales,
  764.             'via_transporte_terrestre' => $via_transporte_terrestre,
  765.             'via_transporte_aereo' => $via_transporte_aereo,
  766.             'kilos_transporte_terrestre' => $kilos_transporte_terrestre,
  767.             'kilos_transporte_aereo' => $kilos_transporte_aereo,
  768.             'tipo_carga_ambiente' => $tipo_carga_ambiente,
  769.             'tipo_carga_refrigerado' => $tipo_carga_refrigerado,
  770.             'tipo_carga_congelado' => $tipo_carga_congelado,
  771.             'tipo_carga_temperatura_controlada' => $tipo_carga_temperatura_controlada,
  772.             'tiempo_entrega_promedio_d' => $tiempo_entrega_promedio_d,
  773.             'tiempo_entrega_promedio_h' => $tiempo_entrega_promedio_h,
  774.             'tiempo_entrega_promedio_m' => $tiempo_entrega_promedio_m,
  775.             'tiempo_entrega_tipo_carga_ambiente_d' => $tiempo_entrega_tipo_carga_ambiente_d,
  776.             'tiempo_entrega_tipo_carga_ambiente_h' => $tiempo_entrega_tipo_carga_ambiente_h,
  777.             'tiempo_entrega_tipo_carga_ambiente_m' => $tiempo_entrega_tipo_carga_ambiente_m,
  778.             'tiempo_entrega_tipo_carga_refrigerado_d' => $tiempo_entrega_tipo_carga_refrigerado_d,
  779.             'tiempo_entrega_tipo_carga_refrigerado_h' => $tiempo_entrega_tipo_carga_refrigerado_h,
  780.             'tiempo_entrega_tipo_carga_refrigerado_m' => $tiempo_entrega_tipo_carga_refrigerado_m,
  781.             'tiempo_entrega_tipo_carga_congelado_d' => $tiempo_entrega_tipo_carga_congelado_d,
  782.             'tiempo_entrega_tipo_carga_congelado_h' => $tiempo_entrega_tipo_carga_congelado_h,
  783.             'tiempo_entrega_tipo_carga_congelado_m' => $tiempo_entrega_tipo_carga_congelado_m,
  784.             'tiempo_entrega_tipo_carga_temperatura_controlada_d' => $tiempo_entrega_tipo_carga_temperatura_controlada_d,
  785.             'tiempo_entrega_tipo_carga_temperatura_controlada_h' => $tiempo_entrega_tipo_carga_temperatura_controlada_h,
  786.             'tiempo_entrega_tipo_carga_temperatura_controlada_m' => $tiempo_entrega_tipo_carga_temperatura_controlada_m,
  787.             'total_documentos_tributarios' => $total_documentos_tributarios,
  788.         );
  789.     }
  790.     /**
  791.      * @Route("/dashboard/graficos/", name="dashboard_graficos")
  792.      * @IsGranted("ROLE_USER")
  793.      */
  794.     public function dashboard_graficos(Request $request): Response
  795.     {
  796.         try
  797.         {
  798.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  799.             if(!$dto)
  800.             {
  801.                 $dto = new DashboardBuscarDto();
  802.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  803.                 $dto->fechaHasta = (new \DateTime('today'));
  804.             }
  805.             else
  806.             {
  807.                 if($dto->supermandante)
  808.                 {
  809.                     $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  810.                 }
  811.                 if($dto->cliente)
  812.                 {
  813.                     $posicion 0;
  814.                     foreach($dto->cliente as $item_cliente){
  815.                         $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  816.                         $posicion++;
  817.                     }
  818.                 }
  819.                 if($dto->clienteFinal)
  820.                 {
  821.                     $posicion 0;
  822.                     foreach($dto->clienteFinal as $item_cliente){
  823.                         $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  824.                         $posicion++;
  825.                     }
  826.                 }
  827.             }
  828.             $form $this->createForm(DashboardBuscarFormType::class, $dto);
  829.             $form->handleRequest($request);
  830.             if ($form->isSubmitted() && $form->isValid()) {
  831.                 $dto->tipoCarga null;
  832.                 $dto->tipoEstadoOrden null;
  833.                 $dto->region null;
  834.                 $dto->viaTransporte null;
  835.             }
  836.             if($this->security->isGranted('ROLE_CLIENTE'))
  837.             {
  838.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  839.                 {
  840.                     $dto->cliente = array();
  841.                     $user $this->security->getUser();
  842.                     if (!$user) {
  843.                         throw new \LogicException('No se identifica el usuario actual');
  844.                     }
  845.                     foreach($user->getClientes() as $item_cliente)
  846.                     {
  847.                         $dto->cliente[] = $item_cliente;
  848.                     }
  849.                 }
  850.             }
  851.             if($this->security->isGranted('ROLE_TEVA'))
  852.             {
  853.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  854.                 {
  855.                     $dto->cliente = array();
  856.                     $clientes $this->clienteRepository->findBy(array('activo' => 1'integracionTeva' => 1), array());
  857.                     foreach($clientes as $item_cliente)
  858.                     {
  859.                         $dto->cliente[] = $item_cliente;
  860.                     }
  861.                 }
  862.             }
  863.             $cliente_final = array();
  864.             if($dto->clienteFinal)
  865.             {
  866.                 foreach($dto->clienteFinal as $item_cliente_final)
  867.                 {
  868.                     $cliente_final[] = $item_cliente_final;
  869.                 }
  870.             }
  871.             if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
  872.             {
  873.                 if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
  874.                 {
  875.                     $user $this->security->getUser();
  876.                     if (!$user) {
  877.                         throw new \LogicException('No se identifica el usuario actual');
  878.                     }
  879.                     $cliente_final $user->getClientesFinales();
  880.                 }
  881.             }
  882.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'$dto);
  883.             $resumen $this->dashboard_get_datos_resumen($dto$cliente_final);            
  884.             $estados_orden $this->ordenRepository->getDashboadEstadoOrden($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  885.             $fechas_temperaturas $this->ordenRepository->getDashboadFechasTemperaturas($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  886.             $tiempo_promedio_region $this->ordenRepository->getDashboadTiempoPromedioRegion($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  887.             $tiempo_promedio_ciudad $this->ordenRepository->getDashboadTiempoPromedioCiudad($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  888.             $resumen_dia $this->ordenRepository->getDashboadResumenDia($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  889.             $kilos_region $this->ordenRepository->getDashboadKilosRegion($dto->supermandante$dto->cliente$cliente_final$dto->fechaDesde$dto->fechaHasta$dto->tipoCarga$dto->tipoEstadoOrden$dto->region$dto->viaTransporte);
  890.             return $this->render('dashboard/graficos.html.twig', array(
  891.                 'form' => $form->createView(),
  892.                 'filtros' => $dto->getFiltros(),
  893.                 'resumen' => $resumen,
  894.                 'estados_orden' => $estados_orden,
  895.                 'fechas_temperaturas' => $fechas_temperaturas,
  896.                 'tiempo_promedio_region' => $tiempo_promedio_region,
  897.                 'tiempo_promedio_ciudad' => $tiempo_promedio_ciudad,
  898.                 'resumen_dia' => $resumen_dia,
  899.                 'kilos_region' => $kilos_region
  900.             ));
  901.         } catch(\Exception $e){
  902.             $this->logger->error($e->getMessage(), [
  903.                 'exception' => $e,
  904.                 'trace'  => $e->getTraceAsString(), 
  905.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  906.                 'method' => $request->getMethod(), // GET, POST, etc.
  907.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  908.                 'params' => $request->request->all()
  909.             ]);
  910.             $this->addFlash('danger',$e->getMessage());
  911.             return $this->redirectToRoute('app_admin_index');
  912.         }
  913.     }
  914.     /**
  915.      * @Route("/dashboard/datos/", name="dashboard_datos")
  916.      * @IsGranted("ROLE_USER")
  917.      */
  918.     public function dashboard_datos(Request $request)
  919.     {
  920.         try
  921.         {
  922.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'NULL);
  923.             return $this->dashboard_datos_page($request1);
  924.         }
  925.         catch(\Exception $e){
  926.             $this->logger->error($e->getMessage(), [
  927.                 'exception' => $e,
  928.                 'trace'  => $e->getTraceAsString(), 
  929.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  930.                 'method' => $request->getMethod(), // GET, POST, etc.
  931.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  932.                 'params' => $request->request->all()
  933.             ]);
  934.             $this->addFlash('danger',$e->getMessage());
  935.             return $this->redirectToRoute('app_admin_index');
  936.         }
  937.     }
  938.     /**
  939.      * @Route("/dashboard/datos/page/{currentPage}/", name="dashboard_datos_page")
  940.      * @IsGranted("ROLE_USER")
  941.      */
  942.     public function dashboard_datos_page(Request $request$currentPage 1): Response
  943.     {
  944.         try{
  945.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  946.             if(!$dto)
  947.             {
  948.                 $dto = new DashboardBuscarDto();
  949.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  950.                 $dto->fechaHasta = (new \DateTime('today'));
  951.             }
  952.             else
  953.             {
  954.                 if($dto->supermandante)
  955.                 {
  956.                     $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  957.                 }
  958.                 if($dto->estadoOrden)
  959.                 {
  960.                     $dto->estadoOrden $this->entityManager->merge($dto->estadoOrden); 
  961.                 }
  962.                 if($dto->tipoTransporte)
  963.                 {
  964.                     $dto->tipoTransporte $this->entityManager->merge($dto->tipoTransporte); 
  965.                 }
  966.                 if($dto->cliente)
  967.                 {
  968.                     $posicion 0;
  969.                     foreach($dto->cliente as $item_cliente){
  970.                         $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  971.                         $posicion++;
  972.                     }
  973.                 }
  974.                 if($dto->clienteFinal)
  975.                 {
  976.                     $posicion 0;
  977.                     foreach($dto->clienteFinal as $item_cliente){
  978.                         $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  979.                         $posicion++;
  980.                     }
  981.                 }
  982.             }
  983.             $form $this->createForm(DashboardDatosFormType::class, $dto);
  984.             $form->handleRequest($request);
  985.             if ($form->isSubmitted() && $form->isValid()) {
  986.                 $dto->tipoCarga null;
  987.                 $dto->tipoEstadoOrden null;
  988.                 $dto->region null;
  989.                 $dto->viaTransporte null;
  990.             }
  991.             if($this->security->isGranted('ROLE_CLIENTE'))
  992.             {
  993.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  994.                 {
  995.                     $dto->cliente = array();
  996.                     $user $this->security->getUser();
  997.                     if (!$user) {
  998.                         throw new \LogicException('No se identifica el usuario actual');
  999.                     }
  1000.                     foreach($user->getClientes() as $item_cliente)
  1001.                     {
  1002.                         $dto->cliente[] = $item_cliente;
  1003.                     }
  1004.                 }
  1005.             }
  1006.             if($this->security->isGranted('ROLE_TEVA'))
  1007.             {
  1008.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  1009.                 {
  1010.                     $dto->cliente = array();
  1011.                     $clientes $this->clienteRepository->findBy(array('activo' => 1'integracionTeva' => 1), array());
  1012.                     foreach($clientes as $item_cliente)
  1013.                     {
  1014.                         $dto->cliente[] = $item_cliente;
  1015.                     }
  1016.                 }
  1017.             }
  1018.             $cliente_final = array();
  1019.             if($dto->clienteFinal)
  1020.             {
  1021.                 foreach($dto->clienteFinal as $item_cliente_final)
  1022.                 {
  1023.                     $cliente_final[] = $item_cliente_final;
  1024.                 }
  1025.             }
  1026.             if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
  1027.             {
  1028.                 if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
  1029.                 {
  1030.                     $user $this->security->getUser();
  1031.                     if (!$user) {
  1032.                         throw new \LogicException('No se identifica el usuario actual');
  1033.                     }
  1034.                     $cliente_final $user->getClientesFinales();
  1035.                 }
  1036.             }
  1037.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'$dto);
  1038.             //$lista = $this->ordenRepository->getOrdenesPorDashboardBuscarDto($dto, $cliente_final);
  1039.             $limit 100;
  1040.             $total $this->ordenRepository->countOrdenesPorDashboardBuscarDto($dto$cliente_final);
  1041.             $lista $this->ordenRepository->getOrdenesPorDashboardBuscarDto($dto$cliente_final$currentPage$limit);
  1042.             $maxPages ceil($total['total'] / $limit);
  1043.             if(!$lista)
  1044.             {
  1045.                 $this->addFlash("error"'No se encuentra ordenes coincidentes');
  1046.             }
  1047.             return $this->render('dashboard/datos.html.twig', array(
  1048.                 'form' => $form->createView(),
  1049.                 'lista' => $lista,
  1050.                 'thisPage' => $currentPage,
  1051.                 'maxPages' => $maxPages,
  1052.                 'total' => $total['total'],
  1053.             ));
  1054.         }
  1055.         catch(\Exception $e){
  1056.             $this->logger->error($e->getMessage(), [
  1057.                 'exception' => $e,
  1058.                 'trace'  => $e->getTraceAsString(), 
  1059.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  1060.                 'method' => $request->getMethod(), // GET, POST, etc.
  1061.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  1062.                 'params' => $request->request->all()
  1063.             ]);
  1064.             $this->addFlash('danger',$e->getMessage());
  1065.             return $this->redirectToRoute('app_admin_index');
  1066.         }
  1067.     }
  1068.    
  1069.     /**
  1070.      * @Route("/dashboard/datos/excel/", name="dashboard_datos_excel")
  1071.      * @IsGranted("ROLE_USER")
  1072.      */
  1073.     public function dashboard_datos_excel(Request $request): Response
  1074.     {
  1075.         try{
  1076.             set_time_limit(0);
  1077.             
  1078.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  1079.             if(!$dto)
  1080.             {
  1081.                 $dto = new DashboardBuscarDto();
  1082.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  1083.                 $dto->fechaHasta = (new \DateTime('today'));
  1084.             }
  1085.             else
  1086.             {
  1087.                 if($dto->supermandante)
  1088.                 {
  1089.                     $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  1090.                 }
  1091.                 if($dto->estadoOrden)
  1092.                 {
  1093.                     $dto->estadoOrden $this->entityManager->merge($dto->estadoOrden); 
  1094.                 }
  1095.                 if($dto->tipoTransporte)
  1096.                 {
  1097.                     $dto->tipoTransporte $this->entityManager->merge($dto->tipoTransporte); 
  1098.                 }
  1099.                 if($dto->cliente)
  1100.                 {
  1101.                     $posicion 0;
  1102.                     foreach($dto->cliente as $item_cliente){
  1103.                         $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  1104.                         $posicion++;
  1105.                     }
  1106.                 }
  1107.                 if($dto->clienteFinal)
  1108.                 {
  1109.                     $posicion 0;
  1110.                     foreach($dto->clienteFinal as $item_cliente){
  1111.                         $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  1112.                         $posicion++;
  1113.                     }
  1114.                 }
  1115.             }
  1116.             if($this->security->isGranted('ROLE_CLIENTE'))
  1117.             {
  1118.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  1119.                 {
  1120.                     $dto->cliente = array();
  1121.                     $user $this->security->getUser();
  1122.                     if (!$user) {
  1123.                         throw new \LogicException('No se identifica el usuario actual');
  1124.                     }
  1125.                     foreach($user->getClientes() as $item_cliente)
  1126.                     {
  1127.                         $dto->cliente[] = $item_cliente;
  1128.                     }
  1129.                 }
  1130.             }
  1131.             if($this->security->isGranted('ROLE_TEVA'))
  1132.             {
  1133.                 if(!$dto->cliente || sizeof($dto->cliente) == 0)
  1134.                 {
  1135.                     $dto->cliente = array();
  1136.                     $clientes $this->clienteRepository->findBy(array('activo' => 1'integracionTeva' => 1), array());
  1137.                     foreach($clientes as $item_cliente)
  1138.                     {
  1139.                         $dto->cliente[] = $item_cliente;
  1140.                     }
  1141.                 }
  1142.             }
  1143.             
  1144.             $cliente_final = array();
  1145.             if($dto->clienteFinal)
  1146.             {
  1147.                 foreach($dto->clienteFinal as $item_cliente_final)
  1148.                 {
  1149.                     $cliente_final[] = $item_cliente_final;
  1150.                 }
  1151.             }
  1152.             if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
  1153.             {
  1154.                 if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
  1155.                 {
  1156.                     $user $this->security->getUser();
  1157.                     if (!$user) {
  1158.                         throw new \LogicException('No se identifica el usuario actual');
  1159.                     }
  1160.                     $cliente_final $user->getClientesFinales();
  1161.                 }
  1162.             }
  1163.             
  1164.             $lista $this->ordenRepository->getOrdenesPorDashboardBuscarDtoAll($dto$cliente_final);
  1165.             if(!$lista)
  1166.             {
  1167.                 $this->addFlash("error"'No se encuentra ordenes coincidentes');
  1168.             }
  1169.             $ahora = new \DateTime('now');
  1170.             $esTransfarma   $this->security->isGranted('ROLE_TRANSFARMA');
  1171.             $esMandante     $this->security->isGranted('ROLE_CLIENTE');
  1172.             $esClienteFinal $this->security->isGranted('ROLE_CLIENTE_FINAL');
  1173.             $ocultarPesos = ($esMandante || $esClienteFinal);
  1174.             $spreadsheet = new Spreadsheet();
  1175.             /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  1176.             $sheet $spreadsheet->getActiveSheet();
  1177.             $sheet->setShowGridlines(false);
  1178.             $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  1179.             $drawing->setName('logo');
  1180.             $drawing->setDescription('logo');
  1181.             $drawing->setPath('media/logo_transfarma_verde.png'); // put your path and image here
  1182.             $drawing->setCoordinates('A1');
  1183.             $drawing->setWorksheet($sheet);
  1184.             $sheet->setCellValue('A6''DASHBOARD');
  1185.             $sheet->getStyle('A6')->getFont()->setBoldtrue );
  1186.             $sheet->setCellValue('A7'$ahora->format('d-m-Y H:i'));
  1187.             $sheet->mergeCells("A6:Z6"); 
  1188.             $sheet->mergeCells("A7:Z7"); 
  1189.                                 
  1190.             $sheet->setCellValue('A9''Nro');
  1191.             $sheet->setCellValue('B9''Codigo de Barra');
  1192.             $sheet->setCellValue('C9''Fecha de Solicitud');
  1193.             $sheet->setCellValue('D9''Mandante');
  1194.             $sheet->setCellValue('E9''Cliente');
  1195.             $sheet->setCellValue('F9''Estado');
  1196.             $sheet->setCellValue('G9''Origen');
  1197.             $sheet->setCellValue('H9''Ciudad de Origen');
  1198.             $sheet->setCellValue('I9''Destino');
  1199.             $sheet->setCellValue('J9''Dirección');
  1200.             $sheet->setCellValue('K9''Comuna');
  1201.             $sheet->setCellValue('L9''Región');
  1202.             $sheet->setCellValue('M9''Zona');
  1203.             $sheet->setCellValue('N9''Base de Cobertura');
  1204.             $sheet->setCellValue('O9''Documento');
  1205.             $sheet->setCellValue('P9''Nº Doc');
  1206.             $sheet->setCellValue('Q9''Orden de Compra');
  1207.             $sheet->setCellValue('R9''Tipo de Servicio');
  1208.             $sheet->setCellValue('S9''Tipo de Carga');
  1209.             $sheet->setCellValue('T9''Tipo de Transporte');
  1210.             $sheet->setCellValue('U9''Via de Transporte');
  1211.             $sheet->setCellValue('V9''Requiere Cedible');
  1212.             $sheet->setCellValue('W9''Seguro');
  1213.             $sheet->setCellValue('X9''Cenabast');
  1214.             $sheet->setCellValue('Y9''Muestra Médica');
  1215.             $sheet->setCellValue('Z9''Bultos');
  1216.             if (!$ocultarPesos) {
  1217.                 $sheet->setCellValue('AA9''Peso Kilos');
  1218.                 $sheet->setCellValue('AB9''Peso Vol.');
  1219.             }
  1220.             $sheet->setCellValue('AC9''Nombre Receptor');
  1221.             $sheet->setCellValue('AD9''RUT Receptor');
  1222.             $sheet->setCellValue('AE9''Fecha Recepcion');
  1223.             $sheet->setCellValue('AF9''Fecha Ruta');
  1224.             if($this->security->isGranted('ROLE_TRANSFARMA'))
  1225.             {
  1226.                 $sheet->setCellValue('AG9''Patente Ruta');
  1227.             }
  1228.             $sheet->setCellValue('AH9''Tramo Vehiculo');
  1229.             $sheet->setCellValue('AI9''Tiempo Transcurrido (hrs)');
  1230.             $sheet->setCellValue('AJ9''Lead Time MT (Hrs)');
  1231.             $sheet->setCellValue('AK9''OTIF (ON TIME)');
  1232.             $sheet->setCellValue('AL9''Bultos (cantidad PK Solicitados)');
  1233.             $sheet->setCellValue('AM9''Bultos (cantidad PK recibidos)');
  1234.             $sheet->setCellValue('AN9''OTIF (IN FULL)');
  1235.             $sheet->setCellValue('AO9''Clasificación OTIF');
  1236.             $sheet->setCellValue('AP9''Clasificación Compliance OTIF');
  1237.             
  1238.            // Peso Max lo ve Transfarma + Mandante + Cliente Final
  1239.             if ($esTransfarma || $ocultarPesos) {
  1240.                 $sheet->setCellValue('AQ9''Peso Max. (Transfarma)');
  1241.             }
  1242.             // Estas columnas SOLO Transfarma
  1243.             if ($esTransfarma) {
  1244.                 $sheet->setCellValue('AR9''Codigo de Delivery');
  1245.                 $sheet->setCellValue('AS9''Código Reversa');
  1246.                 $sheet->setCellValue('AT9''Estado');
  1247.                 $sheet->setCellValue('AU9''Subestado');
  1248.                 $sheet->setCellValue('AV9''Codigo Data Logger');
  1249.                 $sheet->setCellValue('AW9''Codigo Vacutec');
  1250.                 $sheet->setCellValue('AX9''Manifiesto Ruta asignado');
  1251.             }
  1252.             
  1253.             $fila 9;
  1254.             $i 0;
  1255.             foreach($lista as $item)
  1256.             {
  1257.                 $i++;
  1258.                 $fila++;
  1259.                 $sheet->setCellValue('A'.$fila$i);
  1260.                 $sheet->setCellValue('B'.$fila$item["codigo_barra"]);
  1261.                 $sheet->setCellValue('C'.$fila, (new \DateTime($item["fecha_solicitud"]))->format('d-m-Y'));
  1262.                 $sheet->setCellValue('D'.$fila$item["nombre_cliente"]);
  1263.                 $sheet->setCellValue('E'.$fila$item["nombre_cliente_final"]);
  1264.                 $sheet->setCellValue('F'.$fila$item["nombre_estado"]);
  1265.                 $sheet->setCellValue('G'.$fila$item["nombre_direccion_origen"]);
  1266.                 $sheet->setCellValue('H'.$fila$item["ciudad_direccion_origen"]);
  1267.                 $sheet->setCellValue('I'.$fila$item["nombre_direccion_destino"]);
  1268.                 $sheet->setCellValue('J'.$fila$item["direccion"]);
  1269.                 $sheet->setCellValue('K'.$fila$item["nombre_comuna"]);
  1270.                 $sheet->setCellValue('L'.$fila$item["nombre_region"]);
  1271.                 $sheet->setCellValue('M'.$fila$item["nombre_zona"]);
  1272.                 $sheet->setCellValue('N'.$fila$item["nombre_sucursal"]);
  1273.                 
  1274.                 $documentos '';
  1275.                 if($item['tipo_documento_01'])
  1276.                 {
  1277.                     $documentos $documentos.$item['tipo_documento_01'].' '.$item['folio_tipo_documento_01'].' ';
  1278.                     if($item['copia_tipo_documento01'])
  1279.                     {
  1280.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento01'].') ';
  1281.                     }
  1282.                 }
  1283.                 if($item['tipo_documento_02'])
  1284.                 {
  1285.                     $documentos $documentos.$item['tipo_documento_02'].' '.$item['folio_tipo_documento_02'].' ';
  1286.                     if($item['copia_tipo_documento02'])
  1287.                     {
  1288.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento02'].') ';
  1289.                     }
  1290.                 }
  1291.                 if($item['tipo_documento_03'])
  1292.                 {
  1293.                     $documentos $documentos.$item['tipo_documento_03'].' '.$item['folio_tipo_documento_03'].' ';
  1294.                     if($item['copia_tipo_documento03'])
  1295.                     {
  1296.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento03'].') ';
  1297.                     }
  1298.                 }
  1299.                 if($item['tipo_documento_04'])
  1300.                 {
  1301.                     $documentos $documentos.$item['tipo_documento_04'].' '.$item['folio_tipo_documento_04'].' ';
  1302.                     if($item['copia_tipo_documento04'])
  1303.                     {
  1304.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento04'].') ';
  1305.                     }
  1306.                 }
  1307.                 if($item['tipo_documento_05'])
  1308.                 {
  1309.                     $documentos $documentos.$item['tipo_documento_05'].' '.$item['folio_tipo_documento_05'].' ';
  1310.                     if($item['copia_tipo_documento05'])
  1311.                     {
  1312.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento05'].') ';
  1313.                     }
  1314.                 }
  1315.                 if($item['tipo_documento_06'])
  1316.                 {
  1317.                     $documentos $documentos.$item['tipo_documento_06'].' '.$item['folio_tipo_documento_06'].' ';
  1318.                     if($item['copia_tipo_documento06'])
  1319.                     {
  1320.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento06'].') ';
  1321.                     }
  1322.                 }
  1323.                 if($item['tipo_documento_07'])
  1324.                 {
  1325.                     $documentos $documentos.$item['tipo_documento_07'].' '.$item['folio_tipo_documento_07'].' ';
  1326.                     if($item['copia_tipo_documento07'])
  1327.                     {
  1328.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento07'].') ';
  1329.                     }
  1330.                 }
  1331.                 if($item['tipo_documento_08'])
  1332.                 {
  1333.                     $documentos $documentos.$item['tipo_documento_08'].' '.$item['folio_tipo_documento_08'].' ';
  1334.                     if($item['copia_tipo_documento08'])
  1335.                     {
  1336.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento08'].') ';
  1337.                     }
  1338.                 }
  1339.                 if($item['tipo_documento_09'])
  1340.                 {
  1341.                     $documentos $documentos.$item['tipo_documento_09'].' '.$item['folio_tipo_documento_09'].' ';
  1342.                     if($item['copia_tipo_documento09'])
  1343.                     {
  1344.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento09'].') ';
  1345.                     }
  1346.                 }
  1347.                 if($item['tipo_documento_10'])
  1348.                 {
  1349.                     $documentos $documentos.$item['tipo_documento_10'].' '.$item['folio_tipo_documento_10'].' ';
  1350.                     if($item['copia_tipo_documento10'])
  1351.                     {
  1352.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento10'].') ';
  1353.                     }
  1354.                 }
  1355.                 if($item['tipo_documento_11'])
  1356.                 {
  1357.                     $documentos $documentos.$item['tipo_documento_11'].' '.$item['folio_tipo_documento_11'].' ';
  1358.                     if($item['copia_tipo_documento11'])
  1359.                     {
  1360.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento11'].') ';
  1361.                     }
  1362.                 }
  1363.                 if($item['tipo_documento_12'])
  1364.                 {
  1365.                     $documentos $documentos.$item['tipo_documento_12'].' '.$item['folio_tipo_documento_12'].' ';
  1366.                     if($item['copia_tipo_documento12'])
  1367.                     {
  1368.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento12'].') ';
  1369.                     }
  1370.                 }
  1371.                 if($item['tipo_documento_13'])
  1372.                 {
  1373.                     $documentos $documentos.$item['tipo_documento_13'].' '.$item['folio_tipo_documento_13'].' ';
  1374.                     if($item['copia_tipo_documento13'])
  1375.                     {
  1376.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento13'].') ';
  1377.                     }
  1378.                 }
  1379.                 if($item['tipo_documento_14'])
  1380.                 {
  1381.                     $documentos $documentos.$item['tipo_documento_14'].' '.$item['folio_tipo_documento_14'].' ';
  1382.                     if($item['copia_tipo_documento14'])
  1383.                     {
  1384.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento14'].') ';
  1385.                     }
  1386.                 }
  1387.                 if($item['tipo_documento_15'])
  1388.                 {
  1389.                     $documentos $documentos.$item['tipo_documento_15'].' '.$item['folio_tipo_documento_15'].' ';
  1390.                     if($item['copia_tipo_documento15'])
  1391.                     {
  1392.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento15'].') ';
  1393.                     }
  1394.                 }
  1395.                 if($item['tipo_documento_16'])
  1396.                 {
  1397.                     $documentos $documentos.$item['tipo_documento_16'].' '.$item['folio_tipo_documento_16'].' ';
  1398.                     if($item['copia_tipo_documento16'])
  1399.                     {
  1400.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento16'].') ';
  1401.                     }
  1402.                 }
  1403.                 if($item['tipo_documento_17'])
  1404.                 {
  1405.                     $documentos $documentos.$item['tipo_documento_17'].' '.$item['folio_tipo_documento_17'].' ';
  1406.                     if($item['copia_tipo_documento17'])
  1407.                     {
  1408.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento17'].') ';
  1409.                     }
  1410.                 }
  1411.                 if($item['tipo_documento_18'])
  1412.                 {
  1413.                     $documentos $documentos.$item['tipo_documento_18'].' '.$item['folio_tipo_documento_18'].' ';
  1414.                     if($item['copia_tipo_documento18'])
  1415.                     {
  1416.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento18'].') ';
  1417.                     }
  1418.                 }
  1419.                 if($item['tipo_documento_19'])
  1420.                 {
  1421.                     $documentos $documentos.$item['tipo_documento_19'].' '.$item['folio_tipo_documento_19'].' ';
  1422.                     if($item['copia_tipo_documento19'])
  1423.                     {
  1424.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento19'].') ';
  1425.                     }
  1426.                 }
  1427.                 if($item['tipo_documento_20'])
  1428.                 {
  1429.                     $documentos $documentos.$item['tipo_documento_20'].' '.$item['folio_tipo_documento_20'].' ';
  1430.                     if($item['copia_tipo_documento20'])
  1431.                     {
  1432.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento20'].') ';
  1433.                     }
  1434.                 }
  1435.                 if($item['tipo_documento_21'])
  1436.                 {
  1437.                     $documentos $documentos.$item['tipo_documento_21'].' '.$item['folio_tipo_documento_21'].' ';
  1438.                     if($item['copia_tipo_documento21'])
  1439.                     {
  1440.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento21'].') ';
  1441.                     }
  1442.                 }
  1443.                 if($item['tipo_documento_22'])
  1444.                 {
  1445.                     $documentos $documentos.$item['tipo_documento_22'].' '.$item['folio_tipo_documento_22'].' ';
  1446.                     if($item['copia_tipo_documento22'])
  1447.                     {
  1448.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento22'].') ';
  1449.                     }
  1450.                 }
  1451.                 if($item['tipo_documento_23'])
  1452.                 {
  1453.                     $documentos $documentos.$item['tipo_documento_23'].' '.$item['folio_tipo_documento_23'].' ';
  1454.                     if($item['copia_tipo_documento23'])
  1455.                     {
  1456.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento23'].') ';
  1457.                     }
  1458.                 }
  1459.                 if($item['tipo_documento_24'])
  1460.                 {
  1461.                     $documentos $documentos.$item['tipo_documento_24'].' '.$item['folio_tipo_documento_24'].' ';
  1462.                     if($item['copia_tipo_documento24'])
  1463.                     {
  1464.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento24'].') ';
  1465.                     }
  1466.                 }
  1467.                 if($item['tipo_documento_25'])
  1468.                 {
  1469.                     $documentos $documentos.$item['tipo_documento_25'].' '.$item['folio_tipo_documento_25'].' ';
  1470.                     if($item['copia_tipo_documento25'])
  1471.                     {
  1472.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento25'].') ';
  1473.                     }
  1474.                 }
  1475.                 if($item['tipo_documento_26'])
  1476.                 {
  1477.                     $documentos $documentos.$item['tipo_documento_26'].' '.$item['folio_tipo_documento_26'].' ';
  1478.                     if($item['copia_tipo_documento26'])
  1479.                     {
  1480.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento26'].') ';
  1481.                     }
  1482.                 }
  1483.                 if($item['tipo_documento_27'])
  1484.                 {
  1485.                     $documentos $documentos.$item['tipo_documento_27'].' '.$item['folio_tipo_documento_27'].' ';
  1486.                     if($item['copia_tipo_documento27'])
  1487.                     {
  1488.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento27'].') ';
  1489.                     }
  1490.                 }
  1491.                 if($item['tipo_documento_28'])
  1492.                 {
  1493.                     $documentos $documentos.$item['tipo_documento_28'].' '.$item['folio_tipo_documento_28'].' ';
  1494.                     if($item['copia_tipo_documento28'])
  1495.                     {
  1496.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento28'].') ';
  1497.                     }
  1498.                 }
  1499.                 if($item['tipo_documento_29'])
  1500.                 {
  1501.                     $documentos $documentos.$item['tipo_documento_29'].' '.$item['folio_tipo_documento_29'].' ';
  1502.                     if($item['copia_tipo_documento29'])
  1503.                     {
  1504.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento29'].') ';
  1505.                     }
  1506.                 }
  1507.                 if($item['tipo_documento_30'])
  1508.                 {
  1509.                     $documentos $documentos.$item['tipo_documento_30'].' '.$item['folio_tipo_documento_30'].' ';
  1510.                     if($item['copia_tipo_documento30'])
  1511.                     {
  1512.                         $documentos $documentos.' (Copia '.$item['copia_tipo_documento30'].') ';
  1513.                     }
  1514.                 }
  1515.                
  1516.                 $sheet->setCellValue('O'.$fila$documentos);
  1517.                 
  1518.                 $sheet->setCellValue('P'.$fila$item["suma_documentos"]);
  1519.                 $sheet->setCellValue('Q'.$fila$item["folio_orden_compra"]);
  1520.                 $sheet->setCellValue('R'.$fila$item["nombre_tipo_servicio"]);
  1521.                 $sheet->setCellValue('S'.$fila$item["nombre_tipo_carga"]);
  1522.                 $sheet->setCellValue('T'.$fila$item["nombre_tipo_transporte"]);
  1523.                 $sheet->setCellValue('U'.$fila$item["nombre_via_transporte"]);
  1524.                 $sheet->setCellValue('V'.$fila$item["requiere_cedible"] ? 'SI' 'NO');
  1525.                 $sheet->setCellValue('W'.$fila$item["seguro"] ? 'SI' 'NO');
  1526.                 $sheet->setCellValue('X'.$fila$item["cenabast"] ? 'SI' 'NO');
  1527.                 $sheet->setCellValue('Y'.$fila$item["muestra_medica"] ? 'SI' 'NO');
  1528.                 $sheet->setCellValue('Z'.$fila$item["suma_bultos"]);
  1529.                 if (!$ocultarPesos) {
  1530.                     $sheet->setCellValue('AA'.$fila$item["suma_peso_kilos"]);
  1531.                     $sheet->setCellValue('AB'.$fila$item["suma_peso_vol"]);
  1532.                 }
  1533.                 $sheet->setCellValue('AC'.$fila$item["nombre_entrega"]);
  1534.                 $sheet->setCellValue('AD'.$fila$item["rut_entrega"]);
  1535.                 if($item["fecha_entrega"])
  1536.                 {
  1537.                     $sheet->setCellValue('AE'.$fila, (new \DateTime($item["fecha_entrega"]))->format('d-m-Y'));
  1538.                 }
  1539.                 if($item["fecha_ruta"])
  1540.                 {
  1541.                     $sheet->setCellValue('AF'.$fila, (new \DateTime($item["fecha_ruta"]))->format('d-m-Y'));
  1542.                 }
  1543.                 if($this->security->isGranted('ROLE_TRANSFARMA'))
  1544.                 {
  1545.                     $sheet->setCellValue('AG'.$fila$item["vehiculo_patente"].$item["urbano_patente"]);
  1546.                 }             
  1547.                 $sheet->setCellValue('AH'.$fila$item["tramo_vehiculo"]);                
  1548.                 $sheet->setCellValue('AI'.$fila$item["tiempo_transcurrido"]);                
  1549.                 $sheet->setCellValue('AJ'.$fila$item["lead_time_cliente"]);                
  1550.                 $sheet->setCellValue('AK'.$fila$item["otif_cliente"]);                
  1551.                 $sheet->setCellValue('AL'.$fila$item["cantidad_bultos_solicitados"]);                
  1552.                 $sheet->setCellValue('AM'.$fila$item["cantidad_bultos_recibidos"]);                
  1553.                 $sheet->setCellValue('AN'.$fila$item["otif_in_full"]);                
  1554.                 $sheet->setCellValue('AO'.$fila$item["otif_cliente"].' - '.$item["otif_in_full"]);                
  1555.                 $sheet->setCellValue('AP'.$fila$item["compliance_cliente"]);                
  1556.                 
  1557.               if ($esTransfarma || $ocultarPesos) {
  1558.                     $sheet->setCellValue('AQ'.$fila$item["suma_kilos"]);
  1559.                 }
  1560.                   if ($esTransfarma) {
  1561.                 $sheet->setCellValue('AR'.$fila$item["codigo_delivery"].' '.$item["dhl_guia"].' '.$item["extern_order_key"]);
  1562.                 $sheet->setCellValue('AS'.$fila$item["codigo_barra_logistica_inversa"]);
  1563.                 $sheet->setCellValue('AT'.$fila$item["nombre_estado"]);
  1564.                 $sheet->setCellValue('AU'.$fila$item["nombre_subestado"]);
  1565.                 $sheet->setCellValue('AV'.$fila$item["codigo_data_logger"]);
  1566.                 $sheet->setCellValue('AW'.$fila$item["codigo_vacutec"]);
  1567.                 $sheet->setCellValue('AX'.$fila$item["codigo_manifiesto"]);
  1568.             }
  1569.                 
  1570.             }
  1571.             //$sheet->setAutoFilter($sheet->calculateWorksheetDimension());
  1572.          
  1573.             
  1574.            if ($esTransfarma) {
  1575.                     $ultimaColumna 'AX';
  1576.                 } elseif ($ocultarPesos) {
  1577.                     $ultimaColumna 'AQ';
  1578.                 } else {
  1579.                     $ultimaColumna 'AP';
  1580.                 }
  1581.                 $sheet->getStyle('A9:'.$ultimaColumna.'9')->getFont()->setBold(true);
  1582.                 $sheet->getStyle('A9:'.$ultimaColumna.'9')->getFont()->getColor()
  1583.                     ->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  1584.                 $sheet->getStyle('A9:'.$ultimaColumna.'9')->getFill()
  1585.                     ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1586.                     ->getStartColor()->setARGB('FF426384');
  1587.                     
  1588.             // Create your Office 2007 Excel (XLSX Format)
  1589.             $writer = new Xlsx($spreadsheet);
  1590.             
  1591.             // Create a Temporary file in the system
  1592.             $fileName 'TRF-DASHBOARD-'.($ahora->format('Ymd-Hi')).'.xlsx';
  1593.             
  1594.             $temp_file tempnam($this->getParameter('kernel.project_dir').'/temp/'$fileName);
  1595.             
  1596.             // Create the excel file in the tmp directory of the system
  1597.             $writer->save($temp_file);
  1598.             
  1599.             // Return the excel file as an attachment
  1600.             return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE);
  1601.             
  1602.         } catch(\Exception $e){
  1603.             $this->logger->error($e->getMessage(), [
  1604.                 'exception' => $e,
  1605.                 'trace'  => $e->getTraceAsString(), 
  1606.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  1607.                 'method' => $request->getMethod(), // GET, POST, etc.
  1608.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  1609.                 'params' => $request->request->all()
  1610.             ]);
  1611.             $this->addFlash('danger',$e->getMessage());
  1612.             return $this->redirectToRoute('app_admin_index');
  1613.         }
  1614.     }
  1615.     /**
  1616.      * @Route("/dashboard/seleccionar-region/",name="dashboard_seleccionar_region")
  1617.      * @param Request $request
  1618.      */
  1619.     public function dashboard_seleccionar_region(Request $request)
  1620.     {
  1621.         try
  1622.         {
  1623.             $regionNombre $request->query->get("region_nombre");
  1624.             $region $this->regionRepository->findOneByNombre($regionNombre);
  1625.             if(!$region)
  1626.             {
  1627.                 $this->addFlash('danger','No se encuentra información de región');
  1628.                 return $this->redirectToRoute('dashboard_inicial');
  1629.             }
  1630.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  1631.             if(!$dto)
  1632.             {
  1633.                 $dto = new DashboardBuscarDto();
  1634.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  1635.                 $dto->fechaHasta = (new \DateTime('today'));
  1636.             }
  1637.             else
  1638.             {
  1639.                 if($dto->supermandante)
  1640.                     {
  1641.                         $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  1642.                     }
  1643.                 if($dto->cliente)
  1644.                     {
  1645.                         $posicion 0;
  1646.                         foreach($dto->cliente as $item_cliente){
  1647.                             $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  1648.                             $posicion++;
  1649.                         }
  1650.                     }
  1651.                 if($dto->clienteFinal)
  1652.                     {
  1653.                         $posicion 0;
  1654.                         foreach($dto->clienteFinal as $item_cliente){
  1655.                             $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  1656.                             $posicion++;
  1657.                         }
  1658.                     }
  1659.             }
  1660.             $dto->region $region;
  1661.             $dto->regionNombre $region->getNombre();
  1662.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'$dto);
  1663.             return $this->redirectToRoute('dashboard_inicial');
  1664.         }
  1665.         catch(\Exception $e){
  1666.             $this->logger->error($e->getMessage(), [
  1667.                 'exception' => $e,
  1668.                 'trace'  => $e->getTraceAsString(), 
  1669.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  1670.                 'method' => $request->getMethod(), // GET, POST, etc.
  1671.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  1672.                 'params' => $request->request->all()
  1673.             ]);
  1674.             $this->addFlash('danger',$e->getMessage());
  1675.             return $this->redirectToRoute('dashboard_inicial');
  1676.         }
  1677.     }
  1678.     /**
  1679.      * @Route("/dashboard/seleccionar-tipo-carga/",name="dashboard_seleccionar_tipo_carga")
  1680.      * @param Request $request
  1681.      */
  1682.     public function dashboard_seleccionar_tipo_carga(Request $request)
  1683.     {
  1684.         try
  1685.         {
  1686.             $tipoCargaId $request->query->get("tipo_carga_id");
  1687.             $tipoCarga $this->tipoCargaRepository->findOneById($tipoCargaId);
  1688.             if(!$tipoCarga)
  1689.             {
  1690.                 $this->addFlash('danger','No se encuentra información de tipo de carga');
  1691.                 return $this->redirectToRoute('dashboard_inicial');
  1692.             }
  1693.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  1694.             if(!$dto)
  1695.             {
  1696.                 $dto = new DashboardBuscarDto();
  1697.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  1698.                 $dto->fechaHasta = (new \DateTime('today'));
  1699.             }
  1700.             else
  1701.             {
  1702.                 if($dto->supermandante)
  1703.                     {
  1704.                         $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  1705.                     }
  1706.                 if($dto->cliente)
  1707.                 {
  1708.                     $posicion 0;
  1709.                     foreach($dto->cliente as $item_cliente){
  1710.                         $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  1711.                         $posicion++;
  1712.                     }
  1713.                 }
  1714.                 if($dto->clienteFinal)
  1715.                 {
  1716.                     $posicion 0;
  1717.                     foreach($dto->clienteFinal as $item_cliente){
  1718.                         $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  1719.                         $posicion++;
  1720.                     }
  1721.                 }
  1722.             }
  1723.             $dto->tipoCarga $tipoCargaId;
  1724.             $dto->tipoCargaNombre $tipoCarga->getNombre();
  1725.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'$dto);
  1726.             return $this->redirectToRoute('dashboard_inicial');
  1727.         }
  1728.         catch(\Exception $e){
  1729.             $this->logger->error($e->getMessage(), [
  1730.                 'exception' => $e,
  1731.                 'trace'  => $e->getTraceAsString(), 
  1732.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  1733.                 'method' => $request->getMethod(), // GET, POST, etc.
  1734.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  1735.                 'params' => $request->request->all()
  1736.             ]);
  1737.             $this->addFlash('danger',$e->getMessage());
  1738.             return $this->redirectToRoute('dashboard_inicial');
  1739.         }
  1740.     }
  1741.     /**
  1742.      * @Route("/dashboard/seleccionar-via-transporte/",name="dashboard_seleccionar_via_transporte")
  1743.      * @param Request $request
  1744.      */
  1745.     public function dashboard_seleccionar_via_transporte(Request $request)
  1746.     {
  1747.         try
  1748.         {
  1749.             $viaTransporteId $request->query->get("via_transporte_id");
  1750.             $viaTransporte $this->viaTransporteRepository->findOneById($viaTransporteId);
  1751.             if(!$viaTransporte)
  1752.             {
  1753.                 $this->addFlash('danger','No se encuentra información de via de transporte');
  1754.                 return $this->redirectToRoute('dashboard_inicial');
  1755.             }
  1756.             $dto $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
  1757.             if(!$dto)
  1758.             {
  1759.                 $dto = new DashboardBuscarDto();
  1760.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  1761.                 $dto->fechaHasta = (new \DateTime('today'));
  1762.             }
  1763.             else
  1764.             {
  1765.                 if($dto->supermandante)
  1766.                     {
  1767.                         $dto->supermandante $this->entityManager->merge($dto->supermandante); 
  1768.                     }
  1769.                 if($dto->cliente)
  1770.                     {
  1771.                         $posicion 0;
  1772.                         foreach($dto->cliente as $item_cliente){
  1773.                             $dto->cliente[$posicion] = $this->entityManager->merge($item_cliente); 
  1774.                             $posicion++;
  1775.                         }
  1776.                     }
  1777.                 if($dto->clienteFinal)
  1778.                     {
  1779.                         $posicion 0;
  1780.                         foreach($dto->clienteFinal as $item_cliente){
  1781.                             $dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente); 
  1782.                             $posicion++;
  1783.                         }
  1784.                     }
  1785.             }
  1786.             $dto->viaTransporte $viaTransporteId;
  1787.             $dto->viaTransporteNombre $viaTransporte->getNombre();
  1788.             $this->session->set('SESION_DASHBOARD_BUSCAR_DTO'$dto);
  1789.             return $this->redirectToRoute('dashboard_inicial');
  1790.         }
  1791.         catch(\Exception $e){
  1792.             $this->logger->error($e->getMessage(), [
  1793.                 'exception' => $e,
  1794.                 'trace'  => $e->getTraceAsString(), 
  1795.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  1796.                 'method' => $request->getMethod(), // GET, POST, etc.
  1797.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  1798.                 'params' => $request->request->all()
  1799.             ]);
  1800.             $this->addFlash('danger',$e->getMessage());
  1801.             return $this->redirectToRoute('dashboard_inicial');
  1802.         }
  1803.     }
  1804.     /**
  1805.      * @Route("/dashboard/temperatura/anterior/", name="dashboard_temperatura_anterior")
  1806.      * @IsGranted("ROLE_USER")
  1807.      */
  1808.     public function dashboard_temperatura_anterior(Request $request): Response
  1809.     {
  1810.         try{
  1811.             $dto = new DashboardTemperaturaDto();
  1812.             $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  1813.             $dto->fechaHasta = (new \DateTime('now'));
  1814.         
  1815.             $lista null;
  1816.             $rango_operacion null;
  1817.             $vehiculo null;
  1818.             $dispositivo null;
  1819.             $fecha_inicio null;
  1820.             $fecha_fin null;
  1821.             $numero_puntos_medidos 0;
  1822.             $limite_inferior null;
  1823.             $limite_superior null;
  1824.             $temperatura_maxima null;
  1825.             $temperatura_minima null;
  1826.             $temperatura_suma 0;
  1827.             $temperatura_promedio null;
  1828.             $desviacion_estandar null;
  1829.             $tiempo_sobre_limite 0;
  1830.             $tiempo_bajo_limite 0;
  1831.             $grafico_minimo = -40;
  1832.             $grafico_maximo 40;
  1833.             $tiempo_sobre_limite_h 0;
  1834.             $tiempo_sobre_limite_m 0;
  1835.             $tiempo_sobre_limite_s 0;
  1836.             $tiempo_bajo_limite_h 0;
  1837.             $tiempo_bajo_limite_m 0;
  1838.             $tiempo_bajo_limite_s 0;
  1839.             $form $this->createForm(DashboardTemperaturaFormType::class, $dto);
  1840.             $form->handleRequest($request);
  1841.             if ($form->isSubmitted() && $form->isValid()) {
  1842.                 $lista $this->bitacoraTemperaturaRepository->findByDashboardTemperaturaDto($dto);
  1843.                 $rango_operacion $this->tipoCargaRepository->findOneById($dto->tipoCarga);
  1844.                 $vehiculo $this->vehiculoRepository->findOneById($dto->vehiculo);
  1845.                 if($vehiculo)
  1846.                 {
  1847.                     $dispositivo $vehiculo->getDispositivo();
  1848.                 }
  1849.                 if($rango_operacion)
  1850.                 {
  1851.                     $limite_inferior $rango_operacion->getMinimo();
  1852.                     $limite_superior $rango_operacion->getMaximo();
  1853.                     $grafico_minimo $rango_operacion->getMinimo();
  1854.                     $grafico_maximo $rango_operacion->getMaximo();
  1855.                 }
  1856.                 $time_anterior null;
  1857.                 foreach($lista as $item)
  1858.                 {
  1859.                     $temperatura_actual $item->getTemp1();
  1860.                     $time_actual $item->getTimestamp();
  1861.                     if($temperatura_actual)
  1862.                     {
  1863.                         if($fecha_inicio == null)
  1864.                         {
  1865.                             $fecha_inicio $time_actual;
  1866.                         }
  1867.                         $fecha_fin $time_actual;
  1868.                         $numero_puntos_medidos++;
  1869.                         $temperatura_suma $temperatura_suma $temperatura_actual;
  1870.                         if((!$temperatura_maxima) or ($temperatura_maxima $temperatura_actual))
  1871.                         {
  1872.                             $temperatura_maxima $temperatura_actual;
  1873.                         }
  1874.                         if((!$temperatura_minima) or ($temperatura_minima $temperatura_actual))
  1875.                         {
  1876.                             $temperatura_minima $temperatura_actual;
  1877.                         }
  1878.                         if(($limite_inferior) and ($temperatura_actual $limite_inferior))
  1879.                         {
  1880.                             if($time_anterior)
  1881.                             {
  1882.                                 $diff $time_actual->diff($time_anterior);
  1883.                                 $segundos $diff->days 24 60 60;
  1884.                                 $segundos += $diff->60 60;
  1885.                                 $segundos += $diff->60;
  1886.                                 $segundos += $diff->s;
  1887.                                 $tiempo_bajo_limite $tiempo_bajo_limite $segundos;
  1888.                             }
  1889.                         }
  1890.                         if(($limite_superior) and ($temperatura_actual $limite_superior))
  1891.                         {
  1892.                             if($time_anterior)
  1893.                             {
  1894.                                 $diff $time_actual->diff($time_anterior);
  1895.                                 $segundos $diff->days 24 60 60;
  1896.                                 $segundos += $diff->60 60;
  1897.                                 $segundos += $diff->60;
  1898.                                 $segundos += $diff->s;
  1899.                                 $tiempo_sobre_limite $tiempo_sobre_limite $segundos;
  1900.                             }
  1901.                         }
  1902.                         $time_anterior $time_actual;
  1903.                     }
  1904.                     
  1905.                 }
  1906.                 if($numero_puntos_medidos 0)
  1907.                 {
  1908.                     $temperatura_promedio $temperatura_suma $numero_puntos_medidos;
  1909.                     // calculo de desviacion estandar
  1910.                     $ans=0;
  1911.                     foreach($lista as $item)
  1912.                     {
  1913.                         if($item->getTemp1())
  1914.                         {
  1915.                             $ans+=pow(($item->getTemp1()-$temperatura_promedio),2);
  1916.                         }
  1917.                     }
  1918.                     $desviacion_estandar sqrt($ans/$numero_puntos_medidos);
  1919.                 }
  1920.                 if($grafico_minimo $temperatura_minima)
  1921.                 {
  1922.                     $grafico_minimo $temperatura_minima;
  1923.                 }
  1924.                 if($grafico_maximo $temperatura_maxima)
  1925.                 {
  1926.                     $grafico_maximo $temperatura_maxima;
  1927.                 }
  1928.                 if($grafico_minimo 0)
  1929.                 {
  1930.                     $grafico_minimo 0;
  1931.                 }else
  1932.                 {
  1933.                     $grafico_minimo $grafico_minimo 5;
  1934.                 }
  1935.                 $grafico_maximo $grafico_maximo 5;
  1936.  
  1937.                 if($tiempo_sobre_limite)
  1938.                 {
  1939.                     $tiempo_sobre_limite_h floor($tiempo_sobre_limite 3600);
  1940.                     $tiempo_sobre_limite_m floor(($tiempo_sobre_limite - ($tiempo_sobre_limite_h 3600)) / 60);
  1941.                     $tiempo_sobre_limite_s = ($tiempo_sobre_limite 60);
  1942.                 }
  1943.                 if($tiempo_bajo_limite)
  1944.                 {
  1945.                     $tiempo_bajo_limite_h floor($tiempo_bajo_limite 3600);
  1946.                     $tiempo_bajo_limite_m floor(($tiempo_bajo_limite - ($tiempo_bajo_limite_h 3600)) / 60);
  1947.                     $tiempo_bajo_limite_s = ($tiempo_sobre_limite 60);
  1948.                 }
  1949.             }
  1950.             $intervalo 120// 2 horas
  1951.             if($fecha_inicio && $fecha_fin)
  1952.             {
  1953.                 $di_fechas $fecha_inicio->diff($fecha_fin);
  1954.                 $minutes $di_fechas->days 24 60;
  1955.                 $minutes += $di_fechas->60;
  1956.                 $minutes += $di_fechas->i;
  1957.                 if($minutes <= 20)
  1958.                 {
  1959.                     $intervalo 1;
  1960.                 }
  1961.                 elseif($minutes 2400)
  1962.                 {
  1963.                     $intervalo 120;
  1964.                 }
  1965.                 else
  1966.                 {
  1967.                     $intervalo = ($minutes 20);
  1968.                 }
  1969.             }
  1970.             return $this->render('dashboard/temperatura2.html.twig', array(
  1971.                 'form' => $form->createView(),
  1972.                 'lista' => $lista,
  1973.                 'rango_operacion' => $rango_operacion,
  1974.                 'vehiculo' => $vehiculo,
  1975.                 'dispositivo' => $dispositivo,
  1976.                 'fecha_inicio' => $fecha_inicio,
  1977.                 'fecha_fin' => $fecha_fin,
  1978.                 'numero_puntos_medidos' => $numero_puntos_medidos,
  1979.                 'limite_inferior' => $limite_inferior,
  1980.                 'limite_superior' => $limite_superior,
  1981.                 'temperatura_maxima' => $temperatura_maxima,
  1982.                 'temperatura_minima' => $temperatura_minima,
  1983.                 'temperatura_promedio' => $temperatura_promedio,
  1984.                 'desviacion_estandar' => $desviacion_estandar,
  1985.                 'tiempo_sobre_limite_h' => $tiempo_sobre_limite_h,
  1986.                 'tiempo_sobre_limite_m' => $tiempo_sobre_limite_m,
  1987.                 'tiempo_sobre_limite_s' => $tiempo_sobre_limite_s,
  1988.                 'tiempo_bajo_limite_h' => $tiempo_bajo_limite_h,
  1989.                 'tiempo_bajo_limite_m' => $tiempo_bajo_limite_m,
  1990.                 'tiempo_bajo_limite_s' => $tiempo_bajo_limite_s,
  1991.                 'grafico_minimo' => $grafico_minimo,
  1992.                 'grafico_maximo' => $grafico_maximo,
  1993.                 'intervalo' => $intervalo,
  1994.             ));
  1995.         }
  1996.         catch(\Exception $e){
  1997.             $this->logger->error($e->getMessage(), [
  1998.                 'exception' => $e,
  1999.                 'trace'  => $e->getTraceAsString(), 
  2000.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  2001.                 'method' => $request->getMethod(), // GET, POST, etc.
  2002.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  2003.                 'params' => $request->request->all()
  2004.             ]);
  2005.             $this->addFlash('danger',$e->getMessage());
  2006.             return $this->redirectToRoute('dashboard_inicial');
  2007.         }
  2008.     }
  2009.     /**
  2010.      * @Route("/dashboard/temperatura/", name="dashboard_temperatura")
  2011.      * @IsGranted("ROLE_USER")
  2012.      */
  2013.     public function dashboard_temperatura(Request $request): Response
  2014.     {
  2015.         try
  2016.         {
  2017.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_1'null);
  2018.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_2'null);
  2019.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_3'null);
  2020.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_4'null);
  2021.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_5'null);
  2022.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_1'null);
  2023.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_2'null);
  2024.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_3'null);
  2025.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_4'null);
  2026.             $this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_5'null);
  2027.             //return $this->redirectToRoute('dashboard_temperatura_buscar');
  2028.             return $this->render('dashboard/temperatura_opciones.html.twig');
  2029.         } 
  2030.         catch(\Exception $e){
  2031.             $this->logger->error($e->getMessage(), [
  2032.                 'exception' => $e,
  2033.                 'trace'  => $e->getTraceAsString(), 
  2034.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  2035.                 'method' => $request->getMethod(), // GET, POST, etc.
  2036.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  2037.                 'params' => $request->request->all()
  2038.             ]);
  2039.             $this->addFlash('danger',$e->getMessage());
  2040.             return $this->redirectToRoute('dashboard_inicial');
  2041.         }
  2042.     }
  2043.     /**
  2044.      * @Route("/dashboard/temperatura/distribucion/dedicada/", name="dashboard_temperatura_distribucion_dedicada")
  2045.      * @IsGranted("ROLE_USER")
  2046.      */
  2047.     public function dashboard_temperatura_distribucion_dedicada(Request $request): Response
  2048.     {
  2049.         try
  2050.         {
  2051.             $dto4 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_4');
  2052.             if(!$dto4)
  2053.             {
  2054.                 $dto4 = new DashboardTemperaturaDto();
  2055.                 $dto4->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2056.                 $dto4->fechaHasta = (new \DateTime('now'));
  2057.             }
  2058.             else
  2059.             {
  2060.                 if($dto4->vehiculo)
  2061.                 {
  2062.                     $dto4->vehiculo $this->entityManager->merge($dto4->vehiculo); 
  2063.                 }
  2064.             }
  2065.             $form4 $this->createForm(DashboardTemperaturaFormType::class, $dto4, array('id_tramo' => 4));
  2066.             $form4->handleRequest($request);
  2067.             if ($form4->isSubmitted() && $form4->isValid()) 
  2068.             {
  2069.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_4'$dto4);
  2070.             }
  2071.             $resultado4 $this->getTemperaturaResultado_v2($dto4);
  2072.  
  2073.             return $this->render('dashboard/temperatura_distribucion_dedicada.html.twig', array(
  2074.                 'form4' => $form4->createView(),
  2075.                 'dto4' => $dto4,
  2076.                 'resultado4' => $resultado4,
  2077.             ));
  2078.         } 
  2079.         catch(\Exception $e){
  2080.             $this->logger->error($e->getMessage(), [
  2081.                 'exception' => $e,
  2082.                 'trace'  => $e->getTraceAsString(), 
  2083.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  2084.                 'method' => $request->getMethod(), // GET, POST, etc.
  2085.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  2086.                 'params' => $request->request->all()
  2087.             ]);
  2088.             $this->addFlash('danger',$e->getMessage());
  2089.             return $this->redirectToRoute('dashboard_temperatura');
  2090.         }
  2091.     }
  2092.     /**
  2093.      * @Route("/dashboard/temperatura/distribucion/courier/", name="dashboard_temperatura_distribucion_courier")
  2094.      * @IsGranted("ROLE_USER")
  2095.      */
  2096.     public function dashboard_temperatura_distribucion_courier(Request $request): Response
  2097.     {
  2098.         try
  2099.         {
  2100.             $dto1 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_1');
  2101.             if(!$dto1)
  2102.             {
  2103.                 $dto1 = new DashboardTemperaturaDto();
  2104.                 $dto1->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2105.                 $dto1->fechaHasta = (new \DateTime('now'));
  2106.             }
  2107.             else
  2108.             {
  2109.                 if($dto1->vehiculo)
  2110.                 {
  2111.                     $dto1->vehiculo $this->entityManager->merge($dto1->vehiculo); 
  2112.                 }
  2113.             }
  2114.             $dto2 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_2');
  2115.             if(!$dto2)
  2116.             {
  2117.                 $dto2 = new DashboardTemperaturaDto();
  2118.                 $dto2->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2119.                 $dto2->fechaHasta = (new \DateTime('now'));
  2120.             }
  2121.             else
  2122.             {
  2123.                 if($dto2->vehiculo)
  2124.                 {
  2125.                     $dto2->vehiculo $this->entityManager->merge($dto2->vehiculo); 
  2126.                 }
  2127.             }
  2128.             $dto3 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_3');
  2129.             if(!$dto3)
  2130.             {
  2131.                 $dto3 = new DashboardTemperaturaDto();
  2132.                 $dto3->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2133.                 $dto3->fechaHasta = (new \DateTime('now'));
  2134.             }
  2135.             else
  2136.             {
  2137.                 if($dto3->vehiculo)
  2138.                 {
  2139.                     $dto3->vehiculo $this->entityManager->merge($dto3->vehiculo); 
  2140.                 }
  2141.             }
  2142.             $dto5 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_5');
  2143.             if(!$dto5)
  2144.             {
  2145.                 $dto5 = new DashboardTemperaturaDto();
  2146.                 $dto5->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2147.                 $dto5->fechaHasta = (new \DateTime('now'));
  2148.             }
  2149.             else
  2150.             {
  2151.                 if($dto5->vehiculo)
  2152.                 {
  2153.                     $dto5->vehiculo $this->entityManager->merge($dto5->vehiculo); 
  2154.                 }
  2155.             }
  2156.             $form1 $this->createForm(DashboardTemperaturaFormType::class, $dto1, array('id_tramo' => 1));
  2157.             $form1->handleRequest($request);
  2158.             if ($form1->isSubmitted() && $form1->isValid()) 
  2159.             {
  2160.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_1'$dto1);
  2161.             }
  2162.             $form2 $this->createForm(DashboardTemperaturaFormType::class, $dto2, array('id_tramo' => 2));
  2163.             $form2->handleRequest($request);
  2164.             if ($form2->isSubmitted() && $form2->isValid()) 
  2165.             {
  2166.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_2'$dto2);
  2167.             }
  2168.             $form3 $this->createForm(DashboardTemperaturaFormType::class, $dto3, array('id_tramo' => 3));
  2169.             $form3->handleRequest($request);
  2170.             if ($form3->isSubmitted() && $form3->isValid()) 
  2171.             {
  2172.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_3'$dto3);
  2173.             }
  2174.             $form5 $this->createForm(DashboardTemperaturaFormType::class, $dto5, array('id_tramo' => 5));
  2175.             $form5->handleRequest($request);
  2176.             if ($form5->isSubmitted() && $form5->isValid()) 
  2177.             {
  2178.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_5'$dto5);
  2179.             }
  2180.             $resultado1 $this->getTemperaturaResultado_v2($dto1);
  2181.             $resultado2 $this->getTemperaturaResultado_v2($dto2);
  2182.             $resultado3 $this->getTemperaturaResultado_v2($dto3);
  2183.             $resultado5 $this->getTemperaturaResultado_v2($dto5);
  2184.  
  2185.             return $this->render('dashboard/temperatura_distribucion_courier.html.twig', array(
  2186.                 'form1' => $form1->createView(),
  2187.                 'form2' => $form2->createView(),
  2188.                 'form3' => $form3->createView(),
  2189.                 'form5' => $form5->createView(),
  2190.                 'dto1' => $dto1,
  2191.                 'dto2' => $dto2,
  2192.                 'dto3' => $dto3,
  2193.                 'dto5' => $dto5,
  2194.                 'resultado1' => $resultado1,
  2195.                 'resultado2' => $resultado2,
  2196.                 'resultado3' => $resultado3,
  2197.                 'resultado5' => $resultado5,
  2198.             ));
  2199.         }
  2200.         catch(\Exception $e){
  2201.             $this->logger->error($e->getMessage(), [
  2202.                 'exception' => $e,
  2203.                 'trace'  => $e->getTraceAsString(), 
  2204.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  2205.                 'method' => $request->getMethod(), // GET, POST, etc.
  2206.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  2207.                 'params' => $request->request->all()
  2208.             ]);
  2209.             $this->addFlash('danger',$e->getMessage());
  2210.             return $this->redirectToRoute('dashboard_temperatura');
  2211.         }
  2212.     }
  2213.     
  2214.     /**
  2215.      * @Route("/dashboard/temperatura/distribucion/excel/{tramo}/", name="dashboard_temperatura_distribucion_excel")
  2216.      * @IsGranted("ROLE_USER")
  2217.      */
  2218.     public function dashboard_temperatura_distribucion_excel(Request $requestint $tramo)
  2219.     {
  2220.         try
  2221.         {
  2222.             $ahora = new \DateTime('now');
  2223.             $sesion '';
  2224.             if($tramo == 1)
  2225.                 $sesion 'SESION_DASHBOARD_TEMPERATURA_DTO_1';
  2226.             elseif($tramo == 2)
  2227.                 $sesion 'SESION_DASHBOARD_TEMPERATURA_DTO_2';
  2228.             elseif($tramo == 3)
  2229.                 $sesion 'SESION_DASHBOARD_TEMPERATURA_DTO_3';
  2230.             elseif($tramo == 4)
  2231.                 $sesion 'SESION_DASHBOARD_TEMPERATURA_DTO_4';
  2232.             $dto $this->session->get($sesion);
  2233.             if(!$dto)
  2234.             {
  2235.                 $dto = new DashboardTemperaturaDto();
  2236.                 $dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2237.                 $dto->fechaHasta = (new \DateTime('now'));
  2238.             }
  2239.             else
  2240.             {
  2241.                 if($dto->vehiculo)
  2242.                 {
  2243.                     $dto->vehiculo $this->entityManager->merge($dto->vehiculo); 
  2244.                 }
  2245.             }
  2246.  
  2247.             $resultado $this->getTemperaturaResultado_v2($dto);
  2248.             if(!$resultado)
  2249.             {
  2250.                 $this->addFlash("error"'No se encuentra informacion de bitacora');
  2251.                 return $this->redirectToRoute("dashboard_temperatura");
  2252.             }
  2253.             $spreadsheet = new Spreadsheet();
  2254.             /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  2255.             $sheet $spreadsheet->getActiveSheet();
  2256.             $sheet->setShowGridlines(false);
  2257.             $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  2258.             $drawing->setName('logo');
  2259.             $drawing->setDescription('logo');
  2260.             $drawing->setPath('media/logo_transfarma_verde.png'); // put your path and image here
  2261.             $drawing->setCoordinates('A1');
  2262.             $drawing->setWorksheet($sheet);
  2263.             $sheet->setCellValue('A6''BITACORA');
  2264.             $sheet->getStyle('A6')->getFont()->setBoldtrue );
  2265.             $sheet->setCellValue('A7'$ahora->format('d-m-Y H:i'));
  2266.             $sheet->mergeCells("A6:E6"); 
  2267.             $sheet->mergeCells("A7:D7"); 
  2268.                                                     
  2269.             $sheet->setCellValue('A9''Latitud');
  2270.             $sheet->setCellValue('B9''Longuitud');
  2271.             $sheet->setCellValue('C9''Timestamp');
  2272.             $sheet->setCellValue('D9''Temperatura');
  2273.             $sheet->setCellValue('E9''Humedad');
  2274.             
  2275.             $fila 9;
  2276.             foreach($resultado["lista"] as $item)
  2277.             {
  2278.                 $fila++;
  2279.             
  2280.                 $sheet->setCellValue('A'.$fila$item->getLatitud());
  2281.                 $sheet->setCellValue('B'.$fila$item->getLonguitud());
  2282.                 $sheet->setCellValue('C'.$fila$item->getTimestamp() ? $item->getTimestamp()->format('d-m-Y H:i:s') : '');
  2283.                 $sheet->setCellValue('D'.$fila$item->getTemp1());
  2284.                 $sheet->setCellValue('E'.$fila$item->getHum1());
  2285.             }
  2286.             //$sheet->setAutoFilter($sheet->calculateWorksheetDimension());
  2287.             $sheet->getColumnDimension('A')->setAutoSize(true);
  2288.             $sheet->getColumnDimension('B')->setAutoSize(true);
  2289.             $sheet->getColumnDimension('C')->setAutoSize(true);
  2290.             $sheet->getColumnDimension('D')->setAutoSize(true);
  2291.             $sheet->getColumnDimension('E')->setAutoSize(true);
  2292.             
  2293.             $sheet->getStyle('A9:E9')->getFont()->setBoldtrue );
  2294.             $sheet->getStyle('A9:E9')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
  2295.             $sheet->getStyle('A9:E9')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FF426384');
  2296.             $sheet->getStyle('A9:E'.$fila)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
  2297.             // Create your Office 2007 Excel (XLSX Format)
  2298.             $writer = new Xlsx($spreadsheet);
  2299.             
  2300.             // Create a Temporary file in the system
  2301.             $fileName 'BITACORA-'.($ahora->format('Ymd-Hi')).'.xlsx';
  2302.             $temp_file tempnam($this->getParameter('kernel.project_dir').'/temp/'$fileName);
  2303.             
  2304.             // Create the excel file in the tmp directory of the system
  2305.             $writer->save($temp_file);
  2306.             
  2307.             // Return the excel file as an attachment
  2308.             return $this->file($temp_file$fileNameResponseHeaderBag::DISPOSITION_INLINE);  
  2309.         } 
  2310.         catch(\Exception $e){
  2311.             $this->logger->error($e->getMessage(), [
  2312.                 'exception' => $e,
  2313.                 'trace'  => $e->getTraceAsString(), 
  2314.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  2315.                 'method' => $request->getMethod(), // GET, POST, etc.
  2316.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  2317.                 'params' => $request->request->all()
  2318.             ]);
  2319.             $this->addFlash('danger',$e->getMessage());
  2320.             return $this->redirectToRoute('dashboard_temperatura');
  2321.         }
  2322.     }
  2323.     /**
  2324.      * @Route("/dashboard/temperatura/buscar/", name="dashboard_temperatura_buscar")
  2325.      * @IsGranted("ROLE_USER")
  2326.      */
  2327.     public function dashboard_temperatura_buscar(Request $request): Response
  2328.     {
  2329.         try
  2330.         {
  2331.             $dto1 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_1');
  2332.             if(!$dto1)
  2333.             {
  2334.                 $dto1 = new DashboardTemperaturaDto();
  2335.                 $dto1->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2336.                 $dto1->fechaHasta = (new \DateTime('now'));
  2337.             }
  2338.             else
  2339.             {
  2340.                 if($dto1->vehiculo)
  2341.                 {
  2342.                     $dto1->vehiculo $this->entityManager->merge($dto1->vehiculo); 
  2343.                 }
  2344.             }
  2345.             $dto2 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_2');
  2346.             if(!$dto2)
  2347.             {
  2348.                 $dto2 = new DashboardTemperaturaDto();
  2349.                 $dto2->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2350.                 $dto2->fechaHasta = (new \DateTime('now'));
  2351.             }
  2352.             else
  2353.             {
  2354.                 if($dto2->vehiculo)
  2355.                 {
  2356.                     $dto2->vehiculo $this->entityManager->merge($dto2->vehiculo); 
  2357.                 }
  2358.             }
  2359.             $dto3 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_3');
  2360.             if(!$dto3)
  2361.             {
  2362.                 $dto3 = new DashboardTemperaturaDto();
  2363.                 $dto3->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2364.                 $dto3->fechaHasta = (new \DateTime('now'));
  2365.             }
  2366.             else
  2367.             {
  2368.                 if($dto3->vehiculo)
  2369.                 {
  2370.                     $dto3->vehiculo $this->entityManager->merge($dto3->vehiculo); 
  2371.                 }
  2372.             }
  2373.             $dto4 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_4');
  2374.             if(!$dto4)
  2375.             {
  2376.                 $dto4 = new DashboardTemperaturaDto();
  2377.                 $dto4->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2378.                 $dto4->fechaHasta = (new \DateTime('now'));
  2379.             }
  2380.             else
  2381.             {
  2382.                 if($dto4->vehiculo)
  2383.                 {
  2384.                     $dto4->vehiculo $this->entityManager->merge($dto4->vehiculo); 
  2385.                 }
  2386.             }
  2387.             $dto5 $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_5');
  2388.             if(!$dto5)
  2389.             {
  2390.                 $dto5 = new DashboardTemperaturaDto();
  2391.                 $dto5->fechaDesde = (new \DateTime('today'))->modify('-7 day');
  2392.                 $dto5->fechaHasta = (new \DateTime('now'));
  2393.             }
  2394.             else
  2395.             {
  2396.                 if($dto5->vehiculo)
  2397.                 {
  2398.                     $dto5->vehiculo $this->entityManager->merge($dto5->vehiculo); 
  2399.                 }
  2400.             }
  2401.             $form1 $this->createForm(DashboardTemperaturaFormType::class, $dto1, array('id_tramo' => 1));
  2402.             $form1->handleRequest($request);
  2403.             if ($form1->isSubmitted() && $form1->isValid()) 
  2404.             {
  2405.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_1'$dto1);
  2406.             }
  2407.             $form2 $this->createForm(DashboardTemperaturaFormType::class, $dto2, array('id_tramo' => 2));
  2408.             $form2->handleRequest($request);
  2409.             if ($form2->isSubmitted() && $form2->isValid()) 
  2410.             {
  2411.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_2'$dto2);
  2412.             }
  2413.             $form3 $this->createForm(DashboardTemperaturaFormType::class, $dto3, array('id_tramo' => 3));
  2414.             $form3->handleRequest($request);
  2415.             if ($form3->isSubmitted() && $form3->isValid()) 
  2416.             {
  2417.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_3'$dto3);
  2418.             }
  2419.             $form4 $this->createForm(DashboardTemperaturaFormType::class, $dto4, array('id_tramo' => 4));
  2420.             $form4->handleRequest($request);
  2421.             if ($form4->isSubmitted() && $form4->isValid()) 
  2422.             {
  2423.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_4'$dto4);
  2424.             }
  2425.             $form5 $this->createForm(DashboardTemperaturaFormType::class, $dto5, array('id_tramo' => 5));
  2426.             $form5->handleRequest($request);
  2427.             if ($form5->isSubmitted() && $form5->isValid()) 
  2428.             {
  2429.                 $this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_5'$dto5);
  2430.             }
  2431.             $resultado1 $this->getTemperaturaResultado_v2($dto1);
  2432.             $resultado2 $this->getTemperaturaResultado_v2($dto2);
  2433.             $resultado3 $this->getTemperaturaResultado_v2($dto3);
  2434.             $resultado4 $this->getTemperaturaResultado_v2($dto4);
  2435.             $resultado5 $this->getTemperaturaResultado_v2($dto5);
  2436.             $resultado_general = array();
  2437.             $grafico_minimo_general 0;
  2438.             $grafico_maximo_general 25;
  2439.             if($resultado1->lista_grafico)
  2440.             {
  2441.                 if($grafico_minimo_general $resultado1->grafico_minimo)
  2442.                 {
  2443.                     $grafico_minimo_general $resultado1->grafico_minimo;
  2444.                 }
  2445.                 if($grafico_maximo_general $resultado1->grafico_maximo)
  2446.                 {
  2447.                     $grafico_maximo_general $resultado1->grafico_maximo;
  2448.                 }
  2449.                 foreach($resultado1->lista_grafico as $item_temperatura)
  2450.                 {
  2451.                     if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')])) 
  2452.                     {
  2453.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo1 $item_temperatura->getTemp1();
  2454.                     }
  2455.                     else
  2456.                     {
  2457.                         $dto = new DTOTemperaturaGeneral();
  2458.                         $dto->fecha $item_temperatura->getTimestamp();
  2459.                         $dto->tramo1 $item_temperatura->getTemp1();
  2460.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
  2461.                     }
  2462.                 }
  2463.             }
  2464.             if($resultado2->lista)
  2465.             {
  2466.                 if($grafico_minimo_general $resultado2->grafico_minimo)
  2467.                 {
  2468.                     $grafico_minimo_general $resultado2->grafico_minimo;
  2469.                 }
  2470.                 if($grafico_maximo_general $resultado2->grafico_maximo)
  2471.                 {
  2472.                     $grafico_maximo_general $resultado2->grafico_maximo;
  2473.                 }
  2474.                 foreach($resultado2->lista_grafico as $item_temperatura)
  2475.                 {
  2476.                     if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')])) 
  2477.                     {
  2478.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo2 $item_temperatura->getTemp1();
  2479.                     }
  2480.                     else
  2481.                     {
  2482.                         $dto = new DTOTemperaturaGeneral();
  2483.                         $dto->fecha $item_temperatura->getTimestamp();
  2484.                         $dto->tramo2 $item_temperatura->getTemp1();
  2485.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
  2486.                     }
  2487.                 }
  2488.             }                
  2489.             if($resultado3->lista)
  2490.             {
  2491.                 if($grafico_minimo_general $resultado3->grafico_minimo)
  2492.                 {
  2493.                     $grafico_minimo_general $resultado3->grafico_minimo;
  2494.                 }
  2495.                 if($grafico_maximo_general $resultado3->grafico_maximo)
  2496.                 {
  2497.                     $grafico_maximo_general $resultado3->grafico_maximo;
  2498.                 }
  2499.                 foreach($resultado3->lista_grafico as $item_temperatura)
  2500.                 {
  2501.                     if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')])) 
  2502.                     {
  2503.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo3 $item_temperatura->getTemp1();
  2504.                     }
  2505.                     else
  2506.                     {
  2507.                         $dto = new DTOTemperaturaGeneral();
  2508.                         $dto->fecha $item_temperatura->getTimestamp();
  2509.                         $dto->tramo3 $item_temperatura->getTemp1();
  2510.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
  2511.                     }
  2512.                 }
  2513.             }
  2514.             if($resultado4->lista_grafico)
  2515.             {
  2516.                 if($grafico_minimo_general $resultado4->grafico_minimo)
  2517.                 {
  2518.                     $grafico_minimo_general $resultado4->grafico_minimo;
  2519.                 }
  2520.                 if($grafico_maximo_general $resultado4->grafico_maximo)
  2521.                 {
  2522.                     $grafico_maximo_general $resultado4->grafico_maximo;
  2523.                 }
  2524.                 foreach($resultado4->lista_grafico as $item_temperatura)
  2525.                 {
  2526.                     if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')])) 
  2527.                     {
  2528.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo1 $item_temperatura->getTemp1();
  2529.                     }
  2530.                     else
  2531.                     {
  2532.                         $dto = new DTOTemperaturaGeneral();
  2533.                         $dto->fecha $item_temperatura->getTimestamp();
  2534.                         $dto->tramo4 $item_temperatura->getTemp1();
  2535.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
  2536.                     }
  2537.                 }
  2538.             }
  2539.             if($resultado5->lista_grafico)
  2540.             {
  2541.                 if($grafico_minimo_general $resultado5->grafico_minimo)
  2542.                 {
  2543.                     $grafico_minimo_general $resultado5->grafico_minimo;
  2544.                 }
  2545.                 if($grafico_maximo_general $resultado5->grafico_maximo)
  2546.                 {
  2547.                     $grafico_maximo_general $resultado5->grafico_maximo;
  2548.                 }
  2549.                 foreach($resultado5->lista_grafico as $item_temperatura)
  2550.                 {
  2551.                     if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')])) 
  2552.                     {
  2553.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo1 $item_temperatura->getTemp1();
  2554.                     }
  2555.                     else
  2556.                     {
  2557.                         $dto = new DTOTemperaturaGeneral();
  2558.                         $dto->fecha $item_temperatura->getTimestamp();
  2559.                         $dto->tramo5 $item_temperatura->getTemp1();
  2560.                         $resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
  2561.                     }
  2562.                 }
  2563.             }
  2564.             ksort($resultado_general);
  2565.             return $this->render('dashboard/temperatura_buscar.html.twig', array(
  2566.                 'form1' => $form1->createView(),
  2567.                 'form2' => $form2->createView(),
  2568.                 'form3' => $form3->createView(),
  2569.                 'form4' => $form4->createView(),
  2570.                 'form5' => $form5->createView(),
  2571.                 'dto1' => $dto1,
  2572.                 'dto2' => $dto2,
  2573.                 'dto3' => $dto3,
  2574.                 'dto4' => $dto4,
  2575.                 'dto5' => $dto5,
  2576.                 'resultado1' => $resultado1,
  2577.                 'resultado2' => $resultado2,
  2578.                 'resultado3' => $resultado3,
  2579.                 'resultado4' => $resultado4,
  2580.                 'resultado5' => $resultado5,
  2581.                 'resultado_general' => $resultado_general,
  2582.                 'grafico_minimo_general' => $grafico_minimo_general,
  2583.                 'grafico_maximo_general' => $grafico_maximo_general,
  2584.             ));
  2585.         }
  2586.         catch(\Exception $e){
  2587.             $this->logger->error($e->getMessage(), [
  2588.                 'exception' => $e,
  2589.                 'trace'  => $e->getTraceAsString(), 
  2590.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  2591.                 'method' => $request->getMethod(), // GET, POST, etc.
  2592.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  2593.                 'params' => $request->request->all()
  2594.             ]);
  2595.             $this->addFlash('danger',$e->getMessage());
  2596.             return $this->redirectToRoute('dashboard_temperatura');
  2597.         }
  2598.     }
  2599.     function getTemperaturaResultado_v1(DashboardTemperaturaDto $dto)
  2600.     {
  2601.         $tipo_carga_id 1//Refrigerado
  2602.         $dispositivo null;
  2603.         $fecha_inicio null;
  2604.         $fecha_fin null;
  2605.         $numero_puntos_medidos 0;
  2606.         $limite_inferior null;
  2607.         $limite_superior null;
  2608.         $temperatura_maxima null;
  2609.         $temperatura_minima null;
  2610.         $temperatura_suma 0;
  2611.         $temperatura_promedio null;
  2612.         $desviacion_estandar null;
  2613.         $tiempo_sobre_limite 0;
  2614.         $tiempo_bajo_limite 0;
  2615.         $grafico_minimo 0;
  2616.         $grafico_maximo 25;
  2617.         $tiempo_sobre_limite_h 0;
  2618.         $tiempo_sobre_limite_m 0;
  2619.         $tiempo_sobre_limite_s 0;
  2620.         $tiempo_bajo_limite_h 0;
  2621.         $tiempo_bajo_limite_m 0;
  2622.         $tiempo_bajo_limite_s 0;
  2623.         $lista $this->bitacoraTemperaturaRepository->findByDashboardTemperaturaDto($dto);
  2624.         $rango_operacion $this->tipoCargaRepository->findOneById($tipo_carga_id);
  2625.         $vehiculo $this->vehiculoRepository->findOneById($dto->vehiculo);
  2626.         if($vehiculo)
  2627.         {
  2628.             $dispositivo $vehiculo->getDispositivo();
  2629.         }
  2630.         $resultado = new DashboardTemperaturaResultadoDto();
  2631.         if($rango_operacion)
  2632.         {
  2633.             $limite_inferior $rango_operacion->getMinimo();
  2634.             $limite_superior $rango_operacion->getMaximo();
  2635.             $grafico_minimo 0// $rango_operacion->getMinimo();
  2636.             $grafico_maximo 25//$rango_operacion->getMaximo();
  2637.         }
  2638.         $time_anterior null;
  2639.         foreach($lista as $item)
  2640.         {
  2641.             $temperatura_actual $item->getTemp1();
  2642.             $time_actual $item->getTimestamp();
  2643.             if($temperatura_actual)
  2644.             {
  2645.                 if($fecha_inicio == null)
  2646.                 {
  2647.                     $fecha_inicio $time_actual;
  2648.                 }
  2649.                 $fecha_fin $time_actual;
  2650.                 $numero_puntos_medidos++;
  2651.                 $temperatura_suma $temperatura_suma $temperatura_actual;
  2652.                 if((!$temperatura_maxima) or ($temperatura_maxima $temperatura_actual))
  2653.                 {
  2654.                     $temperatura_maxima $temperatura_actual;
  2655.                 }
  2656.                 if((!$temperatura_minima) or ($temperatura_minima $temperatura_actual))
  2657.                 {
  2658.                     $temperatura_minima $temperatura_actual;
  2659.                 }
  2660.                 if(($limite_inferior) and ($temperatura_actual $limite_inferior))
  2661.                 {
  2662.                     if($time_anterior)
  2663.                     {
  2664.                         $diff $time_actual->diff($time_anterior);
  2665.                         $segundos $diff->days 24 60 60;
  2666.                         $segundos += $diff->60 60;
  2667.                         $segundos += $diff->60;
  2668.                         $segundos += $diff->s;
  2669.                         $tiempo_bajo_limite $tiempo_bajo_limite $segundos;
  2670.                     }
  2671.                 }
  2672.                 if(($limite_superior) and ($temperatura_actual $limite_superior))
  2673.                 {
  2674.                     if($time_anterior)
  2675.                     {
  2676.                         $diff $time_actual->diff($time_anterior);
  2677.                         $segundos $diff->days 24 60 60;
  2678.                         $segundos += $diff->60 60;
  2679.                         $segundos += $diff->60;
  2680.                         $segundos += $diff->s;
  2681.                         $tiempo_sobre_limite $tiempo_sobre_limite $segundos;
  2682.                     }
  2683.                 }
  2684.                 $time_anterior $time_actual;
  2685.             }
  2686.         }
  2687.         if($numero_puntos_medidos 0)
  2688.         {
  2689.             $temperatura_promedio $temperatura_suma $numero_puntos_medidos;
  2690.             // calculo de desviacion estandar
  2691.             $ans=0;
  2692.             foreach($lista as $item)
  2693.             {
  2694.                 if($item->getTemp1())
  2695.                 {
  2696.                     $ans+=pow(($item->getTemp1()-$temperatura_promedio),2);
  2697.                 }
  2698.             }
  2699.             $desviacion_estandar sqrt($ans/$numero_puntos_medidos);
  2700.         }
  2701.         if($grafico_minimo $temperatura_minima)
  2702.         {
  2703.             $grafico_minimo $temperatura_minima;
  2704.         }
  2705.         if($grafico_maximo $temperatura_maxima)
  2706.         {
  2707.             $grafico_maximo $temperatura_maxima;
  2708.         }
  2709.         if($grafico_minimo 0)
  2710.         {
  2711.             $grafico_minimo 0;
  2712.         }
  2713.         if($tiempo_sobre_limite)
  2714.         {
  2715.             $tiempo_sobre_limite_h floor($tiempo_sobre_limite 3600);
  2716.             $tiempo_sobre_limite_m floor(($tiempo_sobre_limite - ($tiempo_sobre_limite_h 3600)) / 60);
  2717.             $tiempo_sobre_limite_s = ($tiempo_sobre_limite 60);
  2718.         }
  2719.         if($tiempo_bajo_limite)
  2720.         {
  2721.             $tiempo_bajo_limite_h floor($tiempo_bajo_limite 3600);
  2722.             $tiempo_bajo_limite_m floor(($tiempo_bajo_limite - ($tiempo_bajo_limite_h 3600)) / 60);
  2723.             $tiempo_bajo_limite_s = ($tiempo_sobre_limite 60);
  2724.         }
  2725.        
  2726.         $cantidad_referencia 30;
  2727.         $total_datos count($lista);
  2728.         $intervalo max(1floor($total_datos $cantidad_referencia));
  2729.         $lista_grafico = new ArrayCollection();
  2730.         $contador_intervalo 0;
  2731.         $anterior_minimo 0;
  2732.         $anterior_maximo 0;
  2733.         foreach($lista as $item)
  2734.         {
  2735.             $contador_intervalo++;
  2736.             if($anterior_minimo == 0)
  2737.             {
  2738.                 if($item->getTemp1() == $temperatura_minima)
  2739.                 {
  2740.                     $contador_intervalo $intervalo;
  2741.                     $anterior_minimo 1;
  2742.                 }
  2743.             }
  2744.             else
  2745.             {
  2746.                 if($item->getTemp1() != $temperatura_minima)
  2747.                 {
  2748.                     $anterior_minimo 0;
  2749.                 }
  2750.             }
  2751.             if($anterior_maximo == 0)
  2752.             {
  2753.                 if($item->getTemp1() == $temperatura_maxima)
  2754.                 {
  2755.                     $contador_intervalo $intervalo;
  2756.                     $anterior_maximo 1;
  2757.                 }
  2758.             }
  2759.             else
  2760.             {
  2761.                 if($item->getTemp1() != $temperatura_maxima)
  2762.                 {
  2763.                     $anterior_maximo 0;
  2764.                 }
  2765.             }
  2766.             if($contador_intervalo >= $intervalo)
  2767.             {
  2768.                 $lista_grafico[] = $item;
  2769.                 $contador_intervalo 0;
  2770.             }
  2771.         }
  2772.         
  2773.         $resultado = new DashboardTemperaturaResultadoDto();
  2774.         $resultado->lista $lista;
  2775.         $resultado->lista_grafico $lista_grafico;
  2776.         $resultado->rango_operacion $rango_operacion;
  2777.         $resultado->vehiculo $vehiculo;
  2778.         $resultado->dispositivo $dispositivo;
  2779.         $resultado->fecha_inicio $fecha_inicio;
  2780.         $resultado->fecha_fin $fecha_fin;
  2781.         $resultado->numero_puntos_medidos $numero_puntos_medidos;
  2782.         $resultado->limite_inferior $limite_inferior;
  2783.         $resultado->limite_superior $limite_superior;
  2784.         $resultado->temperatura_maxima $temperatura_maxima;
  2785.         $resultado->temperatura_minima $temperatura_minima;
  2786.         $resultado->temperatura_promedio $temperatura_promedio;
  2787.         $resultado->desviacion_estandar $desviacion_estandar;
  2788.         $resultado->tiempo_sobre_limite_h $tiempo_sobre_limite_h;
  2789.         $resultado->tiempo_sobre_limite_m $tiempo_sobre_limite_m;
  2790.         $resultado->tiempo_sobre_limite_s $tiempo_sobre_limite_s;
  2791.         $resultado->tiempo_bajo_limite_h $tiempo_bajo_limite_h;
  2792.         $resultado->tiempo_bajo_limite_m $tiempo_bajo_limite_m;
  2793.         $resultado->tiempo_bajo_limite_s $tiempo_bajo_limite_s;
  2794.         $resultado->grafico_minimo $grafico_minimo;
  2795.         $resultado->grafico_maximo $grafico_maximo;
  2796.         $resultado->intervalo $intervalo;
  2797.         return $resultado;
  2798.     }
  2799.     function getTemperaturaResultado_v2(DashboardTemperaturaDto $dto)
  2800.     {
  2801.         $rango_operacion null;
  2802.         $lista $this->bitacoraTemperaturaRepository->findByDashboardTemperaturaDto($dto);
  2803.         $vehiculo $dto->vehiculo;
  2804.         if($vehiculo)
  2805.         {
  2806.             $rango_operacion $vehiculo->getRango();
  2807.         }
  2808.      
  2809.         $contador 0;
  2810.         $min 0;
  2811.         $max 20;
  2812.         if($rango_operacion)
  2813.         {
  2814.             $max $rango_operacion->getHasta();
  2815.         }
  2816.       
  2817.         $primer_punto null;
  2818.         $ultimo_punto null;
  2819.         foreach($lista as $item_detalle)
  2820.         {
  2821.             $contador++;
  2822.             if(!$primer_punto)
  2823.             {
  2824.                 $primer_punto $item_detalle->getTimestamp();
  2825.             }
  2826.             elseif($primer_punto $item_detalle->getTimestamp())
  2827.             {
  2828.                 $primer_punto $item_detalle->getTimestamp();
  2829.             }
  2830.             if(!$ultimo_punto)
  2831.             {
  2832.                 $ultimo_punto $item_detalle->getTimestamp();
  2833.             }
  2834.             elseif($ultimo_punto $item_detalle->getTimestamp())
  2835.             {
  2836.                 $ultimo_punto $item_detalle->getTimestamp();
  2837.             }
  2838.             if($item_detalle->getTemp1() < $min)
  2839.             {
  2840.                 $min $item_detalle->getTemp1();
  2841.             }
  2842.             if($item_detalle->getTemp1() > $max)
  2843.             {
  2844.                 $max $item_detalle->getTemp1();
  2845.             }
  2846.         }
  2847.         $max round($max 20PHP_ROUND_HALF_UP);
  2848.         return array(
  2849.             'lista' => $lista,
  2850.             'contador' => $contador,
  2851.             'min' => $min,
  2852.             'max' => $max,
  2853.             'primer_punto' => $primer_punto,
  2854.             'ultimo_punto' => $ultimo_punto,
  2855.             'vehiculo' => $vehiculo,
  2856.             'rango' => $rango_operacion
  2857.         );
  2858.     }
  2859.     function distanceCalculation($point1_lat$point1_long$point2_lat$point2_long$unit 'km'$decimals 2
  2860.     {
  2861.         // Cálculo de la distancia en grados
  2862.         $degrees rad2deg(acos((sin(deg2rad($point1_lat))*sin(deg2rad($point2_lat))) + (cos(deg2rad($point1_lat))*cos(deg2rad($point2_lat))*cos(deg2rad($point1_long-$point2_long)))));
  2863.     
  2864.         // Conversión de la distancia en grados a la unidad escogida (kilómetros, millas o millas naúticas)
  2865.         switch($unit) {
  2866.             case 'km':
  2867.                 $distance $degrees 111.13384// 1 grado = 111.13384 km, basándose en el diametro promedio de la Tierra (12.735 km)
  2868.                 break;
  2869.             case 'mi':
  2870.                 $distance $degrees 69.05482// 1 grado = 69.05482 millas, basándose en el diametro promedio de la Tierra (7.913,1 millas)
  2871.                 break;
  2872.             case 'nmi':
  2873.                 $distance =  $degrees 59.97662// 1 grado = 59.97662 millas naúticas, basándose en el diametro promedio de la Tierra (6,876.3 millas naúticas)
  2874.         }
  2875.         return round($distance$decimals);
  2876.     }
  2877.     /**
  2878.      * @Route("/dashboard/localizacion/", name="dashboard_localizacion")
  2879.      * @IsGranted("ROLE_USER")
  2880.      */
  2881.     public function dashboard_localizacion(Request $request): Response
  2882.     {
  2883.         try
  2884.         {
  2885.             $dto = new DashboardLocalizacionDto();
  2886.        
  2887.             $lista null;
  2888.        
  2889.             $form $this->createForm(DashboardLocalizacionFormType::class, $dto);
  2890.             $form->handleRequest($request);
  2891.             if ($form->isSubmitted() && $form->isValid()) 
  2892.             {
  2893.                 $lista $this->vehiculoRepository->getLocalizacion($dto->vehiculo);
  2894.                 
  2895.             }
  2896.             
  2897.             return $this->render('dashboard/localizacion2.html.twig', array(
  2898.                 'form' => $form->createView(),
  2899.                 'lista' => $lista,
  2900.             ));
  2901.         } 
  2902.         catch(\Exception $e){
  2903.             $this->logger->error($e->getMessage(), [
  2904.                 'exception' => $e,
  2905.                 'trace'  => $e->getTraceAsString(), 
  2906.                 'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
  2907.                 'method' => $request->getMethod(), // GET, POST, etc.
  2908.                 'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
  2909.                 'params' => $request->request->all()
  2910.             ]);
  2911.             $this->addFlash('danger',$e->getMessage());
  2912.             return $this->redirectToRoute('app_admin_index');
  2913.         }
  2914.     }
  2915. }