<?php
namespace App\Controller;
use App\DTO\DashboardBuscarDto;
use App\DTO\DashboardLocalizacionDto;
use App\DTO\DashboardTemperaturaDto;
use App\DTO\DashboardTemperaturaResultadoDto;
use App\DTO\DTOTemperaturaGeneral;
use App\DTO\DocumentoTributarioListarDto;
use App\Form\DashboardBuscarFormType;
use App\Form\DashboardLocalizacionFormType;
use App\Form\DashboardTemperaturaFormType;
use App\Repository\BitacoraTemperaturaRepository;
use App\Repository\ClienteRepository;
use App\Repository\GeneradorTemperaturaRangoRepository;
use App\Repository\MatrizTransitoRepository;
use App\Repository\OrdenRepository;
use App\Repository\RegionRepository;
use App\Repository\RutaRepository;
use App\Repository\TipoCargaRepository;
use App\Repository\TipoEstadoOrdenRepository;
use App\Repository\VehiculoRepository;
use App\Repository\ViaTransporteRepository;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Core\Security;
use App\Services\BaseOptimizadaHelper;
use Psr\Log\LoggerInterface;
class DashboardController extends AbstractController
{
private $security;
private $entityManager;
private $session;
private $logger;
private $clienteRepository;
private $generadorTemperaturaRangoRepository;
private $matrizTransitoRepository;
private $ordenRepository;
private $regionRepository;
private $rutaRepository;
private $tipoCargaRepository;
private $tipoEstadoOrdenRepository;
private $vehiculoRepository;
private $viaTransporteRepository;
public function __construct(Security $security, EntityManagerInterface $entityManager,
SessionInterface $session,
LoggerInterface $logger,
BitacoraTemperaturaRepository $bitacoraTemperaturaRepository,
ClienteRepository $clienteRepository,
GeneradorTemperaturaRangoRepository $generadorTemperaturaRangoRepository,
MatrizTransitoRepository $matrizTransitoRepository,
OrdenRepository $ordenRepository,
RegionRepository $regionRepository,
RutaRepository $rutaRepository,
TipoCargaRepository $tipoCargaRepository,
TipoEstadoOrdenRepository $tipoEstadoOrdenRepository,
VehiculoRepository $vehiculoRepository,
ViaTransporteRepository $viaTransporteRepository
)
{
date_default_timezone_set("America/Santiago");
$this->security = $security;
$this->entityManager = $entityManager;
$this->session = $session;
$this->logger = $logger;
$this->bitacoraTemperaturaRepository = $bitacoraTemperaturaRepository;
$this->clienteRepository = $clienteRepository;
$this->generadorTemperaturaRangoRepository = $generadorTemperaturaRangoRepository;
$this->matrizTransitoRepository = $matrizTransitoRepository;
$this->ordenRepository = $ordenRepository;
$this->regionRepository = $regionRepository;
$this->rutaRepository = $rutaRepository;
$this->tipoCargaRepository = $tipoCargaRepository;
$this->tipoEstadoOrdenRepository = $tipoEstadoOrdenRepository;
$this->vehiculoRepository = $vehiculoRepository;
$this->viaTransporteRepository = $viaTransporteRepository;
if(!$this->session->isStarted()) //Starting the session if not done yet
{
$this->session->start();
}
}
/**
* @Route("/", name="app_admin_index")
* @IsGranted("ROLE_USER")
*/
public function index(Request $request): Response
{
try{
//return $this->render("admin/mantencion.html.twig");
return $this->render('admin/main.html.twig');
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
/**
* @Route("/dashboard/", name="dashboard")
* @IsGranted("ROLE_USER")
*/
public function dashboard(Request $request): Response
{
try
{
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', null);
return $this->render('dashboard/index.html.twig');
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
/**
* @Route("/dashboard/inicial/", name="dashboard_inicial")
* @IsGranted("ROLE_USER")
*/
public function dashboard_inicial(Request $request): Response
{
try
{
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
if(!is_array($dto->cliente))
{
$dto->cliente = $this->entityManager->merge($dto->cliente);
}
else
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
else
{
$dto->cliente = array();
}
if($dto->clienteFinal)
{
if(!is_array($dto->clienteFinal))
{
$dto->clienteFinal = $this->entityManager->merge($dto->clienteFinal);
}
else
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
else
{
$dto->clienteFinal = array();
}
if($dto->tipoCarga)
{
$dto->tipoCarga = $this->entityManager->merge($dto->tipoCarga);
}
if($dto->region)
{
$dto->region = $this->entityManager->merge($dto->region);
}
if($dto->viaTransporte)
{
$dto->viaTransporte = $this->entityManager->merge($dto->viaTransporte);
}
}
$form = $this->createForm(DashboardBuscarFormType::class, $dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$dto->tipoCarga = null;
$dto->tipoEstadoOrden = null;
$dto->region = null;
$dto->viaTransporte = null;
}
if($this->security->isGranted('ROLE_CLIENTE'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
foreach($user->getClientes() as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
if($this->security->isGranted('ROLE_TEVA'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$clientes = $this->clienteRepository->findBy(array('activo' => 1, 'integracionTeva' => 1), array());
foreach($clientes as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
$cliente_final = array();
if($dto->clienteFinal)
{
foreach($dto->clienteFinal as $item_cliente_final)
{
$cliente_final[] = $item_cliente_final;
}
}
if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
{
if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
{
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
$cliente_final = $user->getClientesFinales();
}
}
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
$lista = $this->ordenRepository->findPorDashboardBuscarDto($dto, $cliente_final, TRUE);
$resumen = $this->dashboard_get_datos_resumen($dto, $cliente_final);
$regiones = $this->ordenRepository->getDashboadRegiones($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$fechas = $this->ordenRepository->getDashboadFechas($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$dto_gd = new DocumentoTributarioListarDto();
$dto_gd->fechaSolicitudInicial = $dto->fechaDesde;
$dto_gd->fechaSolicitudFinal = $dto->fechaHasta;
$dto_gd->folio = null;
$dto_gd->supermandante = $dto->supermandante;
$dto_gd->cliente = $dto->cliente;
$dto_gd->clienteFinal = $cliente_final;
$dto_gd->estadoDocumentoTributario = null;
$dto_gd->agencia = null;
$dto_gd->tipoDocumentoGestionDocumental = null;
$dto_gd->region = $dto->region;
$baseOptimizadaHelper = new BaseOptimizadaHelper();
$total_gd = $baseOptimizadaHelper->getSpGestionDocumentalListTodosCount($dto_gd, $cliente_final);
return $this->render('dashboard/inicial.html.twig', array(
'form' => $form->createView(),
'filtros' => $dto->getFiltros(),
'resumen' => $resumen,
'regiones' => $regiones,
'fechas' => $fechas,
'lista' => $lista,
'total_gd' => $total_gd['total']
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
/**
* @Route("/dashboard/seleccionar-tipo-estado-orden/",name="dashboard_seleccionar_tipo_estado_orden")
* @param Request $request
*/
public function dashboard_seleccionar_tipo_estado_orden(Request $request)
{
try
{
$tipoEstadoOrdenId = $request->query->get("tipo_estado_orden_id");
$tipoEstadoOrden = $this->tipoEstadoOrdenRepository->findOneById($tipoEstadoOrdenId);
if(!$tipoEstadoOrden)
{
$this->addFlash('danger','No se encuentra información de tipo de estado');
return $this->redirectToRoute('dashboard_inicial');
}
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
$dto->tipoEstadoOrden = $tipoEstadoOrdenId;
$dto->tipoEstadoOrdenNombre = $tipoEstadoOrden->getNombre();
if($this->security->isGranted('ROLE_CLIENTE'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
foreach($user->getClientes() as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
if($this->security->isGranted('ROLE_TEVA'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$clientes = $this->clienteRepository->findBy(array('activo' => 1, 'integracionTeva' => 1), array());
foreach($clientes as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
$cliente_final = array();
if($dto->clienteFinal)
{
foreach($dto->clienteFinal as $item_cliente_final)
{
$cliente_final[] = $item_cliente_final;
}
}
if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
{
if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
{
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
$cliente_final = $user->getClientesFinales();
}
}
//$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
//return $this->redirectToRoute('dashboard_inicial');
$lista = $this->ordenRepository->findPorDashboardBuscarDto($dto, $cliente_final, TRUE);
return $this->render('dashboard/tipo_estado_orden.html.twig', array(
'lista' => $lista,
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_inicial');
}
}
/**
* @Route("/dashboard/seleccionar-tipo-estado-orden/excel/", name="dashboard_seleccionar_tipo_estado_orden_excel")
* @IsGranted("ROLE_USER")
*/
public function dashboard_seleccionar_tipo_estado_orden_excel(Request $request): Response
{
try{
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
if($this->security->isGranted('ROLE_CLIENTE'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
foreach($user->getClientes() as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
if($this->security->isGranted('ROLE_TEVA'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$clientes = $this->clienteRepository->findBy(array('activo' => 1, 'integracionTeva' => 1), array());
foreach($clientes as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
$cliente_final = array();
if($dto->clienteFinal)
{
foreach($dto->clienteFinal as $item_cliente_final)
{
$cliente_final[] = $item_cliente_final;
}
}
if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
{
if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
{
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
$cliente_final = $user->getClientesFinales();
}
}
$lista = $this->ordenRepository->findPorDashboardBuscarDto($dto, $cliente_final, TRUE);
if(!$lista)
{
$this->addFlash("error", 'No se encuentra ordenes coincidentes');
}
$ahora = new \DateTime('now');
$spreadsheet = new Spreadsheet();
/* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
$sheet = $spreadsheet->getActiveSheet();
$sheet->setShowGridlines(false);
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('logo');
$drawing->setDescription('logo');
$drawing->setPath('media/logo_transfarma_verde.png'); // put your path and image here
$drawing->setCoordinates('A1');
$drawing->setWorksheet($sheet);
$sheet->setCellValue('A6', 'DASHBOARD');
$sheet->getStyle('A6')->getFont()->setBold( true );
$sheet->setCellValue('A7', $ahora->format('d-m-Y H:i'));
$sheet->mergeCells("A6:Q6");
$sheet->mergeCells("A7:Q7");
$sheet->setCellValue('A9', 'Nro');
$sheet->setCellValue('B9', 'Codigo de Barra');
$sheet->setCellValue('C9', 'Fecha de Solicitud');
$sheet->setCellValue('D9', 'Estado');
$sheet->setCellValue('E9', 'Origen');
$sheet->setCellValue('F9', 'Destino');
$sheet->setCellValue('G9', 'Comuna');
$sheet->setCellValue('H9', 'Región');
$sheet->setCellValue('I9', 'Documento');
$sheet->setCellValue('J9', 'Orden de Compra');
$sheet->setCellValue('K9', 'Tipo de Servicio');
$sheet->setCellValue('L9', 'Tipo de Carga');
$sheet->setCellValue('M9', 'Tipo de Transporte');
$sheet->setCellValue('N9', 'Via de Transporte');
$sheet->setCellValue('O9', 'Requiere Cedible');
$sheet->setCellValue('P9', 'Seguro');
$sheet->setCellValue('Q9', 'Cenabast');
$sheet->setCellValue('R9', 'Muestra Médica');
$sheet->setCellValue('S9', 'Peso Fisico');
$sheet->setCellValue('T9', 'Peso Vol.');
$sheet->setCellValue('U9', 'Peso Max. (Transfarma)');
$sheet->setCellValue('V9', 'Bultos');
if(!$this->security->isGranted('ROLE_CLIENTE'))
{
$sheet->setCellValue('W9', 'Kilos (Operador)');
}
$fila = 9;
$i = 0;
foreach($lista as $item)
{
$i++;
$fila++;
$sheet->setCellValue('A'.$fila, $i);
$sheet->setCellValue('B'.$fila, $item->getCodigoBarra());
$sheet->setCellValue('C'.$fila, $item->getFechaSolicitud()->format('d-m-Y'));
$sheet->setCellValue('D'.$fila, $item->getEstadoOrden());
$sheet->setCellValue('E'.$fila, $item->getDireccionOrigen());
$sheet->setCellValue('F'.$fila, $item->getDireccionDestino());
if($item->getDireccionDestino()->getComuna())
{
$sheet->setCellValue('G'.$fila, $item->getDireccionDestino()->getComuna());
if($item->getDireccionDestino()->getComuna()->getRegion())
{
$sheet->setCellValue('H'.$fila, $item->getDireccionDestino()->getComuna()->getRegion());
}
}
$sheet->setCellValue('I'.$fila, $item->getTipoDocumento().' '.$item->getFolioTipoDocumento());
$sheet->setCellValue('J'.$fila, $item->getFolioOrdenCompra());
$sheet->setCellValue('K'.$fila, $item->getTipoServicio());
$sheet->setCellValue('L'.$fila, $item->getTipoCarga());
$sheet->setCellValue('M'.$fila, $item->getTipoTransporte());
$sheet->setCellValue('N'.$fila, $item->getViaTransporte());
$sheet->setCellValue('O'.$fila, $item->getRequiereCedible() ? 'SI' : 'NO');
$sheet->setCellValue('P'.$fila, $item->getSeguro() ? 'SI' : 'NO');
$sheet->setCellValue('Q'.$fila, $item->isCenabast() ? 'SI' : 'NO');
$sheet->setCellValue('R'.$fila, $item->isMuestraMedica() ? 'SI' : 'NO');
$sheet->setCellValue('S'.$fila, $item->getSumaPeso());
$sheet->setCellValue('T'.$fila, $item->getSumaPesoVol());
$sheet->setCellValue('U'.$fila, $item->getSumaPesoMax());
$sheet->setCellValue('V'.$fila, $item->getSumaBultos());
if(!$this->security->isGranted('ROLE_CLIENTE'))
{
$sheet->setCellValue('W'.$fila, $item->getUrbanoPeso());
}
}
//$sheet->setAutoFilter($sheet->calculateWorksheetDimension());
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);
$sheet->getColumnDimension('D')->setAutoSize(true);
$sheet->getColumnDimension('E')->setAutoSize(true);
$sheet->getColumnDimension('F')->setAutoSize(true);
$sheet->getColumnDimension('G')->setAutoSize(true);
$sheet->getColumnDimension('H')->setAutoSize(true);
$sheet->getColumnDimension('I')->setAutoSize(true);
$sheet->getColumnDimension('J')->setAutoSize(true);
$sheet->getColumnDimension('K')->setAutoSize(true);
$sheet->getColumnDimension('L')->setAutoSize(true);
$sheet->getColumnDimension('M')->setAutoSize(true);
$sheet->getColumnDimension('N')->setAutoSize(true);
$sheet->getColumnDimension('O')->setAutoSize(true);
$sheet->getColumnDimension('P')->setAutoSize(true);
$sheet->getColumnDimension('Q')->setAutoSize(true);
$sheet->getColumnDimension('R')->setAutoSize(true);
$sheet->getColumnDimension('S')->setAutoSize(true);
$sheet->getColumnDimension('T')->setAutoSize(true);
$sheet->getColumnDimension('U')->setAutoSize(true);
$sheet->getColumnDimension('V')->setAutoSize(true);
$sheet->getColumnDimension('W')->setAutoSize(true);
$sheet->getStyle('A9:W9')->getFont()->setBold( true );
$sheet->getStyle('A9:W9')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle('A9:W9')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FF426384');
// Create your Office 2007 Excel (XLSX Format)
$writer = new Xlsx($spreadsheet);
// Create a Temporary file in the system
$fileName = 'TRF-DASHBOARD-'.($ahora->format('Ymd-Hi')).'.xlsx';
$temp_file = tempnam($this->getParameter('kernel.project_dir').'/temp/', $fileName);
// Create the excel file in the tmp directory of the system
$writer->save($temp_file);
// Return the excel file as an attachment
return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
} catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
private function dashboard_get_datos_resumen(DashboardBuscarDto $dto, $cliente_final)
{
$resumen = $this->ordenRepository->getDashboadResumen($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$envios_total = 0;
$envios_entregados = 0;
$envios_parciales = 0;
$envios_error = 0;
$envios_no_entregados = 0;
$envios_devueltos = 0;
$metricas_kilos_total = 0;
$metricas_bultos_total = 0;
$metricas_kilos_promedio = 0;
$metricas_bultos_promedio = 0;
$metricas_envios_promedio = 0;
$sla_no_entregados = 0;
$sla_entregados = 0;
$sla_parciales = 0;
$via_transporte_terrestre = 0;
$via_transporte_aereo = 0;
$kilos_transporte_terrestre = 0;
$kilos_transporte_aereo = 0;
$tipo_carga_ambiente = 0;
$tipo_carga_refrigerado = 0;
$tipo_carga_congelado = 0;
$tipo_carga_temperatura_controlada = 0;
$tiempo_entrega_promedio = 0;
$tiempo_entrega_tipo_carga_ambiente = 0;
$tiempo_entrega_tipo_carga_refrigerado = 0;
$tiempo_entrega_tipo_carga_congelado = 0;
$tiempo_entrega_tipo_carga_temperatura_controlada = 0;
$total_documentos_tributarios = 0;
if($resumen)
{
$envios_total = $resumen["envios_total"];
$envios_entregados = $resumen["envios_entregados"];
$envios_parciales = $resumen["envios_parciales"];
$envios_error = $resumen["envios_error"];
$envios_no_entregados = $resumen["envios_no_entregados"];
$envios_devueltos = $resumen["envios_devueltos"];
$metricas_kilos_total = $resumen["metricas_kilos_total"];
$metricas_bultos_total = $resumen["metricas_bultos_total"];
$metricas_kilos_promedio = $resumen["metricas_kilos_promedio"];
$metricas_bultos_promedio = $resumen["metricas_bultos_promedio"];
$metricas_envios_promedio = $resumen["metricas_envios_promedio"];
$sla_no_entregados = $resumen["sla_no_entregados"];
$sla_entregados = $resumen["sla_entregados"];
$sla_parciales = $resumen["sla_parciales"];
$via_transporte_terrestre = $resumen["via_transporte_terrestre"];
$via_transporte_aereo = $resumen["via_transporte_aereo"];
$kilos_transporte_terrestre = $resumen["kilos_transporte_terrestre"];
$kilos_transporte_aereo = $resumen["kilos_transporte_aereo"];
$tipo_carga_ambiente = $resumen["tipo_carga_ambiente"];
$tipo_carga_refrigerado = $resumen["tipo_carga_refrigerado"];
$tipo_carga_congelado = $resumen["tipo_carga_congelado"];
$tipo_carga_temperatura_controlada = $resumen["tipo_carga_temperatura_controlada"];
$tiempo_entrega_promedio = $resumen["tiempo_entrega_promedio"];
$tiempo_entrega_tipo_carga_ambiente = $resumen["tiempo_entrega_tipo_carga_ambiente"];
$tiempo_entrega_tipo_carga_refrigerado = $resumen["tiempo_entrega_tipo_carga_refrigerado"];
$tiempo_entrega_tipo_carga_congelado = $resumen["tiempo_entrega_tipo_carga_congelado"];
$tiempo_entrega_tipo_carga_temperatura_controlada = $resumen["tiempo_entrega_tipo_carga_temperatura_controlada"];
$total_documentos_tributarios = $resumen["total_documentos_tributarios"];
}
$tiempo_entrega_promedio_d = 0;
$tiempo_entrega_promedio_h = 0;
$tiempo_entrega_promedio_m = 0;
$tiempo_entrega_tipo_carga_ambiente_d = 0;
$tiempo_entrega_tipo_carga_ambiente_h = 0;
$tiempo_entrega_tipo_carga_ambiente_m = 0;
$tiempo_entrega_tipo_carga_refrigerado_d = 0;
$tiempo_entrega_tipo_carga_refrigerado_h = 0;
$tiempo_entrega_tipo_carga_refrigerado_m = 0;
$tiempo_entrega_tipo_carga_congelado_d = 0;
$tiempo_entrega_tipo_carga_congelado_h = 0;
$tiempo_entrega_tipo_carga_congelado_m = 0;
$tiempo_entrega_tipo_carga_temperatura_controlada_d = 0;
$tiempo_entrega_tipo_carga_temperatura_controlada_h = 0;
$tiempo_entrega_tipo_carga_temperatura_controlada_m = 0;
if($tiempo_entrega_promedio)
{
$tiempo_entrega_promedio_d = floor($tiempo_entrega_promedio / 1440);
$tiempo_entrega_promedio_h = floor(($tiempo_entrega_promedio - ($tiempo_entrega_promedio_d * 1440)) / 60);
$tiempo_entrega_promedio_m = ($tiempo_entrega_promedio % 60);
}
if($tiempo_entrega_tipo_carga_ambiente)
{
$tiempo_entrega_tipo_carga_ambiente_d = floor($tiempo_entrega_tipo_carga_ambiente / 1440);
$tiempo_entrega_tipo_carga_ambiente_h = floor(($tiempo_entrega_tipo_carga_ambiente - ($tiempo_entrega_tipo_carga_ambiente_d * 1440)) / 60);
$tiempo_entrega_tipo_carga_ambiente_m = ($tiempo_entrega_tipo_carga_ambiente % 60);
}
if($tiempo_entrega_tipo_carga_refrigerado)
{
$tiempo_entrega_tipo_carga_refrigerado_d = floor($tiempo_entrega_tipo_carga_refrigerado / 1440);
$tiempo_entrega_tipo_carga_refrigerado_h = floor(($tiempo_entrega_tipo_carga_refrigerado - ($tiempo_entrega_tipo_carga_refrigerado_d * 1440)) / 60);
$tiempo_entrega_tipo_carga_refrigerado_m = ($tiempo_entrega_tipo_carga_refrigerado % 60);
}
if($tiempo_entrega_tipo_carga_congelado)
{
$tiempo_entrega_tipo_carga_congelado_d = floor($tiempo_entrega_tipo_carga_congelado / 1440);
$tiempo_entrega_tipo_carga_congelado_h = floor(($tiempo_entrega_tipo_carga_congelado - ($tiempo_entrega_tipo_carga_congelado_d * 1440)) / 60);
$tiempo_entrega_tipo_carga_congelado_m = ($tiempo_entrega_tipo_carga_congelado % 60);
}
if($tiempo_entrega_tipo_carga_temperatura_controlada)
{
$tiempo_entrega_tipo_carga_temperatura_controlada_d = floor($tiempo_entrega_tipo_carga_temperatura_controlada / 1440);
$tiempo_entrega_tipo_carga_temperatura_controlada_h = floor(($tiempo_entrega_tipo_carga_temperatura_controlada - ($tiempo_entrega_tipo_carga_temperatura_controlada_d * 1440)) / 60);
$tiempo_entrega_tipo_carga_temperatura_controlada_m = ($tiempo_entrega_tipo_carga_temperatura_controlada % 60);
}
return array(
'envios_total' => $envios_total,
'envios_entregados' => $envios_entregados,
'envios_parciales' => $envios_parciales,
'envios_error' => $envios_error,
'envios_no_entregados' => $envios_no_entregados,
'envios_devueltos' => $envios_devueltos,
'metricas_kilos_total' => $metricas_kilos_total,
'metricas_bultos_total' => $metricas_bultos_total,
'metricas_kilos_promedio' => $metricas_kilos_promedio,
'metricas_bultos_promedio' => $metricas_bultos_promedio,
'metricas_envios_promedio' => $metricas_envios_promedio,
'sla_no_entregados' => $sla_no_entregados,
'sla_entregados' => $sla_entregados,
'sla_parciales' => $sla_parciales,
'via_transporte_terrestre' => $via_transporte_terrestre,
'via_transporte_aereo' => $via_transporte_aereo,
'kilos_transporte_terrestre' => $kilos_transporte_terrestre,
'kilos_transporte_aereo' => $kilos_transporte_aereo,
'tipo_carga_ambiente' => $tipo_carga_ambiente,
'tipo_carga_refrigerado' => $tipo_carga_refrigerado,
'tipo_carga_congelado' => $tipo_carga_congelado,
'tipo_carga_temperatura_controlada' => $tipo_carga_temperatura_controlada,
'tiempo_entrega_promedio_d' => $tiempo_entrega_promedio_d,
'tiempo_entrega_promedio_h' => $tiempo_entrega_promedio_h,
'tiempo_entrega_promedio_m' => $tiempo_entrega_promedio_m,
'tiempo_entrega_tipo_carga_ambiente_d' => $tiempo_entrega_tipo_carga_ambiente_d,
'tiempo_entrega_tipo_carga_ambiente_h' => $tiempo_entrega_tipo_carga_ambiente_h,
'tiempo_entrega_tipo_carga_ambiente_m' => $tiempo_entrega_tipo_carga_ambiente_m,
'tiempo_entrega_tipo_carga_refrigerado_d' => $tiempo_entrega_tipo_carga_refrigerado_d,
'tiempo_entrega_tipo_carga_refrigerado_h' => $tiempo_entrega_tipo_carga_refrigerado_h,
'tiempo_entrega_tipo_carga_refrigerado_m' => $tiempo_entrega_tipo_carga_refrigerado_m,
'tiempo_entrega_tipo_carga_congelado_d' => $tiempo_entrega_tipo_carga_congelado_d,
'tiempo_entrega_tipo_carga_congelado_h' => $tiempo_entrega_tipo_carga_congelado_h,
'tiempo_entrega_tipo_carga_congelado_m' => $tiempo_entrega_tipo_carga_congelado_m,
'tiempo_entrega_tipo_carga_temperatura_controlada_d' => $tiempo_entrega_tipo_carga_temperatura_controlada_d,
'tiempo_entrega_tipo_carga_temperatura_controlada_h' => $tiempo_entrega_tipo_carga_temperatura_controlada_h,
'tiempo_entrega_tipo_carga_temperatura_controlada_m' => $tiempo_entrega_tipo_carga_temperatura_controlada_m,
'total_documentos_tributarios' => $total_documentos_tributarios,
);
}
/**
* @Route("/dashboard/graficos/", name="dashboard_graficos")
* @IsGranted("ROLE_USER")
*/
public function dashboard_graficos(Request $request): Response
{
try
{
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
$form = $this->createForm(DashboardBuscarFormType::class, $dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$dto->tipoCarga = null;
$dto->tipoEstadoOrden = null;
$dto->region = null;
$dto->viaTransporte = null;
}
if($this->security->isGranted('ROLE_CLIENTE'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
foreach($user->getClientes() as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
if($this->security->isGranted('ROLE_TEVA'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$clientes = $this->clienteRepository->findBy(array('activo' => 1, 'integracionTeva' => 1), array());
foreach($clientes as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
$cliente_final = array();
if($dto->clienteFinal)
{
foreach($dto->clienteFinal as $item_cliente_final)
{
$cliente_final[] = $item_cliente_final;
}
}
if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
{
if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
{
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
$cliente_final = $user->getClientesFinales();
}
}
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
$resumen = $this->dashboard_get_datos_resumen($dto, $cliente_final);
$estados_orden = $this->ordenRepository->getDashboadEstadoOrden($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$fechas_temperaturas = $this->ordenRepository->getDashboadFechasTemperaturas($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$tiempo_promedio_region = $this->ordenRepository->getDashboadTiempoPromedioRegion($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$tiempo_promedio_ciudad = $this->ordenRepository->getDashboadTiempoPromedioCiudad($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$resumen_dia = $this->ordenRepository->getDashboadResumenDia($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
$kilos_region = $this->ordenRepository->getDashboadKilosRegion($dto->supermandante, $dto->cliente, $cliente_final, $dto->fechaDesde, $dto->fechaHasta, $dto->tipoCarga, $dto->tipoEstadoOrden, $dto->region, $dto->viaTransporte);
return $this->render('dashboard/graficos.html.twig', array(
'form' => $form->createView(),
'filtros' => $dto->getFiltros(),
'resumen' => $resumen,
'estados_orden' => $estados_orden,
'fechas_temperaturas' => $fechas_temperaturas,
'tiempo_promedio_region' => $tiempo_promedio_region,
'tiempo_promedio_ciudad' => $tiempo_promedio_ciudad,
'resumen_dia' => $resumen_dia,
'kilos_region' => $kilos_region
));
} catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
/**
* @Route("/dashboard/datos/", name="dashboard_datos")
* @IsGranted("ROLE_USER")
*/
public function dashboard_datos(Request $request)
{
try
{
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', NULL);
return $this->dashboard_datos_page($request, 1);
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
/**
* @Route("/dashboard/datos/page/{currentPage}/", name="dashboard_datos_page")
* @IsGranted("ROLE_USER")
*/
public function dashboard_datos_page(Request $request, $currentPage = 1): Response
{
try{
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
$form = $this->createForm(DashboardBuscarFormType::class, $dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$dto->tipoCarga = null;
$dto->tipoEstadoOrden = null;
$dto->region = null;
$dto->viaTransporte = null;
}
if($this->security->isGranted('ROLE_CLIENTE'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
foreach($user->getClientes() as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
if($this->security->isGranted('ROLE_TEVA'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$clientes = $this->clienteRepository->findBy(array('activo' => 1, 'integracionTeva' => 1), array());
foreach($clientes as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
$cliente_final = array();
if($dto->clienteFinal)
{
foreach($dto->clienteFinal as $item_cliente_final)
{
$cliente_final[] = $item_cliente_final;
}
}
if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
{
if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
{
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
$cliente_final = $user->getClientesFinales();
}
}
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
//$lista = $this->ordenRepository->getOrdenesPorDashboardBuscarDto($dto, $cliente_final);
$limit = 100;
$total = $this->ordenRepository->countOrdenesPorDashboardBuscarDto($dto, $cliente_final);
$lista = $this->ordenRepository->getOrdenesPorDashboardBuscarDto($dto, $cliente_final, $currentPage, $limit);
$maxPages = ceil($total['total'] / $limit);
if(!$lista)
{
$this->addFlash("error", 'No se encuentra ordenes coincidentes');
}
return $this->render('dashboard/datos.html.twig', array(
'form' => $form->createView(),
'lista' => $lista,
'thisPage' => $currentPage,
'maxPages' => $maxPages,
'total' => $total['total'],
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
/**
* @Route("/dashboard/datos/excel/", name="dashboard_datos_excel")
* @IsGranted("ROLE_USER")
*/
public function dashboard_datos_excel(Request $request): Response
{
try{
set_time_limit(0);
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
if($this->security->isGranted('ROLE_CLIENTE'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
foreach($user->getClientes() as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
if($this->security->isGranted('ROLE_TEVA'))
{
if(!$dto->cliente || sizeof($dto->cliente) == 0)
{
$dto->cliente = array();
$clientes = $this->clienteRepository->findBy(array('activo' => 1, 'integracionTeva' => 1), array());
foreach($clientes as $item_cliente)
{
$dto->cliente[] = $item_cliente;
}
}
}
$cliente_final = array();
if($dto->clienteFinal)
{
foreach($dto->clienteFinal as $item_cliente_final)
{
$cliente_final[] = $item_cliente_final;
}
}
if($this->security->isGranted('ROLE_CLIENTE_FINAL'))
{
if(!$dto->clienteFinal || sizeof($dto->clienteFinal) == 0)
{
$user = $this->security->getUser();
if (!$user) {
throw new \LogicException('No se identifica el usuario actual');
}
$cliente_final = $user->getClientesFinales();
}
}
$lista = $this->ordenRepository->getOrdenesPorDashboardBuscarDtoAll($dto, $cliente_final);
if(!$lista)
{
$this->addFlash("error", 'No se encuentra ordenes coincidentes');
}
$ahora = new \DateTime('now');
$esTransfarma = $this->security->isGranted('ROLE_TRANSFARMA');
$esMandante = $this->security->isGranted('ROLE_CLIENTE');
$esClienteFinal = $this->security->isGranted('ROLE_CLIENTE_FINAL');
$ocultarPesos = ($esMandante || $esClienteFinal);
$spreadsheet = new Spreadsheet();
/* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
$sheet = $spreadsheet->getActiveSheet();
$sheet->setShowGridlines(false);
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('logo');
$drawing->setDescription('logo');
$drawing->setPath('media/logo_transfarma_verde.png'); // put your path and image here
$drawing->setCoordinates('A1');
$drawing->setWorksheet($sheet);
$sheet->setCellValue('A6', 'DASHBOARD');
$sheet->getStyle('A6')->getFont()->setBold( true );
$sheet->setCellValue('A7', $ahora->format('d-m-Y H:i'));
$sheet->mergeCells("A6:Z6");
$sheet->mergeCells("A7:Z7");
$sheet->setCellValue('A9', 'Nro');
$sheet->setCellValue('B9', 'Codigo de Barra');
$sheet->setCellValue('C9', 'Fecha de Solicitud');
$sheet->setCellValue('D9', 'Mandante');
$sheet->setCellValue('E9', 'Cliente');
$sheet->setCellValue('F9', 'Estado');
$sheet->setCellValue('G9', 'Origen');
$sheet->setCellValue('H9', 'Ciudad de Origen');
$sheet->setCellValue('I9', 'Destino');
$sheet->setCellValue('J9', 'Dirección');
$sheet->setCellValue('K9', 'Comuna');
$sheet->setCellValue('L9', 'Región');
$sheet->setCellValue('M9', 'Zona');
$sheet->setCellValue('N9', 'Base de Cobertura');
$sheet->setCellValue('O9', 'Documento');
$sheet->setCellValue('P9', 'Nº Doc');
$sheet->setCellValue('Q9', 'Orden de Compra');
$sheet->setCellValue('R9', 'Tipo de Servicio');
$sheet->setCellValue('S9', 'Tipo de Carga');
$sheet->setCellValue('T9', 'Tipo de Transporte');
$sheet->setCellValue('U9', 'Via de Transporte');
$sheet->setCellValue('V9', 'Requiere Cedible');
$sheet->setCellValue('W9', 'Seguro');
$sheet->setCellValue('X9', 'Cenabast');
$sheet->setCellValue('Y9', 'Muestra Médica');
$sheet->setCellValue('Z9', 'Bultos');
if (!$ocultarPesos) {
$sheet->setCellValue('AA9', 'Peso Kilos');
$sheet->setCellValue('AB9', 'Peso Vol.');
}
$sheet->setCellValue('AC9', 'Nombre Receptor');
$sheet->setCellValue('AD9', 'RUT Receptor');
$sheet->setCellValue('AE9', 'Fecha Recepcion');
$sheet->setCellValue('AF9', 'Fecha Ruta');
if($this->security->isGranted('ROLE_TRANSFARMA'))
{
$sheet->setCellValue('AG9', 'Patente Ruta');
}
$sheet->setCellValue('AH9', 'Tramo Vehiculo');
$sheet->setCellValue('AI9', 'Tiempo Transcurrido (hrs)');
$sheet->setCellValue('AJ9', 'Lead Time MT (Hrs)');
$sheet->setCellValue('AK9', 'OTIF (ON TIME)');
$sheet->setCellValue('AL9', 'Bultos (cantidad PK Solicitados)');
$sheet->setCellValue('AM9', 'Bultos (cantidad PK recibidos)');
$sheet->setCellValue('AN9', 'OTIF (IN FULL)');
$sheet->setCellValue('AO9', 'Clasificación OTIF');
$sheet->setCellValue('AP9', 'Clasificación Compliance OTIF');
// Peso Max lo ve Transfarma + Mandante + Cliente Final
if ($esTransfarma || $ocultarPesos) {
$sheet->setCellValue('AQ9', 'Peso Max. (Transfarma)');
}
// Estas columnas SOLO Transfarma
if ($esTransfarma) {
$sheet->setCellValue('AR9', 'Codigo de Delivery');
$sheet->setCellValue('AS9', 'Código Reversa');
$sheet->setCellValue('AT9', 'Estado');
$sheet->setCellValue('AU9', 'Subestado');
$sheet->setCellValue('AV9', 'Codigo Data Logger');
$sheet->setCellValue('AW9', 'Codigo Vacutec');
$sheet->setCellValue('AX9', 'Manifiesto Ruta asignado');
}
$fila = 9;
$i = 0;
foreach($lista as $item)
{
$i++;
$fila++;
$sheet->setCellValue('A'.$fila, $i);
$sheet->setCellValue('B'.$fila, $item["codigo_barra"]);
$sheet->setCellValue('C'.$fila, (new \DateTime($item["fecha_solicitud"]))->format('d-m-Y'));
$sheet->setCellValue('D'.$fila, $item["nombre_cliente"]);
$sheet->setCellValue('E'.$fila, $item["nombre_cliente_final"]);
$sheet->setCellValue('F'.$fila, $item["nombre_estado"]);
$sheet->setCellValue('G'.$fila, $item["nombre_direccion_origen"]);
$sheet->setCellValue('H'.$fila, $item["ciudad_direccion_origen"]);
$sheet->setCellValue('I'.$fila, $item["nombre_direccion_destino"]);
$sheet->setCellValue('J'.$fila, $item["direccion"]);
$sheet->setCellValue('K'.$fila, $item["nombre_comuna"]);
$sheet->setCellValue('L'.$fila, $item["nombre_region"]);
$sheet->setCellValue('M'.$fila, $item["nombre_zona"]);
$sheet->setCellValue('N'.$fila, $item["nombre_sucursal"]);
$documentos = '';
if($item['tipo_documento_01'])
{
$documentos = $documentos.$item['tipo_documento_01'].' '.$item['folio_tipo_documento_01'].' ';
if($item['copia_tipo_documento01'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento01'].') ';
}
}
if($item['tipo_documento_02'])
{
$documentos = $documentos.$item['tipo_documento_02'].' '.$item['folio_tipo_documento_02'].' ';
if($item['copia_tipo_documento02'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento02'].') ';
}
}
if($item['tipo_documento_03'])
{
$documentos = $documentos.$item['tipo_documento_03'].' '.$item['folio_tipo_documento_03'].' ';
if($item['copia_tipo_documento03'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento03'].') ';
}
}
if($item['tipo_documento_04'])
{
$documentos = $documentos.$item['tipo_documento_04'].' '.$item['folio_tipo_documento_04'].' ';
if($item['copia_tipo_documento04'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento04'].') ';
}
}
if($item['tipo_documento_05'])
{
$documentos = $documentos.$item['tipo_documento_05'].' '.$item['folio_tipo_documento_05'].' ';
if($item['copia_tipo_documento05'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento05'].') ';
}
}
if($item['tipo_documento_06'])
{
$documentos = $documentos.$item['tipo_documento_06'].' '.$item['folio_tipo_documento_06'].' ';
if($item['copia_tipo_documento06'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento06'].') ';
}
}
if($item['tipo_documento_07'])
{
$documentos = $documentos.$item['tipo_documento_07'].' '.$item['folio_tipo_documento_07'].' ';
if($item['copia_tipo_documento07'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento07'].') ';
}
}
if($item['tipo_documento_08'])
{
$documentos = $documentos.$item['tipo_documento_08'].' '.$item['folio_tipo_documento_08'].' ';
if($item['copia_tipo_documento08'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento08'].') ';
}
}
if($item['tipo_documento_09'])
{
$documentos = $documentos.$item['tipo_documento_09'].' '.$item['folio_tipo_documento_09'].' ';
if($item['copia_tipo_documento09'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento09'].') ';
}
}
if($item['tipo_documento_10'])
{
$documentos = $documentos.$item['tipo_documento_10'].' '.$item['folio_tipo_documento_10'].' ';
if($item['copia_tipo_documento10'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento10'].') ';
}
}
if($item['tipo_documento_11'])
{
$documentos = $documentos.$item['tipo_documento_11'].' '.$item['folio_tipo_documento_11'].' ';
if($item['copia_tipo_documento11'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento11'].') ';
}
}
if($item['tipo_documento_12'])
{
$documentos = $documentos.$item['tipo_documento_12'].' '.$item['folio_tipo_documento_12'].' ';
if($item['copia_tipo_documento12'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento12'].') ';
}
}
if($item['tipo_documento_13'])
{
$documentos = $documentos.$item['tipo_documento_13'].' '.$item['folio_tipo_documento_13'].' ';
if($item['copia_tipo_documento13'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento13'].') ';
}
}
if($item['tipo_documento_14'])
{
$documentos = $documentos.$item['tipo_documento_14'].' '.$item['folio_tipo_documento_14'].' ';
if($item['copia_tipo_documento14'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento14'].') ';
}
}
if($item['tipo_documento_15'])
{
$documentos = $documentos.$item['tipo_documento_15'].' '.$item['folio_tipo_documento_15'].' ';
if($item['copia_tipo_documento15'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento15'].') ';
}
}
if($item['tipo_documento_16'])
{
$documentos = $documentos.$item['tipo_documento_16'].' '.$item['folio_tipo_documento_16'].' ';
if($item['copia_tipo_documento16'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento16'].') ';
}
}
if($item['tipo_documento_17'])
{
$documentos = $documentos.$item['tipo_documento_17'].' '.$item['folio_tipo_documento_17'].' ';
if($item['copia_tipo_documento17'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento17'].') ';
}
}
if($item['tipo_documento_18'])
{
$documentos = $documentos.$item['tipo_documento_18'].' '.$item['folio_tipo_documento_18'].' ';
if($item['copia_tipo_documento18'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento18'].') ';
}
}
if($item['tipo_documento_19'])
{
$documentos = $documentos.$item['tipo_documento_19'].' '.$item['folio_tipo_documento_19'].' ';
if($item['copia_tipo_documento19'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento19'].') ';
}
}
if($item['tipo_documento_20'])
{
$documentos = $documentos.$item['tipo_documento_20'].' '.$item['folio_tipo_documento_20'].' ';
if($item['copia_tipo_documento20'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento20'].') ';
}
}
if($item['tipo_documento_21'])
{
$documentos = $documentos.$item['tipo_documento_21'].' '.$item['folio_tipo_documento_21'].' ';
if($item['copia_tipo_documento21'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento21'].') ';
}
}
if($item['tipo_documento_22'])
{
$documentos = $documentos.$item['tipo_documento_22'].' '.$item['folio_tipo_documento_22'].' ';
if($item['copia_tipo_documento22'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento22'].') ';
}
}
if($item['tipo_documento_23'])
{
$documentos = $documentos.$item['tipo_documento_23'].' '.$item['folio_tipo_documento_23'].' ';
if($item['copia_tipo_documento23'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento23'].') ';
}
}
if($item['tipo_documento_24'])
{
$documentos = $documentos.$item['tipo_documento_24'].' '.$item['folio_tipo_documento_24'].' ';
if($item['copia_tipo_documento24'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento24'].') ';
}
}
if($item['tipo_documento_25'])
{
$documentos = $documentos.$item['tipo_documento_25'].' '.$item['folio_tipo_documento_25'].' ';
if($item['copia_tipo_documento25'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento25'].') ';
}
}
if($item['tipo_documento_26'])
{
$documentos = $documentos.$item['tipo_documento_26'].' '.$item['folio_tipo_documento_26'].' ';
if($item['copia_tipo_documento26'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento26'].') ';
}
}
if($item['tipo_documento_27'])
{
$documentos = $documentos.$item['tipo_documento_27'].' '.$item['folio_tipo_documento_27'].' ';
if($item['copia_tipo_documento27'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento27'].') ';
}
}
if($item['tipo_documento_28'])
{
$documentos = $documentos.$item['tipo_documento_28'].' '.$item['folio_tipo_documento_28'].' ';
if($item['copia_tipo_documento28'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento28'].') ';
}
}
if($item['tipo_documento_29'])
{
$documentos = $documentos.$item['tipo_documento_29'].' '.$item['folio_tipo_documento_29'].' ';
if($item['copia_tipo_documento29'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento29'].') ';
}
}
if($item['tipo_documento_30'])
{
$documentos = $documentos.$item['tipo_documento_30'].' '.$item['folio_tipo_documento_30'].' ';
if($item['copia_tipo_documento30'])
{
$documentos = $documentos.' (Copia '.$item['copia_tipo_documento30'].') ';
}
}
$sheet->setCellValue('O'.$fila, $documentos);
$sheet->setCellValue('P'.$fila, $item["suma_documentos"]);
$sheet->setCellValue('Q'.$fila, $item["folio_orden_compra"]);
$sheet->setCellValue('R'.$fila, $item["nombre_tipo_servicio"]);
$sheet->setCellValue('S'.$fila, $item["nombre_tipo_carga"]);
$sheet->setCellValue('T'.$fila, $item["nombre_tipo_transporte"]);
$sheet->setCellValue('U'.$fila, $item["nombre_via_transporte"]);
$sheet->setCellValue('V'.$fila, $item["requiere_cedible"] ? 'SI' : 'NO');
$sheet->setCellValue('W'.$fila, $item["seguro"] ? 'SI' : 'NO');
$sheet->setCellValue('X'.$fila, $item["cenabast"] ? 'SI' : 'NO');
$sheet->setCellValue('Y'.$fila, $item["muestra_medica"] ? 'SI' : 'NO');
$sheet->setCellValue('Z'.$fila, $item["suma_bultos"]);
if (!$ocultarPesos) {
$sheet->setCellValue('AA'.$fila, $item["suma_peso_kilos"]);
$sheet->setCellValue('AB'.$fila, $item["suma_peso_vol"]);
}
$sheet->setCellValue('AC'.$fila, $item["nombre_entrega"]);
$sheet->setCellValue('AD'.$fila, $item["rut_entrega"]);
if($item["fecha_entrega"])
{
$sheet->setCellValue('AE'.$fila, (new \DateTime($item["fecha_entrega"]))->format('d-m-Y'));
}
if($item["fecha_ruta"])
{
$sheet->setCellValue('AF'.$fila, (new \DateTime($item["fecha_ruta"]))->format('d-m-Y'));
}
if($this->security->isGranted('ROLE_TRANSFARMA'))
{
$sheet->setCellValue('AG'.$fila, $item["vehiculo_patente"].$item["urbano_patente"]);
}
$sheet->setCellValue('AH'.$fila, $item["tramo_vehiculo"]);
$sheet->setCellValue('AI'.$fila, $item["tiempo_transcurrido"]);
$sheet->setCellValue('AJ'.$fila, $item["lead_time_cliente"]);
$sheet->setCellValue('AK'.$fila, $item["otif_cliente"]);
$sheet->setCellValue('AL'.$fila, $item["cantidad_bultos_solicitados"]);
$sheet->setCellValue('AM'.$fila, $item["cantidad_bultos_recibidos"]);
$sheet->setCellValue('AN'.$fila, $item["otif_in_full"]);
$sheet->setCellValue('AO'.$fila, $item["otif_cliente"].' - '.$item["otif_in_full"]);
$sheet->setCellValue('AP'.$fila, $item["compliance_cliente"]);
if ($esTransfarma || $ocultarPesos) {
$sheet->setCellValue('AQ'.$fila, $item["suma_kilos"]);
}
if ($esTransfarma) {
$sheet->setCellValue('AR'.$fila, $item["codigo_delivery"].' '.$item["dhl_guia"].' '.$item["extern_order_key"]);
$sheet->setCellValue('AS'.$fila, $item["codigo_barra_logistica_inversa"]);
$sheet->setCellValue('AT'.$fila, $item["nombre_estado"]);
$sheet->setCellValue('AU'.$fila, $item["nombre_subestado"]);
$sheet->setCellValue('AV'.$fila, $item["codigo_data_logger"]);
$sheet->setCellValue('AW'.$fila, $item["codigo_vacutec"]);
$sheet->setCellValue('AX'.$fila, $item["codigo_manifiesto"]);
}
}
//$sheet->setAutoFilter($sheet->calculateWorksheetDimension());
if ($esTransfarma) {
$ultimaColumna = 'AX';
} elseif ($ocultarPesos) {
$ultimaColumna = 'AQ';
} else {
$ultimaColumna = 'AP';
}
$sheet->getStyle('A9:'.$ultimaColumna.'9')->getFont()->setBold(true);
$sheet->getStyle('A9:'.$ultimaColumna.'9')->getFont()->getColor()
->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle('A9:'.$ultimaColumna.'9')->getFill()
->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
->getStartColor()->setARGB('FF426384');
// Create your Office 2007 Excel (XLSX Format)
$writer = new Xlsx($spreadsheet);
// Create a Temporary file in the system
$fileName = 'TRF-DASHBOARD-'.($ahora->format('Ymd-Hi')).'.xlsx';
$temp_file = tempnam($this->getParameter('kernel.project_dir').'/temp/', $fileName);
// Create the excel file in the tmp directory of the system
$writer->save($temp_file);
// Return the excel file as an attachment
return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
} catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
/**
* @Route("/dashboard/seleccionar-region/",name="dashboard_seleccionar_region")
* @param Request $request
*/
public function dashboard_seleccionar_region(Request $request)
{
try
{
$regionNombre = $request->query->get("region_nombre");
$region = $this->regionRepository->findOneByNombre($regionNombre);
if(!$region)
{
$this->addFlash('danger','No se encuentra información de región');
return $this->redirectToRoute('dashboard_inicial');
}
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
$dto->region = $region;
$dto->regionNombre = $region->getNombre();
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
return $this->redirectToRoute('dashboard_inicial');
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_inicial');
}
}
/**
* @Route("/dashboard/seleccionar-tipo-carga/",name="dashboard_seleccionar_tipo_carga")
* @param Request $request
*/
public function dashboard_seleccionar_tipo_carga(Request $request)
{
try
{
$tipoCargaId = $request->query->get("tipo_carga_id");
$tipoCarga = $this->tipoCargaRepository->findOneById($tipoCargaId);
if(!$tipoCarga)
{
$this->addFlash('danger','No se encuentra información de tipo de carga');
return $this->redirectToRoute('dashboard_inicial');
}
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
$dto->tipoCarga = $tipoCargaId;
$dto->tipoCargaNombre = $tipoCarga->getNombre();
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
return $this->redirectToRoute('dashboard_inicial');
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_inicial');
}
}
/**
* @Route("/dashboard/seleccionar-via-transporte/",name="dashboard_seleccionar_via_transporte")
* @param Request $request
*/
public function dashboard_seleccionar_via_transporte(Request $request)
{
try
{
$viaTransporteId = $request->query->get("via_transporte_id");
$viaTransporte = $this->viaTransporteRepository->findOneById($viaTransporteId);
if(!$viaTransporte)
{
$this->addFlash('danger','No se encuentra información de via de transporte');
return $this->redirectToRoute('dashboard_inicial');
}
$dto = $this->session->get('SESION_DASHBOARD_BUSCAR_DTO');
if(!$dto)
{
$dto = new DashboardBuscarDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('today'));
}
else
{
if($dto->supermandante)
{
$dto->supermandante = $this->entityManager->merge($dto->supermandante);
}
if($dto->cliente)
{
$posicion = 0;
foreach($dto->cliente as $item_cliente){
$dto->cliente[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
if($dto->clienteFinal)
{
$posicion = 0;
foreach($dto->clienteFinal as $item_cliente){
$dto->clienteFinal[$posicion] = $this->entityManager->merge($item_cliente);
$posicion++;
}
}
}
$dto->viaTransporte = $viaTransporteId;
$dto->viaTransporteNombre = $viaTransporte->getNombre();
$this->session->set('SESION_DASHBOARD_BUSCAR_DTO', $dto);
return $this->redirectToRoute('dashboard_inicial');
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_inicial');
}
}
/**
* @Route("/dashboard/temperatura/anterior/", name="dashboard_temperatura_anterior")
* @IsGranted("ROLE_USER")
*/
public function dashboard_temperatura_anterior(Request $request): Response
{
try{
$dto = new DashboardTemperaturaDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('now'));
$lista = null;
$rango_operacion = null;
$vehiculo = null;
$dispositivo = null;
$fecha_inicio = null;
$fecha_fin = null;
$numero_puntos_medidos = 0;
$limite_inferior = null;
$limite_superior = null;
$temperatura_maxima = null;
$temperatura_minima = null;
$temperatura_suma = 0;
$temperatura_promedio = null;
$desviacion_estandar = null;
$tiempo_sobre_limite = 0;
$tiempo_bajo_limite = 0;
$grafico_minimo = -40;
$grafico_maximo = 40;
$tiempo_sobre_limite_h = 0;
$tiempo_sobre_limite_m = 0;
$tiempo_sobre_limite_s = 0;
$tiempo_bajo_limite_h = 0;
$tiempo_bajo_limite_m = 0;
$tiempo_bajo_limite_s = 0;
$form = $this->createForm(DashboardTemperaturaFormType::class, $dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$lista = $this->bitacoraTemperaturaRepository->findByDashboardTemperaturaDto($dto);
$rango_operacion = $this->tipoCargaRepository->findOneById($dto->tipoCarga);
$vehiculo = $this->vehiculoRepository->findOneById($dto->vehiculo);
if($vehiculo)
{
$dispositivo = $vehiculo->getDispositivo();
}
if($rango_operacion)
{
$limite_inferior = $rango_operacion->getMinimo();
$limite_superior = $rango_operacion->getMaximo();
$grafico_minimo = $rango_operacion->getMinimo();
$grafico_maximo = $rango_operacion->getMaximo();
}
$time_anterior = null;
foreach($lista as $item)
{
$temperatura_actual = $item->getTemp1();
$time_actual = $item->getTimestamp();
if($temperatura_actual)
{
if($fecha_inicio == null)
{
$fecha_inicio = $time_actual;
}
$fecha_fin = $time_actual;
$numero_puntos_medidos++;
$temperatura_suma = $temperatura_suma + $temperatura_actual;
if((!$temperatura_maxima) or ($temperatura_maxima < $temperatura_actual))
{
$temperatura_maxima = $temperatura_actual;
}
if((!$temperatura_minima) or ($temperatura_minima > $temperatura_actual))
{
$temperatura_minima = $temperatura_actual;
}
if(($limite_inferior) and ($temperatura_actual < $limite_inferior))
{
if($time_anterior)
{
$diff = $time_actual->diff($time_anterior);
$segundos = $diff->days * 24 * 60 * 60;
$segundos += $diff->h * 60 * 60;
$segundos += $diff->i * 60;
$segundos += $diff->s;
$tiempo_bajo_limite = $tiempo_bajo_limite + $segundos;
}
}
if(($limite_superior) and ($temperatura_actual > $limite_superior))
{
if($time_anterior)
{
$diff = $time_actual->diff($time_anterior);
$segundos = $diff->days * 24 * 60 * 60;
$segundos += $diff->h * 60 * 60;
$segundos += $diff->i * 60;
$segundos += $diff->s;
$tiempo_sobre_limite = $tiempo_sobre_limite + $segundos;
}
}
$time_anterior = $time_actual;
}
}
if($numero_puntos_medidos > 0)
{
$temperatura_promedio = $temperatura_suma / $numero_puntos_medidos;
// calculo de desviacion estandar
$ans=0;
foreach($lista as $item)
{
if($item->getTemp1())
{
$ans+=pow(($item->getTemp1()-$temperatura_promedio),2);
}
}
$desviacion_estandar = sqrt($ans/$numero_puntos_medidos);
}
if($grafico_minimo > $temperatura_minima)
{
$grafico_minimo = $temperatura_minima;
}
if($grafico_maximo < $temperatura_maxima)
{
$grafico_maximo = $temperatura_maxima;
}
if($grafico_minimo > 0)
{
$grafico_minimo = 0;
}else
{
$grafico_minimo = $grafico_minimo - 5;
}
$grafico_maximo = $grafico_maximo + 5;
if($tiempo_sobre_limite)
{
$tiempo_sobre_limite_h = floor($tiempo_sobre_limite / 3600);
$tiempo_sobre_limite_m = floor(($tiempo_sobre_limite - ($tiempo_sobre_limite_h * 3600)) / 60);
$tiempo_sobre_limite_s = ($tiempo_sobre_limite % 60);
}
if($tiempo_bajo_limite)
{
$tiempo_bajo_limite_h = floor($tiempo_bajo_limite / 3600);
$tiempo_bajo_limite_m = floor(($tiempo_bajo_limite - ($tiempo_bajo_limite_h * 3600)) / 60);
$tiempo_bajo_limite_s = ($tiempo_sobre_limite % 60);
}
}
$intervalo = 120; // 2 horas
if($fecha_inicio && $fecha_fin)
{
$di_fechas = $fecha_inicio->diff($fecha_fin);
$minutes = $di_fechas->days * 24 * 60;
$minutes += $di_fechas->h * 60;
$minutes += $di_fechas->i;
if($minutes <= 20)
{
$intervalo = 1;
}
elseif($minutes > 2400)
{
$intervalo = 120;
}
else
{
$intervalo = ($minutes / 20);
}
}
return $this->render('dashboard/temperatura2.html.twig', array(
'form' => $form->createView(),
'lista' => $lista,
'rango_operacion' => $rango_operacion,
'vehiculo' => $vehiculo,
'dispositivo' => $dispositivo,
'fecha_inicio' => $fecha_inicio,
'fecha_fin' => $fecha_fin,
'numero_puntos_medidos' => $numero_puntos_medidos,
'limite_inferior' => $limite_inferior,
'limite_superior' => $limite_superior,
'temperatura_maxima' => $temperatura_maxima,
'temperatura_minima' => $temperatura_minima,
'temperatura_promedio' => $temperatura_promedio,
'desviacion_estandar' => $desviacion_estandar,
'tiempo_sobre_limite_h' => $tiempo_sobre_limite_h,
'tiempo_sobre_limite_m' => $tiempo_sobre_limite_m,
'tiempo_sobre_limite_s' => $tiempo_sobre_limite_s,
'tiempo_bajo_limite_h' => $tiempo_bajo_limite_h,
'tiempo_bajo_limite_m' => $tiempo_bajo_limite_m,
'tiempo_bajo_limite_s' => $tiempo_bajo_limite_s,
'grafico_minimo' => $grafico_minimo,
'grafico_maximo' => $grafico_maximo,
'intervalo' => $intervalo,
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_inicial');
}
}
/**
* @Route("/dashboard/temperatura/", name="dashboard_temperatura")
* @IsGranted("ROLE_USER")
*/
public function dashboard_temperatura(Request $request): Response
{
try
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_1', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_2', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_3', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_4', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_5', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_1', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_2', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_3', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_4', null);
$this->session->set('SESION_DASHBOARD_TEMPERATURA_RESULTADO_DTO_5', null);
//return $this->redirectToRoute('dashboard_temperatura_buscar');
return $this->render('dashboard/temperatura_opciones.html.twig');
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_inicial');
}
}
/**
* @Route("/dashboard/temperatura/distribucion/dedicada/", name="dashboard_temperatura_distribucion_dedicada")
* @IsGranted("ROLE_USER")
*/
public function dashboard_temperatura_distribucion_dedicada(Request $request): Response
{
try
{
$dto4 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_4');
if(!$dto4)
{
$dto4 = new DashboardTemperaturaDto();
$dto4->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto4->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto4->vehiculo)
{
$dto4->vehiculo = $this->entityManager->merge($dto4->vehiculo);
}
}
$form4 = $this->createForm(DashboardTemperaturaFormType::class, $dto4, array('id_tramo' => 4));
$form4->handleRequest($request);
if ($form4->isSubmitted() && $form4->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_4', $dto4);
}
$resultado4 = $this->getTemperaturaResultado_v2($dto4);
return $this->render('dashboard/temperatura_distribucion_dedicada.html.twig', array(
'form4' => $form4->createView(),
'dto4' => $dto4,
'resultado4' => $resultado4,
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_temperatura');
}
}
/**
* @Route("/dashboard/temperatura/distribucion/courier/", name="dashboard_temperatura_distribucion_courier")
* @IsGranted("ROLE_USER")
*/
public function dashboard_temperatura_distribucion_courier(Request $request): Response
{
try
{
$dto1 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_1');
if(!$dto1)
{
$dto1 = new DashboardTemperaturaDto();
$dto1->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto1->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto1->vehiculo)
{
$dto1->vehiculo = $this->entityManager->merge($dto1->vehiculo);
}
}
$dto2 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_2');
if(!$dto2)
{
$dto2 = new DashboardTemperaturaDto();
$dto2->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto2->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto2->vehiculo)
{
$dto2->vehiculo = $this->entityManager->merge($dto2->vehiculo);
}
}
$dto3 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_3');
if(!$dto3)
{
$dto3 = new DashboardTemperaturaDto();
$dto3->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto3->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto3->vehiculo)
{
$dto3->vehiculo = $this->entityManager->merge($dto3->vehiculo);
}
}
$dto5 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_5');
if(!$dto5)
{
$dto5 = new DashboardTemperaturaDto();
$dto5->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto5->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto5->vehiculo)
{
$dto5->vehiculo = $this->entityManager->merge($dto5->vehiculo);
}
}
$form1 = $this->createForm(DashboardTemperaturaFormType::class, $dto1, array('id_tramo' => 1));
$form1->handleRequest($request);
if ($form1->isSubmitted() && $form1->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_1', $dto1);
}
$form2 = $this->createForm(DashboardTemperaturaFormType::class, $dto2, array('id_tramo' => 2));
$form2->handleRequest($request);
if ($form2->isSubmitted() && $form2->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_2', $dto2);
}
$form3 = $this->createForm(DashboardTemperaturaFormType::class, $dto3, array('id_tramo' => 3));
$form3->handleRequest($request);
if ($form3->isSubmitted() && $form3->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_3', $dto3);
}
$form5 = $this->createForm(DashboardTemperaturaFormType::class, $dto5, array('id_tramo' => 5));
$form5->handleRequest($request);
if ($form5->isSubmitted() && $form5->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_5', $dto5);
}
$resultado1 = $this->getTemperaturaResultado_v2($dto1);
$resultado2 = $this->getTemperaturaResultado_v2($dto2);
$resultado3 = $this->getTemperaturaResultado_v2($dto3);
$resultado5 = $this->getTemperaturaResultado_v2($dto5);
return $this->render('dashboard/temperatura_distribucion_courier.html.twig', array(
'form1' => $form1->createView(),
'form2' => $form2->createView(),
'form3' => $form3->createView(),
'form5' => $form5->createView(),
'dto1' => $dto1,
'dto2' => $dto2,
'dto3' => $dto3,
'dto5' => $dto5,
'resultado1' => $resultado1,
'resultado2' => $resultado2,
'resultado3' => $resultado3,
'resultado5' => $resultado5,
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_temperatura');
}
}
/**
* @Route("/dashboard/temperatura/distribucion/excel/{tramo}/", name="dashboard_temperatura_distribucion_excel")
* @IsGranted("ROLE_USER")
*/
public function dashboard_temperatura_distribucion_excel(Request $request, int $tramo)
{
try
{
$ahora = new \DateTime('now');
$sesion = '';
if($tramo == 1)
$sesion = 'SESION_DASHBOARD_TEMPERATURA_DTO_1';
elseif($tramo == 2)
$sesion = 'SESION_DASHBOARD_TEMPERATURA_DTO_2';
elseif($tramo == 3)
$sesion = 'SESION_DASHBOARD_TEMPERATURA_DTO_3';
elseif($tramo == 4)
$sesion = 'SESION_DASHBOARD_TEMPERATURA_DTO_4';
$dto = $this->session->get($sesion);
if(!$dto)
{
$dto = new DashboardTemperaturaDto();
$dto->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto->vehiculo)
{
$dto->vehiculo = $this->entityManager->merge($dto->vehiculo);
}
}
$resultado = $this->getTemperaturaResultado_v2($dto);
if(!$resultado)
{
$this->addFlash("error", 'No se encuentra informacion de bitacora');
return $this->redirectToRoute("dashboard_temperatura");
}
$spreadsheet = new Spreadsheet();
/* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
$sheet = $spreadsheet->getActiveSheet();
$sheet->setShowGridlines(false);
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('logo');
$drawing->setDescription('logo');
$drawing->setPath('media/logo_transfarma_verde.png'); // put your path and image here
$drawing->setCoordinates('A1');
$drawing->setWorksheet($sheet);
$sheet->setCellValue('A6', 'BITACORA');
$sheet->getStyle('A6')->getFont()->setBold( true );
$sheet->setCellValue('A7', $ahora->format('d-m-Y H:i'));
$sheet->mergeCells("A6:E6");
$sheet->mergeCells("A7:D7");
$sheet->setCellValue('A9', 'Latitud');
$sheet->setCellValue('B9', 'Longuitud');
$sheet->setCellValue('C9', 'Timestamp');
$sheet->setCellValue('D9', 'Temperatura');
$sheet->setCellValue('E9', 'Humedad');
$fila = 9;
foreach($resultado["lista"] as $item)
{
$fila++;
$sheet->setCellValue('A'.$fila, $item->getLatitud());
$sheet->setCellValue('B'.$fila, $item->getLonguitud());
$sheet->setCellValue('C'.$fila, $item->getTimestamp() ? $item->getTimestamp()->format('d-m-Y H:i:s') : '');
$sheet->setCellValue('D'.$fila, $item->getTemp1());
$sheet->setCellValue('E'.$fila, $item->getHum1());
}
//$sheet->setAutoFilter($sheet->calculateWorksheetDimension());
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);
$sheet->getColumnDimension('D')->setAutoSize(true);
$sheet->getColumnDimension('E')->setAutoSize(true);
$sheet->getStyle('A9:E9')->getFont()->setBold( true );
$sheet->getStyle('A9:E9')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
$sheet->getStyle('A9:E9')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('FF426384');
$sheet->getStyle('A9:E'.$fila)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP);
// Create your Office 2007 Excel (XLSX Format)
$writer = new Xlsx($spreadsheet);
// Create a Temporary file in the system
$fileName = 'BITACORA-'.($ahora->format('Ymd-Hi')).'.xlsx';
$temp_file = tempnam($this->getParameter('kernel.project_dir').'/temp/', $fileName);
// Create the excel file in the tmp directory of the system
$writer->save($temp_file);
// Return the excel file as an attachment
return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_temperatura');
}
}
/**
* @Route("/dashboard/temperatura/buscar/", name="dashboard_temperatura_buscar")
* @IsGranted("ROLE_USER")
*/
public function dashboard_temperatura_buscar(Request $request): Response
{
try
{
$dto1 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_1');
if(!$dto1)
{
$dto1 = new DashboardTemperaturaDto();
$dto1->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto1->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto1->vehiculo)
{
$dto1->vehiculo = $this->entityManager->merge($dto1->vehiculo);
}
}
$dto2 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_2');
if(!$dto2)
{
$dto2 = new DashboardTemperaturaDto();
$dto2->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto2->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto2->vehiculo)
{
$dto2->vehiculo = $this->entityManager->merge($dto2->vehiculo);
}
}
$dto3 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_3');
if(!$dto3)
{
$dto3 = new DashboardTemperaturaDto();
$dto3->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto3->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto3->vehiculo)
{
$dto3->vehiculo = $this->entityManager->merge($dto3->vehiculo);
}
}
$dto4 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_4');
if(!$dto4)
{
$dto4 = new DashboardTemperaturaDto();
$dto4->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto4->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto4->vehiculo)
{
$dto4->vehiculo = $this->entityManager->merge($dto4->vehiculo);
}
}
$dto5 = $this->session->get('SESION_DASHBOARD_TEMPERATURA_DTO_5');
if(!$dto5)
{
$dto5 = new DashboardTemperaturaDto();
$dto5->fechaDesde = (new \DateTime('today'))->modify('-7 day');
$dto5->fechaHasta = (new \DateTime('now'));
}
else
{
if($dto5->vehiculo)
{
$dto5->vehiculo = $this->entityManager->merge($dto5->vehiculo);
}
}
$form1 = $this->createForm(DashboardTemperaturaFormType::class, $dto1, array('id_tramo' => 1));
$form1->handleRequest($request);
if ($form1->isSubmitted() && $form1->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_1', $dto1);
}
$form2 = $this->createForm(DashboardTemperaturaFormType::class, $dto2, array('id_tramo' => 2));
$form2->handleRequest($request);
if ($form2->isSubmitted() && $form2->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_2', $dto2);
}
$form3 = $this->createForm(DashboardTemperaturaFormType::class, $dto3, array('id_tramo' => 3));
$form3->handleRequest($request);
if ($form3->isSubmitted() && $form3->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_3', $dto3);
}
$form4 = $this->createForm(DashboardTemperaturaFormType::class, $dto4, array('id_tramo' => 4));
$form4->handleRequest($request);
if ($form4->isSubmitted() && $form4->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_4', $dto4);
}
$form5 = $this->createForm(DashboardTemperaturaFormType::class, $dto5, array('id_tramo' => 5));
$form5->handleRequest($request);
if ($form5->isSubmitted() && $form5->isValid())
{
$this->session->set('SESION_DASHBOARD_TEMPERATURA_DTO_5', $dto5);
}
$resultado1 = $this->getTemperaturaResultado_v2($dto1);
$resultado2 = $this->getTemperaturaResultado_v2($dto2);
$resultado3 = $this->getTemperaturaResultado_v2($dto3);
$resultado4 = $this->getTemperaturaResultado_v2($dto4);
$resultado5 = $this->getTemperaturaResultado_v2($dto5);
$resultado_general = array();
$grafico_minimo_general = 0;
$grafico_maximo_general = 25;
if($resultado1->lista_grafico)
{
if($grafico_minimo_general > $resultado1->grafico_minimo)
{
$grafico_minimo_general = $resultado1->grafico_minimo;
}
if($grafico_maximo_general < $resultado1->grafico_maximo)
{
$grafico_maximo_general = $resultado1->grafico_maximo;
}
foreach($resultado1->lista_grafico as $item_temperatura)
{
if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]))
{
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo1 = $item_temperatura->getTemp1();
}
else
{
$dto = new DTOTemperaturaGeneral();
$dto->fecha = $item_temperatura->getTimestamp();
$dto->tramo1 = $item_temperatura->getTemp1();
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
}
}
}
if($resultado2->lista)
{
if($grafico_minimo_general > $resultado2->grafico_minimo)
{
$grafico_minimo_general = $resultado2->grafico_minimo;
}
if($grafico_maximo_general < $resultado2->grafico_maximo)
{
$grafico_maximo_general = $resultado2->grafico_maximo;
}
foreach($resultado2->lista_grafico as $item_temperatura)
{
if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]))
{
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo2 = $item_temperatura->getTemp1();
}
else
{
$dto = new DTOTemperaturaGeneral();
$dto->fecha = $item_temperatura->getTimestamp();
$dto->tramo2 = $item_temperatura->getTemp1();
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
}
}
}
if($resultado3->lista)
{
if($grafico_minimo_general > $resultado3->grafico_minimo)
{
$grafico_minimo_general = $resultado3->grafico_minimo;
}
if($grafico_maximo_general < $resultado3->grafico_maximo)
{
$grafico_maximo_general = $resultado3->grafico_maximo;
}
foreach($resultado3->lista_grafico as $item_temperatura)
{
if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]))
{
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo3 = $item_temperatura->getTemp1();
}
else
{
$dto = new DTOTemperaturaGeneral();
$dto->fecha = $item_temperatura->getTimestamp();
$dto->tramo3 = $item_temperatura->getTemp1();
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
}
}
}
if($resultado4->lista_grafico)
{
if($grafico_minimo_general > $resultado4->grafico_minimo)
{
$grafico_minimo_general = $resultado4->grafico_minimo;
}
if($grafico_maximo_general < $resultado4->grafico_maximo)
{
$grafico_maximo_general = $resultado4->grafico_maximo;
}
foreach($resultado4->lista_grafico as $item_temperatura)
{
if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]))
{
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo1 = $item_temperatura->getTemp1();
}
else
{
$dto = new DTOTemperaturaGeneral();
$dto->fecha = $item_temperatura->getTimestamp();
$dto->tramo4 = $item_temperatura->getTemp1();
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
}
}
}
if($resultado5->lista_grafico)
{
if($grafico_minimo_general > $resultado5->grafico_minimo)
{
$grafico_minimo_general = $resultado5->grafico_minimo;
}
if($grafico_maximo_general < $resultado5->grafico_maximo)
{
$grafico_maximo_general = $resultado5->grafico_maximo;
}
foreach($resultado5->lista_grafico as $item_temperatura)
{
if (isset($resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]))
{
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')]->tramo1 = $item_temperatura->getTemp1();
}
else
{
$dto = new DTOTemperaturaGeneral();
$dto->fecha = $item_temperatura->getTimestamp();
$dto->tramo5 = $item_temperatura->getTemp1();
$resultado_general[$item_temperatura->getTimestamp()->format('Y-m-d H:i:s')] = $dto;
}
}
}
ksort($resultado_general);
return $this->render('dashboard/temperatura_buscar.html.twig', array(
'form1' => $form1->createView(),
'form2' => $form2->createView(),
'form3' => $form3->createView(),
'form4' => $form4->createView(),
'form5' => $form5->createView(),
'dto1' => $dto1,
'dto2' => $dto2,
'dto3' => $dto3,
'dto4' => $dto4,
'dto5' => $dto5,
'resultado1' => $resultado1,
'resultado2' => $resultado2,
'resultado3' => $resultado3,
'resultado4' => $resultado4,
'resultado5' => $resultado5,
'resultado_general' => $resultado_general,
'grafico_minimo_general' => $grafico_minimo_general,
'grafico_maximo_general' => $grafico_maximo_general,
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('dashboard_temperatura');
}
}
function getTemperaturaResultado_v1(DashboardTemperaturaDto $dto)
{
$tipo_carga_id = 1; //Refrigerado
$dispositivo = null;
$fecha_inicio = null;
$fecha_fin = null;
$numero_puntos_medidos = 0;
$limite_inferior = null;
$limite_superior = null;
$temperatura_maxima = null;
$temperatura_minima = null;
$temperatura_suma = 0;
$temperatura_promedio = null;
$desviacion_estandar = null;
$tiempo_sobre_limite = 0;
$tiempo_bajo_limite = 0;
$grafico_minimo = 0;
$grafico_maximo = 25;
$tiempo_sobre_limite_h = 0;
$tiempo_sobre_limite_m = 0;
$tiempo_sobre_limite_s = 0;
$tiempo_bajo_limite_h = 0;
$tiempo_bajo_limite_m = 0;
$tiempo_bajo_limite_s = 0;
$lista = $this->bitacoraTemperaturaRepository->findByDashboardTemperaturaDto($dto);
$rango_operacion = $this->tipoCargaRepository->findOneById($tipo_carga_id);
$vehiculo = $this->vehiculoRepository->findOneById($dto->vehiculo);
if($vehiculo)
{
$dispositivo = $vehiculo->getDispositivo();
}
$resultado = new DashboardTemperaturaResultadoDto();
if($rango_operacion)
{
$limite_inferior = $rango_operacion->getMinimo();
$limite_superior = $rango_operacion->getMaximo();
$grafico_minimo = 0; // $rango_operacion->getMinimo();
$grafico_maximo = 25; //$rango_operacion->getMaximo();
}
$time_anterior = null;
foreach($lista as $item)
{
$temperatura_actual = $item->getTemp1();
$time_actual = $item->getTimestamp();
if($temperatura_actual)
{
if($fecha_inicio == null)
{
$fecha_inicio = $time_actual;
}
$fecha_fin = $time_actual;
$numero_puntos_medidos++;
$temperatura_suma = $temperatura_suma + $temperatura_actual;
if((!$temperatura_maxima) or ($temperatura_maxima < $temperatura_actual))
{
$temperatura_maxima = $temperatura_actual;
}
if((!$temperatura_minima) or ($temperatura_minima > $temperatura_actual))
{
$temperatura_minima = $temperatura_actual;
}
if(($limite_inferior) and ($temperatura_actual < $limite_inferior))
{
if($time_anterior)
{
$diff = $time_actual->diff($time_anterior);
$segundos = $diff->days * 24 * 60 * 60;
$segundos += $diff->h * 60 * 60;
$segundos += $diff->i * 60;
$segundos += $diff->s;
$tiempo_bajo_limite = $tiempo_bajo_limite + $segundos;
}
}
if(($limite_superior) and ($temperatura_actual > $limite_superior))
{
if($time_anterior)
{
$diff = $time_actual->diff($time_anterior);
$segundos = $diff->days * 24 * 60 * 60;
$segundos += $diff->h * 60 * 60;
$segundos += $diff->i * 60;
$segundos += $diff->s;
$tiempo_sobre_limite = $tiempo_sobre_limite + $segundos;
}
}
$time_anterior = $time_actual;
}
}
if($numero_puntos_medidos > 0)
{
$temperatura_promedio = $temperatura_suma / $numero_puntos_medidos;
// calculo de desviacion estandar
$ans=0;
foreach($lista as $item)
{
if($item->getTemp1())
{
$ans+=pow(($item->getTemp1()-$temperatura_promedio),2);
}
}
$desviacion_estandar = sqrt($ans/$numero_puntos_medidos);
}
if($grafico_minimo > $temperatura_minima)
{
$grafico_minimo = $temperatura_minima;
}
if($grafico_maximo < $temperatura_maxima)
{
$grafico_maximo = $temperatura_maxima;
}
if($grafico_minimo > 0)
{
$grafico_minimo = 0;
}
if($tiempo_sobre_limite)
{
$tiempo_sobre_limite_h = floor($tiempo_sobre_limite / 3600);
$tiempo_sobre_limite_m = floor(($tiempo_sobre_limite - ($tiempo_sobre_limite_h * 3600)) / 60);
$tiempo_sobre_limite_s = ($tiempo_sobre_limite % 60);
}
if($tiempo_bajo_limite)
{
$tiempo_bajo_limite_h = floor($tiempo_bajo_limite / 3600);
$tiempo_bajo_limite_m = floor(($tiempo_bajo_limite - ($tiempo_bajo_limite_h * 3600)) / 60);
$tiempo_bajo_limite_s = ($tiempo_sobre_limite % 60);
}
$cantidad_referencia = 30;
$total_datos = count($lista);
$intervalo = max(1, floor($total_datos / $cantidad_referencia));
$lista_grafico = new ArrayCollection();
$contador_intervalo = 0;
$anterior_minimo = 0;
$anterior_maximo = 0;
foreach($lista as $item)
{
$contador_intervalo++;
if($anterior_minimo == 0)
{
if($item->getTemp1() == $temperatura_minima)
{
$contador_intervalo = $intervalo;
$anterior_minimo = 1;
}
}
else
{
if($item->getTemp1() != $temperatura_minima)
{
$anterior_minimo = 0;
}
}
if($anterior_maximo == 0)
{
if($item->getTemp1() == $temperatura_maxima)
{
$contador_intervalo = $intervalo;
$anterior_maximo = 1;
}
}
else
{
if($item->getTemp1() != $temperatura_maxima)
{
$anterior_maximo = 0;
}
}
if($contador_intervalo >= $intervalo)
{
$lista_grafico[] = $item;
$contador_intervalo = 0;
}
}
$resultado = new DashboardTemperaturaResultadoDto();
$resultado->lista = $lista;
$resultado->lista_grafico = $lista_grafico;
$resultado->rango_operacion = $rango_operacion;
$resultado->vehiculo = $vehiculo;
$resultado->dispositivo = $dispositivo;
$resultado->fecha_inicio = $fecha_inicio;
$resultado->fecha_fin = $fecha_fin;
$resultado->numero_puntos_medidos = $numero_puntos_medidos;
$resultado->limite_inferior = $limite_inferior;
$resultado->limite_superior = $limite_superior;
$resultado->temperatura_maxima = $temperatura_maxima;
$resultado->temperatura_minima = $temperatura_minima;
$resultado->temperatura_promedio = $temperatura_promedio;
$resultado->desviacion_estandar = $desviacion_estandar;
$resultado->tiempo_sobre_limite_h = $tiempo_sobre_limite_h;
$resultado->tiempo_sobre_limite_m = $tiempo_sobre_limite_m;
$resultado->tiempo_sobre_limite_s = $tiempo_sobre_limite_s;
$resultado->tiempo_bajo_limite_h = $tiempo_bajo_limite_h;
$resultado->tiempo_bajo_limite_m = $tiempo_bajo_limite_m;
$resultado->tiempo_bajo_limite_s = $tiempo_bajo_limite_s;
$resultado->grafico_minimo = $grafico_minimo;
$resultado->grafico_maximo = $grafico_maximo;
$resultado->intervalo = $intervalo;
return $resultado;
}
function getTemperaturaResultado_v2(DashboardTemperaturaDto $dto)
{
$rango_operacion = null;
$lista = $this->bitacoraTemperaturaRepository->findByDashboardTemperaturaDto($dto);
$vehiculo = $dto->vehiculo;
if($vehiculo)
{
$rango_operacion = $vehiculo->getRango();
}
$contador = 0;
$min = 0;
$max = 20;
if($rango_operacion)
{
$max = $rango_operacion->getHasta();
}
$primer_punto = null;
$ultimo_punto = null;
foreach($lista as $item_detalle)
{
$contador++;
if(!$primer_punto)
{
$primer_punto = $item_detalle->getTimestamp();
}
elseif($primer_punto > $item_detalle->getTimestamp())
{
$primer_punto = $item_detalle->getTimestamp();
}
if(!$ultimo_punto)
{
$ultimo_punto = $item_detalle->getTimestamp();
}
elseif($ultimo_punto < $item_detalle->getTimestamp())
{
$ultimo_punto = $item_detalle->getTimestamp();
}
if($item_detalle->getTemp1() < $min)
{
$min = $item_detalle->getTemp1();
}
if($item_detalle->getTemp1() > $max)
{
$max = $item_detalle->getTemp1();
}
}
$max = round($max + 2, 0, PHP_ROUND_HALF_UP);
return array(
'lista' => $lista,
'contador' => $contador,
'min' => $min,
'max' => $max,
'primer_punto' => $primer_punto,
'ultimo_punto' => $ultimo_punto,
'vehiculo' => $vehiculo,
'rango' => $rango_operacion
);
}
function distanceCalculation($point1_lat, $point1_long, $point2_lat, $point2_long, $unit = 'km', $decimals = 2)
{
// Cálculo de la distancia en grados
$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)))));
// Conversión de la distancia en grados a la unidad escogida (kilómetros, millas o millas naúticas)
switch($unit) {
case 'km':
$distance = $degrees * 111.13384; // 1 grado = 111.13384 km, basándose en el diametro promedio de la Tierra (12.735 km)
break;
case 'mi':
$distance = $degrees * 69.05482; // 1 grado = 69.05482 millas, basándose en el diametro promedio de la Tierra (7.913,1 millas)
break;
case 'nmi':
$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)
}
return round($distance, $decimals);
}
/**
* @Route("/dashboard/localizacion/", name="dashboard_localizacion")
* @IsGranted("ROLE_USER")
*/
public function dashboard_localizacion(Request $request): Response
{
try
{
$dto = new DashboardLocalizacionDto();
$lista = null;
$form = $this->createForm(DashboardLocalizacionFormType::class, $dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$lista = $this->vehiculoRepository->getLocalizacion($dto->vehiculo);
}
return $this->render('dashboard/localizacion2.html.twig', array(
'form' => $form->createView(),
'lista' => $lista,
));
}
catch(\Exception $e){
$this->logger->error($e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'url' => $request->getUri(), // Devuelve la URL completa: https://tu-dominio.com/ruta?param=1
'method' => $request->getMethod(), // GET, POST, etc.
'user' => $this->getUser() ? $this->getUser()->getUsername() : '',
'params' => $request->request->all()
]);
$this->addFlash('danger',$e->getMessage());
return $this->redirectToRoute('app_admin_index');
}
}
}