<?php
/*
* Autor: Carlos Iglesias
* Description: Grafica Controller to handle routes and views
* Date: 15/September/2021
*/
namespace App\Controller;
use App\Service\GraficaService;
use App\Service\ShipmentService;
use App\Service\ChartGoalService;
use App\Service\SolicitudService;
use App\Service\ChartHistoryService;
use App\Service\FidelizacionService;
use DateInterval;
use DatePeriod;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
set_time_limit(0);
class GraficaController extends AbstractController
{
/**
* @Route("/grafica", name="_grafica")
*/
public function grafica(Request $request, GraficaService $graficaService, ChartHistoryService $chartHistoryService)
{
$meses = [
'Enero',
'Febrero',
'Marzo',
'Abril',
'Mayo',
'Junio',
'Julio',
'Agosto',
'Septiembre',
'Octubre',
'Noviembre',
'Diciembre',
];
return $this->render('grafica.html.twig',[
"meses" => json_encode($meses),
]);
}
/**
* @Route("/graficas", name="_graficas_json")
*/
public function getGraficas(Request $request, GraficaService $graficaService, ChartHistoryService $chartHistoryService, SolicitudService $solicitudService, FidelizacionService $fidelizacionService, ChartGoalService $chartGoalService) {
$year = $request->query->get('year') ?? '2023';
$fidelizacion = $this->getGraficaFidelizacion($fidelizacionService, $chartHistoryService);
$solicitudes = $this->getGraficaSolicitudes($year, $solicitudService, $graficaService, $chartHistoryService);
$datosDeUsoArray = $this->getGraficaRempateOEmpate($year, $graficaService, $chartHistoryService, true);
$porcentajesEmpatesDelivery = $this->getGraficaRempateOEmpate($year, $graficaService, $chartHistoryService, false);
$empateGlobal = $this->graficaEmpateGlobal($year, $datosDeUsoArray, $porcentajesEmpatesDelivery, $chartHistoryService, $solicitudes);
$porcentajesEmpate = [];
$porcentajesEmpatesDeliveryArray = [];
$porcentajesEmpateGlobal = [];
$porcentajesSolicitudes = [];
$porcentajesFidelizacion = [];
$metasEmpate = [];
$metasEmpateDelivery = [];
$metasEmpateGlobal = [];
$metasSolicitudes = [];
$metasFidelizacion = [];
for ($i=0; $i < 12; $i++) {
$date = new \DateTime("01-01-".date($year));
$date->modify("+". $i ." month");
$porcentajesEmpate['data'][] = $this->generateDataChart($date, 'empate', $chartHistoryService);
$porcentajesEmpatesDeliveryArray['data'][] = $this->generateDataChart($date, 'empate_delivery', $chartHistoryService);
$porcentajesEmpateGlobal['data'][] = $this->generateDataChart($date, 'empate_global', $chartHistoryService);
$porcentajesSolicitudes['data'][] = $this->generateDataChart($date, 'solicitudes', $chartHistoryService);
$porcentajesFidelizacion['data'][] = $this->generateDataChart($date, 'fidelizacion', $chartHistoryService);
$metasEmpate['data'][] = $this->generateDataChartGoal($date, 'empate', $chartGoalService);
$metasEmpateDelivery['data'][] = $this->generateDataChartGoal($date, 'empate_delivery', $chartGoalService);
$metasEmpateGlobal['data'][] = $this->generateDataChartGoal($date, 'empate_global', $chartGoalService);
$metasSolicitudes['data'][] = $this->generateDataChartGoal($date, 'solicitudes', $chartGoalService);
$metasFidelizacion['data'][] = $this->generateDataChartGoal($date, 'fidelizacion', $chartGoalService);
}
return $this->json([
"porcentajes" => $porcentajesEmpate,
"porcentajesEmpatesDelivery" => $porcentajesEmpatesDeliveryArray,
"porcentajesGlobales" => $porcentajesEmpateGlobal,
"solicitudes" => $porcentajesSolicitudes,
'fidelizacion' => $porcentajesFidelizacion,
'metasEmpate' => $metasEmpate,
'metasEmpateDelivery' => $metasEmpateDelivery,
'metasEmpateGlobal' => $metasEmpateGlobal,
'metasSolicitudes' => $metasSolicitudes,
'metasFidelizacion' => $metasFidelizacion,
]);
}
public function generateDataChart($date, $type, ChartHistoryService $chartHistoryService)
{
$data = $chartHistoryService->getChartHistoryByDate($date, $type);
if (empty($data)) {
$dataChart = 0.0;
} else {
$dataChart = $data->getPercent();
}
return $dataChart;
}
public function generateDataChartGoal($date, $type, ChartGoalService $chartGoalService)
{
$data = $chartGoalService->getChartGoalByDate($date, $type);
if (empty($data)) {
$dataChart = 0.0;
} else {
$dataChart = $data->getPercent();
}
return $dataChart;
}
public function getGraficaRempateOEmpate($year, GraficaService $graficaService, ChartHistoryService $chartHistoryService, bool $isEmpate)
{
$data = [];
for ($i=0; $i < 12; $i++) {
$month = $i+1;
$startDate = date_create("$year-$month-01");
$endDate = date_create("$year-$month-01")->modify('+7 days')->modify("+1 month");
$reempatesOrEmpates = $isEmpate ?
$graficaService->getEmpatesByRangeDates($startDate, $endDate) :
$graficaService->getReempatesByRangeDates($startDate, $endDate);
$shipments = $graficaService->getShipmentsByMonthAndYear($i+1, date("Y", strtotime("$year-01-01")));
$porcentaje = ($shipments != 0 && $reempatesOrEmpates != 0) ? ($reempatesOrEmpates/$shipments) : 0;
$total = (float) number_format($porcentaje*100, 3, '.', ',');
$data[] = $total;
$date = new \DateTime("01-01-".date("Y", strtotime("$year-01-01")));
$date->modify("+". $i ." month");
$isEmpate ? $chartHistoryService->createChartHistory($date, $total, 'empate') : $chartHistoryService->createChartHistory($date, $total, 'empate_delivery');
}
return $data;
}
public function getGraficaSolicitudes($year, SolicitudService $solicitudService, GraficaService $graficaService, ChartHistoryService $chartHistoryService)
{
for ($i=0; $i < 12; $i++) {
$solicitudesCerradas = $solicitudService->getSolicitudesCerradas($i+1, date("Y", strtotime("$year-01-01")));
$shipments = $graficaService->getShipmentsByMonthAndYear($i+1, date("Y", strtotime("$year-01-01")));
$porcentaje = ($shipments != 0 && $solicitudesCerradas != 0) ? ($solicitudesCerradas/$shipments) : 0;
$total = (float) number_format($porcentaje*100, 3, '.', ',');
$data[] = $total;
$date = new \DateTime("01-01-".date("Y", strtotime("$year-01-01")));
$date->modify("+". $i ." month");
$chartHistoryService->createChartHistory($date, $total, 'solicitudes');
}
return $data;
}
public function getGraficaFidelizacion(FidelizacionService $fidelizacionService, ChartHistoryService $chartHistoryService)
{
for ($i=0; $i < 12; $i++) {
$fidelizados = $fidelizacionService->getFidelizacionByFidelizado($i+1);
$notFidelizados = $fidelizacionService->getFidelizacionNotFidelizado($i+1);
$total = $fidelizados + $notFidelizados;
$porcentaje = ($total != 0 && $fidelizados != 0) ? ($fidelizados/$total) : 0;
$total = (float) number_format($porcentaje*100, 3, '.', ',');
$data[] = $total;
$date = new \DateTime("01-01-".date("Y"));
$date->modify("+". $i ." month");
$chartHistoryService->createChartHistory($date, $total, 'fidelizacion');
}
return $data;
}
public function graficaEmpateGlobal($year, $empatesArray, $empatesDeliveryArray, ChartHistoryService $chartHistoryService, $solicitudes) {
$empatesPorcentajes = $empatesArray;
$empatesDeliveryPorcentajes = $empatesDeliveryArray;
$countPorcentajes = count($empatesPorcentajes);
$porcentajesGlobal = array();
for ($i=0; $i < $countPorcentajes; $i++) {
array_push($porcentajesGlobal, number_format((($solicitudes[$i]+$empatesPorcentajes[$i]+$empatesDeliveryPorcentajes[$i])/3), 3, '.', ','));
$date = new \DateTime("01-01-".date("Y", strtotime("$year-01-01")));
$date->modify("+". $i ." month");
$chartHistoryService->createChartHistory($date, $porcentajesGlobal[$i], 'empate_global');
}
$arrayFinal[0] = [
"name" => 'Empate Global',
"data" => $porcentajesGlobal
];
$porcentajesJson = json_encode($arrayFinal);
return $porcentajesJson;
}
/**
* @Route("/dashboard", name="_dashboard")
*/
public function graficaModalidad(Request $request, GraficaService $graficaService, ShipmentService $shipmentService)
{
$fechaActual = new \DateTime();
$fechaClon = clone $fechaActual;
$fechaHace1Mes = date_modify($fechaClon,'-45day');
$countTotal = $graficaService->countTotalShipments($fechaHace1Mes, $fechaActual);
$subTypes = $shipmentService->getAllSubTypes($fechaHace1Mes, $fechaActual);
$countPerSubType = [];
$countPerRegion = [];
$subTypesArr = [];
$regionesArr = [];
$cantidadArr = [];
$ciudadArr = [];
$countRegion = 0;
$graficaBarrasInfo = $graficaService->getDestinationsCount($fechaHace1Mes, $fechaActual);
for($j = 0; $j<count($graficaBarrasInfo); $j++){
$cantidadArr[$j] = $graficaBarrasInfo[$j][1];
$ciudadArr[$j] = $graficaBarrasInfo[$j]['name'];
// $countPerSubType[$j] = (float)number_format($porcentaje, 3, '.', ',');
}
for($i = 0; $i<count($subTypes); $i++){
$subTypesArr[$i] = $subTypes[$i]['subType'];
$count = $graficaService->countTotalShipments($fechaHace1Mes, $fechaActual, $subTypes[$i]['subType']);
$porcentaje = ($count/$countTotal)*100;
$countPerSubType[$i] = (float)number_format($porcentaje, 3, '.', ',');
}
$graficaRegionInfo = $graficaService->getShipmentsPorRegion($fechaHace1Mes, $fechaActual);
for($i=0; $i<count($graficaRegionInfo); $i++){
$porcentaje = ($graficaRegionInfo[$i]['cantidad']/$countTotal)*100;
$countPerRegion[$i] = (float)number_format($porcentaje, 3, '.', ',');
$countRegion = $countRegion + $graficaRegionInfo[$i]['cantidad'];
$regionesArr[$i] = $graficaRegionInfo[$i]['region'];
}
$porcentaje = (($countTotal-$countRegion)/$countTotal)*100;
$countPerRegion[$i] = (float)number_format($porcentaje, 3, '.', ',');
$regionesArr[$i] = 'Sin región';
$regionesArrJson = json_encode($regionesArr);
$porcentajeRegiones = json_encode(array_values($countPerRegion));
$subTypesArrJson = json_encode($subTypesArr);
$porcentajesJson = json_encode(array_values($countPerSubType));
$cantidadJson = json_encode(array_values($cantidadArr));
$ciudadesJson = json_encode(array_values($ciudadArr));
return $this->render('/graficas/graficaFiltros.html.twig',[
"porcentajes" => $porcentajesJson,
"subTypesJson" => $subTypesArrJson,
'subTypes' => $subTypes,
'dateToday' => $fechaActual->format('d-m-Y'),
'dateHace1Mes' => $fechaHace1Mes->format('d-m-Y'),
'cantidadJson' => $cantidadJson,
'ciudadesJson' => $ciudadesJson,
'regionesJson' => $regionesArrJson,
'porcentajeRegiones' => $porcentajeRegiones
]);
}
/**
* @Route("/filtrarGrafica", name="_filtrar_grafica")
*/
public function filtrarGrafica(Request $request, GraficaService $graficaService, ShipmentService $shipmentService){
$subTypesCall = $request->query->get("subTypes");
$dateInicio = $request->query->get("dateInicio");
$dateFinal = $request->query->get("dateFinal");
$indexNameSelected = $request->query->get("indexNameSelected");
$subTypesArr = [];
for($j=0;$j<count($subTypesCall); $j++){
$subTypesArr[$j] = $subTypesCall[$j]['name'];
}
$dateInicio = new \DateTime($dateInicio);
$dateFinal = new \DateTime($dateFinal);
$countTotal = $graficaService->countTotalShipments($dateInicio, $dateFinal);
// $subTypes = $shipmentService->getAllSubTypes($dateInicio, $dateFinal);
$countPerSubType = [];
for($i = 0; $i<count($subTypesArr); $i++){
$count = $graficaService->countTotalShipments($dateInicio, $dateFinal, $subTypesArr[$i]);
if($count == 0 || $countTotal == 0){
$porcentaje = 0;
}else{
$porcentaje = ($count/$countTotal)*100;
}
$countPerSubType[$i] = (float)number_format($porcentaje, 3, '.', ',');
}
$subTypesArrJson = json_encode($subTypesArr);
$porcentajesJson = json_encode(array_values($countPerSubType));
$countRegion = 0;
$graficaRegionInfo = $graficaService->getShipmentsPorRegion($dateInicio, $dateFinal, $subTypesArr);
for($i=0; $i<count($graficaRegionInfo); $i++){
$porcentaje = ($graficaRegionInfo[$i]['cantidad']/$countTotal)*100;
$countPerRegion[$i] = (float)number_format($porcentaje, 3, '.', ',');
$countRegion = $countRegion + $graficaRegionInfo[$i]['cantidad'];
$regionesArr[$i] = $graficaRegionInfo[$i]['region'];
}
$porcentaje = (($countTotal-$countRegion)/$countTotal)*100;
$countPerRegion[$i] = (float)number_format($porcentaje, 3, '.', ',');
$regionesArr[$i] = 'Sin región';
$regionesArrJson = json_encode($regionesArr);
$porcentajeRegiones = json_encode(array_values($countPerRegion));
if($indexNameSelected != '' && $indexNameSelected != null){
if($indexNameSelected == 'Sin región'){
$region = 'Sin regíon';
}else{
$region = $graficaService->getRegionByName($indexNameSelected);
}
}else{
$region = null;
}
$graficaBarrasInfo = $graficaService->getDestinationsCount($dateInicio, $dateFinal, $subTypesArr, $region);
if(empty($graficaBarrasInfo)){
return $this->json(["data" => 'Tú búsqueda no arrojo ningún resultado.']);
}
for($j = 0; $j<count($graficaBarrasInfo); $j++){
$cantidadArr[$j] = $graficaBarrasInfo[$j][1];
$ciudadArr[$j] = $graficaBarrasInfo[$j]['name'];
// $countPerSubType[$j] = (float)number_format($porcentaje, 3, '.', ',');
}
$response[0] = $subTypesArrJson;
$response[1] = $porcentajesJson;
$response[2] = $regionesArrJson;
$response[3] = $porcentajeRegiones;
$response[4] = $cantidadArr;
$response[5] = $ciudadArr;
return $this->json(["data" => $response]);
}
/**
* @Route("/getRoutesByState", name="get_route_by_state")
*/
public function getRoutesByState(Request $request, GraficaService $graficaService, ShipmentService $shipmentService)
{
$stateName = $request->query->get("stateName");
$subTypes = $request->query->get("subTypes");
$region = $request->query->get("region");
$dateInicio = $request->query->get("dateInicio");
$dateFinal = $request->query->get("dateFinal");
$subTypesArr = [];
$returnArr = [];
if ($subTypes == null) {
return $this->json(['error' => 'No se encontraron rutas'])->setStatusCode(400);
}
for($j=0;$j<count($subTypes); $j++){
$subTypesArr[$j] = $subTypes[$j]['name'];
}
$dateInicio = new \DateTime($dateInicio);
$dateFinal = new \DateTime($dateFinal);
$state = $graficaService->getStateByName($stateName);
if($region == 'Sin región'){
$region = 'Sin regíon';
}else{
$region = $graficaService->getRegionByName($region);
}
$shipments = $shipmentService->getAllRoutesByState($dateInicio, $dateFinal, $state, $subTypesArr, $region);
foreach($shipments as $shipment){
$returnArr[] = [
'idExample' => $shipment['id'],
'destination' => $shipment['finalDestination'],
'quantity' => $shipment['quantity']
];
}
return $this->json(["data" => $returnArr]);
}
/**
* @Route("/metas_json", name="_graficas_metas_json")
*/
public function metas(Request $request, ChartGoalService $chartGoalService)
{
$year = $request->query->get("year") ?? '2022';
$type = $request->query->get("type") ?? 'empate';
$chartValues = ['data' => []];
for ($i=0; $i < 12; $i++) {
$date = new \DateTime("01-01-".date($year));
$date->modify("+". $i ." month");
$chart = $chartGoalService->getChartGoalByDate($date, $type);
if (empty($chart)) {
array_push($chartValues['data'], 0.0);
} else {
array_push($chartValues['data'], $chart->getPercent());
}
}
return $this->json(['metas' => $chartValues]);
}
/**
* @Route("/guardar_metas", name="_guardar_metas")
*/
public function guardarMetas(Request $request, ChartGoalService $chartGoalService)
{
$values = $request->get("values");
$type = $request->get("type") ?? 'empate';
$year = $request->get("year") ?? '2022';
$total = count($values);
$chartValues = ['data' => []];
for ($i=0; $i < $total; $i++) {
$date = new \DateTime("01-01-".date($year));
$date->modify("+". $i ." month");
$chartGoalService->createChartGoal($date, $values[$i], $type);
$chart = $chartGoalService->getChartGoalByDate($date, $type);
if (empty($chart)) {
array_push($chartValues['data'], 0.0);
} else {
array_push($chartValues['data'], $chart->getPercent());
}
}
return $this->json(['metas' => $chartValues]);
}
}