src/Controller/DashboardController.php line 59

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